OSDN Git Service

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