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