OSDN Git Service

Fix CREATE TABLE ... LIKE ... INCLUDING INDEXES to not cause unwanted
[pg-rex/syncrep.git] / src / backend / parser / parse_utilcmd.c
1 /*-------------------------------------------------------------------------
2  *
3  * parse_utilcmd.c
4  *        Perform parse analysis work for various utility commands
5  *
6  * Formerly we did this work during parse_analyze() in analyze.c.  However
7  * that is fairly unsafe in the presence of querytree caching, since any
8  * database state that we depend on in making the transformations might be
9  * obsolete by the time the utility command is executed; and utility commands
10  * have no infrastructure for holding locks or rechecking plan validity.
11  * Hence these functions are now called at the start of execution of their
12  * respective utility commands.
13  *
14  * NOTE: in general we must avoid scribbling on the passed-in raw parse
15  * tree, since it might be in a plan cache.  The simplest solution is
16  * a quick copyObject() call before manipulating the query tree.
17  *
18  *
19  * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
20  * Portions Copyright (c) 1994, Regents of the University of California
21  *
22  *      $PostgreSQL: pgsql/src/backend/parser/parse_utilcmd.c,v 2.9 2008/02/07 17:09:51 tgl Exp $
23  *
24  *-------------------------------------------------------------------------
25  */
26
27 #include "postgres.h"
28
29 #include "access/genam.h"
30 #include "access/heapam.h"
31 #include "access/reloptions.h"
32 #include "catalog/dependency.h"
33 #include "catalog/heap.h"
34 #include "catalog/index.h"
35 #include "catalog/namespace.h"
36 #include "catalog/pg_opclass.h"
37 #include "catalog/pg_type.h"
38 #include "commands/defrem.h"
39 #include "commands/tablecmds.h"
40 #include "commands/tablespace.h"
41 #include "miscadmin.h"
42 #include "nodes/makefuncs.h"
43 #include "optimizer/clauses.h"
44 #include "parser/analyze.h"
45 #include "parser/gramparse.h"
46 #include "parser/parse_clause.h"
47 #include "parser/parse_expr.h"
48 #include "parser/parse_relation.h"
49 #include "parser/parse_type.h"
50 #include "parser/parse_utilcmd.h"
51 #include "rewrite/rewriteManip.h"
52 #include "utils/acl.h"
53 #include "utils/builtins.h"
54 #include "utils/lsyscache.h"
55 #include "utils/relcache.h"
56 #include "utils/syscache.h"
57
58
59 /* State shared by transformCreateStmt and its subroutines */
60 typedef struct
61 {
62         const char *stmtType;           /* "CREATE TABLE" or "ALTER TABLE" */
63         RangeVar   *relation;           /* relation to create */
64         Relation        rel;                    /* opened/locked rel, if ALTER */
65         List       *inhRelations;       /* relations to inherit from */
66         bool            isalter;                /* true if altering existing table */
67         bool            hasoids;                /* does relation have an OID column? */
68         List       *columns;            /* ColumnDef items */
69         List       *ckconstraints;      /* CHECK constraints */
70         List       *fkconstraints;      /* FOREIGN KEY constraints */
71         List       *ixconstraints;      /* index-creating constraints */
72         List       *inh_indexes;        /* cloned indexes from INCLUDING INDEXES */
73         List       *blist;                      /* "before list" of things to do before
74                                                                  * creating the table */
75         List       *alist;                      /* "after list" of things to do after creating
76                                                                  * the table */
77         IndexStmt  *pkey;                       /* PRIMARY KEY index, if any */
78 } CreateStmtContext;
79
80 /* State shared by transformCreateSchemaStmt and its subroutines */
81 typedef struct
82 {
83         const char *stmtType;           /* "CREATE SCHEMA" or "ALTER SCHEMA" */
84         char       *schemaname;         /* name of schema */
85         char       *authid;                     /* owner of schema */
86         List       *sequences;          /* CREATE SEQUENCE items */
87         List       *tables;                     /* CREATE TABLE items */
88         List       *views;                      /* CREATE VIEW items */
89         List       *indexes;            /* CREATE INDEX items */
90         List       *triggers;           /* CREATE TRIGGER items */
91         List       *grants;                     /* GRANT items */
92 } CreateSchemaStmtContext;
93
94
95 static void transformColumnDefinition(ParseState *pstate,
96                                                   CreateStmtContext *cxt,
97                                                   ColumnDef *column);
98 static void transformTableConstraint(ParseState *pstate,
99                                                  CreateStmtContext *cxt,
100                                                  Constraint *constraint);
101 static void transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
102                                          InhRelation *inhrelation);
103 static IndexStmt *generateClonedIndexStmt(CreateStmtContext *cxt,
104                                                 Relation parent_index, AttrNumber *attmap);
105 static List *get_opclass(Oid opclass, Oid actual_datatype);
106 static void transformIndexConstraints(ParseState *pstate,
107                                                   CreateStmtContext *cxt);
108 static IndexStmt *transformIndexConstraint(Constraint *constraint,
109                                                  CreateStmtContext *cxt);
110 static void transformFKConstraints(ParseState *pstate,
111                                            CreateStmtContext *cxt,
112                                            bool skipValidation,
113                                            bool isAddConstraint);
114 static void transformConstraintAttrs(List *constraintList);
115 static void transformColumnType(ParseState *pstate, ColumnDef *column);
116 static void setSchemaName(char *context_schema, char **stmt_schema_name);
117
118
119 /*
120  * transformCreateStmt -
121  *        parse analysis for CREATE TABLE
122  *
123  * Returns a List of utility commands to be done in sequence.  One of these
124  * will be the transformed CreateStmt, but there may be additional actions
125  * to be done before and after the actual DefineRelation() call.
126  *
127  * SQL92 allows constraints to be scattered all over, so thumb through
128  * the columns and collect all constraints into one place.
129  * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
130  * then expand those into multiple IndexStmt blocks.
131  *        - thomas 1997-12-02
132  */
133 List *
134 transformCreateStmt(CreateStmt *stmt, const char *queryString)
135 {
136         ParseState *pstate;
137         CreateStmtContext cxt;
138         List       *result;
139         List       *save_alist;
140         ListCell   *elements;
141
142         /*
143          * We must not scribble on the passed-in CreateStmt, so copy it.  (This is
144          * overkill, but easy.)
145          */
146         stmt = (CreateStmt *) copyObject(stmt);
147
148         /*
149          * If the target relation name isn't schema-qualified, make it so.  This
150          * prevents some corner cases in which added-on rewritten commands might
151          * think they should apply to other relations that have the same name and
152          * are earlier in the search path.      "istemp" is equivalent to a
153          * specification of pg_temp, so no need for anything extra in that case.
154          */
155         if (stmt->relation->schemaname == NULL && !stmt->relation->istemp)
156         {
157                 Oid                     namespaceid = RangeVarGetCreationNamespace(stmt->relation);
158
159                 stmt->relation->schemaname = get_namespace_name(namespaceid);
160         }
161
162         /* Set up pstate */
163         pstate = make_parsestate(NULL);
164         pstate->p_sourcetext = queryString;
165
166         cxt.stmtType = "CREATE TABLE";
167         cxt.relation = stmt->relation;
168         cxt.rel = NULL;
169         cxt.inhRelations = stmt->inhRelations;
170         cxt.isalter = false;
171         cxt.columns = NIL;
172         cxt.ckconstraints = NIL;
173         cxt.fkconstraints = NIL;
174         cxt.ixconstraints = NIL;
175         cxt.inh_indexes = NIL;
176         cxt.blist = NIL;
177         cxt.alist = NIL;
178         cxt.pkey = NULL;
179         cxt.hasoids = interpretOidsOption(stmt->options);
180
181         /*
182          * Run through each primary element in the table creation clause. Separate
183          * column defs from constraints, and do preliminary analysis.
184          */
185         foreach(elements, stmt->tableElts)
186         {
187                 Node       *element = lfirst(elements);
188
189                 switch (nodeTag(element))
190                 {
191                         case T_ColumnDef:
192                                 transformColumnDefinition(pstate, &cxt,
193                                                                                   (ColumnDef *) element);
194                                 break;
195
196                         case T_Constraint:
197                                 transformTableConstraint(pstate, &cxt,
198                                                                                  (Constraint *) element);
199                                 break;
200
201                         case T_FkConstraint:
202                                 /* No pre-transformation needed */
203                                 cxt.fkconstraints = lappend(cxt.fkconstraints, element);
204                                 break;
205
206                         case T_InhRelation:
207                                 transformInhRelation(pstate, &cxt,
208                                                                          (InhRelation *) element);
209                                 break;
210
211                         default:
212                                 elog(ERROR, "unrecognized node type: %d",
213                                          (int) nodeTag(element));
214                                 break;
215                 }
216         }
217
218         /*
219          * transformIndexConstraints wants cxt.alist to contain only index
220          * statements, so transfer anything we already have into save_alist.
221          */
222         save_alist = cxt.alist;
223         cxt.alist = NIL;
224
225         Assert(stmt->constraints == NIL);
226
227         /*
228          * Postprocess constraints that give rise to index definitions.
229          */
230         transformIndexConstraints(pstate, &cxt);
231
232         /*
233          * Postprocess foreign-key constraints.
234          */
235         transformFKConstraints(pstate, &cxt, true, false);
236
237         /*
238          * Output results.
239          */
240         stmt->tableElts = cxt.columns;
241         stmt->constraints = cxt.ckconstraints;
242
243         result = lappend(cxt.blist, stmt);
244         result = list_concat(result, cxt.alist);
245         result = list_concat(result, save_alist);
246
247         return result;
248 }
249
250 /*
251  * transformColumnDefinition -
252  *              transform a single ColumnDef within CREATE TABLE
253  *              Also used in ALTER TABLE ADD COLUMN
254  */
255 static void
256 transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
257                                                   ColumnDef *column)
258 {
259         bool            is_serial;
260         bool            saw_nullable;
261         bool            saw_default;
262         Constraint *constraint;
263         ListCell   *clist;
264
265         cxt->columns = lappend(cxt->columns, column);
266
267         /* Check for SERIAL pseudo-types */
268         is_serial = false;
269         if (list_length(column->typename->names) == 1)
270         {
271                 char       *typname = strVal(linitial(column->typename->names));
272
273                 if (strcmp(typname, "serial") == 0 ||
274                         strcmp(typname, "serial4") == 0)
275                 {
276                         is_serial = true;
277                         column->typename->names = NIL;
278                         column->typename->typeid = INT4OID;
279                 }
280                 else if (strcmp(typname, "bigserial") == 0 ||
281                                  strcmp(typname, "serial8") == 0)
282                 {
283                         is_serial = true;
284                         column->typename->names = NIL;
285                         column->typename->typeid = INT8OID;
286                 }
287         }
288
289         /* Do necessary work on the column type declaration */
290         transformColumnType(pstate, column);
291
292         /* Special actions for SERIAL pseudo-types */
293         if (is_serial)
294         {
295                 Oid                     snamespaceid;
296                 char       *snamespace;
297                 char       *sname;
298                 char       *qstring;
299                 A_Const    *snamenode;
300                 FuncCall   *funccallnode;
301                 CreateSeqStmt *seqstmt;
302                 AlterSeqStmt *altseqstmt;
303                 List       *attnamelist;
304
305                 /*
306                  * Determine namespace and name to use for the sequence.
307                  *
308                  * Although we use ChooseRelationName, it's not guaranteed that the
309                  * selected sequence name won't conflict; given sufficiently long
310                  * field names, two different serial columns in the same table could
311                  * be assigned the same sequence name, and we'd not notice since we
312                  * aren't creating the sequence quite yet.  In practice this seems
313                  * quite unlikely to be a problem, especially since few people would
314                  * need two serial columns in one table.
315                  */
316                 if (cxt->rel)
317                         snamespaceid = RelationGetNamespace(cxt->rel);
318                 else
319                         snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
320                 snamespace = get_namespace_name(snamespaceid);
321                 sname = ChooseRelationName(cxt->relation->relname,
322                                                                    column->colname,
323                                                                    "seq",
324                                                                    snamespaceid);
325
326                 ereport(NOTICE,
327                                 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
328                                                 cxt->stmtType, sname,
329                                                 cxt->relation->relname, column->colname)));
330
331                 /*
332                  * Build a CREATE SEQUENCE command to create the sequence object, and
333                  * add it to the list of things to be done before this CREATE/ALTER
334                  * TABLE.
335                  */
336                 seqstmt = makeNode(CreateSeqStmt);
337                 seqstmt->sequence = makeRangeVar(snamespace, sname);
338                 seqstmt->options = NIL;
339
340                 cxt->blist = lappend(cxt->blist, seqstmt);
341
342                 /*
343                  * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence
344                  * as owned by this column, and add it to the list of things to be
345                  * done after this CREATE/ALTER TABLE.
346                  */
347                 altseqstmt = makeNode(AlterSeqStmt);
348                 altseqstmt->sequence = makeRangeVar(snamespace, sname);
349                 attnamelist = list_make3(makeString(snamespace),
350                                                                  makeString(cxt->relation->relname),
351                                                                  makeString(column->colname));
352                 altseqstmt->options = list_make1(makeDefElem("owned_by",
353                                                                                                          (Node *) attnamelist));
354
355                 cxt->alist = lappend(cxt->alist, altseqstmt);
356
357                 /*
358                  * Create appropriate constraints for SERIAL.  We do this in full,
359                  * rather than shortcutting, so that we will detect any conflicting
360                  * constraints the user wrote (like a different DEFAULT).
361                  *
362                  * Create an expression tree representing the function call
363                  * nextval('sequencename').  We cannot reduce the raw tree to cooked
364                  * form until after the sequence is created, but there's no need to do
365                  * so.
366                  */
367                 qstring = quote_qualified_identifier(snamespace, sname);
368                 snamenode = makeNode(A_Const);
369                 snamenode->val.type = T_String;
370                 snamenode->val.val.str = qstring;
371                 snamenode->typename = SystemTypeName("regclass");
372                 funccallnode = makeNode(FuncCall);
373                 funccallnode->funcname = SystemFuncName("nextval");
374                 funccallnode->args = list_make1(snamenode);
375                 funccallnode->agg_star = false;
376                 funccallnode->agg_distinct = false;
377                 funccallnode->location = -1;
378
379                 constraint = makeNode(Constraint);
380                 constraint->contype = CONSTR_DEFAULT;
381                 constraint->raw_expr = (Node *) funccallnode;
382                 constraint->cooked_expr = NULL;
383                 constraint->keys = NIL;
384                 column->constraints = lappend(column->constraints, constraint);
385
386                 constraint = makeNode(Constraint);
387                 constraint->contype = CONSTR_NOTNULL;
388                 column->constraints = lappend(column->constraints, constraint);
389         }
390
391         /* Process column constraints, if any... */
392         transformConstraintAttrs(column->constraints);
393
394         saw_nullable = false;
395         saw_default = false;
396
397         foreach(clist, column->constraints)
398         {
399                 constraint = lfirst(clist);
400
401                 /*
402                  * If this column constraint is a FOREIGN KEY constraint, then we fill
403                  * in the current attribute's name and throw it into the list of FK
404                  * constraints to be processed later.
405                  */
406                 if (IsA(constraint, FkConstraint))
407                 {
408                         FkConstraint *fkconstraint = (FkConstraint *) constraint;
409
410                         fkconstraint->fk_attrs = list_make1(makeString(column->colname));
411                         cxt->fkconstraints = lappend(cxt->fkconstraints, fkconstraint);
412                         continue;
413                 }
414
415                 Assert(IsA(constraint, Constraint));
416
417                 switch (constraint->contype)
418                 {
419                         case CONSTR_NULL:
420                                 if (saw_nullable && column->is_not_null)
421                                         ereport(ERROR,
422                                                         (errcode(ERRCODE_SYNTAX_ERROR),
423                                                          errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
424                                                                   column->colname, cxt->relation->relname)));
425                                 column->is_not_null = FALSE;
426                                 saw_nullable = true;
427                                 break;
428
429                         case CONSTR_NOTNULL:
430                                 if (saw_nullable && !column->is_not_null)
431                                         ereport(ERROR,
432                                                         (errcode(ERRCODE_SYNTAX_ERROR),
433                                                          errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
434                                                                   column->colname, cxt->relation->relname)));
435                                 column->is_not_null = TRUE;
436                                 saw_nullable = true;
437                                 break;
438
439                         case CONSTR_DEFAULT:
440                                 if (saw_default)
441                                         ereport(ERROR,
442                                                         (errcode(ERRCODE_SYNTAX_ERROR),
443                                                          errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
444                                                                   column->colname, cxt->relation->relname)));
445                                 column->raw_default = constraint->raw_expr;
446                                 Assert(constraint->cooked_expr == NULL);
447                                 saw_default = true;
448                                 break;
449
450                         case CONSTR_PRIMARY:
451                         case CONSTR_UNIQUE:
452                                 if (constraint->keys == NIL)
453                                         constraint->keys = list_make1(makeString(column->colname));
454                                 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
455                                 break;
456
457                         case CONSTR_CHECK:
458                                 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
459                                 break;
460
461                         case CONSTR_ATTR_DEFERRABLE:
462                         case CONSTR_ATTR_NOT_DEFERRABLE:
463                         case CONSTR_ATTR_DEFERRED:
464                         case CONSTR_ATTR_IMMEDIATE:
465                                 /* transformConstraintAttrs took care of these */
466                                 break;
467
468                         default:
469                                 elog(ERROR, "unrecognized constraint type: %d",
470                                          constraint->contype);
471                                 break;
472                 }
473         }
474 }
475
476 /*
477  * transformTableConstraint
478  *              transform a Constraint node within CREATE TABLE or ALTER TABLE
479  */
480 static void
481 transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt,
482                                                  Constraint *constraint)
483 {
484         switch (constraint->contype)
485         {
486                 case CONSTR_PRIMARY:
487                 case CONSTR_UNIQUE:
488                         cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
489                         break;
490
491                 case CONSTR_CHECK:
492                         cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
493                         break;
494
495                 case CONSTR_NULL:
496                 case CONSTR_NOTNULL:
497                 case CONSTR_DEFAULT:
498                 case CONSTR_ATTR_DEFERRABLE:
499                 case CONSTR_ATTR_NOT_DEFERRABLE:
500                 case CONSTR_ATTR_DEFERRED:
501                 case CONSTR_ATTR_IMMEDIATE:
502                         elog(ERROR, "invalid context for constraint type %d",
503                                  constraint->contype);
504                         break;
505
506                 default:
507                         elog(ERROR, "unrecognized constraint type: %d",
508                                  constraint->contype);
509                         break;
510         }
511 }
512
513 /*
514  * transformInhRelation
515  *
516  * Change the LIKE <subtable> portion of a CREATE TABLE statement into
517  * column definitions which recreate the user defined column portions of
518  * <subtable>.
519  */
520 static void
521 transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
522                                          InhRelation *inhRelation)
523 {
524         AttrNumber      parent_attno;
525         Relation        relation;
526         TupleDesc       tupleDesc;
527         TupleConstr *constr;
528         AclResult       aclresult;
529         bool            including_defaults = false;
530         bool            including_constraints = false;
531         bool            including_indexes = false;
532         ListCell   *elem;
533
534         relation = heap_openrv(inhRelation->relation, AccessShareLock);
535
536         if (relation->rd_rel->relkind != RELKIND_RELATION)
537                 ereport(ERROR,
538                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
539                                  errmsg("inherited relation \"%s\" is not a table",
540                                                 inhRelation->relation->relname)));
541
542         /*
543          * Check for SELECT privilages
544          */
545         aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
546                                                                   ACL_SELECT);
547         if (aclresult != ACLCHECK_OK)
548                 aclcheck_error(aclresult, ACL_KIND_CLASS,
549                                            RelationGetRelationName(relation));
550
551         tupleDesc = RelationGetDescr(relation);
552         constr = tupleDesc->constr;
553
554         foreach(elem, inhRelation->options)
555         {
556                 int                     option = lfirst_int(elem);
557
558                 switch (option)
559                 {
560                         case CREATE_TABLE_LIKE_INCLUDING_DEFAULTS:
561                                 including_defaults = true;
562                                 break;
563                         case CREATE_TABLE_LIKE_EXCLUDING_DEFAULTS:
564                                 including_defaults = false;
565                                 break;
566                         case CREATE_TABLE_LIKE_INCLUDING_CONSTRAINTS:
567                                 including_constraints = true;
568                                 break;
569                         case CREATE_TABLE_LIKE_EXCLUDING_CONSTRAINTS:
570                                 including_constraints = false;
571                                 break;
572                         case CREATE_TABLE_LIKE_INCLUDING_INDEXES:
573                                 including_indexes = true;
574                                 break;
575                         case CREATE_TABLE_LIKE_EXCLUDING_INDEXES:
576                                 including_indexes = false;
577                                 break;
578                         default:
579                                 elog(ERROR, "unrecognized CREATE TABLE LIKE option: %d",
580                                          option);
581                 }
582         }
583
584         /*
585          * Insert the copied attributes into the cxt for the new table definition.
586          */
587         for (parent_attno = 1; parent_attno <= tupleDesc->natts;
588                  parent_attno++)
589         {
590                 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
591                 char       *attributeName = NameStr(attribute->attname);
592                 ColumnDef  *def;
593
594                 /*
595                  * Ignore dropped columns in the parent.
596                  */
597                 if (attribute->attisdropped)
598                         continue;
599
600                 /*
601                  * Create a new column, which is marked as NOT inherited.
602                  *
603                  * For constraints, ONLY the NOT NULL constraint is inherited by the
604                  * new column definition per SQL99.
605                  */
606                 def = makeNode(ColumnDef);
607                 def->colname = pstrdup(attributeName);
608                 def->typename = makeTypeNameFromOid(attribute->atttypid,
609                                                                                         attribute->atttypmod);
610                 def->inhcount = 0;
611                 def->is_local = true;
612                 def->is_not_null = attribute->attnotnull;
613                 def->raw_default = NULL;
614                 def->cooked_default = NULL;
615                 def->constraints = NIL;
616
617                 /*
618                  * Add to column list
619                  */
620                 cxt->columns = lappend(cxt->columns, def);
621
622                 /*
623                  * Copy default, if present and the default has been requested
624                  */
625                 if (attribute->atthasdef && including_defaults)
626                 {
627                         char       *this_default = NULL;
628                         AttrDefault *attrdef;
629                         int                     i;
630
631                         /* Find default in constraint structure */
632                         Assert(constr != NULL);
633                         attrdef = constr->defval;
634                         for (i = 0; i < constr->num_defval; i++)
635                         {
636                                 if (attrdef[i].adnum == parent_attno)
637                                 {
638                                         this_default = attrdef[i].adbin;
639                                         break;
640                                 }
641                         }
642                         Assert(this_default != NULL);
643
644                         /*
645                          * If default expr could contain any vars, we'd need to fix 'em,
646                          * but it can't; so default is ready to apply to child.
647                          */
648
649                         def->cooked_default = pstrdup(this_default);
650                 }
651         }
652
653         /*
654          * Copy CHECK constraints if requested, being careful to adjust attribute
655          * numbers
656          */
657         if (including_constraints && tupleDesc->constr)
658         {
659                 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
660                 int                     ccnum;
661
662                 for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
663                 {
664                         char       *ccname = tupleDesc->constr->check[ccnum].ccname;
665                         char       *ccbin = tupleDesc->constr->check[ccnum].ccbin;
666                         Node       *ccbin_node = stringToNode(ccbin);
667                         Constraint *n = makeNode(Constraint);
668
669                         change_varattnos_of_a_node(ccbin_node, attmap);
670
671                         n->contype = CONSTR_CHECK;
672                         n->name = pstrdup(ccname);
673                         n->raw_expr = NULL;
674                         n->cooked_expr = nodeToString(ccbin_node);
675                         n->indexspace = NULL;
676                         cxt->ckconstraints = lappend(cxt->ckconstraints, (Node *) n);
677                 }
678         }
679
680         /*
681          * Likewise, copy indexes if requested
682          */
683         if (including_indexes && relation->rd_rel->relhasindex)
684         {
685                 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
686                 List       *parent_indexes;
687                 ListCell   *l;
688
689                 parent_indexes = RelationGetIndexList(relation);
690
691                 foreach(l, parent_indexes)
692                 {
693                         Oid                     parent_index_oid = lfirst_oid(l);
694                         Relation        parent_index;
695                         IndexStmt  *index_stmt;
696
697                         parent_index = index_open(parent_index_oid, AccessShareLock);
698
699                         /* Build CREATE INDEX statement to recreate the parent_index */
700                         index_stmt = generateClonedIndexStmt(cxt, parent_index, attmap);
701
702                         /* Save it in the inh_indexes list for the time being */
703                         cxt->inh_indexes = lappend(cxt->inh_indexes, index_stmt);
704
705                         index_close(parent_index, AccessShareLock);
706                 }
707         }
708
709         /*
710          * Close the parent rel, but keep our AccessShareLock on it until xact
711          * commit.      That will prevent someone else from deleting or ALTERing the
712          * parent before the child is committed.
713          */
714         heap_close(relation, NoLock);
715 }
716
717 /*
718  * Generate an IndexStmt node using information from an already existing index
719  * "source_idx".  Attribute numbers should be adjusted according to attmap.
720  */
721 static IndexStmt *
722 generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
723                                                 AttrNumber *attmap)
724 {
725         Oid                     source_relid = RelationGetRelid(source_idx);
726         HeapTuple       ht_idxrel;
727         HeapTuple       ht_idx;
728         Form_pg_class idxrelrec;
729         Form_pg_index idxrec;
730         Form_pg_am      amrec;
731         oidvector  *indclass;
732         IndexStmt  *index;
733         List       *indexprs;
734         ListCell   *indexpr_item;
735         Oid                     indrelid;
736         int                     keyno;
737         Oid                     keycoltype;
738         Datum           datum;
739         bool            isnull;
740
741         /*
742          * Fetch pg_class tuple of source index.  We can't use the copy in the
743          * relcache entry because it doesn't include optional fields.
744          */
745         ht_idxrel = SearchSysCache(RELOID,
746                                                            ObjectIdGetDatum(source_relid),
747                                                            0, 0, 0);
748         if (!HeapTupleIsValid(ht_idxrel))
749                 elog(ERROR, "cache lookup failed for relation %u", source_relid);
750         idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
751
752         /* Fetch pg_index tuple for source index from relcache entry */
753         ht_idx = source_idx->rd_indextuple;
754         idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
755         indrelid = idxrec->indrelid;
756
757         /* Fetch pg_am tuple for source index from relcache entry */
758         amrec = source_idx->rd_am;
759
760         /* Must get indclass the hard way, since it's not stored in relcache */
761         datum = SysCacheGetAttr(INDEXRELID, ht_idx,
762                                                         Anum_pg_index_indclass, &isnull);
763         Assert(!isnull);
764         indclass = (oidvector *) DatumGetPointer(datum);
765
766         /* Begin building the IndexStmt */
767         index = makeNode(IndexStmt);
768         index->relation = cxt->relation;
769         index->accessMethod = pstrdup(NameStr(amrec->amname));
770         if (OidIsValid(idxrelrec->reltablespace))
771                 index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
772         else
773                 index->tableSpace = NULL;
774         index->unique = idxrec->indisunique;
775         index->primary = idxrec->indisprimary;
776         index->concurrent = false;
777
778         /*
779          * We don't try to preserve the name of the source index; instead, just
780          * let DefineIndex() choose a reasonable name.
781          */
782         index->idxname = NULL;
783
784         /*
785          * If the index is marked PRIMARY, it's certainly from a constraint;
786          * else, if it's not marked UNIQUE, it certainly isn't; else, we have
787          * to search pg_depend to see if there's an associated unique constraint.
788          */
789         if (index->primary)
790                 index->isconstraint = true;
791         else if (!index->unique)
792                 index->isconstraint = false;
793         else
794                 index->isconstraint = OidIsValid(get_index_constraint(source_relid));
795
796         /* Get the index expressions, if any */
797         datum = SysCacheGetAttr(INDEXRELID, ht_idx,
798                                                         Anum_pg_index_indexprs, &isnull);
799         if (!isnull)
800         {
801                 char       *exprsString;
802
803                 exprsString = DatumGetCString(DirectFunctionCall1(textout, datum));
804                 indexprs = (List *) stringToNode(exprsString);
805         }
806         else
807                 indexprs = NIL;
808
809         /* Build the list of IndexElem */
810         index->indexParams = NIL;
811
812         indexpr_item = list_head(indexprs);
813         for (keyno = 0; keyno < idxrec->indnatts; keyno++)
814         {
815                 IndexElem  *iparam;
816                 AttrNumber      attnum = idxrec->indkey.values[keyno];
817                 int16           opt = source_idx->rd_indoption[keyno];
818
819                 iparam = makeNode(IndexElem);
820
821                 if (AttributeNumberIsValid(attnum))
822                 {
823                         /* Simple index column */
824                         char       *attname;
825
826                         attname = get_relid_attribute_name(indrelid, attnum);
827                         keycoltype = get_atttype(indrelid, attnum);
828
829                         iparam->name = attname;
830                         iparam->expr = NULL;
831                 }
832                 else
833                 {
834                         /* Expressional index */
835                         Node       *indexkey;
836
837                         if (indexpr_item == NULL)
838                                 elog(ERROR, "too few entries in indexprs list");
839                         indexkey = (Node *) lfirst(indexpr_item);
840                         indexpr_item = lnext(indexpr_item);
841
842                         /* OK to modify indexkey since we are working on a private copy */
843                         change_varattnos_of_a_node(indexkey, attmap);
844
845                         iparam->name = NULL;
846                         iparam->expr = indexkey;
847
848                         keycoltype = exprType(indexkey);
849                 }
850
851                 /* Add the operator class name, if non-default */
852                 iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
853
854                 iparam->ordering = SORTBY_DEFAULT;
855                 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
856
857                 /* Adjust options if necessary */
858                 if (amrec->amcanorder)
859                 {
860                         /*
861                          * If it supports sort ordering, copy DESC and NULLS opts.
862                          * Don't set non-default settings unnecessarily, though,
863                          * so as to improve the chance of recognizing equivalence
864                          * to constraint indexes.
865                          */
866                         if (opt & INDOPTION_DESC)
867                         {
868                                 iparam->ordering = SORTBY_DESC;
869                                 if ((opt & INDOPTION_NULLS_FIRST) == 0)
870                                         iparam->nulls_ordering = SORTBY_NULLS_LAST;
871                         }
872                         else
873                         {
874                                 if (opt & INDOPTION_NULLS_FIRST)
875                                         iparam->nulls_ordering = SORTBY_NULLS_FIRST;
876                         }
877                 }
878
879                 index->indexParams = lappend(index->indexParams, iparam);
880         }
881
882         /* Copy reloptions if any */
883         datum = SysCacheGetAttr(RELOID, ht_idxrel,
884                                                         Anum_pg_class_reloptions, &isnull);
885         if (!isnull)
886                 index->options = untransformRelOptions(datum);
887
888         /* If it's a partial index, decompile and append the predicate */
889         datum = SysCacheGetAttr(INDEXRELID, ht_idx,
890                                                         Anum_pg_index_indpred, &isnull);
891         if (!isnull)
892         {
893                 char       *pred_str;
894
895                 /* Convert text string to node tree */
896                 pred_str = DatumGetCString(DirectFunctionCall1(textout, datum));
897                 index->whereClause = (Node *) stringToNode(pred_str);
898                 /* Adjust attribute numbers */
899                 change_varattnos_of_a_node(index->whereClause, attmap);
900         }
901
902         /* Clean up */
903         ReleaseSysCache(ht_idxrel);
904
905         return index;
906 }
907
908 /*
909  * get_opclass                  - fetch name of an index operator class
910  *
911  * If the opclass is the default for the given actual_datatype, then
912  * the return value is NIL.
913  */
914 static List *
915 get_opclass(Oid opclass, Oid actual_datatype)
916 {
917         HeapTuple       ht_opc;
918         Form_pg_opclass opc_rec;
919         List       *result = NIL;
920
921         ht_opc = SearchSysCache(CLAOID,
922                                                         ObjectIdGetDatum(opclass),
923                                                         0, 0, 0);
924         if (!HeapTupleIsValid(ht_opc))
925                 elog(ERROR, "cache lookup failed for opclass %u", opclass);
926         opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
927
928         if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
929         {
930                 /* For simplicity, we always schema-qualify the name */
931                 char       *nsp_name = get_namespace_name(opc_rec->opcnamespace);
932                 char       *opc_name = pstrdup(NameStr(opc_rec->opcname));
933
934                 result = list_make2(makeString(nsp_name), makeString(opc_name));
935         }
936
937         ReleaseSysCache(ht_opc);
938         return result;
939 }
940
941
942 /*
943  * transformIndexConstraints
944  *              Handle UNIQUE and PRIMARY KEY constraints, which create indexes.
945  *              We also merge in any index definitions arising from
946  *              LIKE ... INCLUDING INDEXES.
947  */
948 static void
949 transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
950 {
951         IndexStmt  *index;
952         List       *indexlist = NIL;
953         ListCell   *lc;
954
955         /*
956          * Run through the constraints that need to generate an index. For PRIMARY
957          * KEY, mark each column as NOT NULL and create an index. For UNIQUE,
958          * create an index as for PRIMARY KEY, but do not insist on NOT NULL.
959          */
960         foreach(lc, cxt->ixconstraints)
961         {
962                 Constraint *constraint = (Constraint *) lfirst(lc);
963
964                 Assert(IsA(constraint, Constraint));
965                 Assert(constraint->contype == CONSTR_PRIMARY ||
966                            constraint->contype == CONSTR_UNIQUE);
967
968                 index = transformIndexConstraint(constraint, cxt);
969
970                 indexlist = lappend(indexlist, index);
971         }
972
973         /* Add in any indexes defined by LIKE ... INCLUDING INDEXES */
974         foreach(lc, cxt->inh_indexes)
975         {
976                 index = (IndexStmt *) lfirst(lc);
977
978                 if (index->primary)
979                 {
980                         if (cxt->pkey != NULL)
981                                 ereport(ERROR,
982                                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
983                                                  errmsg("multiple primary keys for table \"%s\" are not allowed",
984                                                                 cxt->relation->relname)));
985                         cxt->pkey = index;
986                 }
987
988                 indexlist = lappend(indexlist, index);
989         }
990
991         /*
992          * Scan the index list and remove any redundant index specifications. This
993          * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
994          * strict reading of SQL92 would suggest raising an error instead, but
995          * that strikes me as too anal-retentive. - tgl 2001-02-14
996          *
997          * XXX in ALTER TABLE case, it'd be nice to look for duplicate
998          * pre-existing indexes, too.
999          */
1000         Assert(cxt->alist == NIL);
1001         if (cxt->pkey != NULL)
1002         {
1003                 /* Make sure we keep the PKEY index in preference to others... */
1004                 cxt->alist = list_make1(cxt->pkey);
1005         }
1006
1007         foreach(lc, indexlist)
1008         {
1009                 bool            keep = true;
1010                 ListCell   *k;
1011
1012                 index = lfirst(lc);
1013
1014                 /* if it's pkey, it's already in cxt->alist */
1015                 if (index == cxt->pkey)
1016                         continue;
1017
1018                 foreach(k, cxt->alist)
1019                 {
1020                         IndexStmt  *priorindex = lfirst(k);
1021
1022                         if (equal(index->indexParams, priorindex->indexParams) &&
1023                                 equal(index->whereClause, priorindex->whereClause) &&
1024                                 strcmp(index->accessMethod, priorindex->accessMethod) == 0)
1025                         {
1026                                 priorindex->unique |= index->unique;
1027                                 /*
1028                                  * If the prior index is as yet unnamed, and this one is
1029                                  * named, then transfer the name to the prior index. This
1030                                  * ensures that if we have named and unnamed constraints,
1031                                  * we'll use (at least one of) the names for the index.
1032                                  */
1033                                 if (priorindex->idxname == NULL)
1034                                         priorindex->idxname = index->idxname;
1035                                 keep = false;
1036                                 break;
1037                         }
1038                 }
1039
1040                 if (keep)
1041                         cxt->alist = lappend(cxt->alist, index);
1042         }
1043 }
1044
1045 /*
1046  * transformIndexConstraint
1047  *              Transform one UNIQUE or PRIMARY KEY constraint for
1048  *              transformIndexConstraints.
1049  */
1050 static IndexStmt *
1051 transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
1052 {
1053         IndexStmt  *index;
1054         ListCell   *keys;
1055         IndexElem  *iparam;
1056
1057         index = makeNode(IndexStmt);
1058
1059         index->unique = true;
1060         index->primary = (constraint->contype == CONSTR_PRIMARY);
1061         if (index->primary)
1062         {
1063                 if (cxt->pkey != NULL)
1064                         ereport(ERROR,
1065                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1066                          errmsg("multiple primary keys for table \"%s\" are not allowed",
1067                                         cxt->relation->relname)));
1068                 cxt->pkey = index;
1069
1070                 /*
1071                  * In ALTER TABLE case, a primary index might already exist, but
1072                  * DefineIndex will check for it.
1073                  */
1074         }
1075         index->isconstraint = true;
1076
1077         if (constraint->name != NULL)
1078                 index->idxname = pstrdup(constraint->name);
1079         else
1080                 index->idxname = NULL;  /* DefineIndex will choose name */
1081
1082         index->relation = cxt->relation;
1083         index->accessMethod = DEFAULT_INDEX_TYPE;
1084         index->options = constraint->options;
1085         index->tableSpace = constraint->indexspace;
1086         index->indexParams = NIL;
1087         index->whereClause = NULL;
1088         index->concurrent = false;
1089
1090         /*
1091          * Make sure referenced keys exist.  If we are making a PRIMARY KEY index,
1092          * also make sure they are NOT NULL, if possible. (Although we could leave
1093          * it to DefineIndex to mark the columns NOT NULL, it's more efficient to
1094          * get it right the first time.)
1095          */
1096         foreach(keys, constraint->keys)
1097         {
1098                 char       *key = strVal(lfirst(keys));
1099                 bool            found = false;
1100                 ColumnDef  *column = NULL;
1101                 ListCell   *columns;
1102
1103                 foreach(columns, cxt->columns)
1104                 {
1105                         column = (ColumnDef *) lfirst(columns);
1106                         Assert(IsA(column, ColumnDef));
1107                         if (strcmp(column->colname, key) == 0)
1108                         {
1109                                 found = true;
1110                                 break;
1111                         }
1112                 }
1113                 if (found)
1114                 {
1115                         /* found column in the new table; force it to be NOT NULL */
1116                         if (constraint->contype == CONSTR_PRIMARY)
1117                                 column->is_not_null = TRUE;
1118                 }
1119                 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1120                 {
1121                         /*
1122                          * column will be a system column in the new table, so accept it.
1123                          * System columns can't ever be null, so no need to worry about
1124                          * PRIMARY/NOT NULL constraint.
1125                          */
1126                         found = true;
1127                 }
1128                 else if (cxt->inhRelations)
1129                 {
1130                         /* try inherited tables */
1131                         ListCell   *inher;
1132
1133                         foreach(inher, cxt->inhRelations)
1134                         {
1135                                 RangeVar   *inh = (RangeVar *) lfirst(inher);
1136                                 Relation        rel;
1137                                 int                     count;
1138
1139                                 Assert(IsA(inh, RangeVar));
1140                                 rel = heap_openrv(inh, AccessShareLock);
1141                                 if (rel->rd_rel->relkind != RELKIND_RELATION)
1142                                         ereport(ERROR,
1143                                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1144                                                    errmsg("inherited relation \"%s\" is not a table",
1145                                                                   inh->relname)));
1146                                 for (count = 0; count < rel->rd_att->natts; count++)
1147                                 {
1148                                         Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1149                                         char       *inhname = NameStr(inhattr->attname);
1150
1151                                         if (inhattr->attisdropped)
1152                                                 continue;
1153                                         if (strcmp(key, inhname) == 0)
1154                                         {
1155                                                 found = true;
1156
1157                                                 /*
1158                                                  * We currently have no easy way to force an inherited
1159                                                  * column to be NOT NULL at creation, if its parent
1160                                                  * wasn't so already. We leave it to DefineIndex to
1161                                                  * fix things up in this case.
1162                                                  */
1163                                                 break;
1164                                         }
1165                                 }
1166                                 heap_close(rel, NoLock);
1167                                 if (found)
1168                                         break;
1169                         }
1170                 }
1171
1172                 /*
1173                  * In the ALTER TABLE case, don't complain about index keys not
1174                  * created in the command; they may well exist already. DefineIndex
1175                  * will complain about them if not, and will also take care of marking
1176                  * them NOT NULL.
1177                  */
1178                 if (!found && !cxt->isalter)
1179                         ereport(ERROR,
1180                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
1181                                          errmsg("column \"%s\" named in key does not exist",
1182                                                         key)));
1183
1184                 /* Check for PRIMARY KEY(foo, foo) */
1185                 foreach(columns, index->indexParams)
1186                 {
1187                         iparam = (IndexElem *) lfirst(columns);
1188                         if (iparam->name && strcmp(key, iparam->name) == 0)
1189                         {
1190                                 if (index->primary)
1191                                         ereport(ERROR,
1192                                                         (errcode(ERRCODE_DUPLICATE_COLUMN),
1193                                                          errmsg("column \"%s\" appears twice in primary key constraint",
1194                                                                         key)));
1195                                 else
1196                                         ereport(ERROR,
1197                                                         (errcode(ERRCODE_DUPLICATE_COLUMN),
1198                                         errmsg("column \"%s\" appears twice in unique constraint",
1199                                                    key)));
1200                         }
1201                 }
1202
1203                 /* OK, add it to the index definition */
1204                 iparam = makeNode(IndexElem);
1205                 iparam->name = pstrdup(key);
1206                 iparam->expr = NULL;
1207                 iparam->opclass = NIL;
1208                 iparam->ordering = SORTBY_DEFAULT;
1209                 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1210                 index->indexParams = lappend(index->indexParams, iparam);
1211         }
1212
1213         return index;
1214 }
1215
1216 /*
1217  * transformFKConstraints
1218  *              handle FOREIGN KEY constraints
1219  */
1220 static void
1221 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1222                                            bool skipValidation, bool isAddConstraint)
1223 {
1224         ListCell   *fkclist;
1225
1226         if (cxt->fkconstraints == NIL)
1227                 return;
1228
1229         /*
1230          * If CREATE TABLE or adding a column with NULL default, we can safely
1231          * skip validation of the constraint.
1232          */
1233         if (skipValidation)
1234         {
1235                 foreach(fkclist, cxt->fkconstraints)
1236                 {
1237                         FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1238
1239                         fkconstraint->skip_validation = true;
1240                 }
1241         }
1242
1243         /*
1244          * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1245          * CONSTRAINT command to execute after the basic command is complete. (If
1246          * called from ADD CONSTRAINT, that routine will add the FK constraints to
1247          * its own subcommand list.)
1248          *
1249          * Note: the ADD CONSTRAINT command must also execute after any index
1250          * creation commands.  Thus, this should run after
1251          * transformIndexConstraints, so that the CREATE INDEX commands are
1252          * already in cxt->alist.
1253          */
1254         if (!isAddConstraint)
1255         {
1256                 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1257
1258                 alterstmt->relation = cxt->relation;
1259                 alterstmt->cmds = NIL;
1260                 alterstmt->relkind = OBJECT_TABLE;
1261
1262                 foreach(fkclist, cxt->fkconstraints)
1263                 {
1264                         FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1265                         AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1266
1267                         altercmd->subtype = AT_ProcessedConstraint;
1268                         altercmd->name = NULL;
1269                         altercmd->def = (Node *) fkconstraint;
1270                         alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1271                 }
1272
1273                 cxt->alist = lappend(cxt->alist, alterstmt);
1274         }
1275 }
1276
1277 /*
1278  * transformIndexStmt - parse analysis for CREATE INDEX
1279  *
1280  * Note: this is a no-op for an index not using either index expressions or
1281  * a predicate expression.      There are several code paths that create indexes
1282  * without bothering to call this, because they know they don't have any
1283  * such expressions to deal with.
1284  */
1285 IndexStmt *
1286 transformIndexStmt(IndexStmt *stmt, const char *queryString)
1287 {
1288         Relation        rel;
1289         ParseState *pstate;
1290         RangeTblEntry *rte;
1291         ListCell   *l;
1292
1293         /*
1294          * We must not scribble on the passed-in IndexStmt, so copy it.  (This is
1295          * overkill, but easy.)
1296          */
1297         stmt = (IndexStmt *) copyObject(stmt);
1298
1299         /*
1300          * Open the parent table with appropriate locking.      We must do this
1301          * because addRangeTableEntry() would acquire only AccessShareLock,
1302          * leaving DefineIndex() needing to do a lock upgrade with consequent risk
1303          * of deadlock.  Make sure this stays in sync with the type of lock
1304          * DefineIndex() wants.
1305          */
1306         rel = heap_openrv(stmt->relation,
1307                                   (stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock));
1308
1309         /* Set up pstate */
1310         pstate = make_parsestate(NULL);
1311         pstate->p_sourcetext = queryString;
1312
1313         /*
1314          * Put the parent table into the rtable so that the expressions can refer
1315          * to its fields without qualification.
1316          */
1317         rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1318
1319         /* no to join list, yes to namespaces */
1320         addRTEtoQuery(pstate, rte, false, true, true);
1321
1322         /* take care of the where clause */
1323         if (stmt->whereClause)
1324                 stmt->whereClause = transformWhereClause(pstate,
1325                                                                                                  stmt->whereClause,
1326                                                                                                  "WHERE");
1327
1328         /* take care of any index expressions */
1329         foreach(l, stmt->indexParams)
1330         {
1331                 IndexElem  *ielem = (IndexElem *) lfirst(l);
1332
1333                 if (ielem->expr)
1334                 {
1335                         ielem->expr = transformExpr(pstate, ielem->expr);
1336
1337                         /*
1338                          * We check only that the result type is legitimate; this is for
1339                          * consistency with what transformWhereClause() checks for the
1340                          * predicate.  DefineIndex() will make more checks.
1341                          */
1342                         if (expression_returns_set(ielem->expr))
1343                                 ereport(ERROR,
1344                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1345                                                  errmsg("index expression cannot return a set")));
1346                 }
1347         }
1348
1349         /*
1350          * Check that only the base rel is mentioned.
1351          */
1352         if (list_length(pstate->p_rtable) != 1)
1353                 ereport(ERROR,
1354                                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1355                                  errmsg("index expressions and predicates can refer only to the table being indexed")));
1356
1357         free_parsestate(pstate);
1358
1359         /* Close relation, but keep the lock */
1360         heap_close(rel, NoLock);
1361
1362         return stmt;
1363 }
1364
1365
1366 /*
1367  * transformRuleStmt -
1368  *        transform a CREATE RULE Statement. The action is a list of parse
1369  *        trees which is transformed into a list of query trees, and we also
1370  *        transform the WHERE clause if any.
1371  *
1372  * actions and whereClause are output parameters that receive the
1373  * transformed results.
1374  *
1375  * Note that we must not scribble on the passed-in RuleStmt, so we do
1376  * copyObject() on the actions and WHERE clause.
1377  */
1378 void
1379 transformRuleStmt(RuleStmt *stmt, const char *queryString,
1380                                   List **actions, Node **whereClause)
1381 {
1382         Relation        rel;
1383         ParseState *pstate;
1384         RangeTblEntry *oldrte;
1385         RangeTblEntry *newrte;
1386
1387         /*
1388          * To avoid deadlock, make sure the first thing we do is grab
1389          * AccessExclusiveLock on the target relation.  This will be needed by
1390          * DefineQueryRewrite(), and we don't want to grab a lesser lock
1391          * beforehand.
1392          */
1393         rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1394
1395         /* Set up pstate */
1396         pstate = make_parsestate(NULL);
1397         pstate->p_sourcetext = queryString;
1398
1399         /*
1400          * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1401          * Set up their RTEs in the main pstate for use in parsing the rule
1402          * qualification.
1403          */
1404         oldrte = addRangeTableEntryForRelation(pstate, rel,
1405                                                                                    makeAlias("*OLD*", NIL),
1406                                                                                    false, false);
1407         newrte = addRangeTableEntryForRelation(pstate, rel,
1408                                                                                    makeAlias("*NEW*", NIL),
1409                                                                                    false, false);
1410         /* Must override addRangeTableEntry's default access-check flags */
1411         oldrte->requiredPerms = 0;
1412         newrte->requiredPerms = 0;
1413
1414         /*
1415          * They must be in the namespace too for lookup purposes, but only add the
1416          * one(s) that are relevant for the current kind of rule.  In an UPDATE
1417          * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1418          * there's no need to be so picky for INSERT & DELETE.  We do not add them
1419          * to the joinlist.
1420          */
1421         switch (stmt->event)
1422         {
1423                 case CMD_SELECT:
1424                         addRTEtoQuery(pstate, oldrte, false, true, true);
1425                         break;
1426                 case CMD_UPDATE:
1427                         addRTEtoQuery(pstate, oldrte, false, true, true);
1428                         addRTEtoQuery(pstate, newrte, false, true, true);
1429                         break;
1430                 case CMD_INSERT:
1431                         addRTEtoQuery(pstate, newrte, false, true, true);
1432                         break;
1433                 case CMD_DELETE:
1434                         addRTEtoQuery(pstate, oldrte, false, true, true);
1435                         break;
1436                 default:
1437                         elog(ERROR, "unrecognized event type: %d",
1438                                  (int) stmt->event);
1439                         break;
1440         }
1441
1442         /* take care of the where clause */
1443         *whereClause = transformWhereClause(pstate,
1444                                                                           (Node *) copyObject(stmt->whereClause),
1445                                                                                 "WHERE");
1446
1447         if (list_length(pstate->p_rtable) != 2)         /* naughty, naughty... */
1448                 ereport(ERROR,
1449                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1450                                  errmsg("rule WHERE condition cannot contain references to other relations")));
1451
1452         /* aggregates not allowed (but subselects are okay) */
1453         if (pstate->p_hasAggs)
1454                 ereport(ERROR,
1455                                 (errcode(ERRCODE_GROUPING_ERROR),
1456                    errmsg("cannot use aggregate function in rule WHERE condition")));
1457
1458         /*
1459          * 'instead nothing' rules with a qualification need a query rangetable so
1460          * the rewrite handler can add the negated rule qualification to the
1461          * original query. We create a query with the new command type CMD_NOTHING
1462          * here that is treated specially by the rewrite system.
1463          */
1464         if (stmt->actions == NIL)
1465         {
1466                 Query      *nothing_qry = makeNode(Query);
1467
1468                 nothing_qry->commandType = CMD_NOTHING;
1469                 nothing_qry->rtable = pstate->p_rtable;
1470                 nothing_qry->jointree = makeFromExpr(NIL, NULL);                /* no join wanted */
1471
1472                 *actions = list_make1(nothing_qry);
1473         }
1474         else
1475         {
1476                 ListCell   *l;
1477                 List       *newactions = NIL;
1478
1479                 /*
1480                  * transform each statement, like parse_sub_analyze()
1481                  */
1482                 foreach(l, stmt->actions)
1483                 {
1484                         Node       *action = (Node *) lfirst(l);
1485                         ParseState *sub_pstate = make_parsestate(NULL);
1486                         Query      *sub_qry,
1487                                            *top_subqry;
1488                         bool            has_old,
1489                                                 has_new;
1490
1491                         /*
1492                          * Since outer ParseState isn't parent of inner, have to pass down
1493                          * the query text by hand.
1494                          */
1495                         sub_pstate->p_sourcetext = queryString;
1496
1497                         /*
1498                          * Set up OLD/NEW in the rtable for this statement.  The entries
1499                          * are added only to relnamespace, not varnamespace, because we
1500                          * don't want them to be referred to by unqualified field names
1501                          * nor "*" in the rule actions.  We decide later whether to put
1502                          * them in the joinlist.
1503                          */
1504                         oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
1505                                                                                                    makeAlias("*OLD*", NIL),
1506                                                                                                    false, false);
1507                         newrte = addRangeTableEntryForRelation(sub_pstate, rel,
1508                                                                                                    makeAlias("*NEW*", NIL),
1509                                                                                                    false, false);
1510                         oldrte->requiredPerms = 0;
1511                         newrte->requiredPerms = 0;
1512                         addRTEtoQuery(sub_pstate, oldrte, false, true, false);
1513                         addRTEtoQuery(sub_pstate, newrte, false, true, false);
1514
1515                         /* Transform the rule action statement */
1516                         top_subqry = transformStmt(sub_pstate,
1517                                                                            (Node *) copyObject(action));
1518
1519                         /*
1520                          * We cannot support utility-statement actions (eg NOTIFY) with
1521                          * nonempty rule WHERE conditions, because there's no way to make
1522                          * the utility action execute conditionally.
1523                          */
1524                         if (top_subqry->commandType == CMD_UTILITY &&
1525                                 *whereClause != NULL)
1526                                 ereport(ERROR,
1527                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1528                                                  errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
1529
1530                         /*
1531                          * If the action is INSERT...SELECT, OLD/NEW have been pushed down
1532                          * into the SELECT, and that's what we need to look at. (Ugly
1533                          * kluge ... try to fix this when we redesign querytrees.)
1534                          */
1535                         sub_qry = getInsertSelectQuery(top_subqry, NULL);
1536
1537                         /*
1538                          * If the sub_qry is a setop, we cannot attach any qualifications
1539                          * to it, because the planner won't notice them.  This could
1540                          * perhaps be relaxed someday, but for now, we may as well reject
1541                          * such a rule immediately.
1542                          */
1543                         if (sub_qry->setOperations != NULL && *whereClause != NULL)
1544                                 ereport(ERROR,
1545                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1546                                                  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1547
1548                         /*
1549                          * Validate action's use of OLD/NEW, qual too
1550                          */
1551                         has_old =
1552                                 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1553                                 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
1554                         has_new =
1555                                 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1556                                 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
1557
1558                         switch (stmt->event)
1559                         {
1560                                 case CMD_SELECT:
1561                                         if (has_old)
1562                                                 ereport(ERROR,
1563                                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1564                                                                  errmsg("ON SELECT rule cannot use OLD")));
1565                                         if (has_new)
1566                                                 ereport(ERROR,
1567                                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1568                                                                  errmsg("ON SELECT rule cannot use NEW")));
1569                                         break;
1570                                 case CMD_UPDATE:
1571                                         /* both are OK */
1572                                         break;
1573                                 case CMD_INSERT:
1574                                         if (has_old)
1575                                                 ereport(ERROR,
1576                                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1577                                                                  errmsg("ON INSERT rule cannot use OLD")));
1578                                         break;
1579                                 case CMD_DELETE:
1580                                         if (has_new)
1581                                                 ereport(ERROR,
1582                                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1583                                                                  errmsg("ON DELETE rule cannot use NEW")));
1584                                         break;
1585                                 default:
1586                                         elog(ERROR, "unrecognized event type: %d",
1587                                                  (int) stmt->event);
1588                                         break;
1589                         }
1590
1591                         /*
1592                          * For efficiency's sake, add OLD to the rule action's jointree
1593                          * only if it was actually referenced in the statement or qual.
1594                          *
1595                          * For INSERT, NEW is not really a relation (only a reference to
1596                          * the to-be-inserted tuple) and should never be added to the
1597                          * jointree.
1598                          *
1599                          * For UPDATE, we treat NEW as being another kind of reference to
1600                          * OLD, because it represents references to *transformed* tuples
1601                          * of the existing relation.  It would be wrong to enter NEW
1602                          * separately in the jointree, since that would cause a double
1603                          * join of the updated relation.  It's also wrong to fail to make
1604                          * a jointree entry if only NEW and not OLD is mentioned.
1605                          */
1606                         if (has_old || (has_new && stmt->event == CMD_UPDATE))
1607                         {
1608                                 /*
1609                                  * If sub_qry is a setop, manipulating its jointree will do no
1610                                  * good at all, because the jointree is dummy. (This should be
1611                                  * a can't-happen case because of prior tests.)
1612                                  */
1613                                 if (sub_qry->setOperations != NULL)
1614                                         ereport(ERROR,
1615                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1616                                                          errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1617                                 /* hack so we can use addRTEtoQuery() */
1618                                 sub_pstate->p_rtable = sub_qry->rtable;
1619                                 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
1620                                 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
1621                                 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
1622                         }
1623
1624                         newactions = lappend(newactions, top_subqry);
1625
1626                         free_parsestate(sub_pstate);
1627                 }
1628
1629                 *actions = newactions;
1630         }
1631
1632         free_parsestate(pstate);
1633
1634         /* Close relation, but keep the exclusive lock */
1635         heap_close(rel, NoLock);
1636 }
1637
1638
1639 /*
1640  * transformAlterTableStmt -
1641  *              parse analysis for ALTER TABLE
1642  *
1643  * Returns a List of utility commands to be done in sequence.  One of these
1644  * will be the transformed AlterTableStmt, but there may be additional actions
1645  * to be done before and after the actual AlterTable() call.
1646  */
1647 List *
1648 transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
1649 {
1650         Relation        rel;
1651         ParseState *pstate;
1652         CreateStmtContext cxt;
1653         List       *result;
1654         List       *save_alist;
1655         ListCell   *lcmd,
1656                            *l;
1657         List       *newcmds = NIL;
1658         bool            skipValidation = true;
1659         AlterTableCmd *newcmd;
1660
1661         /*
1662          * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
1663          * is overkill, but easy.)
1664          */
1665         stmt = (AlterTableStmt *) copyObject(stmt);
1666
1667         /*
1668          * Acquire exclusive lock on the target relation, which will be held until
1669          * end of transaction.  This ensures any decisions we make here based on
1670          * the state of the relation will still be good at execution. We must get
1671          * exclusive lock now because execution will; taking a lower grade lock
1672          * now and trying to upgrade later risks deadlock.
1673          */
1674         rel = relation_openrv(stmt->relation, AccessExclusiveLock);
1675
1676         /* Set up pstate */
1677         pstate = make_parsestate(NULL);
1678         pstate->p_sourcetext = queryString;
1679
1680         cxt.stmtType = "ALTER TABLE";
1681         cxt.relation = stmt->relation;
1682         cxt.rel = rel;
1683         cxt.inhRelations = NIL;
1684         cxt.isalter = true;
1685         cxt.hasoids = false;            /* need not be right */
1686         cxt.columns = NIL;
1687         cxt.ckconstraints = NIL;
1688         cxt.fkconstraints = NIL;
1689         cxt.ixconstraints = NIL;
1690         cxt.inh_indexes = NIL;
1691         cxt.blist = NIL;
1692         cxt.alist = NIL;
1693         cxt.pkey = NULL;
1694
1695         /*
1696          * The only subtypes that currently require parse transformation handling
1697          * are ADD COLUMN and ADD CONSTRAINT.  These largely re-use code from
1698          * CREATE TABLE.
1699          */
1700         foreach(lcmd, stmt->cmds)
1701         {
1702                 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
1703
1704                 switch (cmd->subtype)
1705                 {
1706                         case AT_AddColumn:
1707                                 {
1708                                         ColumnDef  *def = (ColumnDef *) cmd->def;
1709
1710                                         Assert(IsA(cmd->def, ColumnDef));
1711                                         transformColumnDefinition(pstate, &cxt,
1712                                                                                           (ColumnDef *) cmd->def);
1713
1714                                         /*
1715                                          * If the column has a non-null default, we can't skip
1716                                          * validation of foreign keys.
1717                                          */
1718                                         if (((ColumnDef *) cmd->def)->raw_default != NULL)
1719                                                 skipValidation = false;
1720
1721                                         newcmds = lappend(newcmds, cmd);
1722
1723                                         /*
1724                                          * Convert an ADD COLUMN ... NOT NULL constraint to a
1725                                          * separate command
1726                                          */
1727                                         if (def->is_not_null)
1728                                         {
1729                                                 /* Remove NOT NULL from AddColumn */
1730                                                 def->is_not_null = false;
1731
1732                                                 /* Add as a separate AlterTableCmd */
1733                                                 newcmd = makeNode(AlterTableCmd);
1734                                                 newcmd->subtype = AT_SetNotNull;
1735                                                 newcmd->name = pstrdup(def->colname);
1736                                                 newcmds = lappend(newcmds, newcmd);
1737                                         }
1738
1739                                         /*
1740                                          * All constraints are processed in other ways. Remove the
1741                                          * original list
1742                                          */
1743                                         def->constraints = NIL;
1744
1745                                         break;
1746                                 }
1747                         case AT_AddConstraint:
1748
1749                                 /*
1750                                  * The original AddConstraint cmd node doesn't go to newcmds
1751                                  */
1752
1753                                 if (IsA(cmd->def, Constraint))
1754                                         transformTableConstraint(pstate, &cxt,
1755                                                                                          (Constraint *) cmd->def);
1756                                 else if (IsA(cmd->def, FkConstraint))
1757                                 {
1758                                         cxt.fkconstraints = lappend(cxt.fkconstraints, cmd->def);
1759                                         skipValidation = false;
1760                                 }
1761                                 else
1762                                         elog(ERROR, "unrecognized node type: %d",
1763                                                  (int) nodeTag(cmd->def));
1764                                 break;
1765
1766                         case AT_ProcessedConstraint:
1767
1768                                 /*
1769                                  * Already-transformed ADD CONSTRAINT, so just make it look
1770                                  * like the standard case.
1771                                  */
1772                                 cmd->subtype = AT_AddConstraint;
1773                                 newcmds = lappend(newcmds, cmd);
1774                                 break;
1775
1776                         default:
1777                                 newcmds = lappend(newcmds, cmd);
1778                                 break;
1779                 }
1780         }
1781
1782         /*
1783          * transformIndexConstraints wants cxt.alist to contain only index
1784          * statements, so transfer anything we already have into save_alist
1785          * immediately.
1786          */
1787         save_alist = cxt.alist;
1788         cxt.alist = NIL;
1789
1790         /* Postprocess index and FK constraints */
1791         transformIndexConstraints(pstate, &cxt);
1792
1793         transformFKConstraints(pstate, &cxt, skipValidation, true);
1794
1795         /*
1796          * Push any index-creation commands into the ALTER, so that they can be
1797          * scheduled nicely by tablecmds.c.  Note that tablecmds.c assumes that
1798          * the IndexStmt attached to an AT_AddIndex subcommand has already been
1799          * through transformIndexStmt.
1800          */
1801         foreach(l, cxt.alist)
1802         {
1803                 Node       *idxstmt = (Node *) lfirst(l);
1804
1805                 Assert(IsA(idxstmt, IndexStmt));
1806                 newcmd = makeNode(AlterTableCmd);
1807                 newcmd->subtype = AT_AddIndex;
1808                 newcmd->def = (Node *) transformIndexStmt((IndexStmt *) idxstmt,
1809                                                                                                   queryString);
1810                 newcmds = lappend(newcmds, newcmd);
1811         }
1812         cxt.alist = NIL;
1813
1814         /* Append any CHECK or FK constraints to the commands list */
1815         foreach(l, cxt.ckconstraints)
1816         {
1817                 newcmd = makeNode(AlterTableCmd);
1818                 newcmd->subtype = AT_AddConstraint;
1819                 newcmd->def = (Node *) lfirst(l);
1820                 newcmds = lappend(newcmds, newcmd);
1821         }
1822         foreach(l, cxt.fkconstraints)
1823         {
1824                 newcmd = makeNode(AlterTableCmd);
1825                 newcmd->subtype = AT_AddConstraint;
1826                 newcmd->def = (Node *) lfirst(l);
1827                 newcmds = lappend(newcmds, newcmd);
1828         }
1829
1830         /* Close rel but keep lock */
1831         relation_close(rel, NoLock);
1832
1833         /*
1834          * Output results.
1835          */
1836         stmt->cmds = newcmds;
1837
1838         result = lappend(cxt.blist, stmt);
1839         result = list_concat(result, cxt.alist);
1840         result = list_concat(result, save_alist);
1841
1842         return result;
1843 }
1844
1845
1846 /*
1847  * Preprocess a list of column constraint clauses
1848  * to attach constraint attributes to their primary constraint nodes
1849  * and detect inconsistent/misplaced constraint attributes.
1850  *
1851  * NOTE: currently, attributes are only supported for FOREIGN KEY primary
1852  * constraints, but someday they ought to be supported for other constraints.
1853  */
1854 static void
1855 transformConstraintAttrs(List *constraintList)
1856 {
1857         Node       *lastprimarynode = NULL;
1858         bool            saw_deferrability = false;
1859         bool            saw_initially = false;
1860         ListCell   *clist;
1861
1862         foreach(clist, constraintList)
1863         {
1864                 Node       *node = lfirst(clist);
1865
1866                 if (!IsA(node, Constraint))
1867                 {
1868                         lastprimarynode = node;
1869                         /* reset flags for new primary node */
1870                         saw_deferrability = false;
1871                         saw_initially = false;
1872                 }
1873                 else
1874                 {
1875                         Constraint *con = (Constraint *) node;
1876
1877                         switch (con->contype)
1878                         {
1879                                 case CONSTR_ATTR_DEFERRABLE:
1880                                         if (lastprimarynode == NULL ||
1881                                                 !IsA(lastprimarynode, FkConstraint))
1882                                                 ereport(ERROR,
1883                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1884                                                                  errmsg("misplaced DEFERRABLE clause")));
1885                                         if (saw_deferrability)
1886                                                 ereport(ERROR,
1887                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1888                                                                  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
1889                                         saw_deferrability = true;
1890                                         ((FkConstraint *) lastprimarynode)->deferrable = true;
1891                                         break;
1892                                 case CONSTR_ATTR_NOT_DEFERRABLE:
1893                                         if (lastprimarynode == NULL ||
1894                                                 !IsA(lastprimarynode, FkConstraint))
1895                                                 ereport(ERROR,
1896                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1897                                                                  errmsg("misplaced NOT DEFERRABLE clause")));
1898                                         if (saw_deferrability)
1899                                                 ereport(ERROR,
1900                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1901                                                                  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
1902                                         saw_deferrability = true;
1903                                         ((FkConstraint *) lastprimarynode)->deferrable = false;
1904                                         if (saw_initially &&
1905                                                 ((FkConstraint *) lastprimarynode)->initdeferred)
1906                                                 ereport(ERROR,
1907                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1908                                                                  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
1909                                         break;
1910                                 case CONSTR_ATTR_DEFERRED:
1911                                         if (lastprimarynode == NULL ||
1912                                                 !IsA(lastprimarynode, FkConstraint))
1913                                                 ereport(ERROR,
1914                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1915                                                          errmsg("misplaced INITIALLY DEFERRED clause")));
1916                                         if (saw_initially)
1917                                                 ereport(ERROR,
1918                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1919                                                                  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
1920                                         saw_initially = true;
1921                                         ((FkConstraint *) lastprimarynode)->initdeferred = true;
1922
1923                                         /*
1924                                          * If only INITIALLY DEFERRED appears, assume DEFERRABLE
1925                                          */
1926                                         if (!saw_deferrability)
1927                                                 ((FkConstraint *) lastprimarynode)->deferrable = true;
1928                                         else if (!((FkConstraint *) lastprimarynode)->deferrable)
1929                                                 ereport(ERROR,
1930                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1931                                                                  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
1932                                         break;
1933                                 case CONSTR_ATTR_IMMEDIATE:
1934                                         if (lastprimarynode == NULL ||
1935                                                 !IsA(lastprimarynode, FkConstraint))
1936                                                 ereport(ERROR,
1937                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1938                                                         errmsg("misplaced INITIALLY IMMEDIATE clause")));
1939                                         if (saw_initially)
1940                                                 ereport(ERROR,
1941                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1942                                                                  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
1943                                         saw_initially = true;
1944                                         ((FkConstraint *) lastprimarynode)->initdeferred = false;
1945                                         break;
1946                                 default:
1947                                         /* Otherwise it's not an attribute */
1948                                         lastprimarynode = node;
1949                                         /* reset flags for new primary node */
1950                                         saw_deferrability = false;
1951                                         saw_initially = false;
1952                                         break;
1953                         }
1954                 }
1955         }
1956 }
1957
1958 /*
1959  * Special handling of type definition for a column
1960  */
1961 static void
1962 transformColumnType(ParseState *pstate, ColumnDef *column)
1963 {
1964         /*
1965          * All we really need to do here is verify that the type is valid.
1966          */
1967         Type            ctype = typenameType(pstate, column->typename, NULL);
1968
1969         ReleaseSysCache(ctype);
1970 }
1971
1972
1973 /*
1974  * transformCreateSchemaStmt -
1975  *        analyzes the CREATE SCHEMA statement
1976  *
1977  * Split the schema element list into individual commands and place
1978  * them in the result list in an order such that there are no forward
1979  * references (e.g. GRANT to a table created later in the list). Note
1980  * that the logic we use for determining forward references is
1981  * presently quite incomplete.
1982  *
1983  * SQL92 also allows constraints to make forward references, so thumb through
1984  * the table columns and move forward references to a posterior alter-table
1985  * command.
1986  *
1987  * The result is a list of parse nodes that still need to be analyzed ---
1988  * but we can't analyze the later commands until we've executed the earlier
1989  * ones, because of possible inter-object references.
1990  *
1991  * Note: this breaks the rules a little bit by modifying schema-name fields
1992  * within passed-in structs.  However, the transformation would be the same
1993  * if done over, so it should be all right to scribble on the input to this
1994  * extent.
1995  */
1996 List *
1997 transformCreateSchemaStmt(CreateSchemaStmt *stmt)
1998 {
1999         CreateSchemaStmtContext cxt;
2000         List       *result;
2001         ListCell   *elements;
2002
2003         cxt.stmtType = "CREATE SCHEMA";
2004         cxt.schemaname = stmt->schemaname;
2005         cxt.authid = stmt->authid;
2006         cxt.sequences = NIL;
2007         cxt.tables = NIL;
2008         cxt.views = NIL;
2009         cxt.indexes = NIL;
2010         cxt.triggers = NIL;
2011         cxt.grants = NIL;
2012
2013         /*
2014          * Run through each schema element in the schema element list. Separate
2015          * statements by type, and do preliminary analysis.
2016          */
2017         foreach(elements, stmt->schemaElts)
2018         {
2019                 Node       *element = lfirst(elements);
2020
2021                 switch (nodeTag(element))
2022                 {
2023                         case T_CreateSeqStmt:
2024                                 {
2025                                         CreateSeqStmt *elp = (CreateSeqStmt *) element;
2026
2027                                         setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
2028                                         cxt.sequences = lappend(cxt.sequences, element);
2029                                 }
2030                                 break;
2031
2032                         case T_CreateStmt:
2033                                 {
2034                                         CreateStmt *elp = (CreateStmt *) element;
2035
2036                                         setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2037
2038                                         /*
2039                                          * XXX todo: deal with constraints
2040                                          */
2041                                         cxt.tables = lappend(cxt.tables, element);
2042                                 }
2043                                 break;
2044
2045                         case T_ViewStmt:
2046                                 {
2047                                         ViewStmt   *elp = (ViewStmt *) element;
2048
2049                                         setSchemaName(cxt.schemaname, &elp->view->schemaname);
2050
2051                                         /*
2052                                          * XXX todo: deal with references between views
2053                                          */
2054                                         cxt.views = lappend(cxt.views, element);
2055                                 }
2056                                 break;
2057
2058                         case T_IndexStmt:
2059                                 {
2060                                         IndexStmt  *elp = (IndexStmt *) element;
2061
2062                                         setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2063                                         cxt.indexes = lappend(cxt.indexes, element);
2064                                 }
2065                                 break;
2066
2067                         case T_CreateTrigStmt:
2068                                 {
2069                                         CreateTrigStmt *elp = (CreateTrigStmt *) element;
2070
2071                                         setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2072                                         cxt.triggers = lappend(cxt.triggers, element);
2073                                 }
2074                                 break;
2075
2076                         case T_GrantStmt:
2077                                 cxt.grants = lappend(cxt.grants, element);
2078                                 break;
2079
2080                         default:
2081                                 elog(ERROR, "unrecognized node type: %d",
2082                                          (int) nodeTag(element));
2083                 }
2084         }
2085
2086         result = NIL;
2087         result = list_concat(result, cxt.sequences);
2088         result = list_concat(result, cxt.tables);
2089         result = list_concat(result, cxt.views);
2090         result = list_concat(result, cxt.indexes);
2091         result = list_concat(result, cxt.triggers);
2092         result = list_concat(result, cxt.grants);
2093
2094         return result;
2095 }
2096
2097 /*
2098  * setSchemaName
2099  *              Set or check schema name in an element of a CREATE SCHEMA command
2100  */
2101 static void
2102 setSchemaName(char *context_schema, char **stmt_schema_name)
2103 {
2104         if (*stmt_schema_name == NULL)
2105                 *stmt_schema_name = context_schema;
2106         else if (strcmp(context_schema, *stmt_schema_name) != 0)
2107                 ereport(ERROR,
2108                                 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
2109                                  errmsg("CREATE specifies a schema (%s) "
2110                                                 "different from the one being created (%s)",
2111                                                 *stmt_schema_name, context_schema)));
2112 }