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