OSDN Git Service

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