OSDN Git Service

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