OSDN Git Service

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