OSDN Git Service

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