OSDN Git Service

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