OSDN Git Service

Message style and spelling improvements
[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         TupleDesc       tupdesc;
849         int                     i;
850         Oid                     ofTypeId;
851
852         AssertArg(ofTypename);
853
854         tuple = typenameType(NULL, ofTypename, NULL);
855         check_of_type(tuple);
856         ofTypeId = HeapTupleGetOid(tuple);
857         ofTypename->typeOid = ofTypeId;         /* cached for later */
858
859         tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
860         for (i = 0; i < tupdesc->natts; i++)
861         {
862                 Form_pg_attribute attr = tupdesc->attrs[i];
863                 ColumnDef  *n;
864
865                 if (attr->attisdropped)
866                         continue;
867
868                 n = makeNode(ColumnDef);
869                 n->colname = pstrdup(NameStr(attr->attname));
870                 n->typeName = makeTypeNameFromOid(attr->atttypid, attr->atttypmod);
871                 n->inhcount = 0;
872                 n->is_local = true;
873                 n->is_not_null = false;
874                 n->is_from_type = true;
875                 n->storage = 0;
876                 n->raw_default = NULL;
877                 n->cooked_default = NULL;
878                 n->collClause = NULL;
879                 n->collOid = attr->attcollation;
880                 n->constraints = NIL;
881                 cxt->columns = lappend(cxt->columns, n);
882         }
883         DecrTupleDescRefCount(tupdesc);
884
885         ReleaseSysCache(tuple);
886 }
887
888 /*
889  * chooseIndexName
890  *
891  * Compute name for an index.  This must match code in indexcmds.c.
892  *
893  * XXX this is inherently broken because the indexes aren't created
894  * immediately, so we fail to resolve conflicts when the same name is
895  * derived for multiple indexes.  However, that's a reasonably uncommon
896  * situation, so we'll live with it for now.
897  */
898 static char *
899 chooseIndexName(const RangeVar *relation, IndexStmt *index_stmt)
900 {
901         Oid                     namespaceId;
902         List       *colnames;
903
904         namespaceId = RangeVarGetCreationNamespace(relation);
905         colnames = ChooseIndexColumnNames(index_stmt->indexParams);
906         return ChooseIndexName(relation->relname, namespaceId,
907                                                    colnames, index_stmt->excludeOpNames,
908                                                    index_stmt->primary, index_stmt->isconstraint);
909 }
910
911 /*
912  * Generate an IndexStmt node using information from an already existing index
913  * "source_idx".  Attribute numbers should be adjusted according to attmap.
914  */
915 static IndexStmt *
916 generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
917                                                 AttrNumber *attmap)
918 {
919         Oid                     source_relid = RelationGetRelid(source_idx);
920         Form_pg_attribute *attrs = RelationGetDescr(source_idx)->attrs;
921         HeapTuple       ht_idxrel;
922         HeapTuple       ht_idx;
923         Form_pg_class idxrelrec;
924         Form_pg_index idxrec;
925         Form_pg_am      amrec;
926         oidvector  *indcollation;
927         oidvector  *indclass;
928         IndexStmt  *index;
929         List       *indexprs;
930         ListCell   *indexpr_item;
931         Oid                     indrelid;
932         int                     keyno;
933         Oid                     keycoltype;
934         Datum           datum;
935         bool            isnull;
936
937         /*
938          * Fetch pg_class tuple of source index.  We can't use the copy in the
939          * relcache entry because it doesn't include optional fields.
940          */
941         ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
942         if (!HeapTupleIsValid(ht_idxrel))
943                 elog(ERROR, "cache lookup failed for relation %u", source_relid);
944         idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
945
946         /* Fetch pg_index tuple for source index from relcache entry */
947         ht_idx = source_idx->rd_indextuple;
948         idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
949         indrelid = idxrec->indrelid;
950
951         /* Fetch pg_am tuple for source index from relcache entry */
952         amrec = source_idx->rd_am;
953
954         /* Extract indcollation from the pg_index tuple */
955         datum = SysCacheGetAttr(INDEXRELID, ht_idx,
956                                                         Anum_pg_index_indcollation, &isnull);
957         Assert(!isnull);
958         indcollation = (oidvector *) DatumGetPointer(datum);
959
960         /* Extract indclass from the pg_index tuple */
961         datum = SysCacheGetAttr(INDEXRELID, ht_idx,
962                                                         Anum_pg_index_indclass, &isnull);
963         Assert(!isnull);
964         indclass = (oidvector *) DatumGetPointer(datum);
965
966         /* Begin building the IndexStmt */
967         index = makeNode(IndexStmt);
968         index->relation = cxt->relation;
969         index->accessMethod = pstrdup(NameStr(amrec->amname));
970         if (OidIsValid(idxrelrec->reltablespace))
971                 index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
972         else
973                 index->tableSpace = NULL;
974         index->indexOid = InvalidOid;
975         index->unique = idxrec->indisunique;
976         index->primary = idxrec->indisprimary;
977         index->concurrent = false;
978
979         /*
980          * We don't try to preserve the name of the source index; instead, just
981          * let DefineIndex() choose a reasonable name.
982          */
983         index->idxname = NULL;
984
985         /*
986          * If the index is marked PRIMARY or has an exclusion condition, it's
987          * certainly from a constraint; else, if it's not marked UNIQUE, it
988          * certainly isn't.  If it is or might be from a constraint, we have to
989          * fetch the pg_constraint record.
990          */
991         if (index->primary || index->unique || idxrec->indisexclusion)
992         {
993                 Oid                     constraintId = get_index_constraint(source_relid);
994
995                 if (OidIsValid(constraintId))
996                 {
997                         HeapTuple       ht_constr;
998                         Form_pg_constraint conrec;
999
1000                         ht_constr = SearchSysCache1(CONSTROID,
1001                                                                                 ObjectIdGetDatum(constraintId));
1002                         if (!HeapTupleIsValid(ht_constr))
1003                                 elog(ERROR, "cache lookup failed for constraint %u",
1004                                          constraintId);
1005                         conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
1006
1007                         index->isconstraint = true;
1008                         index->deferrable = conrec->condeferrable;
1009                         index->initdeferred = conrec->condeferred;
1010
1011                         /* If it's an exclusion constraint, we need the operator names */
1012                         if (idxrec->indisexclusion)
1013                         {
1014                                 Datum      *elems;
1015                                 int                     nElems;
1016                                 int                     i;
1017
1018                                 Assert(conrec->contype == CONSTRAINT_EXCLUSION);
1019                                 /* Extract operator OIDs from the pg_constraint tuple */
1020                                 datum = SysCacheGetAttr(CONSTROID, ht_constr,
1021                                                                                 Anum_pg_constraint_conexclop,
1022                                                                                 &isnull);
1023                                 if (isnull)
1024                                         elog(ERROR, "null conexclop for constraint %u",
1025                                                  constraintId);
1026
1027                                 deconstruct_array(DatumGetArrayTypeP(datum),
1028                                                                   OIDOID, sizeof(Oid), true, 'i',
1029                                                                   &elems, NULL, &nElems);
1030
1031                                 for (i = 0; i < nElems; i++)
1032                                 {
1033                                         Oid                     operid = DatumGetObjectId(elems[i]);
1034                                         HeapTuple       opertup;
1035                                         Form_pg_operator operform;
1036                                         char       *oprname;
1037                                         char       *nspname;
1038                                         List       *namelist;
1039
1040                                         opertup = SearchSysCache1(OPEROID,
1041                                                                                           ObjectIdGetDatum(operid));
1042                                         if (!HeapTupleIsValid(opertup))
1043                                                 elog(ERROR, "cache lookup failed for operator %u",
1044                                                          operid);
1045                                         operform = (Form_pg_operator) GETSTRUCT(opertup);
1046                                         oprname = pstrdup(NameStr(operform->oprname));
1047                                         /* For simplicity we always schema-qualify the op name */
1048                                         nspname = get_namespace_name(operform->oprnamespace);
1049                                         namelist = list_make2(makeString(nspname),
1050                                                                                   makeString(oprname));
1051                                         index->excludeOpNames = lappend(index->excludeOpNames,
1052                                                                                                         namelist);
1053                                         ReleaseSysCache(opertup);
1054                                 }
1055                         }
1056
1057                         ReleaseSysCache(ht_constr);
1058                 }
1059                 else
1060                         index->isconstraint = false;
1061         }
1062         else
1063                 index->isconstraint = false;
1064
1065         /* Get the index expressions, if any */
1066         datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1067                                                         Anum_pg_index_indexprs, &isnull);
1068         if (!isnull)
1069         {
1070                 char       *exprsString;
1071
1072                 exprsString = TextDatumGetCString(datum);
1073                 indexprs = (List *) stringToNode(exprsString);
1074         }
1075         else
1076                 indexprs = NIL;
1077
1078         /* Build the list of IndexElem */
1079         index->indexParams = NIL;
1080
1081         indexpr_item = list_head(indexprs);
1082         for (keyno = 0; keyno < idxrec->indnatts; keyno++)
1083         {
1084                 IndexElem  *iparam;
1085                 AttrNumber      attnum = idxrec->indkey.values[keyno];
1086                 int16           opt = source_idx->rd_indoption[keyno];
1087
1088                 iparam = makeNode(IndexElem);
1089
1090                 if (AttributeNumberIsValid(attnum))
1091                 {
1092                         /* Simple index column */
1093                         char       *attname;
1094
1095                         attname = get_relid_attribute_name(indrelid, attnum);
1096                         keycoltype = get_atttype(indrelid, attnum);
1097
1098                         iparam->name = attname;
1099                         iparam->expr = NULL;
1100                 }
1101                 else
1102                 {
1103                         /* Expressional index */
1104                         Node       *indexkey;
1105
1106                         if (indexpr_item == NULL)
1107                                 elog(ERROR, "too few entries in indexprs list");
1108                         indexkey = (Node *) lfirst(indexpr_item);
1109                         indexpr_item = lnext(indexpr_item);
1110
1111                         /* OK to modify indexkey since we are working on a private copy */
1112                         change_varattnos_of_a_node(indexkey, attmap);
1113
1114                         iparam->name = NULL;
1115                         iparam->expr = indexkey;
1116
1117                         keycoltype = exprType(indexkey);
1118                 }
1119
1120                 /* Copy the original index column name */
1121                 iparam->indexcolname = pstrdup(NameStr(attrs[keyno]->attname));
1122
1123                 /* Add the collation name, if non-default */
1124                 iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
1125
1126                 /* Add the operator class name, if non-default */
1127                 iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1128
1129                 iparam->ordering = SORTBY_DEFAULT;
1130                 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1131
1132                 /* Adjust options if necessary */
1133                 if (amrec->amcanorder)
1134                 {
1135                         /*
1136                          * If it supports sort ordering, copy DESC and NULLS opts. Don't
1137                          * set non-default settings unnecessarily, though, so as to
1138                          * improve the chance of recognizing equivalence to constraint
1139                          * indexes.
1140                          */
1141                         if (opt & INDOPTION_DESC)
1142                         {
1143                                 iparam->ordering = SORTBY_DESC;
1144                                 if ((opt & INDOPTION_NULLS_FIRST) == 0)
1145                                         iparam->nulls_ordering = SORTBY_NULLS_LAST;
1146                         }
1147                         else
1148                         {
1149                                 if (opt & INDOPTION_NULLS_FIRST)
1150                                         iparam->nulls_ordering = SORTBY_NULLS_FIRST;
1151                         }
1152                 }
1153
1154                 index->indexParams = lappend(index->indexParams, iparam);
1155         }
1156
1157         /* Copy reloptions if any */
1158         datum = SysCacheGetAttr(RELOID, ht_idxrel,
1159                                                         Anum_pg_class_reloptions, &isnull);
1160         if (!isnull)
1161                 index->options = untransformRelOptions(datum);
1162
1163         /* If it's a partial index, decompile and append the predicate */
1164         datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1165                                                         Anum_pg_index_indpred, &isnull);
1166         if (!isnull)
1167         {
1168                 char       *pred_str;
1169
1170                 /* Convert text string to node tree */
1171                 pred_str = TextDatumGetCString(datum);
1172                 index->whereClause = (Node *) stringToNode(pred_str);
1173                 /* Adjust attribute numbers */
1174                 change_varattnos_of_a_node(index->whereClause, attmap);
1175         }
1176
1177         /* Clean up */
1178         ReleaseSysCache(ht_idxrel);
1179
1180         return index;
1181 }
1182
1183 /*
1184  * get_collation                - fetch qualified name of a collation
1185  *
1186  * If collation is InvalidOid or is the default for the given actual_datatype,
1187  * then the return value is NIL.
1188  */
1189 static List *
1190 get_collation(Oid collation, Oid actual_datatype)
1191 {
1192         List       *result;
1193         HeapTuple       ht_coll;
1194         Form_pg_collation coll_rec;
1195         char       *nsp_name;
1196         char       *coll_name;
1197
1198         if (!OidIsValid(collation))
1199                 return NIL;                             /* easy case */
1200         if (collation == get_typcollation(actual_datatype))
1201                 return NIL;                             /* just let it default */
1202
1203         ht_coll = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
1204         if (!HeapTupleIsValid(ht_coll))
1205                 elog(ERROR, "cache lookup failed for collation %u", collation);
1206         coll_rec = (Form_pg_collation) GETSTRUCT(ht_coll);
1207
1208         /* For simplicity, we always schema-qualify the name */
1209         nsp_name = get_namespace_name(coll_rec->collnamespace);
1210         coll_name = pstrdup(NameStr(coll_rec->collname));
1211         result = list_make2(makeString(nsp_name), makeString(coll_name));
1212
1213         ReleaseSysCache(ht_coll);
1214         return result;
1215 }
1216
1217 /*
1218  * get_opclass                  - fetch qualified name of an index operator class
1219  *
1220  * If the opclass is the default for the given actual_datatype, then
1221  * the return value is NIL.
1222  */
1223 static List *
1224 get_opclass(Oid opclass, Oid actual_datatype)
1225 {
1226         List       *result = NIL;
1227         HeapTuple       ht_opc;
1228         Form_pg_opclass opc_rec;
1229
1230         ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1231         if (!HeapTupleIsValid(ht_opc))
1232                 elog(ERROR, "cache lookup failed for opclass %u", opclass);
1233         opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
1234
1235         if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
1236         {
1237                 /* For simplicity, we always schema-qualify the name */
1238                 char       *nsp_name = get_namespace_name(opc_rec->opcnamespace);
1239                 char       *opc_name = pstrdup(NameStr(opc_rec->opcname));
1240
1241                 result = list_make2(makeString(nsp_name), makeString(opc_name));
1242         }
1243
1244         ReleaseSysCache(ht_opc);
1245         return result;
1246 }
1247
1248
1249 /*
1250  * transformIndexConstraints
1251  *              Handle UNIQUE, PRIMARY KEY, EXCLUDE constraints, which create indexes.
1252  *              We also merge in any index definitions arising from
1253  *              LIKE ... INCLUDING INDEXES.
1254  */
1255 static void
1256 transformIndexConstraints(CreateStmtContext *cxt)
1257 {
1258         IndexStmt  *index;
1259         List       *indexlist = NIL;
1260         ListCell   *lc;
1261
1262         /*
1263          * Run through the constraints that need to generate an index. For PRIMARY
1264          * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
1265          * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
1266          * NULL.
1267          */
1268         foreach(lc, cxt->ixconstraints)
1269         {
1270                 Constraint *constraint = (Constraint *) lfirst(lc);
1271
1272                 Assert(IsA(constraint, Constraint));
1273                 Assert(constraint->contype == CONSTR_PRIMARY ||
1274                            constraint->contype == CONSTR_UNIQUE ||
1275                            constraint->contype == CONSTR_EXCLUSION);
1276
1277                 index = transformIndexConstraint(constraint, cxt);
1278
1279                 indexlist = lappend(indexlist, index);
1280         }
1281
1282         /* Add in any indexes defined by LIKE ... INCLUDING INDEXES */
1283         foreach(lc, cxt->inh_indexes)
1284         {
1285                 index = (IndexStmt *) lfirst(lc);
1286
1287                 if (index->primary)
1288                 {
1289                         if (cxt->pkey != NULL)
1290                                 ereport(ERROR,
1291                                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1292                                                  errmsg("multiple primary keys for table \"%s\" are not allowed",
1293                                                                 cxt->relation->relname)));
1294                         cxt->pkey = index;
1295                 }
1296
1297                 indexlist = lappend(indexlist, index);
1298         }
1299
1300         /*
1301          * Scan the index list and remove any redundant index specifications. This
1302          * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1303          * strict reading of SQL92 would suggest raising an error instead, but
1304          * that strikes me as too anal-retentive. - tgl 2001-02-14
1305          *
1306          * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1307          * pre-existing indexes, too.
1308          */
1309         Assert(cxt->alist == NIL);
1310         if (cxt->pkey != NULL)
1311         {
1312                 /* Make sure we keep the PKEY index in preference to others... */
1313                 cxt->alist = list_make1(cxt->pkey);
1314         }
1315
1316         foreach(lc, indexlist)
1317         {
1318                 bool            keep = true;
1319                 ListCell   *k;
1320
1321                 index = lfirst(lc);
1322
1323                 /* if it's pkey, it's already in cxt->alist */
1324                 if (index == cxt->pkey)
1325                         continue;
1326
1327                 foreach(k, cxt->alist)
1328                 {
1329                         IndexStmt  *priorindex = lfirst(k);
1330
1331                         if (equal(index->indexParams, priorindex->indexParams) &&
1332                                 equal(index->whereClause, priorindex->whereClause) &&
1333                                 equal(index->excludeOpNames, priorindex->excludeOpNames) &&
1334                                 strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
1335                                 index->deferrable == priorindex->deferrable &&
1336                                 index->initdeferred == priorindex->initdeferred)
1337                         {
1338                                 priorindex->unique |= index->unique;
1339
1340                                 /*
1341                                  * If the prior index is as yet unnamed, and this one is
1342                                  * named, then transfer the name to the prior index. This
1343                                  * ensures that if we have named and unnamed constraints,
1344                                  * we'll use (at least one of) the names for the index.
1345                                  */
1346                                 if (priorindex->idxname == NULL)
1347                                         priorindex->idxname = index->idxname;
1348                                 keep = false;
1349                                 break;
1350                         }
1351                 }
1352
1353                 if (keep)
1354                         cxt->alist = lappend(cxt->alist, index);
1355         }
1356 }
1357
1358 /*
1359  * transformIndexConstraint
1360  *              Transform one UNIQUE, PRIMARY KEY, or EXCLUDE constraint for
1361  *              transformIndexConstraints.
1362  */
1363 static IndexStmt *
1364 transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
1365 {
1366         IndexStmt  *index;
1367         ListCell   *lc;
1368
1369         index = makeNode(IndexStmt);
1370
1371         index->unique = (constraint->contype != CONSTR_EXCLUSION);
1372         index->primary = (constraint->contype == CONSTR_PRIMARY);
1373         if (index->primary)
1374         {
1375                 if (cxt->pkey != NULL)
1376                         ereport(ERROR,
1377                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1378                          errmsg("multiple primary keys for table \"%s\" are not allowed",
1379                                         cxt->relation->relname),
1380                                          parser_errposition(cxt->pstate, constraint->location)));
1381                 cxt->pkey = index;
1382
1383                 /*
1384                  * In ALTER TABLE case, a primary index might already exist, but
1385                  * DefineIndex will check for it.
1386                  */
1387         }
1388         index->isconstraint = true;
1389         index->deferrable = constraint->deferrable;
1390         index->initdeferred = constraint->initdeferred;
1391
1392         if (constraint->conname != NULL)
1393                 index->idxname = pstrdup(constraint->conname);
1394         else
1395                 index->idxname = NULL;  /* DefineIndex will choose name */
1396
1397         index->relation = cxt->relation;
1398         index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
1399         index->options = constraint->options;
1400         index->tableSpace = constraint->indexspace;
1401         index->whereClause = constraint->where_clause;
1402         index->indexParams = NIL;
1403         index->excludeOpNames = NIL;
1404         index->indexOid = InvalidOid;
1405         index->concurrent = false;
1406
1407         /*
1408          * If it's ALTER TABLE ADD CONSTRAINT USING INDEX, look up the index and
1409          * verify it's usable, then extract the implied column name list.  (We
1410          * will not actually need the column name list at runtime, but we need it
1411          * now to check for duplicate column entries below.)
1412          */
1413         if (constraint->indexname != NULL)
1414         {
1415                 char       *index_name = constraint->indexname;
1416                 Relation        heap_rel = cxt->rel;
1417                 Oid                     index_oid;
1418                 Relation        index_rel;
1419                 Form_pg_index index_form;
1420                 oidvector  *indclass;
1421                 Datum           indclassDatum;
1422                 bool            isnull;
1423                 int                     i;
1424
1425                 /* Grammar should not allow this with explicit column list */
1426                 Assert(constraint->keys == NIL);
1427
1428                 /* Grammar should only allow PRIMARY and UNIQUE constraints */
1429                 Assert(constraint->contype == CONSTR_PRIMARY ||
1430                            constraint->contype == CONSTR_UNIQUE);
1431
1432                 /* Must be ALTER, not CREATE, but grammar doesn't enforce that */
1433                 if (!cxt->isalter)
1434                         ereport(ERROR,
1435                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1436                                          errmsg("cannot use an existing index in CREATE TABLE"),
1437                                          parser_errposition(cxt->pstate, constraint->location)));
1438
1439                 /* Look for the index in the same schema as the table */
1440                 index_oid = get_relname_relid(index_name, RelationGetNamespace(heap_rel));
1441
1442                 if (!OidIsValid(index_oid))
1443                         ereport(ERROR,
1444                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
1445                                          errmsg("index \"%s\" does not exist", index_name),
1446                                          parser_errposition(cxt->pstate, constraint->location)));
1447
1448                 /* Open the index (this will throw an error if it is not an index) */
1449                 index_rel = index_open(index_oid, AccessShareLock);
1450                 index_form = index_rel->rd_index;
1451
1452                 /* Check that it does not have an associated constraint already */
1453                 if (OidIsValid(get_index_constraint(index_oid)))
1454                         ereport(ERROR,
1455                                         (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1456                            errmsg("index \"%s\" is already associated with a constraint",
1457                                           index_name),
1458                                          parser_errposition(cxt->pstate, constraint->location)));
1459
1460                 /* Perform validity checks on the index */
1461                 if (index_form->indrelid != RelationGetRelid(heap_rel))
1462                         ereport(ERROR,
1463                                         (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1464                                          errmsg("index \"%s\" does not belong to table \"%s\"",
1465                                                         index_name, RelationGetRelationName(heap_rel)),
1466                                          parser_errposition(cxt->pstate, constraint->location)));
1467
1468                 if (!index_form->indisvalid)
1469                         ereport(ERROR,
1470                                         (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1471                                          errmsg("index \"%s\" is not valid", index_name),
1472                                          parser_errposition(cxt->pstate, constraint->location)));
1473
1474                 if (!index_form->indisready)
1475                         ereport(ERROR,
1476                                         (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1477                                          errmsg("index \"%s\" is not ready", index_name),
1478                                          parser_errposition(cxt->pstate, constraint->location)));
1479
1480                 if (!index_form->indisunique)
1481                         ereport(ERROR,
1482                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1483                                          errmsg("\"%s\" is not a unique index", index_name),
1484                                          errdetail("Cannot create a primary key or unique constraint using such an index."),
1485                                          parser_errposition(cxt->pstate, constraint->location)));
1486
1487                 if (RelationGetIndexExpressions(index_rel) != NIL)
1488                         ereport(ERROR,
1489                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1490                                          errmsg("index \"%s\" contains expressions", index_name),
1491                                          errdetail("Cannot create a primary key or unique constraint using such an index."),
1492                                          parser_errposition(cxt->pstate, constraint->location)));
1493
1494                 if (RelationGetIndexPredicate(index_rel) != NIL)
1495                         ereport(ERROR,
1496                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1497                                          errmsg("\"%s\" is a partial index", index_name),
1498                                          errdetail("Cannot create a primary key or unique constraint using such an index."),
1499                                          parser_errposition(cxt->pstate, constraint->location)));
1500
1501                 /*
1502                  * It's probably unsafe to change a deferred index to non-deferred. (A
1503                  * non-constraint index couldn't be deferred anyway, so this case
1504                  * should never occur; no need to sweat, but let's check it.)
1505                  */
1506                 if (!index_form->indimmediate && !constraint->deferrable)
1507                         ereport(ERROR,
1508                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1509                                          errmsg("\"%s\" is a deferrable index", index_name),
1510                                          errdetail("Cannot create a non-deferrable constraint using a deferrable index."),
1511                                          parser_errposition(cxt->pstate, constraint->location)));
1512
1513                 /*
1514                  * Insist on it being a btree.  That's the only kind that supports
1515                  * uniqueness at the moment anyway; but we must have an index that
1516                  * exactly matches what you'd get from plain ADD CONSTRAINT syntax,
1517                  * else dump and reload will produce a different index (breaking
1518                  * pg_upgrade in particular).
1519                  */
1520                 if (index_rel->rd_rel->relam != get_am_oid(DEFAULT_INDEX_TYPE, false))
1521                         ereport(ERROR,
1522                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1523                                          errmsg("index \"%s\" is not a b-tree", index_name),
1524                                          parser_errposition(cxt->pstate, constraint->location)));
1525
1526                 /* Must get indclass the hard way */
1527                 indclassDatum = SysCacheGetAttr(INDEXRELID, index_rel->rd_indextuple,
1528                                                                                 Anum_pg_index_indclass, &isnull);
1529                 Assert(!isnull);
1530                 indclass = (oidvector *) DatumGetPointer(indclassDatum);
1531
1532                 for (i = 0; i < index_form->indnatts; i++)
1533                 {
1534                         int2            attnum = index_form->indkey.values[i];
1535                         Form_pg_attribute attform;
1536                         char       *attname;
1537                         Oid                     defopclass;
1538
1539                         /*
1540                          * We shouldn't see attnum == 0 here, since we already rejected
1541                          * expression indexes.  If we do, SystemAttributeDefinition will
1542                          * throw an error.
1543                          */
1544                         if (attnum > 0)
1545                         {
1546                                 Assert(attnum <= heap_rel->rd_att->natts);
1547                                 attform = heap_rel->rd_att->attrs[attnum - 1];
1548                         }
1549                         else
1550                                 attform = SystemAttributeDefinition(attnum,
1551                                                                                            heap_rel->rd_rel->relhasoids);
1552                         attname = pstrdup(NameStr(attform->attname));
1553
1554                         /*
1555                          * Insist on default opclass and sort options.  While the index
1556                          * would still work as a constraint with non-default settings, it
1557                          * might not provide exactly the same uniqueness semantics as
1558                          * you'd get from a normally-created constraint; and there's also
1559                          * the dump/reload problem mentioned above.
1560                          */
1561                         defopclass = GetDefaultOpClass(attform->atttypid,
1562                                                                                    index_rel->rd_rel->relam);
1563                         if (indclass->values[i] != defopclass ||
1564                                 index_rel->rd_indoption[i] != 0)
1565                                 ereport(ERROR,
1566                                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1567                                                  errmsg("index \"%s\" does not have default sorting behavior", index_name),
1568                                                  errdetail("Cannot create a primary key or unique constraint using such an index."),
1569                                          parser_errposition(cxt->pstate, constraint->location)));
1570
1571                         constraint->keys = lappend(constraint->keys, makeString(attname));
1572                 }
1573
1574                 /* Close the index relation but keep the lock */
1575                 relation_close(index_rel, NoLock);
1576
1577                 index->indexOid = index_oid;
1578         }
1579
1580         /*
1581          * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
1582          * IndexElems and operator names.  We have to break that apart into
1583          * separate lists.
1584          */
1585         if (constraint->contype == CONSTR_EXCLUSION)
1586         {
1587                 foreach(lc, constraint->exclusions)
1588                 {
1589                         List       *pair = (List *) lfirst(lc);
1590                         IndexElem  *elem;
1591                         List       *opname;
1592
1593                         Assert(list_length(pair) == 2);
1594                         elem = (IndexElem *) linitial(pair);
1595                         Assert(IsA(elem, IndexElem));
1596                         opname = (List *) lsecond(pair);
1597                         Assert(IsA(opname, List));
1598
1599                         index->indexParams = lappend(index->indexParams, elem);
1600                         index->excludeOpNames = lappend(index->excludeOpNames, opname);
1601                 }
1602
1603                 return index;
1604         }
1605
1606         /*
1607          * For UNIQUE and PRIMARY KEY, we just have a list of column names.
1608          *
1609          * Make sure referenced keys exist.  If we are making a PRIMARY KEY index,
1610          * also make sure they are NOT NULL, if possible. (Although we could leave
1611          * it to DefineIndex to mark the columns NOT NULL, it's more efficient to
1612          * get it right the first time.)
1613          */
1614         foreach(lc, constraint->keys)
1615         {
1616                 char       *key = strVal(lfirst(lc));
1617                 bool            found = false;
1618                 ColumnDef  *column = NULL;
1619                 ListCell   *columns;
1620                 IndexElem  *iparam;
1621
1622                 foreach(columns, cxt->columns)
1623                 {
1624                         column = (ColumnDef *) lfirst(columns);
1625                         Assert(IsA(column, ColumnDef));
1626                         if (strcmp(column->colname, key) == 0)
1627                         {
1628                                 found = true;
1629                                 break;
1630                         }
1631                 }
1632                 if (found)
1633                 {
1634                         /* found column in the new table; force it to be NOT NULL */
1635                         if (constraint->contype == CONSTR_PRIMARY)
1636                                 column->is_not_null = TRUE;
1637                 }
1638                 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1639                 {
1640                         /*
1641                          * column will be a system column in the new table, so accept it.
1642                          * System columns can't ever be null, so no need to worry about
1643                          * PRIMARY/NOT NULL constraint.
1644                          */
1645                         found = true;
1646                 }
1647                 else if (cxt->inhRelations)
1648                 {
1649                         /* try inherited tables */
1650                         ListCell   *inher;
1651
1652                         foreach(inher, cxt->inhRelations)
1653                         {
1654                                 RangeVar   *inh = (RangeVar *) lfirst(inher);
1655                                 Relation        rel;
1656                                 int                     count;
1657
1658                                 Assert(IsA(inh, RangeVar));
1659                                 rel = heap_openrv(inh, AccessShareLock);
1660                                 if (rel->rd_rel->relkind != RELKIND_RELATION)
1661                                         ereport(ERROR,
1662                                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1663                                                    errmsg("inherited relation \"%s\" is not a table",
1664                                                                   inh->relname)));
1665                                 for (count = 0; count < rel->rd_att->natts; count++)
1666                                 {
1667                                         Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1668                                         char       *inhname = NameStr(inhattr->attname);
1669
1670                                         if (inhattr->attisdropped)
1671                                                 continue;
1672                                         if (strcmp(key, inhname) == 0)
1673                                         {
1674                                                 found = true;
1675
1676                                                 /*
1677                                                  * We currently have no easy way to force an inherited
1678                                                  * column to be NOT NULL at creation, if its parent
1679                                                  * wasn't so already. We leave it to DefineIndex to
1680                                                  * fix things up in this case.
1681                                                  */
1682                                                 break;
1683                                         }
1684                                 }
1685                                 heap_close(rel, NoLock);
1686                                 if (found)
1687                                         break;
1688                         }
1689                 }
1690
1691                 /*
1692                  * In the ALTER TABLE case, don't complain about index keys not
1693                  * created in the command; they may well exist already. DefineIndex
1694                  * will complain about them if not, and will also take care of marking
1695                  * them NOT NULL.
1696                  */
1697                 if (!found && !cxt->isalter)
1698                         ereport(ERROR,
1699                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
1700                                          errmsg("column \"%s\" named in key does not exist", key),
1701                                          parser_errposition(cxt->pstate, constraint->location)));
1702
1703                 /* Check for PRIMARY KEY(foo, foo) */
1704                 foreach(columns, index->indexParams)
1705                 {
1706                         iparam = (IndexElem *) lfirst(columns);
1707                         if (iparam->name && strcmp(key, iparam->name) == 0)
1708                         {
1709                                 if (index->primary)
1710                                         ereport(ERROR,
1711                                                         (errcode(ERRCODE_DUPLICATE_COLUMN),
1712                                                          errmsg("column \"%s\" appears twice in primary key constraint",
1713                                                                         key),
1714                                          parser_errposition(cxt->pstate, constraint->location)));
1715                                 else
1716                                         ereport(ERROR,
1717                                                         (errcode(ERRCODE_DUPLICATE_COLUMN),
1718                                         errmsg("column \"%s\" appears twice in unique constraint",
1719                                                    key),
1720                                          parser_errposition(cxt->pstate, constraint->location)));
1721                         }
1722                 }
1723
1724                 /* OK, add it to the index definition */
1725                 iparam = makeNode(IndexElem);
1726                 iparam->name = pstrdup(key);
1727                 iparam->expr = NULL;
1728                 iparam->indexcolname = NULL;
1729                 iparam->collation = NIL;
1730                 iparam->opclass = NIL;
1731                 iparam->ordering = SORTBY_DEFAULT;
1732                 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1733                 index->indexParams = lappend(index->indexParams, iparam);
1734         }
1735
1736         return index;
1737 }
1738
1739 /*
1740  * transformFKConstraints
1741  *              handle FOREIGN KEY constraints
1742  */
1743 static void
1744 transformFKConstraints(CreateStmtContext *cxt,
1745                                            bool skipValidation, bool isAddConstraint)
1746 {
1747         ListCell   *fkclist;
1748
1749         if (cxt->fkconstraints == NIL)
1750                 return;
1751
1752         /*
1753          * If CREATE TABLE or adding a column with NULL default, we can safely
1754          * skip validation of FK constraints, and nonetheless mark them valid.
1755          * (This will override any user-supplied NOT VALID flag.)
1756          */
1757         if (skipValidation)
1758         {
1759                 foreach(fkclist, cxt->fkconstraints)
1760                 {
1761                         Constraint *constraint = (Constraint *) lfirst(fkclist);
1762
1763                         constraint->skip_validation = true;
1764                         constraint->initially_valid = true;
1765                 }
1766         }
1767
1768         /*
1769          * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1770          * CONSTRAINT command to execute after the basic command is complete. (If
1771          * called from ADD CONSTRAINT, that routine will add the FK constraints to
1772          * its own subcommand list.)
1773          *
1774          * Note: the ADD CONSTRAINT command must also execute after any index
1775          * creation commands.  Thus, this should run after
1776          * transformIndexConstraints, so that the CREATE INDEX commands are
1777          * already in cxt->alist.
1778          */
1779         if (!isAddConstraint)
1780         {
1781                 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1782
1783                 alterstmt->relation = cxt->relation;
1784                 alterstmt->cmds = NIL;
1785                 alterstmt->relkind = OBJECT_TABLE;
1786
1787                 foreach(fkclist, cxt->fkconstraints)
1788                 {
1789                         Constraint *constraint = (Constraint *) lfirst(fkclist);
1790                         AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1791
1792                         altercmd->subtype = AT_ProcessedConstraint;
1793                         altercmd->name = NULL;
1794                         altercmd->def = (Node *) constraint;
1795                         alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1796                 }
1797
1798                 cxt->alist = lappend(cxt->alist, alterstmt);
1799         }
1800 }
1801
1802 /*
1803  * transformIndexStmt - parse analysis for CREATE INDEX and ALTER TABLE
1804  *
1805  * Note: this is a no-op for an index not using either index expressions or
1806  * a predicate expression.      There are several code paths that create indexes
1807  * without bothering to call this, because they know they don't have any
1808  * such expressions to deal with.
1809  */
1810 IndexStmt *
1811 transformIndexStmt(IndexStmt *stmt, const char *queryString)
1812 {
1813         Relation        rel;
1814         ParseState *pstate;
1815         RangeTblEntry *rte;
1816         ListCell   *l;
1817
1818         /*
1819          * We must not scribble on the passed-in IndexStmt, so copy it.  (This is
1820          * overkill, but easy.)
1821          */
1822         stmt = (IndexStmt *) copyObject(stmt);
1823
1824         /*
1825          * Open the parent table with appropriate locking.      We must do this
1826          * because addRangeTableEntry() would acquire only AccessShareLock,
1827          * leaving DefineIndex() needing to do a lock upgrade with consequent risk
1828          * of deadlock.  Make sure this stays in sync with the type of lock
1829          * DefineIndex() wants. If we are being called by ALTER TABLE, we will
1830          * already hold a higher lock.
1831          */
1832         rel = heap_openrv(stmt->relation,
1833                                   (stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock));
1834
1835         /* Set up pstate */
1836         pstate = make_parsestate(NULL);
1837         pstate->p_sourcetext = queryString;
1838
1839         /*
1840          * Put the parent table into the rtable so that the expressions can refer
1841          * to its fields without qualification.
1842          */
1843         rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1844
1845         /* no to join list, yes to namespaces */
1846         addRTEtoQuery(pstate, rte, false, true, true);
1847
1848         /* take care of the where clause */
1849         if (stmt->whereClause)
1850         {
1851                 stmt->whereClause = transformWhereClause(pstate,
1852                                                                                                  stmt->whereClause,
1853                                                                                                  "WHERE");
1854                 /* we have to fix its collations too */
1855                 assign_expr_collations(pstate, stmt->whereClause);
1856         }
1857
1858         /* take care of any index expressions */
1859         foreach(l, stmt->indexParams)
1860         {
1861                 IndexElem  *ielem = (IndexElem *) lfirst(l);
1862
1863                 if (ielem->expr)
1864                 {
1865                         /* Extract preliminary index col name before transforming expr */
1866                         if (ielem->indexcolname == NULL)
1867                                 ielem->indexcolname = FigureIndexColname(ielem->expr);
1868
1869                         /* Now do parse transformation of the expression */
1870                         ielem->expr = transformExpr(pstate, ielem->expr);
1871
1872                         /* We have to fix its collations too */
1873                         assign_expr_collations(pstate, ielem->expr);
1874
1875                         /*
1876                          * We check only that the result type is legitimate; this is for
1877                          * consistency with what transformWhereClause() checks for the
1878                          * predicate.  DefineIndex() will make more checks.
1879                          */
1880                         if (expression_returns_set(ielem->expr))
1881                                 ereport(ERROR,
1882                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1883                                                  errmsg("index expression cannot return a set")));
1884                 }
1885         }
1886
1887         /*
1888          * Check that only the base rel is mentioned.
1889          */
1890         if (list_length(pstate->p_rtable) != 1)
1891                 ereport(ERROR,
1892                                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1893                                  errmsg("index expressions and predicates can refer only to the table being indexed")));
1894
1895         free_parsestate(pstate);
1896
1897         /* Close relation, but keep the lock */
1898         heap_close(rel, NoLock);
1899
1900         return stmt;
1901 }
1902
1903
1904 /*
1905  * transformRuleStmt -
1906  *        transform a CREATE RULE Statement. The action is a list of parse
1907  *        trees which is transformed into a list of query trees, and we also
1908  *        transform the WHERE clause if any.
1909  *
1910  * actions and whereClause are output parameters that receive the
1911  * transformed results.
1912  *
1913  * Note that we must not scribble on the passed-in RuleStmt, so we do
1914  * copyObject() on the actions and WHERE clause.
1915  */
1916 void
1917 transformRuleStmt(RuleStmt *stmt, const char *queryString,
1918                                   List **actions, Node **whereClause)
1919 {
1920         Relation        rel;
1921         ParseState *pstate;
1922         RangeTblEntry *oldrte;
1923         RangeTblEntry *newrte;
1924
1925         /*
1926          * To avoid deadlock, make sure the first thing we do is grab
1927          * AccessExclusiveLock on the target relation.  This will be needed by
1928          * DefineQueryRewrite(), and we don't want to grab a lesser lock
1929          * beforehand.
1930          */
1931         rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1932
1933         /* Set up pstate */
1934         pstate = make_parsestate(NULL);
1935         pstate->p_sourcetext = queryString;
1936
1937         /*
1938          * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1939          * Set up their RTEs in the main pstate for use in parsing the rule
1940          * qualification.
1941          */
1942         oldrte = addRangeTableEntryForRelation(pstate, rel,
1943                                                                                    makeAlias("old", NIL),
1944                                                                                    false, false);
1945         newrte = addRangeTableEntryForRelation(pstate, rel,
1946                                                                                    makeAlias("new", NIL),
1947                                                                                    false, false);
1948         /* Must override addRangeTableEntry's default access-check flags */
1949         oldrte->requiredPerms = 0;
1950         newrte->requiredPerms = 0;
1951
1952         /*
1953          * They must be in the namespace too for lookup purposes, but only add the
1954          * one(s) that are relevant for the current kind of rule.  In an UPDATE
1955          * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1956          * there's no need to be so picky for INSERT & DELETE.  We do not add them
1957          * to the joinlist.
1958          */
1959         switch (stmt->event)
1960         {
1961                 case CMD_SELECT:
1962                         addRTEtoQuery(pstate, oldrte, false, true, true);
1963                         break;
1964                 case CMD_UPDATE:
1965                         addRTEtoQuery(pstate, oldrte, false, true, true);
1966                         addRTEtoQuery(pstate, newrte, false, true, true);
1967                         break;
1968                 case CMD_INSERT:
1969                         addRTEtoQuery(pstate, newrte, false, true, true);
1970                         break;
1971                 case CMD_DELETE:
1972                         addRTEtoQuery(pstate, oldrte, false, true, true);
1973                         break;
1974                 default:
1975                         elog(ERROR, "unrecognized event type: %d",
1976                                  (int) stmt->event);
1977                         break;
1978         }
1979
1980         /* take care of the where clause */
1981         *whereClause = transformWhereClause(pstate,
1982                                                                           (Node *) copyObject(stmt->whereClause),
1983                                                                                 "WHERE");
1984         /* we have to fix its collations too */
1985         assign_expr_collations(pstate, *whereClause);
1986
1987         if (list_length(pstate->p_rtable) != 2)         /* naughty, naughty... */
1988                 ereport(ERROR,
1989                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1990                                  errmsg("rule WHERE condition cannot contain references to other relations")));
1991
1992         /* aggregates not allowed (but subselects are okay) */
1993         if (pstate->p_hasAggs)
1994                 ereport(ERROR,
1995                                 (errcode(ERRCODE_GROUPING_ERROR),
1996                    errmsg("cannot use aggregate function in rule WHERE condition")));
1997         if (pstate->p_hasWindowFuncs)
1998                 ereport(ERROR,
1999                                 (errcode(ERRCODE_WINDOWING_ERROR),
2000                           errmsg("cannot use window function in rule WHERE condition")));
2001
2002         /*
2003          * 'instead nothing' rules with a qualification need a query rangetable so
2004          * the rewrite handler can add the negated rule qualification to the
2005          * original query. We create a query with the new command type CMD_NOTHING
2006          * here that is treated specially by the rewrite system.
2007          */
2008         if (stmt->actions == NIL)
2009         {
2010                 Query      *nothing_qry = makeNode(Query);
2011
2012                 nothing_qry->commandType = CMD_NOTHING;
2013                 nothing_qry->rtable = pstate->p_rtable;
2014                 nothing_qry->jointree = makeFromExpr(NIL, NULL);                /* no join wanted */
2015
2016                 *actions = list_make1(nothing_qry);
2017         }
2018         else
2019         {
2020                 ListCell   *l;
2021                 List       *newactions = NIL;
2022
2023                 /*
2024                  * transform each statement, like parse_sub_analyze()
2025                  */
2026                 foreach(l, stmt->actions)
2027                 {
2028                         Node       *action = (Node *) lfirst(l);
2029                         ParseState *sub_pstate = make_parsestate(NULL);
2030                         Query      *sub_qry,
2031                                            *top_subqry;
2032                         bool            has_old,
2033                                                 has_new;
2034
2035                         /*
2036                          * Since outer ParseState isn't parent of inner, have to pass down
2037                          * the query text by hand.
2038                          */
2039                         sub_pstate->p_sourcetext = queryString;
2040
2041                         /*
2042                          * Set up OLD/NEW in the rtable for this statement.  The entries
2043                          * are added only to relnamespace, not varnamespace, because we
2044                          * don't want them to be referred to by unqualified field names
2045                          * nor "*" in the rule actions.  We decide later whether to put
2046                          * them in the joinlist.
2047                          */
2048                         oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
2049                                                                                                    makeAlias("old", NIL),
2050                                                                                                    false, false);
2051                         newrte = addRangeTableEntryForRelation(sub_pstate, rel,
2052                                                                                                    makeAlias("new", NIL),
2053                                                                                                    false, false);
2054                         oldrte->requiredPerms = 0;
2055                         newrte->requiredPerms = 0;
2056                         addRTEtoQuery(sub_pstate, oldrte, false, true, false);
2057                         addRTEtoQuery(sub_pstate, newrte, false, true, false);
2058
2059                         /* Transform the rule action statement */
2060                         top_subqry = transformStmt(sub_pstate,
2061                                                                            (Node *) copyObject(action));
2062
2063                         /*
2064                          * We cannot support utility-statement actions (eg NOTIFY) with
2065                          * nonempty rule WHERE conditions, because there's no way to make
2066                          * the utility action execute conditionally.
2067                          */
2068                         if (top_subqry->commandType == CMD_UTILITY &&
2069                                 *whereClause != NULL)
2070                                 ereport(ERROR,
2071                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2072                                                  errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
2073
2074                         /*
2075                          * If the action is INSERT...SELECT, OLD/NEW have been pushed down
2076                          * into the SELECT, and that's what we need to look at. (Ugly
2077                          * kluge ... try to fix this when we redesign querytrees.)
2078                          */
2079                         sub_qry = getInsertSelectQuery(top_subqry, NULL);
2080
2081                         /*
2082                          * If the sub_qry is a setop, we cannot attach any qualifications
2083                          * to it, because the planner won't notice them.  This could
2084                          * perhaps be relaxed someday, but for now, we may as well reject
2085                          * such a rule immediately.
2086                          */
2087                         if (sub_qry->setOperations != NULL && *whereClause != NULL)
2088                                 ereport(ERROR,
2089                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2090                                                  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2091
2092                         /*
2093                          * Validate action's use of OLD/NEW, qual too
2094                          */
2095                         has_old =
2096                                 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
2097                                 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
2098                         has_new =
2099                                 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
2100                                 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
2101
2102                         switch (stmt->event)
2103                         {
2104                                 case CMD_SELECT:
2105                                         if (has_old)
2106                                                 ereport(ERROR,
2107                                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2108                                                                  errmsg("ON SELECT rule cannot use OLD")));
2109                                         if (has_new)
2110                                                 ereport(ERROR,
2111                                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2112                                                                  errmsg("ON SELECT rule cannot use NEW")));
2113                                         break;
2114                                 case CMD_UPDATE:
2115                                         /* both are OK */
2116                                         break;
2117                                 case CMD_INSERT:
2118                                         if (has_old)
2119                                                 ereport(ERROR,
2120                                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2121                                                                  errmsg("ON INSERT rule cannot use OLD")));
2122                                         break;
2123                                 case CMD_DELETE:
2124                                         if (has_new)
2125                                                 ereport(ERROR,
2126                                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2127                                                                  errmsg("ON DELETE rule cannot use NEW")));
2128                                         break;
2129                                 default:
2130                                         elog(ERROR, "unrecognized event type: %d",
2131                                                  (int) stmt->event);
2132                                         break;
2133                         }
2134
2135                         /*
2136                          * OLD/NEW are not allowed in WITH queries, because they would
2137                          * amount to outer references for the WITH, which we disallow.
2138                          * However, they were already in the outer rangetable when we
2139                          * analyzed the query, so we have to check.
2140                          *
2141                          * Note that in the INSERT...SELECT case, we need to examine the
2142                          * CTE lists of both top_subqry and sub_qry.
2143                          *
2144                          * Note that we aren't digging into the body of the query looking
2145                          * for WITHs in nested sub-SELECTs.  A WITH down there can
2146                          * legitimately refer to OLD/NEW, because it'd be an
2147                          * indirect-correlated outer reference.
2148                          */
2149                         if (rangeTableEntry_used((Node *) top_subqry->cteList,
2150                                                                          PRS2_OLD_VARNO, 0) ||
2151                                 rangeTableEntry_used((Node *) sub_qry->cteList,
2152                                                                          PRS2_OLD_VARNO, 0))
2153                                 ereport(ERROR,
2154                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2155                                                  errmsg("cannot refer to OLD within WITH query")));
2156                         if (rangeTableEntry_used((Node *) top_subqry->cteList,
2157                                                                          PRS2_NEW_VARNO, 0) ||
2158                                 rangeTableEntry_used((Node *) sub_qry->cteList,
2159                                                                          PRS2_NEW_VARNO, 0))
2160                                 ereport(ERROR,
2161                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2162                                                  errmsg("cannot refer to NEW within WITH query")));
2163
2164                         /*
2165                          * For efficiency's sake, add OLD to the rule action's jointree
2166                          * only if it was actually referenced in the statement or qual.
2167                          *
2168                          * For INSERT, NEW is not really a relation (only a reference to
2169                          * the to-be-inserted tuple) and should never be added to the
2170                          * jointree.
2171                          *
2172                          * For UPDATE, we treat NEW as being another kind of reference to
2173                          * OLD, because it represents references to *transformed* tuples
2174                          * of the existing relation.  It would be wrong to enter NEW
2175                          * separately in the jointree, since that would cause a double
2176                          * join of the updated relation.  It's also wrong to fail to make
2177                          * a jointree entry if only NEW and not OLD is mentioned.
2178                          */
2179                         if (has_old || (has_new && stmt->event == CMD_UPDATE))
2180                         {
2181                                 /*
2182                                  * If sub_qry is a setop, manipulating its jointree will do no
2183                                  * good at all, because the jointree is dummy. (This should be
2184                                  * a can't-happen case because of prior tests.)
2185                                  */
2186                                 if (sub_qry->setOperations != NULL)
2187                                         ereport(ERROR,
2188                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2189                                                          errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2190                                 /* hack so we can use addRTEtoQuery() */
2191                                 sub_pstate->p_rtable = sub_qry->rtable;
2192                                 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
2193                                 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
2194                                 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
2195                         }
2196
2197                         newactions = lappend(newactions, top_subqry);
2198
2199                         free_parsestate(sub_pstate);
2200                 }
2201
2202                 *actions = newactions;
2203         }
2204
2205         free_parsestate(pstate);
2206
2207         /* Close relation, but keep the exclusive lock */
2208         heap_close(rel, NoLock);
2209 }
2210
2211
2212 /*
2213  * transformAlterTableStmt -
2214  *              parse analysis for ALTER TABLE
2215  *
2216  * Returns a List of utility commands to be done in sequence.  One of these
2217  * will be the transformed AlterTableStmt, but there may be additional actions
2218  * to be done before and after the actual AlterTable() call.
2219  */
2220 List *
2221 transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
2222 {
2223         Relation        rel;
2224         ParseState *pstate;
2225         CreateStmtContext cxt;
2226         List       *result;
2227         List       *save_alist;
2228         ListCell   *lcmd,
2229                            *l;
2230         List       *newcmds = NIL;
2231         bool            skipValidation = true;
2232         AlterTableCmd *newcmd;
2233         LOCKMODE        lockmode;
2234
2235         /*
2236          * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
2237          * is overkill, but easy.)
2238          */
2239         stmt = (AlterTableStmt *) copyObject(stmt);
2240
2241         /*
2242          * Determine the appropriate lock level for this list of subcommands.
2243          */
2244         lockmode = AlterTableGetLockLevel(stmt->cmds);
2245
2246         /*
2247          * Acquire appropriate lock on the target relation, which will be held
2248          * until end of transaction.  This ensures any decisions we make here
2249          * based on the state of the relation will still be good at execution. We
2250          * must get lock now because execution will later require it; taking a
2251          * lower grade lock now and trying to upgrade later risks deadlock.  Any
2252          * new commands we add after this must not upgrade the lock level
2253          * requested here.
2254          */
2255         rel = relation_openrv(stmt->relation, lockmode);
2256
2257         /* Set up pstate and CreateStmtContext */
2258         pstate = make_parsestate(NULL);
2259         pstate->p_sourcetext = queryString;
2260
2261         cxt.pstate = pstate;
2262         cxt.stmtType = "ALTER TABLE";
2263         cxt.relation = stmt->relation;
2264         cxt.rel = rel;
2265         cxt.inhRelations = NIL;
2266         cxt.isalter = true;
2267         cxt.hasoids = false;            /* need not be right */
2268         cxt.columns = NIL;
2269         cxt.ckconstraints = NIL;
2270         cxt.fkconstraints = NIL;
2271         cxt.ixconstraints = NIL;
2272         cxt.inh_indexes = NIL;
2273         cxt.blist = NIL;
2274         cxt.alist = NIL;
2275         cxt.pkey = NULL;
2276
2277         /*
2278          * The only subtypes that currently require parse transformation handling
2279          * are ADD COLUMN and ADD CONSTRAINT.  These largely re-use code from
2280          * CREATE TABLE.
2281          */
2282         foreach(lcmd, stmt->cmds)
2283         {
2284                 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2285
2286                 switch (cmd->subtype)
2287                 {
2288                         case AT_AddColumn:
2289                         case AT_AddColumnToView:
2290                                 {
2291                                         ColumnDef  *def = (ColumnDef *) cmd->def;
2292
2293                                         Assert(IsA(def, ColumnDef));
2294                                         transformColumnDefinition(&cxt, def);
2295
2296                                         /*
2297                                          * If the column has a non-null default, we can't skip
2298                                          * validation of foreign keys.
2299                                          */
2300                                         if (def->raw_default != NULL)
2301                                                 skipValidation = false;
2302
2303                                         /*
2304                                          * All constraints are processed in other ways. Remove the
2305                                          * original list
2306                                          */
2307                                         def->constraints = NIL;
2308
2309                                         newcmds = lappend(newcmds, cmd);
2310                                         break;
2311                                 }
2312                         case AT_AddConstraint:
2313
2314                                 /*
2315                                  * The original AddConstraint cmd node doesn't go to newcmds
2316                                  */
2317                                 if (IsA(cmd->def, Constraint))
2318                                 {
2319                                         transformTableConstraint(&cxt, (Constraint *) cmd->def);
2320                                         if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
2321                                                 skipValidation = false;
2322                                 }
2323                                 else
2324                                         elog(ERROR, "unrecognized node type: %d",
2325                                                  (int) nodeTag(cmd->def));
2326                                 break;
2327
2328                         case AT_ProcessedConstraint:
2329
2330                                 /*
2331                                  * Already-transformed ADD CONSTRAINT, so just make it look
2332                                  * like the standard case.
2333                                  */
2334                                 cmd->subtype = AT_AddConstraint;
2335                                 newcmds = lappend(newcmds, cmd);
2336                                 break;
2337
2338                         default:
2339                                 newcmds = lappend(newcmds, cmd);
2340                                 break;
2341                 }
2342         }
2343
2344         /*
2345          * transformIndexConstraints wants cxt.alist to contain only index
2346          * statements, so transfer anything we already have into save_alist
2347          * immediately.
2348          */
2349         save_alist = cxt.alist;
2350         cxt.alist = NIL;
2351
2352         /* Postprocess index and FK constraints */
2353         transformIndexConstraints(&cxt);
2354
2355         transformFKConstraints(&cxt, skipValidation, true);
2356
2357         /*
2358          * Push any index-creation commands into the ALTER, so that they can be
2359          * scheduled nicely by tablecmds.c.  Note that tablecmds.c assumes that
2360          * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
2361          * subcommand has already been through transformIndexStmt.
2362          */
2363         foreach(l, cxt.alist)
2364         {
2365                 IndexStmt  *idxstmt = (IndexStmt *) lfirst(l);
2366
2367                 Assert(IsA(idxstmt, IndexStmt));
2368                 idxstmt = transformIndexStmt(idxstmt, queryString);
2369                 newcmd = makeNode(AlterTableCmd);
2370                 newcmd->subtype = OidIsValid(idxstmt->indexOid) ? AT_AddIndexConstraint : AT_AddIndex;
2371                 newcmd->def = (Node *) idxstmt;
2372                 newcmds = lappend(newcmds, newcmd);
2373         }
2374         cxt.alist = NIL;
2375
2376         /* Append any CHECK or FK constraints to the commands list */
2377         foreach(l, cxt.ckconstraints)
2378         {
2379                 newcmd = makeNode(AlterTableCmd);
2380                 newcmd->subtype = AT_AddConstraint;
2381                 newcmd->def = (Node *) lfirst(l);
2382                 newcmds = lappend(newcmds, newcmd);
2383         }
2384         foreach(l, cxt.fkconstraints)
2385         {
2386                 newcmd = makeNode(AlterTableCmd);
2387                 newcmd->subtype = AT_AddConstraint;
2388                 newcmd->def = (Node *) lfirst(l);
2389                 newcmds = lappend(newcmds, newcmd);
2390         }
2391
2392         /* Close rel but keep lock */
2393         relation_close(rel, NoLock);
2394
2395         /*
2396          * Output results.
2397          */
2398         stmt->cmds = newcmds;
2399
2400         result = lappend(cxt.blist, stmt);
2401         result = list_concat(result, cxt.alist);
2402         result = list_concat(result, save_alist);
2403
2404         return result;
2405 }
2406
2407
2408 /*
2409  * Preprocess a list of column constraint clauses
2410  * to attach constraint attributes to their primary constraint nodes
2411  * and detect inconsistent/misplaced constraint attributes.
2412  *
2413  * NOTE: currently, attributes are only supported for FOREIGN KEY, UNIQUE,
2414  * and PRIMARY KEY constraints, but someday they ought to be supported
2415  * for other constraint types.
2416  */
2417 static void
2418 transformConstraintAttrs(CreateStmtContext *cxt, List *constraintList)
2419 {
2420         Constraint *lastprimarycon = NULL;
2421         bool            saw_deferrability = false;
2422         bool            saw_initially = false;
2423         ListCell   *clist;
2424
2425 #define SUPPORTS_ATTRS(node)                            \
2426         ((node) != NULL &&                                              \
2427          ((node)->contype == CONSTR_PRIMARY ||  \
2428           (node)->contype == CONSTR_UNIQUE ||   \
2429           (node)->contype == CONSTR_EXCLUSION || \
2430           (node)->contype == CONSTR_FOREIGN))
2431
2432         foreach(clist, constraintList)
2433         {
2434                 Constraint *con = (Constraint *) lfirst(clist);
2435
2436                 if (!IsA(con, Constraint))
2437                         elog(ERROR, "unrecognized node type: %d",
2438                                  (int) nodeTag(con));
2439                 switch (con->contype)
2440                 {
2441                         case CONSTR_ATTR_DEFERRABLE:
2442                                 if (!SUPPORTS_ATTRS(lastprimarycon))
2443                                         ereport(ERROR,
2444                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2445                                                          errmsg("misplaced DEFERRABLE clause"),
2446                                                          parser_errposition(cxt->pstate, con->location)));
2447                                 if (saw_deferrability)
2448                                         ereport(ERROR,
2449                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2450                                                          errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2451                                                          parser_errposition(cxt->pstate, con->location)));
2452                                 saw_deferrability = true;
2453                                 lastprimarycon->deferrable = true;
2454                                 break;
2455
2456                         case CONSTR_ATTR_NOT_DEFERRABLE:
2457                                 if (!SUPPORTS_ATTRS(lastprimarycon))
2458                                         ereport(ERROR,
2459                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2460                                                          errmsg("misplaced NOT DEFERRABLE clause"),
2461                                                          parser_errposition(cxt->pstate, con->location)));
2462                                 if (saw_deferrability)
2463                                         ereport(ERROR,
2464                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2465                                                          errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2466                                                          parser_errposition(cxt->pstate, con->location)));
2467                                 saw_deferrability = true;
2468                                 lastprimarycon->deferrable = false;
2469                                 if (saw_initially &&
2470                                         lastprimarycon->initdeferred)
2471                                         ereport(ERROR,
2472                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2473                                                          errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2474                                                          parser_errposition(cxt->pstate, con->location)));
2475                                 break;
2476
2477                         case CONSTR_ATTR_DEFERRED:
2478                                 if (!SUPPORTS_ATTRS(lastprimarycon))
2479                                         ereport(ERROR,
2480                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2481                                                          errmsg("misplaced INITIALLY DEFERRED clause"),
2482                                                          parser_errposition(cxt->pstate, con->location)));
2483                                 if (saw_initially)
2484                                         ereport(ERROR,
2485                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2486                                                          errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2487                                                          parser_errposition(cxt->pstate, con->location)));
2488                                 saw_initially = true;
2489                                 lastprimarycon->initdeferred = true;
2490
2491                                 /*
2492                                  * If only INITIALLY DEFERRED appears, assume DEFERRABLE
2493                                  */
2494                                 if (!saw_deferrability)
2495                                         lastprimarycon->deferrable = true;
2496                                 else if (!lastprimarycon->deferrable)
2497                                         ereport(ERROR,
2498                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2499                                                          errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2500                                                          parser_errposition(cxt->pstate, con->location)));
2501                                 break;
2502
2503                         case CONSTR_ATTR_IMMEDIATE:
2504                                 if (!SUPPORTS_ATTRS(lastprimarycon))
2505                                         ereport(ERROR,
2506                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2507                                                          errmsg("misplaced INITIALLY IMMEDIATE clause"),
2508                                                          parser_errposition(cxt->pstate, con->location)));
2509                                 if (saw_initially)
2510                                         ereport(ERROR,
2511                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2512                                                          errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2513                                                          parser_errposition(cxt->pstate, con->location)));
2514                                 saw_initially = true;
2515                                 lastprimarycon->initdeferred = false;
2516                                 break;
2517
2518                         default:
2519                                 /* Otherwise it's not an attribute */
2520                                 lastprimarycon = con;
2521                                 /* reset flags for new primary node */
2522                                 saw_deferrability = false;
2523                                 saw_initially = false;
2524                                 break;
2525                 }
2526         }
2527 }
2528
2529 /*
2530  * Special handling of type definition for a column
2531  */
2532 static void
2533 transformColumnType(CreateStmtContext *cxt, ColumnDef *column)
2534 {
2535         /*
2536          * All we really need to do here is verify that the type is valid,
2537          * including any collation spec that might be present.
2538          */
2539         Type            ctype = typenameType(cxt->pstate, column->typeName, NULL);
2540
2541         if (column->collClause)
2542         {
2543                 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
2544
2545                 LookupCollation(cxt->pstate,
2546                                                 column->collClause->collname,
2547                                                 column->collClause->location);
2548                 /* Complain if COLLATE is applied to an uncollatable type */
2549                 if (!OidIsValid(typtup->typcollation))
2550                         ereport(ERROR,
2551                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
2552                                          errmsg("collations are not supported by type %s",
2553                                                         format_type_be(HeapTupleGetOid(ctype))),
2554                                          parser_errposition(cxt->pstate,
2555                                                                                 column->collClause->location)));
2556         }
2557
2558         ReleaseSysCache(ctype);
2559 }
2560
2561
2562 /*
2563  * transformCreateSchemaStmt -
2564  *        analyzes the CREATE SCHEMA statement
2565  *
2566  * Split the schema element list into individual commands and place
2567  * them in the result list in an order such that there are no forward
2568  * references (e.g. GRANT to a table created later in the list). Note
2569  * that the logic we use for determining forward references is
2570  * presently quite incomplete.
2571  *
2572  * SQL92 also allows constraints to make forward references, so thumb through
2573  * the table columns and move forward references to a posterior alter-table
2574  * command.
2575  *
2576  * The result is a list of parse nodes that still need to be analyzed ---
2577  * but we can't analyze the later commands until we've executed the earlier
2578  * ones, because of possible inter-object references.
2579  *
2580  * Note: this breaks the rules a little bit by modifying schema-name fields
2581  * within passed-in structs.  However, the transformation would be the same
2582  * if done over, so it should be all right to scribble on the input to this
2583  * extent.
2584  */
2585 List *
2586 transformCreateSchemaStmt(CreateSchemaStmt *stmt)
2587 {
2588         CreateSchemaStmtContext cxt;
2589         List       *result;
2590         ListCell   *elements;
2591
2592         cxt.stmtType = "CREATE SCHEMA";
2593         cxt.schemaname = stmt->schemaname;
2594         cxt.authid = stmt->authid;
2595         cxt.sequences = NIL;
2596         cxt.tables = NIL;
2597         cxt.views = NIL;
2598         cxt.indexes = NIL;
2599         cxt.triggers = NIL;
2600         cxt.grants = NIL;
2601
2602         /*
2603          * Run through each schema element in the schema element list. Separate
2604          * statements by type, and do preliminary analysis.
2605          */
2606         foreach(elements, stmt->schemaElts)
2607         {
2608                 Node       *element = lfirst(elements);
2609
2610                 switch (nodeTag(element))
2611                 {
2612                         case T_CreateSeqStmt:
2613                                 {
2614                                         CreateSeqStmt *elp = (CreateSeqStmt *) element;
2615
2616                                         setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
2617                                         cxt.sequences = lappend(cxt.sequences, element);
2618                                 }
2619                                 break;
2620
2621                         case T_CreateStmt:
2622                                 {
2623                                         CreateStmt *elp = (CreateStmt *) element;
2624
2625                                         setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2626
2627                                         /*
2628                                          * XXX todo: deal with constraints
2629                                          */
2630                                         cxt.tables = lappend(cxt.tables, element);
2631                                 }
2632                                 break;
2633
2634                         case T_ViewStmt:
2635                                 {
2636                                         ViewStmt   *elp = (ViewStmt *) element;
2637
2638                                         setSchemaName(cxt.schemaname, &elp->view->schemaname);
2639
2640                                         /*
2641                                          * XXX todo: deal with references between views
2642                                          */
2643                                         cxt.views = lappend(cxt.views, element);
2644                                 }
2645                                 break;
2646
2647                         case T_IndexStmt:
2648                                 {
2649                                         IndexStmt  *elp = (IndexStmt *) element;
2650
2651                                         setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2652                                         cxt.indexes = lappend(cxt.indexes, element);
2653                                 }
2654                                 break;
2655
2656                         case T_CreateTrigStmt:
2657                                 {
2658                                         CreateTrigStmt *elp = (CreateTrigStmt *) element;
2659
2660                                         setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2661                                         cxt.triggers = lappend(cxt.triggers, element);
2662                                 }
2663                                 break;
2664
2665                         case T_GrantStmt:
2666                                 cxt.grants = lappend(cxt.grants, element);
2667                                 break;
2668
2669                         default:
2670                                 elog(ERROR, "unrecognized node type: %d",
2671                                          (int) nodeTag(element));
2672                 }
2673         }
2674
2675         result = NIL;
2676         result = list_concat(result, cxt.sequences);
2677         result = list_concat(result, cxt.tables);
2678         result = list_concat(result, cxt.views);
2679         result = list_concat(result, cxt.indexes);
2680         result = list_concat(result, cxt.triggers);
2681         result = list_concat(result, cxt.grants);
2682
2683         return result;
2684 }
2685
2686 /*
2687  * setSchemaName
2688  *              Set or check schema name in an element of a CREATE SCHEMA command
2689  */
2690 static void
2691 setSchemaName(char *context_schema, char **stmt_schema_name)
2692 {
2693         if (*stmt_schema_name == NULL)
2694                 *stmt_schema_name = context_schema;
2695         else if (strcmp(context_schema, *stmt_schema_name) != 0)
2696                 ereport(ERROR,
2697                                 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
2698                                  errmsg("CREATE specifies a schema (%s) "
2699                                                 "different from the one being created (%s)",
2700                                                 *stmt_schema_name, context_schema)));
2701 }