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