OSDN Git Service

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