]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_utilcmd.c
Fix outdated comment
[postgresql] / 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-2011, PostgreSQL Global Development Group
20  * Portions Copyright (c) 1994, Regents of the University of California
21  *
22  *      src/backend/parser/parse_utilcmd.c
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_collation.h"
37 #include "catalog/pg_constraint.h"
38 #include "catalog/pg_opclass.h"
39 #include "catalog/pg_operator.h"
40 #include "catalog/pg_type.h"
41 #include "commands/comment.h"
42 #include "commands/defrem.h"
43 #include "commands/tablecmds.h"
44 #include "commands/tablespace.h"
45 #include "miscadmin.h"
46 #include "nodes/makefuncs.h"
47 #include "nodes/nodeFuncs.h"
48 #include "parser/analyze.h"
49 #include "parser/parse_clause.h"
50 #include "parser/parse_collate.h"
51 #include "parser/parse_expr.h"
52 #include "parser/parse_relation.h"
53 #include "parser/parse_target.h"
54 #include "parser/parse_type.h"
55 #include "parser/parse_utilcmd.h"
56 #include "parser/parser.h"
57 #include "rewrite/rewriteManip.h"
58 #include "storage/lock.h"
59 #include "utils/acl.h"
60 #include "utils/builtins.h"
61 #include "utils/lsyscache.h"
62 #include "utils/relcache.h"
63 #include "utils/syscache.h"
64 #include "utils/typcache.h"
65
66
67 /* State shared by transformCreateStmt and its subroutines */
68 typedef struct
69 {
70         ParseState *pstate;                     /* overall parser state */
71         const char *stmtType;           /* "CREATE [FOREIGN] TABLE" or "ALTER TABLE" */
72         RangeVar   *relation;           /* relation to create */
73         Relation        rel;                    /* opened/locked rel, if ALTER */
74         List       *inhRelations;       /* relations to inherit from */
75         bool            isalter;                /* true if altering existing table */
76         bool            hasoids;                /* does relation have an OID column? */
77         List       *columns;            /* ColumnDef items */
78         List       *ckconstraints;      /* CHECK constraints */
79         List       *fkconstraints;      /* FOREIGN KEY constraints */
80         List       *ixconstraints;      /* index-creating constraints */
81         List       *inh_indexes;        /* cloned indexes from INCLUDING INDEXES */
82         List       *blist;                      /* "before list" of things to do before
83                                                                  * creating the table */
84         List       *alist;                      /* "after list" of things to do after creating
85                                                                  * the table */
86         IndexStmt  *pkey;                       /* PRIMARY KEY index, if any */
87 } CreateStmtContext;
88
89 /* State shared by transformCreateSchemaStmt and its subroutines */
90 typedef struct
91 {
92         const char *stmtType;           /* "CREATE SCHEMA" or "ALTER SCHEMA" */
93         char       *schemaname;         /* name of schema */
94         char       *authid;                     /* owner of schema */
95         List       *sequences;          /* CREATE SEQUENCE items */
96         List       *tables;                     /* CREATE TABLE items */
97         List       *views;                      /* CREATE VIEW items */
98         List       *indexes;            /* CREATE INDEX items */
99         List       *triggers;           /* CREATE TRIGGER items */
100         List       *grants;                     /* GRANT items */
101 } CreateSchemaStmtContext;
102
103
104 static void transformColumnDefinition(CreateStmtContext *cxt,
105                                                   ColumnDef *column);
106 static void transformTableConstraint(CreateStmtContext *cxt,
107                                                  Constraint *constraint);
108 static void transformInhRelation(CreateStmtContext *cxt,
109                                          InhRelation *inhrelation);
110 static void transformOfType(CreateStmtContext *cxt,
111                                 TypeName *ofTypename);
112 static char *chooseIndexName(const RangeVar *relation, IndexStmt *index_stmt);
113 static IndexStmt *generateClonedIndexStmt(CreateStmtContext *cxt,
114                                                 Relation parent_index, AttrNumber *attmap);
115 static List *get_collation(Oid collation, Oid actual_datatype);
116 static List *get_opclass(Oid opclass, Oid actual_datatype);
117 static void transformIndexConstraints(CreateStmtContext *cxt);
118 static IndexStmt *transformIndexConstraint(Constraint *constraint,
119                                                  CreateStmtContext *cxt);
120 static void transformFKConstraints(CreateStmtContext *cxt,
121                                            bool skipValidation,
122                                            bool isAddConstraint);
123 static void transformConstraintAttrs(CreateStmtContext *cxt,
124                                                  List *constraintList);
125 static void transformColumnType(CreateStmtContext *cxt, ColumnDef *column);
126 static void setSchemaName(char *context_schema, char **stmt_schema_name);
127
128
129 /*
130  * transformCreateStmt -
131  *        parse analysis for CREATE TABLE
132  *
133  * Returns a List of utility commands to be done in sequence.  One of these
134  * will be the transformed CreateStmt, but there may be additional actions
135  * to be done before and after the actual DefineRelation() call.
136  *
137  * SQL92 allows constraints to be scattered all over, so thumb through
138  * the columns and collect all constraints into one place.
139  * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
140  * then expand those into multiple IndexStmt blocks.
141  *        - thomas 1997-12-02
142  */
143 List *
144 transformCreateStmt(CreateStmt *stmt, const char *queryString)
145 {
146         ParseState *pstate;
147         CreateStmtContext cxt;
148         List       *result;
149         List       *save_alist;
150         ListCell   *elements;
151         Oid                     namespaceid;
152
153         /*
154          * We must not scribble on the passed-in CreateStmt, so copy it.  (This is
155          * overkill, but easy.)
156          */
157         stmt = (CreateStmt *) copyObject(stmt);
158
159         /*
160          * Look up the creation namespace.      This also checks permissions on the
161          * target namespace, so that we throw any permissions error as early as
162          * possible.
163          */
164         namespaceid = RangeVarGetAndCheckCreationNamespace(stmt->relation);
165
166         /*
167          * If the relation already exists and the user specified "IF NOT EXISTS",
168          * bail out with a NOTICE.
169          */
170         if (stmt->if_not_exists)
171         {
172                 Oid                     existing_relid;
173
174                 existing_relid = get_relname_relid(stmt->relation->relname,
175                                                                                    namespaceid);
176                 if (existing_relid != InvalidOid)
177                 {
178                         ereport(NOTICE,
179                                         (errcode(ERRCODE_DUPLICATE_TABLE),
180                                          errmsg("relation \"%s\" already exists, skipping",
181                                                         stmt->relation->relname)));
182                         return NIL;
183                 }
184         }
185
186         /*
187          * If the target relation name isn't schema-qualified, make it so.  This
188          * prevents some corner cases in which added-on rewritten commands might
189          * think they should apply to other relations that have the same name and
190          * are earlier in the search path.      But a local temp table is effectively
191          * specified to be in pg_temp, so no need for anything extra in that case.
192          */
193         if (stmt->relation->schemaname == NULL
194                 && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
195                 stmt->relation->schemaname = get_namespace_name(namespaceid);
196
197         /* Set up pstate and CreateStmtContext */
198         pstate = make_parsestate(NULL);
199         pstate->p_sourcetext = queryString;
200
201         cxt.pstate = pstate;
202         if (IsA(stmt, CreateForeignTableStmt))
203                 cxt.stmtType = "CREATE FOREIGN TABLE";
204         else
205                 cxt.stmtType = "CREATE TABLE";
206         cxt.relation = stmt->relation;
207         cxt.rel = NULL;
208         cxt.inhRelations = stmt->inhRelations;
209         cxt.isalter = false;
210         cxt.columns = NIL;
211         cxt.ckconstraints = NIL;
212         cxt.fkconstraints = NIL;
213         cxt.ixconstraints = NIL;
214         cxt.inh_indexes = NIL;
215         cxt.blist = NIL;
216         cxt.alist = NIL;
217         cxt.pkey = NULL;
218         cxt.hasoids = interpretOidsOption(stmt->options);
219
220         Assert(!stmt->ofTypename || !stmt->inhRelations);       /* grammar enforces */
221
222         if (stmt->ofTypename)
223                 transformOfType(&cxt, stmt->ofTypename);
224
225         /*
226          * Run through each primary element in the table creation clause. Separate
227          * column defs from constraints, and do preliminary analysis.
228          */
229         foreach(elements, stmt->tableElts)
230         {
231                 Node       *element = lfirst(elements);
232
233                 switch (nodeTag(element))
234                 {
235                         case T_ColumnDef:
236                                 transformColumnDefinition(&cxt, (ColumnDef *) element);
237                                 break;
238
239                         case T_Constraint:
240                                 transformTableConstraint(&cxt, (Constraint *) element);
241                                 break;
242
243                         case T_InhRelation:
244                                 transformInhRelation(&cxt, (InhRelation *) element);
245                                 break;
246
247                         default:
248                                 elog(ERROR, "unrecognized node type: %d",
249                                          (int) nodeTag(element));
250                                 break;
251                 }
252         }
253
254         /*
255          * transformIndexConstraints wants cxt.alist to contain only index
256          * statements, so transfer anything we already have into save_alist.
257          */
258         save_alist = cxt.alist;
259         cxt.alist = NIL;
260
261         Assert(stmt->constraints == NIL);
262
263         /*
264          * Postprocess constraints that give rise to index definitions.
265          */
266         transformIndexConstraints(&cxt);
267
268         /*
269          * Postprocess foreign-key constraints.
270          */
271         transformFKConstraints(&cxt, true, false);
272
273         /*
274          * Output results.
275          */
276         stmt->tableElts = cxt.columns;
277         stmt->constraints = cxt.ckconstraints;
278
279         result = lappend(cxt.blist, stmt);
280         result = list_concat(result, cxt.alist);
281         result = list_concat(result, save_alist);
282
283         return result;
284 }
285
286 /*
287  * transformColumnDefinition -
288  *              transform a single ColumnDef within CREATE TABLE
289  *              Also used in ALTER TABLE ADD COLUMN
290  */
291 static void
292 transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
293 {
294         bool            is_serial;
295         bool            saw_nullable;
296         bool            saw_default;
297         Constraint *constraint;
298         ListCell   *clist;
299
300         cxt->columns = lappend(cxt->columns, column);
301
302         /* Check for SERIAL pseudo-types */
303         is_serial = false;
304         if (column->typeName
305                 && list_length(column->typeName->names) == 1
306                 && !column->typeName->pct_type)
307         {
308                 char       *typname = strVal(linitial(column->typeName->names));
309
310                 if (strcmp(typname, "smallserial") == 0 ||
311                         strcmp(typname, "serial2") == 0)
312                 {
313                         is_serial = true;
314                         column->typeName->names = NIL;
315                         column->typeName->typeOid = INT2OID;
316                 }
317                 else if (strcmp(typname, "serial") == 0 ||
318                         strcmp(typname, "serial4") == 0)
319                 {
320                         is_serial = true;
321                         column->typeName->names = NIL;
322                         column->typeName->typeOid = INT4OID;
323                 }
324                 else if (strcmp(typname, "bigserial") == 0 ||
325                                  strcmp(typname, "serial8") == 0)
326                 {
327                         is_serial = true;
328                         column->typeName->names = NIL;
329                         column->typeName->typeOid = INT8OID;
330                 }
331
332                 /*
333                  * We have to reject "serial[]" explicitly, because once we've set
334                  * typeid, LookupTypeName won't notice arrayBounds.  We don't need any
335                  * special coding for serial(typmod) though.
336                  */
337                 if (is_serial && column->typeName->arrayBounds != NIL)
338                         ereport(ERROR,
339                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
340                                          errmsg("array of serial is not implemented"),
341                                          parser_errposition(cxt->pstate,
342                                                                                 column->typeName->location)));
343         }
344
345         /* Do necessary work on the column type declaration */
346         if (column->typeName)
347                 transformColumnType(cxt, column);
348
349         /* Special actions for SERIAL pseudo-types */
350         if (is_serial)
351         {
352                 Oid                     snamespaceid;
353                 char       *snamespace;
354                 char       *sname;
355                 char       *qstring;
356                 A_Const    *snamenode;
357                 TypeCast   *castnode;
358                 FuncCall   *funccallnode;
359                 CreateSeqStmt *seqstmt;
360                 AlterSeqStmt *altseqstmt;
361                 List       *attnamelist;
362
363                 /*
364                  * Determine namespace and name to use for the sequence.
365                  *
366                  * Although we use ChooseRelationName, it's not guaranteed that the
367                  * selected sequence name won't conflict; given sufficiently long
368                  * field names, two different serial columns in the same table could
369                  * be assigned the same sequence name, and we'd not notice since we
370                  * aren't creating the sequence quite yet.  In practice this seems
371                  * quite unlikely to be a problem, especially since few people would
372                  * need two serial columns in one table.
373                  */
374                 if (cxt->rel)
375                         snamespaceid = RelationGetNamespace(cxt->rel);
376                 else
377                         snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
378                 snamespace = get_namespace_name(snamespaceid);
379                 sname = ChooseRelationName(cxt->relation->relname,
380                                                                    column->colname,
381                                                                    "seq",
382                                                                    snamespaceid);
383
384                 ereport(NOTICE,
385                                 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
386                                                 cxt->stmtType, sname,
387                                                 cxt->relation->relname, column->colname)));
388
389                 /*
390                  * Build a CREATE SEQUENCE command to create the sequence object, and
391                  * add it to the list of things to be done before this CREATE/ALTER
392                  * TABLE.
393                  */
394                 seqstmt = makeNode(CreateSeqStmt);
395                 seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
396                 seqstmt->options = NIL;
397
398                 /*
399                  * If this is ALTER ADD COLUMN, make sure the sequence will be owned
400                  * by the table's owner.  The current user might be someone else
401                  * (perhaps a superuser, or someone who's only a member of the owning
402                  * role), but the SEQUENCE OWNED BY mechanisms will bleat unless table
403                  * and sequence have exactly the same owning role.
404                  */
405                 if (cxt->rel)
406                         seqstmt->ownerId = cxt->rel->rd_rel->relowner;
407                 else
408                         seqstmt->ownerId = InvalidOid;
409
410                 cxt->blist = lappend(cxt->blist, seqstmt);
411
412                 /*
413                  * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence
414                  * as owned by this column, and add it to the list of things to be
415                  * done after this CREATE/ALTER TABLE.
416                  */
417                 altseqstmt = makeNode(AlterSeqStmt);
418                 altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
419                 attnamelist = list_make3(makeString(snamespace),
420                                                                  makeString(cxt->relation->relname),
421                                                                  makeString(column->colname));
422                 altseqstmt->options = list_make1(makeDefElem("owned_by",
423                                                                                                          (Node *) attnamelist));
424
425                 cxt->alist = lappend(cxt->alist, altseqstmt);
426
427                 /*
428                  * Create appropriate constraints for SERIAL.  We do this in full,
429                  * rather than shortcutting, so that we will detect any conflicting
430                  * constraints the user wrote (like a different DEFAULT).
431                  *
432                  * Create an expression tree representing the function call
433                  * nextval('sequencename').  We cannot reduce the raw tree to cooked
434                  * form until after the sequence is created, but there's no need to do
435                  * so.
436                  */
437                 qstring = quote_qualified_identifier(snamespace, sname);
438                 snamenode = makeNode(A_Const);
439                 snamenode->val.type = T_String;
440                 snamenode->val.val.str = qstring;
441                 snamenode->location = -1;
442                 castnode = makeNode(TypeCast);
443                 castnode->typeName = SystemTypeName("regclass");
444                 castnode->arg = (Node *) snamenode;
445                 castnode->location = -1;
446                 funccallnode = makeNode(FuncCall);
447                 funccallnode->funcname = SystemFuncName("nextval");
448                 funccallnode->args = list_make1(castnode);
449                 funccallnode->agg_order = NIL;
450                 funccallnode->agg_star = false;
451                 funccallnode->agg_distinct = false;
452                 funccallnode->func_variadic = false;
453                 funccallnode->over = NULL;
454                 funccallnode->location = -1;
455
456                 constraint = makeNode(Constraint);
457                 constraint->contype = CONSTR_DEFAULT;
458                 constraint->location = -1;
459                 constraint->raw_expr = (Node *) funccallnode;
460                 constraint->cooked_expr = NULL;
461                 column->constraints = lappend(column->constraints, constraint);
462
463                 constraint = makeNode(Constraint);
464                 constraint->contype = CONSTR_NOTNULL;
465                 constraint->location = -1;
466                 column->constraints = lappend(column->constraints, constraint);
467         }
468
469         /* Process column constraints, if any... */
470         transformConstraintAttrs(cxt, column->constraints);
471
472         saw_nullable = false;
473         saw_default = false;
474
475         foreach(clist, column->constraints)
476         {
477                 constraint = lfirst(clist);
478                 Assert(IsA(constraint, Constraint));
479
480                 switch (constraint->contype)
481                 {
482                         case CONSTR_NULL:
483                                 if (saw_nullable && column->is_not_null)
484                                         ereport(ERROR,
485                                                         (errcode(ERRCODE_SYNTAX_ERROR),
486                                                          errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
487                                                                         column->colname, cxt->relation->relname),
488                                                          parser_errposition(cxt->pstate,
489                                                                                                 constraint->location)));
490                                 column->is_not_null = FALSE;
491                                 saw_nullable = true;
492                                 break;
493
494                         case CONSTR_NOTNULL:
495                                 if (saw_nullable && !column->is_not_null)
496                                         ereport(ERROR,
497                                                         (errcode(ERRCODE_SYNTAX_ERROR),
498                                                          errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
499                                                                         column->colname, cxt->relation->relname),
500                                                          parser_errposition(cxt->pstate,
501                                                                                                 constraint->location)));
502                                 column->is_not_null = TRUE;
503                                 saw_nullable = true;
504                                 break;
505
506                         case CONSTR_DEFAULT:
507                                 if (saw_default)
508                                         ereport(ERROR,
509                                                         (errcode(ERRCODE_SYNTAX_ERROR),
510                                                          errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
511                                                                         column->colname, cxt->relation->relname),
512                                                          parser_errposition(cxt->pstate,
513                                                                                                 constraint->location)));
514                                 column->raw_default = constraint->raw_expr;
515                                 Assert(constraint->cooked_expr == NULL);
516                                 saw_default = true;
517                                 break;
518
519                         case CONSTR_CHECK:
520                                 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
521                                 break;
522
523                         case CONSTR_PRIMARY:
524                         case CONSTR_UNIQUE:
525                                 if (constraint->keys == NIL)
526                                         constraint->keys = list_make1(makeString(column->colname));
527                                 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
528                                 break;
529
530                         case CONSTR_EXCLUSION:
531                                 /* grammar does not allow EXCLUDE as a column constraint */
532                                 elog(ERROR, "column exclusion constraints are not supported");
533                                 break;
534
535                         case CONSTR_FOREIGN:
536
537                                 /*
538                                  * Fill in the current attribute's name and throw it into the
539                                  * list of FK constraints to be processed later.
540                                  */
541                                 constraint->fk_attrs = list_make1(makeString(column->colname));
542                                 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
543                                 break;
544
545                         case CONSTR_ATTR_DEFERRABLE:
546                         case CONSTR_ATTR_NOT_DEFERRABLE:
547                         case CONSTR_ATTR_DEFERRED:
548                         case CONSTR_ATTR_IMMEDIATE:
549                                 /* transformConstraintAttrs took care of these */
550                                 break;
551
552                         default:
553                                 elog(ERROR, "unrecognized constraint type: %d",
554                                          constraint->contype);
555                                 break;
556                 }
557         }
558 }
559
560 /*
561  * transformTableConstraint
562  *              transform a Constraint node within CREATE TABLE or ALTER TABLE
563  */
564 static void
565 transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
566 {
567         switch (constraint->contype)
568         {
569                 case CONSTR_PRIMARY:
570                 case CONSTR_UNIQUE:
571                 case CONSTR_EXCLUSION:
572                         cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
573                         break;
574
575                 case CONSTR_CHECK:
576                         cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
577                         break;
578
579                 case CONSTR_FOREIGN:
580                         cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
581                         break;
582
583                 case CONSTR_NULL:
584                 case CONSTR_NOTNULL:
585                 case CONSTR_DEFAULT:
586                 case CONSTR_ATTR_DEFERRABLE:
587                 case CONSTR_ATTR_NOT_DEFERRABLE:
588                 case CONSTR_ATTR_DEFERRED:
589                 case CONSTR_ATTR_IMMEDIATE:
590                         elog(ERROR, "invalid context for constraint type %d",
591                                  constraint->contype);
592                         break;
593
594                 default:
595                         elog(ERROR, "unrecognized constraint type: %d",
596                                  constraint->contype);
597                         break;
598         }
599 }
600
601 /*
602  * transformInhRelation
603  *
604  * Change the LIKE <subtable> portion of a CREATE TABLE statement into
605  * column definitions which recreate the user defined column portions of
606  * <subtable>.
607  */
608 static void
609 transformInhRelation(CreateStmtContext *cxt, InhRelation *inhRelation)
610 {
611         AttrNumber      parent_attno;
612         Relation        relation;
613         TupleDesc       tupleDesc;
614         TupleConstr *constr;
615         AclResult       aclresult;
616         char       *comment;
617
618         relation = parserOpenTable(cxt->pstate, inhRelation->relation,
619                                                            AccessShareLock);
620
621         if (relation->rd_rel->relkind != RELKIND_RELATION)
622                 ereport(ERROR,
623                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
624                                  errmsg("inherited relation \"%s\" is not a table",
625                                                 inhRelation->relation->relname)));
626
627         /*
628          * Check for SELECT privilages
629          */
630         aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
631                                                                   ACL_SELECT);
632         if (aclresult != ACLCHECK_OK)
633                 aclcheck_error(aclresult, ACL_KIND_CLASS,
634                                            RelationGetRelationName(relation));
635
636         tupleDesc = RelationGetDescr(relation);
637         constr = tupleDesc->constr;
638
639         /*
640          * Insert the copied attributes into the cxt for the new table definition.
641          */
642         for (parent_attno = 1; parent_attno <= tupleDesc->natts;
643                  parent_attno++)
644         {
645                 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
646                 char       *attributeName = NameStr(attribute->attname);
647                 ColumnDef  *def;
648
649                 /*
650                  * Ignore dropped columns in the parent.
651                  */
652                 if (attribute->attisdropped)
653                         continue;
654
655                 /*
656                  * Create a new column, which is marked as NOT inherited.
657                  *
658                  * For constraints, ONLY the NOT NULL constraint is inherited by the
659                  * new column definition per SQL99.
660                  */
661                 def = makeNode(ColumnDef);
662                 def->colname = pstrdup(attributeName);
663                 def->typeName = makeTypeNameFromOid(attribute->atttypid,
664                                                                                         attribute->atttypmod);
665                 def->inhcount = 0;
666                 def->is_local = true;
667                 def->is_not_null = attribute->attnotnull;
668                 def->is_from_type = false;
669                 def->storage = 0;
670                 def->raw_default = NULL;
671                 def->cooked_default = NULL;
672                 def->collClause = NULL;
673                 def->collOid = attribute->attcollation;
674                 def->constraints = NIL;
675
676                 /*
677                  * Add to column list
678                  */
679                 cxt->columns = lappend(cxt->columns, def);
680
681                 /*
682                  * Copy default, if present and the default has been requested
683                  */
684                 if (attribute->atthasdef &&
685                         (inhRelation->options & CREATE_TABLE_LIKE_DEFAULTS))
686                 {
687                         Node       *this_default = NULL;
688                         AttrDefault *attrdef;
689                         int                     i;
690
691                         /* Find default in constraint structure */
692                         Assert(constr != NULL);
693                         attrdef = constr->defval;
694                         for (i = 0; i < constr->num_defval; i++)
695                         {
696                                 if (attrdef[i].adnum == parent_attno)
697                                 {
698                                         this_default = stringToNode(attrdef[i].adbin);
699                                         break;
700                                 }
701                         }
702                         Assert(this_default != NULL);
703
704                         /*
705                          * If default expr could contain any vars, we'd need to fix 'em,
706                          * but it can't; so default is ready to apply to child.
707                          */
708
709                         def->cooked_default = this_default;
710                 }
711
712                 /* Likewise, copy storage if requested */
713                 if (inhRelation->options & CREATE_TABLE_LIKE_STORAGE)
714                         def->storage = attribute->attstorage;
715                 else
716                         def->storage = 0;
717
718                 /* Likewise, copy comment if requested */
719                 if ((inhRelation->options & CREATE_TABLE_LIKE_COMMENTS) &&
720                         (comment = GetComment(attribute->attrelid,
721                                                                   RelationRelationId,
722                                                                   attribute->attnum)) != NULL)
723                 {
724                         CommentStmt *stmt = makeNode(CommentStmt);
725
726                         stmt->objtype = OBJECT_COLUMN;
727                         stmt->objname = list_make3(makeString(cxt->relation->schemaname),
728                                                                            makeString(cxt->relation->relname),
729                                                                            makeString(def->colname));
730                         stmt->objargs = NIL;
731                         stmt->comment = comment;
732
733                         cxt->alist = lappend(cxt->alist, stmt);
734                 }
735         }
736
737         /*
738          * Copy CHECK constraints if requested, being careful to adjust attribute
739          * numbers
740          */
741         if ((inhRelation->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
742                 tupleDesc->constr)
743         {
744                 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
745                 int                     ccnum;
746
747                 for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
748                 {
749                         char       *ccname = tupleDesc->constr->check[ccnum].ccname;
750                         char       *ccbin = tupleDesc->constr->check[ccnum].ccbin;
751                         Node       *ccbin_node = stringToNode(ccbin);
752                         Constraint *n = makeNode(Constraint);
753
754                         change_varattnos_of_a_node(ccbin_node, attmap);
755
756                         n->contype = CONSTR_CHECK;
757                         n->location = -1;
758                         n->conname = pstrdup(ccname);
759                         n->raw_expr = NULL;
760                         n->cooked_expr = nodeToString(ccbin_node);
761                         cxt->ckconstraints = lappend(cxt->ckconstraints, n);
762
763                         /* Copy comment on constraint */
764                         if ((inhRelation->options & CREATE_TABLE_LIKE_COMMENTS) &&
765                                 (comment = GetComment(get_constraint_oid(RelationGetRelid(relation),
766                                                                                                                  n->conname, false),
767                                                                           ConstraintRelationId,
768                                                                           0)) != NULL)
769                         {
770                                 CommentStmt *stmt = makeNode(CommentStmt);
771
772                                 stmt->objtype = OBJECT_CONSTRAINT;
773                                 stmt->objname = list_make3(makeString(cxt->relation->schemaname),
774                                                                                    makeString(cxt->relation->relname),
775                                                                                    makeString(n->conname));
776                                 stmt->objargs = NIL;
777                                 stmt->comment = comment;
778
779                                 cxt->alist = lappend(cxt->alist, stmt);
780                         }
781                 }
782         }
783
784         /*
785          * Likewise, copy indexes if requested
786          */
787         if ((inhRelation->options & CREATE_TABLE_LIKE_INDEXES) &&
788                 relation->rd_rel->relhasindex)
789         {
790                 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
791                 List       *parent_indexes;
792                 ListCell   *l;
793
794                 parent_indexes = RelationGetIndexList(relation);
795
796                 foreach(l, parent_indexes)
797                 {
798                         Oid                     parent_index_oid = lfirst_oid(l);
799                         Relation        parent_index;
800                         IndexStmt  *index_stmt;
801
802                         parent_index = index_open(parent_index_oid, AccessShareLock);
803
804                         /* Build CREATE INDEX statement to recreate the parent_index */
805                         index_stmt = generateClonedIndexStmt(cxt, parent_index, attmap);
806
807                         /* Copy comment on index */
808                         if (inhRelation->options & CREATE_TABLE_LIKE_COMMENTS)
809                         {
810                                 comment = GetComment(parent_index_oid, RelationRelationId, 0);
811
812                                 if (comment != NULL)
813                                 {
814                                         CommentStmt *stmt;
815
816                                         /*
817                                          * We have to assign the index a name now, so that we can
818                                          * reference it in CommentStmt.
819                                          */
820                                         if (index_stmt->idxname == NULL)
821                                                 index_stmt->idxname = chooseIndexName(cxt->relation,
822                                                                                                                           index_stmt);
823
824                                         stmt = makeNode(CommentStmt);
825                                         stmt->objtype = OBJECT_INDEX;
826                                         stmt->objname =
827                                                 list_make2(makeString(cxt->relation->schemaname),
828                                                                    makeString(index_stmt->idxname));
829                                         stmt->objargs = NIL;
830                                         stmt->comment = comment;
831
832                                         cxt->alist = lappend(cxt->alist, stmt);
833                                 }
834                         }
835
836                         /* Save it in the inh_indexes list for the time being */
837                         cxt->inh_indexes = lappend(cxt->inh_indexes, index_stmt);
838
839                         index_close(parent_index, AccessShareLock);
840                 }
841         }
842
843         /*
844          * Close the parent rel, but keep our AccessShareLock on it until xact
845          * commit.      That will prevent someone else from deleting or ALTERing the
846          * parent before the child is committed.
847          */
848         heap_close(relation, NoLock);
849 }
850
851 static void
852 transformOfType(CreateStmtContext *cxt, TypeName *ofTypename)
853 {
854         HeapTuple       tuple;
855         TupleDesc       tupdesc;
856         int                     i;
857         Oid                     ofTypeId;
858
859         AssertArg(ofTypename);
860
861         tuple = typenameType(NULL, ofTypename, NULL);
862         check_of_type(tuple);
863         ofTypeId = HeapTupleGetOid(tuple);
864         ofTypename->typeOid = ofTypeId;         /* cached for later */
865
866         tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
867         for (i = 0; i < tupdesc->natts; i++)
868         {
869                 Form_pg_attribute attr = tupdesc->attrs[i];
870                 ColumnDef  *n;
871
872                 if (attr->attisdropped)
873                         continue;
874
875                 n = makeNode(ColumnDef);
876                 n->colname = pstrdup(NameStr(attr->attname));
877                 n->typeName = makeTypeNameFromOid(attr->atttypid, attr->atttypmod);
878                 n->inhcount = 0;
879                 n->is_local = true;
880                 n->is_not_null = false;
881                 n->is_from_type = true;
882                 n->storage = 0;
883                 n->raw_default = NULL;
884                 n->cooked_default = NULL;
885                 n->collClause = NULL;
886                 n->collOid = attr->attcollation;
887                 n->constraints = NIL;
888                 cxt->columns = lappend(cxt->columns, n);
889         }
890         DecrTupleDescRefCount(tupdesc);
891
892         ReleaseSysCache(tuple);
893 }
894
895 /*
896  * chooseIndexName
897  *
898  * Compute name for an index.  This must match code in indexcmds.c.
899  *
900  * XXX this is inherently broken because the indexes aren't created
901  * immediately, so we fail to resolve conflicts when the same name is
902  * derived for multiple indexes.  However, that's a reasonably uncommon
903  * situation, so we'll live with it for now.
904  */
905 static char *
906 chooseIndexName(const RangeVar *relation, IndexStmt *index_stmt)
907 {
908         Oid                     namespaceId;
909         List       *colnames;
910
911         namespaceId = RangeVarGetCreationNamespace(relation);
912         colnames = ChooseIndexColumnNames(index_stmt->indexParams);
913         return ChooseIndexName(relation->relname, namespaceId,
914                                                    colnames, index_stmt->excludeOpNames,
915                                                    index_stmt->primary, index_stmt->isconstraint);
916 }
917
918 /*
919  * Generate an IndexStmt node using information from an already existing index
920  * "source_idx".  Attribute numbers should be adjusted according to attmap.
921  */
922 static IndexStmt *
923 generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
924                                                 AttrNumber *attmap)
925 {
926         Oid                     source_relid = RelationGetRelid(source_idx);
927         Form_pg_attribute *attrs = RelationGetDescr(source_idx)->attrs;
928         HeapTuple       ht_idxrel;
929         HeapTuple       ht_idx;
930         Form_pg_class idxrelrec;
931         Form_pg_index idxrec;
932         Form_pg_am      amrec;
933         oidvector  *indcollation;
934         oidvector  *indclass;
935         IndexStmt  *index;
936         List       *indexprs;
937         ListCell   *indexpr_item;
938         Oid                     indrelid;
939         int                     keyno;
940         Oid                     keycoltype;
941         Datum           datum;
942         bool            isnull;
943
944         /*
945          * Fetch pg_class tuple of source index.  We can't use the copy in the
946          * relcache entry because it doesn't include optional fields.
947          */
948         ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
949         if (!HeapTupleIsValid(ht_idxrel))
950                 elog(ERROR, "cache lookup failed for relation %u", source_relid);
951         idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
952
953         /* Fetch pg_index tuple for source index from relcache entry */
954         ht_idx = source_idx->rd_indextuple;
955         idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
956         indrelid = idxrec->indrelid;
957
958         /* Fetch pg_am tuple for source index from relcache entry */
959         amrec = source_idx->rd_am;
960
961         /* Extract indcollation from the pg_index tuple */
962         datum = SysCacheGetAttr(INDEXRELID, ht_idx,
963                                                         Anum_pg_index_indcollation, &isnull);
964         Assert(!isnull);
965         indcollation = (oidvector *) DatumGetPointer(datum);
966
967         /* Extract indclass from the pg_index tuple */
968         datum = SysCacheGetAttr(INDEXRELID, ht_idx,
969                                                         Anum_pg_index_indclass, &isnull);
970         Assert(!isnull);
971         indclass = (oidvector *) DatumGetPointer(datum);
972
973         /* Begin building the IndexStmt */
974         index = makeNode(IndexStmt);
975         index->relation = cxt->relation;
976         index->accessMethod = pstrdup(NameStr(amrec->amname));
977         if (OidIsValid(idxrelrec->reltablespace))
978                 index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
979         else
980                 index->tableSpace = NULL;
981         index->indexOid = InvalidOid;
982         index->unique = idxrec->indisunique;
983         index->primary = idxrec->indisprimary;
984         index->concurrent = false;
985
986         /*
987          * We don't try to preserve the name of the source index; instead, just
988          * let DefineIndex() choose a reasonable name.
989          */
990         index->idxname = NULL;
991
992         /*
993          * If the index is marked PRIMARY or has an exclusion condition, it's
994          * certainly from a constraint; else, if it's not marked UNIQUE, it
995          * certainly isn't.  If it is or might be from a constraint, we have to
996          * fetch the pg_constraint record.
997          */
998         if (index->primary || index->unique || idxrec->indisexclusion)
999         {
1000                 Oid                     constraintId = get_index_constraint(source_relid);
1001
1002                 if (OidIsValid(constraintId))
1003                 {
1004                         HeapTuple       ht_constr;
1005                         Form_pg_constraint conrec;
1006
1007                         ht_constr = SearchSysCache1(CONSTROID,
1008                                                                                 ObjectIdGetDatum(constraintId));
1009                         if (!HeapTupleIsValid(ht_constr))
1010                                 elog(ERROR, "cache lookup failed for constraint %u",
1011                                          constraintId);
1012                         conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
1013
1014                         index->isconstraint = true;
1015                         index->deferrable = conrec->condeferrable;
1016                         index->initdeferred = conrec->condeferred;
1017
1018                         /* If it's an exclusion constraint, we need the operator names */
1019                         if (idxrec->indisexclusion)
1020                         {
1021                                 Datum      *elems;
1022                                 int                     nElems;
1023                                 int                     i;
1024
1025                                 Assert(conrec->contype == CONSTRAINT_EXCLUSION);
1026                                 /* Extract operator OIDs from the pg_constraint tuple */
1027                                 datum = SysCacheGetAttr(CONSTROID, ht_constr,
1028                                                                                 Anum_pg_constraint_conexclop,
1029                                                                                 &isnull);
1030                                 if (isnull)
1031                                         elog(ERROR, "null conexclop for constraint %u",
1032                                                  constraintId);
1033
1034                                 deconstruct_array(DatumGetArrayTypeP(datum),
1035                                                                   OIDOID, sizeof(Oid), true, 'i',
1036                                                                   &elems, NULL, &nElems);
1037
1038                                 for (i = 0; i < nElems; i++)
1039                                 {
1040                                         Oid                     operid = DatumGetObjectId(elems[i]);
1041                                         HeapTuple       opertup;
1042                                         Form_pg_operator operform;
1043                                         char       *oprname;
1044                                         char       *nspname;
1045                                         List       *namelist;
1046
1047                                         opertup = SearchSysCache1(OPEROID,
1048                                                                                           ObjectIdGetDatum(operid));
1049                                         if (!HeapTupleIsValid(opertup))
1050                                                 elog(ERROR, "cache lookup failed for operator %u",
1051                                                          operid);
1052                                         operform = (Form_pg_operator) GETSTRUCT(opertup);
1053                                         oprname = pstrdup(NameStr(operform->oprname));
1054                                         /* For simplicity we always schema-qualify the op name */
1055                                         nspname = get_namespace_name(operform->oprnamespace);
1056                                         namelist = list_make2(makeString(nspname),
1057                                                                                   makeString(oprname));
1058                                         index->excludeOpNames = lappend(index->excludeOpNames,
1059                                                                                                         namelist);
1060                                         ReleaseSysCache(opertup);
1061                                 }
1062                         }
1063
1064                         ReleaseSysCache(ht_constr);
1065                 }
1066                 else
1067                         index->isconstraint = false;
1068         }
1069         else
1070                 index->isconstraint = false;
1071
1072         /* Get the index expressions, if any */
1073         datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1074                                                         Anum_pg_index_indexprs, &isnull);
1075         if (!isnull)
1076         {
1077                 char       *exprsString;
1078
1079                 exprsString = TextDatumGetCString(datum);
1080                 indexprs = (List *) stringToNode(exprsString);
1081         }
1082         else
1083                 indexprs = NIL;
1084
1085         /* Build the list of IndexElem */
1086         index->indexParams = NIL;
1087
1088         indexpr_item = list_head(indexprs);
1089         for (keyno = 0; keyno < idxrec->indnatts; keyno++)
1090         {
1091                 IndexElem  *iparam;
1092                 AttrNumber      attnum = idxrec->indkey.values[keyno];
1093                 int16           opt = source_idx->rd_indoption[keyno];
1094
1095                 iparam = makeNode(IndexElem);
1096
1097                 if (AttributeNumberIsValid(attnum))
1098                 {
1099                         /* Simple index column */
1100                         char       *attname;
1101
1102                         attname = get_relid_attribute_name(indrelid, attnum);
1103                         keycoltype = get_atttype(indrelid, attnum);
1104
1105                         iparam->name = attname;
1106                         iparam->expr = NULL;
1107                 }
1108                 else
1109                 {
1110                         /* Expressional index */
1111                         Node       *indexkey;
1112
1113                         if (indexpr_item == NULL)
1114                                 elog(ERROR, "too few entries in indexprs list");
1115                         indexkey = (Node *) lfirst(indexpr_item);
1116                         indexpr_item = lnext(indexpr_item);
1117
1118                         /* OK to modify indexkey since we are working on a private copy */
1119                         change_varattnos_of_a_node(indexkey, attmap);
1120
1121                         iparam->name = NULL;
1122                         iparam->expr = indexkey;
1123
1124                         keycoltype = exprType(indexkey);
1125                 }
1126
1127                 /* Copy the original index column name */
1128                 iparam->indexcolname = pstrdup(NameStr(attrs[keyno]->attname));
1129
1130                 /* Add the collation name, if non-default */
1131                 iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
1132
1133                 /* Add the operator class name, if non-default */
1134                 iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1135
1136                 iparam->ordering = SORTBY_DEFAULT;
1137                 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1138
1139                 /* Adjust options if necessary */
1140                 if (amrec->amcanorder)
1141                 {
1142                         /*
1143                          * If it supports sort ordering, copy DESC and NULLS opts. Don't
1144                          * set non-default settings unnecessarily, though, so as to
1145                          * improve the chance of recognizing equivalence to constraint
1146                          * indexes.
1147                          */
1148                         if (opt & INDOPTION_DESC)
1149                         {
1150                                 iparam->ordering = SORTBY_DESC;
1151                                 if ((opt & INDOPTION_NULLS_FIRST) == 0)
1152                                         iparam->nulls_ordering = SORTBY_NULLS_LAST;
1153                         }
1154                         else
1155                         {
1156                                 if (opt & INDOPTION_NULLS_FIRST)
1157                                         iparam->nulls_ordering = SORTBY_NULLS_FIRST;
1158                         }
1159                 }
1160
1161                 index->indexParams = lappend(index->indexParams, iparam);
1162         }
1163
1164         /* Copy reloptions if any */
1165         datum = SysCacheGetAttr(RELOID, ht_idxrel,
1166                                                         Anum_pg_class_reloptions, &isnull);
1167         if (!isnull)
1168                 index->options = untransformRelOptions(datum);
1169
1170         /* If it's a partial index, decompile and append the predicate */
1171         datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1172                                                         Anum_pg_index_indpred, &isnull);
1173         if (!isnull)
1174         {
1175                 char       *pred_str;
1176
1177                 /* Convert text string to node tree */
1178                 pred_str = TextDatumGetCString(datum);
1179                 index->whereClause = (Node *) stringToNode(pred_str);
1180                 /* Adjust attribute numbers */
1181                 change_varattnos_of_a_node(index->whereClause, attmap);
1182         }
1183
1184         /* Clean up */
1185         ReleaseSysCache(ht_idxrel);
1186
1187         return index;
1188 }
1189
1190 /*
1191  * get_collation                - fetch qualified name of a collation
1192  *
1193  * If collation is InvalidOid or is the default for the given actual_datatype,
1194  * then the return value is NIL.
1195  */
1196 static List *
1197 get_collation(Oid collation, Oid actual_datatype)
1198 {
1199         List       *result;
1200         HeapTuple       ht_coll;
1201         Form_pg_collation coll_rec;
1202         char       *nsp_name;
1203         char       *coll_name;
1204
1205         if (!OidIsValid(collation))
1206                 return NIL;                             /* easy case */
1207         if (collation == get_typcollation(actual_datatype))
1208                 return NIL;                             /* just let it default */
1209
1210         ht_coll = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
1211         if (!HeapTupleIsValid(ht_coll))
1212                 elog(ERROR, "cache lookup failed for collation %u", collation);
1213         coll_rec = (Form_pg_collation) GETSTRUCT(ht_coll);
1214
1215         /* For simplicity, we always schema-qualify the name */
1216         nsp_name = get_namespace_name(coll_rec->collnamespace);
1217         coll_name = pstrdup(NameStr(coll_rec->collname));
1218         result = list_make2(makeString(nsp_name), makeString(coll_name));
1219
1220         ReleaseSysCache(ht_coll);
1221         return result;
1222 }
1223
1224 /*
1225  * get_opclass                  - fetch qualified name of an index operator class
1226  *
1227  * If the opclass is the default for the given actual_datatype, then
1228  * the return value is NIL.
1229  */
1230 static List *
1231 get_opclass(Oid opclass, Oid actual_datatype)
1232 {
1233         List       *result = NIL;
1234         HeapTuple       ht_opc;
1235         Form_pg_opclass opc_rec;
1236
1237         ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1238         if (!HeapTupleIsValid(ht_opc))
1239                 elog(ERROR, "cache lookup failed for opclass %u", opclass);
1240         opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
1241
1242         if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
1243         {
1244                 /* For simplicity, we always schema-qualify the name */
1245                 char       *nsp_name = get_namespace_name(opc_rec->opcnamespace);
1246                 char       *opc_name = pstrdup(NameStr(opc_rec->opcname));
1247
1248                 result = list_make2(makeString(nsp_name), makeString(opc_name));
1249         }
1250
1251         ReleaseSysCache(ht_opc);
1252         return result;
1253 }
1254
1255
1256 /*
1257  * transformIndexConstraints
1258  *              Handle UNIQUE, PRIMARY KEY, EXCLUDE constraints, which create indexes.
1259  *              We also merge in any index definitions arising from
1260  *              LIKE ... INCLUDING INDEXES.
1261  */
1262 static void
1263 transformIndexConstraints(CreateStmtContext *cxt)
1264 {
1265         IndexStmt  *index;
1266         List       *indexlist = NIL;
1267         ListCell   *lc;
1268
1269         /*
1270          * Run through the constraints that need to generate an index. For PRIMARY
1271          * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
1272          * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
1273          * NULL.
1274          */
1275         foreach(lc, cxt->ixconstraints)
1276         {
1277                 Constraint *constraint = (Constraint *) lfirst(lc);
1278
1279                 Assert(IsA(constraint, Constraint));
1280                 Assert(constraint->contype == CONSTR_PRIMARY ||
1281                            constraint->contype == CONSTR_UNIQUE ||
1282                            constraint->contype == CONSTR_EXCLUSION);
1283
1284                 index = transformIndexConstraint(constraint, cxt);
1285
1286                 indexlist = lappend(indexlist, index);
1287         }
1288
1289         /* Add in any indexes defined by LIKE ... INCLUDING INDEXES */
1290         foreach(lc, cxt->inh_indexes)
1291         {
1292                 index = (IndexStmt *) lfirst(lc);
1293
1294                 if (index->primary)
1295                 {
1296                         if (cxt->pkey != NULL)
1297                                 ereport(ERROR,
1298                                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1299                                                  errmsg("multiple primary keys for table \"%s\" are not allowed",
1300                                                                 cxt->relation->relname)));
1301                         cxt->pkey = index;
1302                 }
1303
1304                 indexlist = lappend(indexlist, index);
1305         }
1306
1307         /*
1308          * Scan the index list and remove any redundant index specifications. This
1309          * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1310          * strict reading of SQL92 would suggest raising an error instead, but
1311          * that strikes me as too anal-retentive. - tgl 2001-02-14
1312          *
1313          * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1314          * pre-existing indexes, too.
1315          */
1316         Assert(cxt->alist == NIL);
1317         if (cxt->pkey != NULL)
1318         {
1319                 /* Make sure we keep the PKEY index in preference to others... */
1320                 cxt->alist = list_make1(cxt->pkey);
1321         }
1322
1323         foreach(lc, indexlist)
1324         {
1325                 bool            keep = true;
1326                 ListCell   *k;
1327
1328                 index = lfirst(lc);
1329
1330                 /* if it's pkey, it's already in cxt->alist */
1331                 if (index == cxt->pkey)
1332                         continue;
1333
1334                 foreach(k, cxt->alist)
1335                 {
1336                         IndexStmt  *priorindex = lfirst(k);
1337
1338                         if (equal(index->indexParams, priorindex->indexParams) &&
1339                                 equal(index->whereClause, priorindex->whereClause) &&
1340                                 equal(index->excludeOpNames, priorindex->excludeOpNames) &&
1341                                 strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
1342                                 index->deferrable == priorindex->deferrable &&
1343                                 index->initdeferred == priorindex->initdeferred)
1344                         {
1345                                 priorindex->unique |= index->unique;
1346
1347                                 /*
1348                                  * If the prior index is as yet unnamed, and this one is
1349                                  * named, then transfer the name to the prior index. This
1350                                  * ensures that if we have named and unnamed constraints,
1351                                  * we'll use (at least one of) the names for the index.
1352                                  */
1353                                 if (priorindex->idxname == NULL)
1354                                         priorindex->idxname = index->idxname;
1355                                 keep = false;
1356                                 break;
1357                         }
1358                 }
1359
1360                 if (keep)
1361                         cxt->alist = lappend(cxt->alist, index);
1362         }
1363 }
1364
1365 /*
1366  * transformIndexConstraint
1367  *              Transform one UNIQUE, PRIMARY KEY, or EXCLUDE constraint for
1368  *              transformIndexConstraints.
1369  */
1370 static IndexStmt *
1371 transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
1372 {
1373         IndexStmt  *index;
1374         ListCell   *lc;
1375
1376         index = makeNode(IndexStmt);
1377
1378         index->unique = (constraint->contype != CONSTR_EXCLUSION);
1379         index->primary = (constraint->contype == CONSTR_PRIMARY);
1380         if (index->primary)
1381         {
1382                 if (cxt->pkey != NULL)
1383                         ereport(ERROR,
1384                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1385                          errmsg("multiple primary keys for table \"%s\" are not allowed",
1386                                         cxt->relation->relname),
1387                                          parser_errposition(cxt->pstate, constraint->location)));
1388                 cxt->pkey = index;
1389
1390                 /*
1391                  * In ALTER TABLE case, a primary index might already exist, but
1392                  * DefineIndex will check for it.
1393                  */
1394         }
1395         index->isconstraint = true;
1396         index->deferrable = constraint->deferrable;
1397         index->initdeferred = constraint->initdeferred;
1398
1399         if (constraint->conname != NULL)
1400                 index->idxname = pstrdup(constraint->conname);
1401         else
1402                 index->idxname = NULL;  /* DefineIndex will choose name */
1403
1404         index->relation = cxt->relation;
1405         index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
1406         index->options = constraint->options;
1407         index->tableSpace = constraint->indexspace;
1408         index->whereClause = constraint->where_clause;
1409         index->indexParams = NIL;
1410         index->excludeOpNames = NIL;
1411         index->indexOid = InvalidOid;
1412         index->concurrent = false;
1413
1414         /*
1415          * If it's ALTER TABLE ADD CONSTRAINT USING INDEX, look up the index and
1416          * verify it's usable, then extract the implied column name list.  (We
1417          * will not actually need the column name list at runtime, but we need it
1418          * now to check for duplicate column entries below.)
1419          */
1420         if (constraint->indexname != NULL)
1421         {
1422                 char       *index_name = constraint->indexname;
1423                 Relation        heap_rel = cxt->rel;
1424                 Oid                     index_oid;
1425                 Relation        index_rel;
1426                 Form_pg_index index_form;
1427                 oidvector  *indclass;
1428                 Datum           indclassDatum;
1429                 bool            isnull;
1430                 int                     i;
1431
1432                 /* Grammar should not allow this with explicit column list */
1433                 Assert(constraint->keys == NIL);
1434
1435                 /* Grammar should only allow PRIMARY and UNIQUE constraints */
1436                 Assert(constraint->contype == CONSTR_PRIMARY ||
1437                            constraint->contype == CONSTR_UNIQUE);
1438
1439                 /* Must be ALTER, not CREATE, but grammar doesn't enforce that */
1440                 if (!cxt->isalter)
1441                         ereport(ERROR,
1442                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1443                                          errmsg("cannot use an existing index in CREATE TABLE"),
1444                                          parser_errposition(cxt->pstate, constraint->location)));
1445
1446                 /* Look for the index in the same schema as the table */
1447                 index_oid = get_relname_relid(index_name, RelationGetNamespace(heap_rel));
1448
1449                 if (!OidIsValid(index_oid))
1450                         ereport(ERROR,
1451                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
1452                                          errmsg("index \"%s\" does not exist", index_name),
1453                                          parser_errposition(cxt->pstate, constraint->location)));
1454
1455                 /* Open the index (this will throw an error if it is not an index) */
1456                 index_rel = index_open(index_oid, AccessShareLock);
1457                 index_form = index_rel->rd_index;
1458
1459                 /* Check that it does not have an associated constraint already */
1460                 if (OidIsValid(get_index_constraint(index_oid)))
1461                         ereport(ERROR,
1462                                         (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1463                            errmsg("index \"%s\" is already associated with a constraint",
1464                                           index_name),
1465                                          parser_errposition(cxt->pstate, constraint->location)));
1466
1467                 /* Perform validity checks on the index */
1468                 if (index_form->indrelid != RelationGetRelid(heap_rel))
1469                         ereport(ERROR,
1470                                         (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1471                                          errmsg("index \"%s\" does not belong to table \"%s\"",
1472                                                         index_name, RelationGetRelationName(heap_rel)),
1473                                          parser_errposition(cxt->pstate, constraint->location)));
1474
1475                 if (!index_form->indisvalid)
1476                         ereport(ERROR,
1477                                         (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1478                                          errmsg("index \"%s\" is not valid", index_name),
1479                                          parser_errposition(cxt->pstate, constraint->location)));
1480
1481                 if (!index_form->indisready)
1482                         ereport(ERROR,
1483                                         (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1484                                          errmsg("index \"%s\" is not ready", index_name),
1485                                          parser_errposition(cxt->pstate, constraint->location)));
1486
1487                 if (!index_form->indisunique)
1488                         ereport(ERROR,
1489                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1490                                          errmsg("\"%s\" is not a unique index", index_name),
1491                                          errdetail("Cannot create a primary key or unique constraint using such an index."),
1492                                          parser_errposition(cxt->pstate, constraint->location)));
1493
1494                 if (RelationGetIndexExpressions(index_rel) != NIL)
1495                         ereport(ERROR,
1496                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1497                                          errmsg("index \"%s\" contains expressions", index_name),
1498                                          errdetail("Cannot create a primary key or unique constraint using such an index."),
1499                                          parser_errposition(cxt->pstate, constraint->location)));
1500
1501                 if (RelationGetIndexPredicate(index_rel) != NIL)
1502                         ereport(ERROR,
1503                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1504                                          errmsg("\"%s\" is a partial index", index_name),
1505                                          errdetail("Cannot create a primary key or unique constraint using such an index."),
1506                                          parser_errposition(cxt->pstate, constraint->location)));
1507
1508                 /*
1509                  * It's probably unsafe to change a deferred index to non-deferred. (A
1510                  * non-constraint index couldn't be deferred anyway, so this case
1511                  * should never occur; no need to sweat, but let's check it.)
1512                  */
1513                 if (!index_form->indimmediate && !constraint->deferrable)
1514                         ereport(ERROR,
1515                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1516                                          errmsg("\"%s\" is a deferrable index", index_name),
1517                                          errdetail("Cannot create a non-deferrable constraint using a deferrable index."),
1518                                          parser_errposition(cxt->pstate, constraint->location)));
1519
1520                 /*
1521                  * Insist on it being a btree.  That's the only kind that supports
1522                  * uniqueness at the moment anyway; but we must have an index that
1523                  * exactly matches what you'd get from plain ADD CONSTRAINT syntax,
1524                  * else dump and reload will produce a different index (breaking
1525                  * pg_upgrade in particular).
1526                  */
1527                 if (index_rel->rd_rel->relam != get_am_oid(DEFAULT_INDEX_TYPE, false))
1528                         ereport(ERROR,
1529                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1530                                          errmsg("index \"%s\" is not a b-tree", index_name),
1531                                          parser_errposition(cxt->pstate, constraint->location)));
1532
1533                 /* Must get indclass the hard way */
1534                 indclassDatum = SysCacheGetAttr(INDEXRELID, index_rel->rd_indextuple,
1535                                                                                 Anum_pg_index_indclass, &isnull);
1536                 Assert(!isnull);
1537                 indclass = (oidvector *) DatumGetPointer(indclassDatum);
1538
1539                 for (i = 0; i < index_form->indnatts; i++)
1540                 {
1541                         int2            attnum = index_form->indkey.values[i];
1542                         Form_pg_attribute attform;
1543                         char       *attname;
1544                         Oid                     defopclass;
1545
1546                         /*
1547                          * We shouldn't see attnum == 0 here, since we already rejected
1548                          * expression indexes.  If we do, SystemAttributeDefinition will
1549                          * throw an error.
1550                          */
1551                         if (attnum > 0)
1552                         {
1553                                 Assert(attnum <= heap_rel->rd_att->natts);
1554                                 attform = heap_rel->rd_att->attrs[attnum - 1];
1555                         }
1556                         else
1557                                 attform = SystemAttributeDefinition(attnum,
1558                                                                                            heap_rel->rd_rel->relhasoids);
1559                         attname = pstrdup(NameStr(attform->attname));
1560
1561                         /*
1562                          * Insist on default opclass and sort options.  While the index
1563                          * would still work as a constraint with non-default settings, it
1564                          * might not provide exactly the same uniqueness semantics as
1565                          * you'd get from a normally-created constraint; and there's also
1566                          * the dump/reload problem mentioned above.
1567                          */
1568                         defopclass = GetDefaultOpClass(attform->atttypid,
1569                                                                                    index_rel->rd_rel->relam);
1570                         if (indclass->values[i] != defopclass ||
1571                                 index_rel->rd_indoption[i] != 0)
1572                                 ereport(ERROR,
1573                                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1574                                                  errmsg("index \"%s\" does not have default sorting behavior", index_name),
1575                                                  errdetail("Cannot create a primary key or unique constraint using such an index."),
1576                                          parser_errposition(cxt->pstate, constraint->location)));
1577
1578                         constraint->keys = lappend(constraint->keys, makeString(attname));
1579                 }
1580
1581                 /* Close the index relation but keep the lock */
1582                 relation_close(index_rel, NoLock);
1583
1584                 index->indexOid = index_oid;
1585         }
1586
1587         /*
1588          * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
1589          * IndexElems and operator names.  We have to break that apart into
1590          * separate lists.
1591          */
1592         if (constraint->contype == CONSTR_EXCLUSION)
1593         {
1594                 foreach(lc, constraint->exclusions)
1595                 {
1596                         List       *pair = (List *) lfirst(lc);
1597                         IndexElem  *elem;
1598                         List       *opname;
1599
1600                         Assert(list_length(pair) == 2);
1601                         elem = (IndexElem *) linitial(pair);
1602                         Assert(IsA(elem, IndexElem));
1603                         opname = (List *) lsecond(pair);
1604                         Assert(IsA(opname, List));
1605
1606                         index->indexParams = lappend(index->indexParams, elem);
1607                         index->excludeOpNames = lappend(index->excludeOpNames, opname);
1608                 }
1609
1610                 return index;
1611         }
1612
1613         /*
1614          * For UNIQUE and PRIMARY KEY, we just have a list of column names.
1615          *
1616          * Make sure referenced keys exist.  If we are making a PRIMARY KEY index,
1617          * also make sure they are NOT NULL, if possible. (Although we could leave
1618          * it to DefineIndex to mark the columns NOT NULL, it's more efficient to
1619          * get it right the first time.)
1620          */
1621         foreach(lc, constraint->keys)
1622         {
1623                 char       *key = strVal(lfirst(lc));
1624                 bool            found = false;
1625                 ColumnDef  *column = NULL;
1626                 ListCell   *columns;
1627                 IndexElem  *iparam;
1628
1629                 foreach(columns, cxt->columns)
1630                 {
1631                         column = (ColumnDef *) lfirst(columns);
1632                         Assert(IsA(column, ColumnDef));
1633                         if (strcmp(column->colname, key) == 0)
1634                         {
1635                                 found = true;
1636                                 break;
1637                         }
1638                 }
1639                 if (found)
1640                 {
1641                         /* found column in the new table; force it to be NOT NULL */
1642                         if (constraint->contype == CONSTR_PRIMARY)
1643                                 column->is_not_null = TRUE;
1644                 }
1645                 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1646                 {
1647                         /*
1648                          * column will be a system column in the new table, so accept it.
1649                          * System columns can't ever be null, so no need to worry about
1650                          * PRIMARY/NOT NULL constraint.
1651                          */
1652                         found = true;
1653                 }
1654                 else if (cxt->inhRelations)
1655                 {
1656                         /* try inherited tables */
1657                         ListCell   *inher;
1658
1659                         foreach(inher, cxt->inhRelations)
1660                         {
1661                                 RangeVar   *inh = (RangeVar *) lfirst(inher);
1662                                 Relation        rel;
1663                                 int                     count;
1664
1665                                 Assert(IsA(inh, RangeVar));
1666                                 rel = heap_openrv(inh, AccessShareLock);
1667                                 if (rel->rd_rel->relkind != RELKIND_RELATION)
1668                                         ereport(ERROR,
1669                                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1670                                                    errmsg("inherited relation \"%s\" is not a table",
1671                                                                   inh->relname)));
1672                                 for (count = 0; count < rel->rd_att->natts; count++)
1673                                 {
1674                                         Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1675                                         char       *inhname = NameStr(inhattr->attname);
1676
1677                                         if (inhattr->attisdropped)
1678                                                 continue;
1679                                         if (strcmp(key, inhname) == 0)
1680                                         {
1681                                                 found = true;
1682
1683                                                 /*
1684                                                  * We currently have no easy way to force an inherited
1685                                                  * column to be NOT NULL at creation, if its parent
1686                                                  * wasn't so already. We leave it to DefineIndex to
1687                                                  * fix things up in this case.
1688                                                  */
1689                                                 break;
1690                                         }
1691                                 }
1692                                 heap_close(rel, NoLock);
1693                                 if (found)
1694                                         break;
1695                         }
1696                 }
1697
1698                 /*
1699                  * In the ALTER TABLE case, don't complain about index keys not
1700                  * created in the command; they may well exist already. DefineIndex
1701                  * will complain about them if not, and will also take care of marking
1702                  * them NOT NULL.
1703                  */
1704                 if (!found && !cxt->isalter)
1705                         ereport(ERROR,
1706                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
1707                                          errmsg("column \"%s\" named in key does not exist", key),
1708                                          parser_errposition(cxt->pstate, constraint->location)));
1709
1710                 /* Check for PRIMARY KEY(foo, foo) */
1711                 foreach(columns, index->indexParams)
1712                 {
1713                         iparam = (IndexElem *) lfirst(columns);
1714                         if (iparam->name && strcmp(key, iparam->name) == 0)
1715                         {
1716                                 if (index->primary)
1717                                         ereport(ERROR,
1718                                                         (errcode(ERRCODE_DUPLICATE_COLUMN),
1719                                                          errmsg("column \"%s\" appears twice in primary key constraint",
1720                                                                         key),
1721                                          parser_errposition(cxt->pstate, constraint->location)));
1722                                 else
1723                                         ereport(ERROR,
1724                                                         (errcode(ERRCODE_DUPLICATE_COLUMN),
1725                                         errmsg("column \"%s\" appears twice in unique constraint",
1726                                                    key),
1727                                          parser_errposition(cxt->pstate, constraint->location)));
1728                         }
1729                 }
1730
1731                 /* OK, add it to the index definition */
1732                 iparam = makeNode(IndexElem);
1733                 iparam->name = pstrdup(key);
1734                 iparam->expr = NULL;
1735                 iparam->indexcolname = NULL;
1736                 iparam->collation = NIL;
1737                 iparam->opclass = NIL;
1738                 iparam->ordering = SORTBY_DEFAULT;
1739                 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1740                 index->indexParams = lappend(index->indexParams, iparam);
1741         }
1742
1743         return index;
1744 }
1745
1746 /*
1747  * transformFKConstraints
1748  *              handle FOREIGN KEY constraints
1749  */
1750 static void
1751 transformFKConstraints(CreateStmtContext *cxt,
1752                                            bool skipValidation, bool isAddConstraint)
1753 {
1754         ListCell   *fkclist;
1755
1756         if (cxt->fkconstraints == NIL)
1757                 return;
1758
1759         /*
1760          * If CREATE TABLE or adding a column with NULL default, we can safely
1761          * skip validation of FK constraints, and nonetheless mark them valid.
1762          * (This will override any user-supplied NOT VALID flag.)
1763          */
1764         if (skipValidation)
1765         {
1766                 foreach(fkclist, cxt->fkconstraints)
1767                 {
1768                         Constraint *constraint = (Constraint *) lfirst(fkclist);
1769
1770                         constraint->skip_validation = true;
1771                         constraint->initially_valid = true;
1772                 }
1773         }
1774
1775         /*
1776          * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1777          * CONSTRAINT command to execute after the basic command is complete. (If
1778          * called from ADD CONSTRAINT, that routine will add the FK constraints to
1779          * its own subcommand list.)
1780          *
1781          * Note: the ADD CONSTRAINT command must also execute after any index
1782          * creation commands.  Thus, this should run after
1783          * transformIndexConstraints, so that the CREATE INDEX commands are
1784          * already in cxt->alist.
1785          */
1786         if (!isAddConstraint)
1787         {
1788                 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1789
1790                 alterstmt->relation = cxt->relation;
1791                 alterstmt->cmds = NIL;
1792                 alterstmt->relkind = OBJECT_TABLE;
1793
1794                 foreach(fkclist, cxt->fkconstraints)
1795                 {
1796                         Constraint *constraint = (Constraint *) lfirst(fkclist);
1797                         AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1798
1799                         altercmd->subtype = AT_ProcessedConstraint;
1800                         altercmd->name = NULL;
1801                         altercmd->def = (Node *) constraint;
1802                         alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1803                 }
1804
1805                 cxt->alist = lappend(cxt->alist, alterstmt);
1806         }
1807 }
1808
1809 /*
1810  * transformIndexStmt - parse analysis for CREATE INDEX and ALTER TABLE
1811  *
1812  * Note: this is a no-op for an index not using either index expressions or
1813  * a predicate expression.      There are several code paths that create indexes
1814  * without bothering to call this, because they know they don't have any
1815  * such expressions to deal with.
1816  */
1817 IndexStmt *
1818 transformIndexStmt(IndexStmt *stmt, const char *queryString)
1819 {
1820         Relation        rel;
1821         ParseState *pstate;
1822         RangeTblEntry *rte;
1823         ListCell   *l;
1824
1825         /*
1826          * We must not scribble on the passed-in IndexStmt, so copy it.  (This is
1827          * overkill, but easy.)
1828          */
1829         stmt = (IndexStmt *) copyObject(stmt);
1830
1831         /*
1832          * Open the parent table with appropriate locking.      We must do this
1833          * because addRangeTableEntry() would acquire only AccessShareLock,
1834          * leaving DefineIndex() needing to do a lock upgrade with consequent risk
1835          * of deadlock.  Make sure this stays in sync with the type of lock
1836          * DefineIndex() wants. If we are being called by ALTER TABLE, we will
1837          * already hold a higher lock.
1838          */
1839         rel = heap_openrv(stmt->relation,
1840                                   (stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock));
1841
1842         /* Set up pstate */
1843         pstate = make_parsestate(NULL);
1844         pstate->p_sourcetext = queryString;
1845
1846         /*
1847          * Put the parent table into the rtable so that the expressions can refer
1848          * to its fields without qualification.
1849          */
1850         rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1851
1852         /* no to join list, yes to namespaces */
1853         addRTEtoQuery(pstate, rte, false, true, true);
1854
1855         /* take care of the where clause */
1856         if (stmt->whereClause)
1857         {
1858                 stmt->whereClause = transformWhereClause(pstate,
1859                                                                                                  stmt->whereClause,
1860                                                                                                  "WHERE");
1861                 /* we have to fix its collations too */
1862                 assign_expr_collations(pstate, stmt->whereClause);
1863         }
1864
1865         /* take care of any index expressions */
1866         foreach(l, stmt->indexParams)
1867         {
1868                 IndexElem  *ielem = (IndexElem *) lfirst(l);
1869
1870                 if (ielem->expr)
1871                 {
1872                         /* Extract preliminary index col name before transforming expr */
1873                         if (ielem->indexcolname == NULL)
1874                                 ielem->indexcolname = FigureIndexColname(ielem->expr);
1875
1876                         /* Now do parse transformation of the expression */
1877                         ielem->expr = transformExpr(pstate, ielem->expr);
1878
1879                         /* We have to fix its collations too */
1880                         assign_expr_collations(pstate, ielem->expr);
1881
1882                         /*
1883                          * We check only that the result type is legitimate; this is for
1884                          * consistency with what transformWhereClause() checks for the
1885                          * predicate.  DefineIndex() will make more checks.
1886                          */
1887                         if (expression_returns_set(ielem->expr))
1888                                 ereport(ERROR,
1889                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1890                                                  errmsg("index expression cannot return a set")));
1891                 }
1892         }
1893
1894         /*
1895          * Check that only the base rel is mentioned.
1896          */
1897         if (list_length(pstate->p_rtable) != 1)
1898                 ereport(ERROR,
1899                                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1900                                  errmsg("index expressions and predicates can refer only to the table being indexed")));
1901
1902         free_parsestate(pstate);
1903
1904         /* Close relation, but keep the lock */
1905         heap_close(rel, NoLock);
1906
1907         return stmt;
1908 }
1909
1910
1911 /*
1912  * transformRuleStmt -
1913  *        transform a CREATE RULE Statement. The action is a list of parse
1914  *        trees which is transformed into a list of query trees, and we also
1915  *        transform the WHERE clause if any.
1916  *
1917  * actions and whereClause are output parameters that receive the
1918  * transformed results.
1919  *
1920  * Note that we must not scribble on the passed-in RuleStmt, so we do
1921  * copyObject() on the actions and WHERE clause.
1922  */
1923 void
1924 transformRuleStmt(RuleStmt *stmt, const char *queryString,
1925                                   List **actions, Node **whereClause)
1926 {
1927         Relation        rel;
1928         ParseState *pstate;
1929         RangeTblEntry *oldrte;
1930         RangeTblEntry *newrte;
1931
1932         /*
1933          * To avoid deadlock, make sure the first thing we do is grab
1934          * AccessExclusiveLock on the target relation.  This will be needed by
1935          * DefineQueryRewrite(), and we don't want to grab a lesser lock
1936          * beforehand.
1937          */
1938         rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1939
1940         /* Set up pstate */
1941         pstate = make_parsestate(NULL);
1942         pstate->p_sourcetext = queryString;
1943
1944         /*
1945          * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1946          * Set up their RTEs in the main pstate for use in parsing the rule
1947          * qualification.
1948          */
1949         oldrte = addRangeTableEntryForRelation(pstate, rel,
1950                                                                                    makeAlias("old", NIL),
1951                                                                                    false, false);
1952         newrte = addRangeTableEntryForRelation(pstate, rel,
1953                                                                                    makeAlias("new", NIL),
1954                                                                                    false, false);
1955         /* Must override addRangeTableEntry's default access-check flags */
1956         oldrte->requiredPerms = 0;
1957         newrte->requiredPerms = 0;
1958
1959         /*
1960          * They must be in the namespace too for lookup purposes, but only add the
1961          * one(s) that are relevant for the current kind of rule.  In an UPDATE
1962          * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1963          * there's no need to be so picky for INSERT & DELETE.  We do not add them
1964          * to the joinlist.
1965          */
1966         switch (stmt->event)
1967         {
1968                 case CMD_SELECT:
1969                         addRTEtoQuery(pstate, oldrte, false, true, true);
1970                         break;
1971                 case CMD_UPDATE:
1972                         addRTEtoQuery(pstate, oldrte, false, true, true);
1973                         addRTEtoQuery(pstate, newrte, false, true, true);
1974                         break;
1975                 case CMD_INSERT:
1976                         addRTEtoQuery(pstate, newrte, false, true, true);
1977                         break;
1978                 case CMD_DELETE:
1979                         addRTEtoQuery(pstate, oldrte, false, true, true);
1980                         break;
1981                 default:
1982                         elog(ERROR, "unrecognized event type: %d",
1983                                  (int) stmt->event);
1984                         break;
1985         }
1986
1987         /* take care of the where clause */
1988         *whereClause = transformWhereClause(pstate,
1989                                                                           (Node *) copyObject(stmt->whereClause),
1990                                                                                 "WHERE");
1991         /* we have to fix its collations too */
1992         assign_expr_collations(pstate, *whereClause);
1993
1994         if (list_length(pstate->p_rtable) != 2)         /* naughty, naughty... */
1995                 ereport(ERROR,
1996                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1997                                  errmsg("rule WHERE condition cannot contain references to other relations")));
1998
1999         /* aggregates not allowed (but subselects are okay) */
2000         if (pstate->p_hasAggs)
2001                 ereport(ERROR,
2002                                 (errcode(ERRCODE_GROUPING_ERROR),
2003                    errmsg("cannot use aggregate function in rule WHERE condition")));
2004         if (pstate->p_hasWindowFuncs)
2005                 ereport(ERROR,
2006                                 (errcode(ERRCODE_WINDOWING_ERROR),
2007                           errmsg("cannot use window function in rule WHERE condition")));
2008
2009         /*
2010          * 'instead nothing' rules with a qualification need a query rangetable so
2011          * the rewrite handler can add the negated rule qualification to the
2012          * original query. We create a query with the new command type CMD_NOTHING
2013          * here that is treated specially by the rewrite system.
2014          */
2015         if (stmt->actions == NIL)
2016         {
2017                 Query      *nothing_qry = makeNode(Query);
2018
2019                 nothing_qry->commandType = CMD_NOTHING;
2020                 nothing_qry->rtable = pstate->p_rtable;
2021                 nothing_qry->jointree = makeFromExpr(NIL, NULL);                /* no join wanted */
2022
2023                 *actions = list_make1(nothing_qry);
2024         }
2025         else
2026         {
2027                 ListCell   *l;
2028                 List       *newactions = NIL;
2029
2030                 /*
2031                  * transform each statement, like parse_sub_analyze()
2032                  */
2033                 foreach(l, stmt->actions)
2034                 {
2035                         Node       *action = (Node *) lfirst(l);
2036                         ParseState *sub_pstate = make_parsestate(NULL);
2037                         Query      *sub_qry,
2038                                            *top_subqry;
2039                         bool            has_old,
2040                                                 has_new;
2041
2042                         /*
2043                          * Since outer ParseState isn't parent of inner, have to pass down
2044                          * the query text by hand.
2045                          */
2046                         sub_pstate->p_sourcetext = queryString;
2047
2048                         /*
2049                          * Set up OLD/NEW in the rtable for this statement.  The entries
2050                          * are added only to relnamespace, not varnamespace, because we
2051                          * don't want them to be referred to by unqualified field names
2052                          * nor "*" in the rule actions.  We decide later whether to put
2053                          * them in the joinlist.
2054                          */
2055                         oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
2056                                                                                                    makeAlias("old", NIL),
2057                                                                                                    false, false);
2058                         newrte = addRangeTableEntryForRelation(sub_pstate, rel,
2059                                                                                                    makeAlias("new", NIL),
2060                                                                                                    false, false);
2061                         oldrte->requiredPerms = 0;
2062                         newrte->requiredPerms = 0;
2063                         addRTEtoQuery(sub_pstate, oldrte, false, true, false);
2064                         addRTEtoQuery(sub_pstate, newrte, false, true, false);
2065
2066                         /* Transform the rule action statement */
2067                         top_subqry = transformStmt(sub_pstate,
2068                                                                            (Node *) copyObject(action));
2069
2070                         /*
2071                          * We cannot support utility-statement actions (eg NOTIFY) with
2072                          * nonempty rule WHERE conditions, because there's no way to make
2073                          * the utility action execute conditionally.
2074                          */
2075                         if (top_subqry->commandType == CMD_UTILITY &&
2076                                 *whereClause != NULL)
2077                                 ereport(ERROR,
2078                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2079                                                  errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
2080
2081                         /*
2082                          * If the action is INSERT...SELECT, OLD/NEW have been pushed down
2083                          * into the SELECT, and that's what we need to look at. (Ugly
2084                          * kluge ... try to fix this when we redesign querytrees.)
2085                          */
2086                         sub_qry = getInsertSelectQuery(top_subqry, NULL);
2087
2088                         /*
2089                          * If the sub_qry is a setop, we cannot attach any qualifications
2090                          * to it, because the planner won't notice them.  This could
2091                          * perhaps be relaxed someday, but for now, we may as well reject
2092                          * such a rule immediately.
2093                          */
2094                         if (sub_qry->setOperations != NULL && *whereClause != NULL)
2095                                 ereport(ERROR,
2096                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2097                                                  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2098
2099                         /*
2100                          * Validate action's use of OLD/NEW, qual too
2101                          */
2102                         has_old =
2103                                 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
2104                                 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
2105                         has_new =
2106                                 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
2107                                 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
2108
2109                         switch (stmt->event)
2110                         {
2111                                 case CMD_SELECT:
2112                                         if (has_old)
2113                                                 ereport(ERROR,
2114                                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2115                                                                  errmsg("ON SELECT rule cannot use OLD")));
2116                                         if (has_new)
2117                                                 ereport(ERROR,
2118                                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2119                                                                  errmsg("ON SELECT rule cannot use NEW")));
2120                                         break;
2121                                 case CMD_UPDATE:
2122                                         /* both are OK */
2123                                         break;
2124                                 case CMD_INSERT:
2125                                         if (has_old)
2126                                                 ereport(ERROR,
2127                                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2128                                                                  errmsg("ON INSERT rule cannot use OLD")));
2129                                         break;
2130                                 case CMD_DELETE:
2131                                         if (has_new)
2132                                                 ereport(ERROR,
2133                                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2134                                                                  errmsg("ON DELETE rule cannot use NEW")));
2135                                         break;
2136                                 default:
2137                                         elog(ERROR, "unrecognized event type: %d",
2138                                                  (int) stmt->event);
2139                                         break;
2140                         }
2141
2142                         /*
2143                          * OLD/NEW are not allowed in WITH queries, because they would
2144                          * amount to outer references for the WITH, which we disallow.
2145                          * However, they were already in the outer rangetable when we
2146                          * analyzed the query, so we have to check.
2147                          *
2148                          * Note that in the INSERT...SELECT case, we need to examine the
2149                          * CTE lists of both top_subqry and sub_qry.
2150                          *
2151                          * Note that we aren't digging into the body of the query looking
2152                          * for WITHs in nested sub-SELECTs.  A WITH down there can
2153                          * legitimately refer to OLD/NEW, because it'd be an
2154                          * indirect-correlated outer reference.
2155                          */
2156                         if (rangeTableEntry_used((Node *) top_subqry->cteList,
2157                                                                          PRS2_OLD_VARNO, 0) ||
2158                                 rangeTableEntry_used((Node *) sub_qry->cteList,
2159                                                                          PRS2_OLD_VARNO, 0))
2160                                 ereport(ERROR,
2161                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2162                                                  errmsg("cannot refer to OLD within WITH query")));
2163                         if (rangeTableEntry_used((Node *) top_subqry->cteList,
2164                                                                          PRS2_NEW_VARNO, 0) ||
2165                                 rangeTableEntry_used((Node *) sub_qry->cteList,
2166                                                                          PRS2_NEW_VARNO, 0))
2167                                 ereport(ERROR,
2168                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2169                                                  errmsg("cannot refer to NEW within WITH query")));
2170
2171                         /*
2172                          * For efficiency's sake, add OLD to the rule action's jointree
2173                          * only if it was actually referenced in the statement or qual.
2174                          *
2175                          * For INSERT, NEW is not really a relation (only a reference to
2176                          * the to-be-inserted tuple) and should never be added to the
2177                          * jointree.
2178                          *
2179                          * For UPDATE, we treat NEW as being another kind of reference to
2180                          * OLD, because it represents references to *transformed* tuples
2181                          * of the existing relation.  It would be wrong to enter NEW
2182                          * separately in the jointree, since that would cause a double
2183                          * join of the updated relation.  It's also wrong to fail to make
2184                          * a jointree entry if only NEW and not OLD is mentioned.
2185                          */
2186                         if (has_old || (has_new && stmt->event == CMD_UPDATE))
2187                         {
2188                                 /*
2189                                  * If sub_qry is a setop, manipulating its jointree will do no
2190                                  * good at all, because the jointree is dummy. (This should be
2191                                  * a can't-happen case because of prior tests.)
2192                                  */
2193                                 if (sub_qry->setOperations != NULL)
2194                                         ereport(ERROR,
2195                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2196                                                          errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2197                                 /* hack so we can use addRTEtoQuery() */
2198                                 sub_pstate->p_rtable = sub_qry->rtable;
2199                                 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
2200                                 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
2201                                 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
2202                         }
2203
2204                         newactions = lappend(newactions, top_subqry);
2205
2206                         free_parsestate(sub_pstate);
2207                 }
2208
2209                 *actions = newactions;
2210         }
2211
2212         free_parsestate(pstate);
2213
2214         /* Close relation, but keep the exclusive lock */
2215         heap_close(rel, NoLock);
2216 }
2217
2218
2219 /*
2220  * transformAlterTableStmt -
2221  *              parse analysis for ALTER TABLE
2222  *
2223  * Returns a List of utility commands to be done in sequence.  One of these
2224  * will be the transformed AlterTableStmt, but there may be additional actions
2225  * to be done before and after the actual AlterTable() call.
2226  */
2227 List *
2228 transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
2229 {
2230         Relation        rel;
2231         ParseState *pstate;
2232         CreateStmtContext cxt;
2233         List       *result;
2234         List       *save_alist;
2235         ListCell   *lcmd,
2236                            *l;
2237         List       *newcmds = NIL;
2238         bool            skipValidation = true;
2239         AlterTableCmd *newcmd;
2240         LOCKMODE        lockmode;
2241
2242         /*
2243          * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
2244          * is overkill, but easy.)
2245          */
2246         stmt = (AlterTableStmt *) copyObject(stmt);
2247
2248         /*
2249          * Determine the appropriate lock level for this list of subcommands.
2250          */
2251         lockmode = AlterTableGetLockLevel(stmt->cmds);
2252
2253         /*
2254          * Acquire appropriate lock on the target relation, which will be held
2255          * until end of transaction.  This ensures any decisions we make here
2256          * based on the state of the relation will still be good at execution. We
2257          * must get lock now because execution will later require it; taking a
2258          * lower grade lock now and trying to upgrade later risks deadlock.  Any
2259          * new commands we add after this must not upgrade the lock level
2260          * requested here.
2261          */
2262         rel = relation_openrv(stmt->relation, lockmode);
2263
2264         /* Set up pstate and CreateStmtContext */
2265         pstate = make_parsestate(NULL);
2266         pstate->p_sourcetext = queryString;
2267
2268         cxt.pstate = pstate;
2269         cxt.stmtType = "ALTER TABLE";
2270         cxt.relation = stmt->relation;
2271         cxt.rel = rel;
2272         cxt.inhRelations = NIL;
2273         cxt.isalter = true;
2274         cxt.hasoids = false;            /* need not be right */
2275         cxt.columns = NIL;
2276         cxt.ckconstraints = NIL;
2277         cxt.fkconstraints = NIL;
2278         cxt.ixconstraints = NIL;
2279         cxt.inh_indexes = NIL;
2280         cxt.blist = NIL;
2281         cxt.alist = NIL;
2282         cxt.pkey = NULL;
2283
2284         /*
2285          * The only subtypes that currently require parse transformation handling
2286          * are ADD COLUMN and ADD CONSTRAINT.  These largely re-use code from
2287          * CREATE TABLE.
2288          */
2289         foreach(lcmd, stmt->cmds)
2290         {
2291                 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2292
2293                 switch (cmd->subtype)
2294                 {
2295                         case AT_AddColumn:
2296                         case AT_AddColumnToView:
2297                                 {
2298                                         ColumnDef  *def = (ColumnDef *) cmd->def;
2299
2300                                         Assert(IsA(def, ColumnDef));
2301                                         transformColumnDefinition(&cxt, def);
2302
2303                                         /*
2304                                          * If the column has a non-null default, we can't skip
2305                                          * validation of foreign keys.
2306                                          */
2307                                         if (def->raw_default != NULL)
2308                                                 skipValidation = false;
2309
2310                                         /*
2311                                          * All constraints are processed in other ways. Remove the
2312                                          * original list
2313                                          */
2314                                         def->constraints = NIL;
2315
2316                                         newcmds = lappend(newcmds, cmd);
2317                                         break;
2318                                 }
2319                         case AT_AddConstraint:
2320
2321                                 /*
2322                                  * The original AddConstraint cmd node doesn't go to newcmds
2323                                  */
2324                                 if (IsA(cmd->def, Constraint))
2325                                 {
2326                                         transformTableConstraint(&cxt, (Constraint *) cmd->def);
2327                                         if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
2328                                                 skipValidation = false;
2329                                 }
2330                                 else
2331                                         elog(ERROR, "unrecognized node type: %d",
2332                                                  (int) nodeTag(cmd->def));
2333                                 break;
2334
2335                         case AT_ProcessedConstraint:
2336
2337                                 /*
2338                                  * Already-transformed ADD CONSTRAINT, so just make it look
2339                                  * like the standard case.
2340                                  */
2341                                 cmd->subtype = AT_AddConstraint;
2342                                 newcmds = lappend(newcmds, cmd);
2343                                 break;
2344
2345                         default:
2346                                 newcmds = lappend(newcmds, cmd);
2347                                 break;
2348                 }
2349         }
2350
2351         /*
2352          * transformIndexConstraints wants cxt.alist to contain only index
2353          * statements, so transfer anything we already have into save_alist
2354          * immediately.
2355          */
2356         save_alist = cxt.alist;
2357         cxt.alist = NIL;
2358
2359         /* Postprocess index and FK constraints */
2360         transformIndexConstraints(&cxt);
2361
2362         transformFKConstraints(&cxt, skipValidation, true);
2363
2364         /*
2365          * Push any index-creation commands into the ALTER, so that they can be
2366          * scheduled nicely by tablecmds.c.  Note that tablecmds.c assumes that
2367          * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
2368          * subcommand has already been through transformIndexStmt.
2369          */
2370         foreach(l, cxt.alist)
2371         {
2372                 IndexStmt  *idxstmt = (IndexStmt *) lfirst(l);
2373
2374                 Assert(IsA(idxstmt, IndexStmt));
2375                 idxstmt = transformIndexStmt(idxstmt, queryString);
2376                 newcmd = makeNode(AlterTableCmd);
2377                 newcmd->subtype = OidIsValid(idxstmt->indexOid) ? AT_AddIndexConstraint : AT_AddIndex;
2378                 newcmd->def = (Node *) idxstmt;
2379                 newcmds = lappend(newcmds, newcmd);
2380         }
2381         cxt.alist = NIL;
2382
2383         /* Append any CHECK or FK constraints to the commands list */
2384         foreach(l, cxt.ckconstraints)
2385         {
2386                 newcmd = makeNode(AlterTableCmd);
2387                 newcmd->subtype = AT_AddConstraint;
2388                 newcmd->def = (Node *) lfirst(l);
2389                 newcmds = lappend(newcmds, newcmd);
2390         }
2391         foreach(l, cxt.fkconstraints)
2392         {
2393                 newcmd = makeNode(AlterTableCmd);
2394                 newcmd->subtype = AT_AddConstraint;
2395                 newcmd->def = (Node *) lfirst(l);
2396                 newcmds = lappend(newcmds, newcmd);
2397         }
2398
2399         /* Close rel but keep lock */
2400         relation_close(rel, NoLock);
2401
2402         /*
2403          * Output results.
2404          */
2405         stmt->cmds = newcmds;
2406
2407         result = lappend(cxt.blist, stmt);
2408         result = list_concat(result, cxt.alist);
2409         result = list_concat(result, save_alist);
2410
2411         return result;
2412 }
2413
2414
2415 /*
2416  * Preprocess a list of column constraint clauses
2417  * to attach constraint attributes to their primary constraint nodes
2418  * and detect inconsistent/misplaced constraint attributes.
2419  *
2420  * NOTE: currently, attributes are only supported for FOREIGN KEY, UNIQUE,
2421  * EXCLUSION, and PRIMARY KEY constraints, but someday they ought to be
2422  * supported for other constraint types.
2423  */
2424 static void
2425 transformConstraintAttrs(CreateStmtContext *cxt, List *constraintList)
2426 {
2427         Constraint *lastprimarycon = NULL;
2428         bool            saw_deferrability = false;
2429         bool            saw_initially = false;
2430         ListCell   *clist;
2431
2432 #define SUPPORTS_ATTRS(node)                            \
2433         ((node) != NULL &&                                              \
2434          ((node)->contype == CONSTR_PRIMARY ||  \
2435           (node)->contype == CONSTR_UNIQUE ||   \
2436           (node)->contype == CONSTR_EXCLUSION || \
2437           (node)->contype == CONSTR_FOREIGN))
2438
2439         foreach(clist, constraintList)
2440         {
2441                 Constraint *con = (Constraint *) lfirst(clist);
2442
2443                 if (!IsA(con, Constraint))
2444                         elog(ERROR, "unrecognized node type: %d",
2445                                  (int) nodeTag(con));
2446                 switch (con->contype)
2447                 {
2448                         case CONSTR_ATTR_DEFERRABLE:
2449                                 if (!SUPPORTS_ATTRS(lastprimarycon))
2450                                         ereport(ERROR,
2451                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2452                                                          errmsg("misplaced DEFERRABLE clause"),
2453                                                          parser_errposition(cxt->pstate, con->location)));
2454                                 if (saw_deferrability)
2455                                         ereport(ERROR,
2456                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2457                                                          errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2458                                                          parser_errposition(cxt->pstate, con->location)));
2459                                 saw_deferrability = true;
2460                                 lastprimarycon->deferrable = true;
2461                                 break;
2462
2463                         case CONSTR_ATTR_NOT_DEFERRABLE:
2464                                 if (!SUPPORTS_ATTRS(lastprimarycon))
2465                                         ereport(ERROR,
2466                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2467                                                          errmsg("misplaced NOT DEFERRABLE clause"),
2468                                                          parser_errposition(cxt->pstate, con->location)));
2469                                 if (saw_deferrability)
2470                                         ereport(ERROR,
2471                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2472                                                          errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2473                                                          parser_errposition(cxt->pstate, con->location)));
2474                                 saw_deferrability = true;
2475                                 lastprimarycon->deferrable = false;
2476                                 if (saw_initially &&
2477                                         lastprimarycon->initdeferred)
2478                                         ereport(ERROR,
2479                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2480                                                          errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2481                                                          parser_errposition(cxt->pstate, con->location)));
2482                                 break;
2483
2484                         case CONSTR_ATTR_DEFERRED:
2485                                 if (!SUPPORTS_ATTRS(lastprimarycon))
2486                                         ereport(ERROR,
2487                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2488                                                          errmsg("misplaced INITIALLY DEFERRED clause"),
2489                                                          parser_errposition(cxt->pstate, con->location)));
2490                                 if (saw_initially)
2491                                         ereport(ERROR,
2492                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2493                                                          errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2494                                                          parser_errposition(cxt->pstate, con->location)));
2495                                 saw_initially = true;
2496                                 lastprimarycon->initdeferred = true;
2497
2498                                 /*
2499                                  * If only INITIALLY DEFERRED appears, assume DEFERRABLE
2500                                  */
2501                                 if (!saw_deferrability)
2502                                         lastprimarycon->deferrable = true;
2503                                 else if (!lastprimarycon->deferrable)
2504                                         ereport(ERROR,
2505                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2506                                                          errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2507                                                          parser_errposition(cxt->pstate, con->location)));
2508                                 break;
2509
2510                         case CONSTR_ATTR_IMMEDIATE:
2511                                 if (!SUPPORTS_ATTRS(lastprimarycon))
2512                                         ereport(ERROR,
2513                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2514                                                          errmsg("misplaced INITIALLY IMMEDIATE clause"),
2515                                                          parser_errposition(cxt->pstate, con->location)));
2516                                 if (saw_initially)
2517                                         ereport(ERROR,
2518                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2519                                                          errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2520                                                          parser_errposition(cxt->pstate, con->location)));
2521                                 saw_initially = true;
2522                                 lastprimarycon->initdeferred = false;
2523                                 break;
2524
2525                         default:
2526                                 /* Otherwise it's not an attribute */
2527                                 lastprimarycon = con;
2528                                 /* reset flags for new primary node */
2529                                 saw_deferrability = false;
2530                                 saw_initially = false;
2531                                 break;
2532                 }
2533         }
2534 }
2535
2536 /*
2537  * Special handling of type definition for a column
2538  */
2539 static void
2540 transformColumnType(CreateStmtContext *cxt, ColumnDef *column)
2541 {
2542         /*
2543          * All we really need to do here is verify that the type is valid,
2544          * including any collation spec that might be present.
2545          */
2546         Type            ctype = typenameType(cxt->pstate, column->typeName, NULL);
2547
2548         if (column->collClause)
2549         {
2550                 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
2551
2552                 LookupCollation(cxt->pstate,
2553                                                 column->collClause->collname,
2554                                                 column->collClause->location);
2555                 /* Complain if COLLATE is applied to an uncollatable type */
2556                 if (!OidIsValid(typtup->typcollation))
2557                         ereport(ERROR,
2558                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
2559                                          errmsg("collations are not supported by type %s",
2560                                                         format_type_be(HeapTupleGetOid(ctype))),
2561                                          parser_errposition(cxt->pstate,
2562                                                                                 column->collClause->location)));
2563         }
2564
2565         ReleaseSysCache(ctype);
2566 }
2567
2568
2569 /*
2570  * transformCreateSchemaStmt -
2571  *        analyzes the CREATE SCHEMA statement
2572  *
2573  * Split the schema element list into individual commands and place
2574  * them in the result list in an order such that there are no forward
2575  * references (e.g. GRANT to a table created later in the list). Note
2576  * that the logic we use for determining forward references is
2577  * presently quite incomplete.
2578  *
2579  * SQL92 also allows constraints to make forward references, so thumb through
2580  * the table columns and move forward references to a posterior alter-table
2581  * command.
2582  *
2583  * The result is a list of parse nodes that still need to be analyzed ---
2584  * but we can't analyze the later commands until we've executed the earlier
2585  * ones, because of possible inter-object references.
2586  *
2587  * Note: this breaks the rules a little bit by modifying schema-name fields
2588  * within passed-in structs.  However, the transformation would be the same
2589  * if done over, so it should be all right to scribble on the input to this
2590  * extent.
2591  */
2592 List *
2593 transformCreateSchemaStmt(CreateSchemaStmt *stmt)
2594 {
2595         CreateSchemaStmtContext cxt;
2596         List       *result;
2597         ListCell   *elements;
2598
2599         cxt.stmtType = "CREATE SCHEMA";
2600         cxt.schemaname = stmt->schemaname;
2601         cxt.authid = stmt->authid;
2602         cxt.sequences = NIL;
2603         cxt.tables = NIL;
2604         cxt.views = NIL;
2605         cxt.indexes = NIL;
2606         cxt.triggers = NIL;
2607         cxt.grants = NIL;
2608
2609         /*
2610          * Run through each schema element in the schema element list. Separate
2611          * statements by type, and do preliminary analysis.
2612          */
2613         foreach(elements, stmt->schemaElts)
2614         {
2615                 Node       *element = lfirst(elements);
2616
2617                 switch (nodeTag(element))
2618                 {
2619                         case T_CreateSeqStmt:
2620                                 {
2621                                         CreateSeqStmt *elp = (CreateSeqStmt *) element;
2622
2623                                         setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
2624                                         cxt.sequences = lappend(cxt.sequences, element);
2625                                 }
2626                                 break;
2627
2628                         case T_CreateStmt:
2629                                 {
2630                                         CreateStmt *elp = (CreateStmt *) element;
2631
2632                                         setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2633
2634                                         /*
2635                                          * XXX todo: deal with constraints
2636                                          */
2637                                         cxt.tables = lappend(cxt.tables, element);
2638                                 }
2639                                 break;
2640
2641                         case T_ViewStmt:
2642                                 {
2643                                         ViewStmt   *elp = (ViewStmt *) element;
2644
2645                                         setSchemaName(cxt.schemaname, &elp->view->schemaname);
2646
2647                                         /*
2648                                          * XXX todo: deal with references between views
2649                                          */
2650                                         cxt.views = lappend(cxt.views, element);
2651                                 }
2652                                 break;
2653
2654                         case T_IndexStmt:
2655                                 {
2656                                         IndexStmt  *elp = (IndexStmt *) element;
2657
2658                                         setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2659                                         cxt.indexes = lappend(cxt.indexes, element);
2660                                 }
2661                                 break;
2662
2663                         case T_CreateTrigStmt:
2664                                 {
2665                                         CreateTrigStmt *elp = (CreateTrigStmt *) element;
2666
2667                                         setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2668                                         cxt.triggers = lappend(cxt.triggers, element);
2669                                 }
2670                                 break;
2671
2672                         case T_GrantStmt:
2673                                 cxt.grants = lappend(cxt.grants, element);
2674                                 break;
2675
2676                         default:
2677                                 elog(ERROR, "unrecognized node type: %d",
2678                                          (int) nodeTag(element));
2679                 }
2680         }
2681
2682         result = NIL;
2683         result = list_concat(result, cxt.sequences);
2684         result = list_concat(result, cxt.tables);
2685         result = list_concat(result, cxt.views);
2686         result = list_concat(result, cxt.indexes);
2687         result = list_concat(result, cxt.triggers);
2688         result = list_concat(result, cxt.grants);
2689
2690         return result;
2691 }
2692
2693 /*
2694  * setSchemaName
2695  *              Set or check schema name in an element of a CREATE SCHEMA command
2696  */
2697 static void
2698 setSchemaName(char *context_schema, char **stmt_schema_name)
2699 {
2700         if (*stmt_schema_name == NULL)
2701                 *stmt_schema_name = context_schema;
2702         else if (strcmp(context_schema, *stmt_schema_name) != 0)
2703                 ereport(ERROR,
2704                                 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
2705                                  errmsg("CREATE specifies a schema (%s) "
2706                                                 "different from the one being created (%s)",
2707                                                 *stmt_schema_name, context_schema)));
2708 }