OSDN Git Service

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