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