OSDN Git Service

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