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