OSDN Git Service

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