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