OSDN Git Service

pgindent run for 8.3.
[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.6 2007/11/15 21:14:37 momjian 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 is
142          * 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 and
150          * 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 definition.
584          */
585         for (parent_attno = 1; parent_attno <= tupleDesc->natts;
586                  parent_attno++)
587         {
588                 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
589                 char       *attributeName = NameStr(attribute->attname);
590                 ColumnDef  *def;
591
592                 /*
593                  * Ignore dropped columns in the parent.
594                  */
595                 if (attribute->attisdropped)
596                         continue;
597
598                 /*
599                  * Create a new column, which is marked as NOT inherited.
600                  *
601                  * For constraints, ONLY the NOT NULL constraint is inherited by the
602                  * new column definition per SQL99.
603                  */
604                 def = makeNode(ColumnDef);
605                 def->colname = pstrdup(attributeName);
606                 def->typename = makeTypeNameFromOid(attribute->atttypid,
607                                                                                         attribute->atttypmod);
608                 def->inhcount = 0;
609                 def->is_local = true;
610                 def->is_not_null = attribute->attnotnull;
611                 def->raw_default = NULL;
612                 def->cooked_default = NULL;
613                 def->constraints = NIL;
614
615                 /*
616                  * Add to column list
617                  */
618                 cxt->columns = lappend(cxt->columns, def);
619
620                 /*
621                  * Copy default, if present and the default has been requested
622                  */
623                 if (attribute->atthasdef && including_defaults)
624                 {
625                         char       *this_default = NULL;
626                         AttrDefault *attrdef;
627                         int                     i;
628
629                         /* Find default in constraint structure */
630                         Assert(constr != NULL);
631                         attrdef = constr->defval;
632                         for (i = 0; i < constr->num_defval; i++)
633                         {
634                                 if (attrdef[i].adnum == parent_attno)
635                                 {
636                                         this_default = attrdef[i].adbin;
637                                         break;
638                                 }
639                         }
640                         Assert(this_default != NULL);
641
642                         /*
643                          * If default expr could contain any vars, we'd need to fix 'em,
644                          * but it can't; so default is ready to apply to child.
645                          */
646
647                         def->cooked_default = pstrdup(this_default);
648                 }
649         }
650
651         /*
652          * Copy CHECK constraints if requested, being careful to adjust attribute
653          * numbers
654          */
655         if (including_constraints && tupleDesc->constr)
656         {
657                 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
658                 int                     ccnum;
659
660                 for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
661                 {
662                         char       *ccname = tupleDesc->constr->check[ccnum].ccname;
663                         char       *ccbin = tupleDesc->constr->check[ccnum].ccbin;
664                         Node       *ccbin_node = stringToNode(ccbin);
665                         Constraint *n = makeNode(Constraint);
666
667                         change_varattnos_of_a_node(ccbin_node, attmap);
668
669                         n->contype = CONSTR_CHECK;
670                         n->name = pstrdup(ccname);
671                         n->raw_expr = NULL;
672                         n->cooked_expr = nodeToString(ccbin_node);
673                         n->indexspace = NULL;
674                         cxt->ckconstraints = lappend(cxt->ckconstraints, (Node *) n);
675                 }
676         }
677
678         if (including_indexes && relation->rd_rel->relhasindex)
679         {
680                 AttrNumber *attmap;
681                 List       *parent_indexes;
682                 ListCell   *l;
683
684                 attmap = varattnos_map_schema(tupleDesc, cxt->columns);
685                 parent_indexes = RelationGetIndexList(relation);
686
687                 foreach(l, parent_indexes)
688                 {
689                         Oid                     parent_index_oid = lfirst_oid(l);
690                         Relation        parent_index;
691                         IndexStmt  *index_stmt;
692
693                         parent_index = index_open(parent_index_oid, AccessShareLock);
694
695                         /* Build CREATE INDEX statement to recreate the parent_index */
696                         index_stmt = generateClonedIndexStmt(cxt, parent_index,
697                                                                                                  attmap);
698
699                         /* Add the new IndexStmt to the create context */
700                         cxt->inh_indexes = lappend(cxt->inh_indexes, index_stmt);
701
702                         /* Keep our lock on the index till xact commit */
703                         index_close(parent_index, NoLock);
704                 }
705         }
706
707         /*
708          * Close the parent rel, but keep our AccessShareLock on it until xact
709          * commit.      That will prevent someone else from deleting or ALTERing the
710          * parent before the child is committed.
711          */
712         heap_close(relation, NoLock);
713 }
714
715 /*
716  * Generate an IndexStmt entry using information from an already
717  * existing index "source_idx".
718  *
719  * Note: Much of this functionality is cribbed from pg_get_indexdef.
720  */
721 static IndexStmt *
722 generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
723                                                 AttrNumber *attmap)
724 {
725         HeapTuple       ht_idx;
726         HeapTuple       ht_idxrel;
727         HeapTuple       ht_am;
728         Form_pg_index idxrec;
729         Form_pg_class idxrelrec;
730         Form_pg_am      amrec;
731         List       *indexprs = NIL;
732         ListCell   *indexpr_item;
733         Oid                     indrelid;
734         Oid                     source_relid;
735         int                     keyno;
736         Oid                     keycoltype;
737         Datum           indclassDatum;
738         Datum           indoptionDatum;
739         bool            isnull;
740         oidvector  *indclass;
741         int2vector *indoption;
742         IndexStmt  *index;
743         Datum           reloptions;
744
745         source_relid = RelationGetRelid(source_idx);
746
747         /* Fetch pg_index tuple for source index */
748         ht_idx = SearchSysCache(INDEXRELID,
749                                                         ObjectIdGetDatum(source_relid),
750                                                         0, 0, 0);
751         if (!HeapTupleIsValid(ht_idx))
752                 elog(ERROR, "cache lookup failed for index %u", source_relid);
753         idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
754
755         Assert(source_relid == idxrec->indexrelid);
756         indrelid = idxrec->indrelid;
757
758         index = makeNode(IndexStmt);
759         index->unique = idxrec->indisunique;
760         index->concurrent = false;
761         index->primary = idxrec->indisprimary;
762         index->relation = cxt->relation;
763         index->isconstraint = false;
764
765         /*
766          * We don't try to preserve the name of the source index; instead, just
767          * let DefineIndex() choose a reasonable name.
768          */
769         index->idxname = NULL;
770
771         /* Must get indclass and indoption the hard way */
772         indclassDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
773                                                                         Anum_pg_index_indclass, &isnull);
774         Assert(!isnull);
775         indclass = (oidvector *) DatumGetPointer(indclassDatum);
776         indoptionDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
777                                                                          Anum_pg_index_indoption, &isnull);
778         Assert(!isnull);
779         indoption = (int2vector *) DatumGetPointer(indoptionDatum);
780
781         /* Fetch pg_class tuple of source index */
782         ht_idxrel = SearchSysCache(RELOID,
783                                                            ObjectIdGetDatum(source_relid),
784                                                            0, 0, 0);
785         if (!HeapTupleIsValid(ht_idxrel))
786                 elog(ERROR, "cache lookup failed for relation %u", source_relid);
787
788         /*
789          * Store the reloptions for later use by this new index
790          */
791         reloptions = SysCacheGetAttr(RELOID, ht_idxrel,
792                                                                  Anum_pg_class_reloptions, &isnull);
793         if (!isnull)
794                 index->src_options = flatten_reloptions(source_relid);
795
796         idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
797
798         /* Fetch pg_am tuple for the index's access method */
799         ht_am = SearchSysCache(AMOID,
800                                                    ObjectIdGetDatum(idxrelrec->relam),
801                                                    0, 0, 0);
802         if (!HeapTupleIsValid(ht_am))
803                 elog(ERROR, "cache lookup failed for access method %u",
804                          idxrelrec->relam);
805         amrec = (Form_pg_am) GETSTRUCT(ht_am);
806         index->accessMethod = pstrdup(NameStr(amrec->amname));
807
808         /* Get the index expressions, if any */
809         if (!heap_attisnull(ht_idx, Anum_pg_index_indexprs))
810         {
811                 Datum           exprsDatum;
812                 bool            isnull;
813                 char       *exprsString;
814
815                 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
816                                                                          Anum_pg_index_indexprs, &isnull);
817                 exprsString = DatumGetCString(DirectFunctionCall1(textout,
818                                                                                                                   exprsDatum));
819                 Assert(!isnull);
820                 indexprs = (List *) stringToNode(exprsString);
821         }
822
823         indexpr_item = list_head(indexprs);
824
825         for (keyno = 0; keyno < idxrec->indnatts; keyno++)
826         {
827                 IndexElem  *iparam;
828                 AttrNumber      attnum = idxrec->indkey.values[keyno];
829                 int16           opt = indoption->values[keyno];
830
831                 iparam = makeNode(IndexElem);
832
833                 if (AttributeNumberIsValid(attnum))
834                 {
835                         /* Simple index column */
836                         char       *attname;
837
838                         attname = get_relid_attribute_name(indrelid, attnum);
839                         keycoltype = get_atttype(indrelid, attnum);
840
841                         iparam->name = attname;
842                         iparam->expr = NULL;
843                 }
844                 else
845                 {
846                         /* Expressional index */
847                         Node       *indexkey;
848
849                         if (indexpr_item == NULL)
850                                 elog(ERROR, "too few entries in indexprs list");
851                         indexkey = (Node *) lfirst(indexpr_item);
852                         change_varattnos_of_a_node(indexkey, attmap);
853                         iparam->name = NULL;
854                         iparam->expr = indexkey;
855
856                         indexpr_item = lnext(indexpr_item);
857                         keycoltype = exprType(indexkey);
858                 }
859
860                 /* Add the operator class name, if non-default */
861                 iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
862
863                 iparam->ordering = SORTBY_DEFAULT;
864                 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
865
866                 /* Adjust options if necessary */
867                 if (amrec->amcanorder)
868                 {
869                         /* If it supports sort ordering, report DESC and NULLS opts */
870                         if (opt & INDOPTION_DESC)
871                                 iparam->ordering = SORTBY_DESC;
872                         if (opt & INDOPTION_NULLS_FIRST)
873                                 iparam->nulls_ordering = SORTBY_NULLS_FIRST;
874                 }
875
876                 index->indexParams = lappend(index->indexParams, iparam);
877         }
878
879         /* Use the same tablespace as the source index */
880         index->tableSpace = get_tablespace_name(source_idx->rd_node.spcNode);
881
882         /* If it's a partial index, decompile and append the predicate */
883         if (!heap_attisnull(ht_idx, Anum_pg_index_indpred))
884         {
885                 Datum           pred_datum;
886                 bool            isnull;
887                 char       *pred_str;
888
889                 /* Convert text string to node tree */
890                 pred_datum = SysCacheGetAttr(INDEXRELID, ht_idx,
891                                                                          Anum_pg_index_indpred, &isnull);
892                 Assert(!isnull);
893                 pred_str = DatumGetCString(DirectFunctionCall1(textout,
894                                                                                                            pred_datum));
895                 index->whereClause = (Node *) stringToNode(pred_str);
896                 change_varattnos_of_a_node(index->whereClause, attmap);
897         }
898
899         /* Clean up */
900         ReleaseSysCache(ht_idx);
901         ReleaseSysCache(ht_idxrel);
902         ReleaseSysCache(ht_am);
903
904         return index;
905 }
906
907 /*
908  * get_opclass                  - fetch name of an index operator class
909  *
910  * If the opclass is the default for the given actual_datatype, then
911  * the return value is NIL.
912  */
913 static List *
914 get_opclass(Oid opclass, Oid actual_datatype)
915 {
916         HeapTuple       ht_opc;
917         Form_pg_opclass opc_rec;
918         List       *result = NIL;
919
920         ht_opc = SearchSysCache(CLAOID,
921                                                         ObjectIdGetDatum(opclass),
922                                                         0, 0, 0);
923         if (!HeapTupleIsValid(ht_opc))
924                 elog(ERROR, "cache lookup failed for opclass %u", opclass);
925         opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
926
927         if (!OidIsValid(actual_datatype) ||
928                 GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
929         {
930                 char       *nsp_name = get_namespace_name(opc_rec->opcnamespace);
931                 char       *opc_name = NameStr(opc_rec->opcname);
932
933                 result = list_make2(makeString(nsp_name), makeString(opc_name));
934         }
935
936         ReleaseSysCache(ht_opc);
937         return result;
938 }
939
940
941 /*
942  * transformIndexConstraints
943  *              Handle UNIQUE and PRIMARY KEY constraints, which create
944  *              indexes. We also merge index definitions arising from
945  *              LIKE ... INCLUDING INDEXES.
946  */
947 static void
948 transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
949 {
950         IndexStmt  *index;
951         List       *indexlist = NIL;
952         ListCell   *lc;
953
954         /*
955          * Run through the constraints that need to generate an index. For PRIMARY
956          * KEY, mark each column as NOT NULL and create an index. For UNIQUE,
957          * create an index as for PRIMARY KEY, but do not insist on NOT NULL.
958          */
959         foreach(lc, cxt->ixconstraints)
960         {
961                 Constraint *constraint = (Constraint *) lfirst(lc);
962
963                 index = transformIndexConstraint(constraint, cxt);
964                 indexlist = lappend(indexlist, index);
965         }
966
967         /*
968          * Scan the index list and remove any redundant index specifications. This
969          * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
970          * strict reading of SQL92 would suggest raising an error instead, but
971          * that strikes me as too anal-retentive. - tgl 2001-02-14
972          *
973          * XXX in ALTER TABLE case, it'd be nice to look for duplicate
974          * pre-existing indexes, too.
975          */
976         Assert(cxt->alist == NIL);
977         if (cxt->pkey != NULL)
978         {
979                 /* Make sure we keep the PKEY index in preference to others... */
980                 cxt->alist = list_make1(cxt->pkey);
981         }
982
983         foreach(lc, indexlist)
984         {
985                 bool            keep = true;
986                 ListCell   *k;
987
988                 index = lfirst(lc);
989
990                 /* if it's pkey, it's already in cxt->alist */
991                 if (index == cxt->pkey)
992                         continue;
993
994                 foreach(k, cxt->alist)
995                 {
996                         IndexStmt  *priorindex = lfirst(k);
997
998                         if (equal(index->indexParams, priorindex->indexParams))
999                         {
1000                                 /*
1001                                  * If the prior index is as yet unnamed, and this one is
1002                                  * named, then transfer the name to the prior index. This
1003                                  * ensures that if we have named and unnamed constraints,
1004                                  * we'll use (at least one of) the names for the index.
1005                                  */
1006                                 if (priorindex->idxname == NULL)
1007                                         priorindex->idxname = index->idxname;
1008                                 keep = false;
1009                                 break;
1010                         }
1011                 }
1012
1013                 if (keep)
1014                         cxt->alist = lappend(cxt->alist, index);
1015         }
1016
1017         /* Copy indexes defined by LIKE ... INCLUDING INDEXES */
1018         foreach(lc, cxt->inh_indexes)
1019         {
1020                 index = (IndexStmt *) lfirst(lc);
1021
1022                 if (index->primary)
1023                 {
1024                         if (cxt->pkey)
1025                                 ereport(ERROR,
1026                                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1027                                                  errmsg("multiple primary keys for table \"%s\" are not allowed",
1028                                                                 cxt->relation->relname)));
1029
1030                         cxt->pkey = index;
1031                 }
1032
1033                 cxt->alist = lappend(cxt->alist, index);
1034         }
1035 }
1036
1037 static IndexStmt *
1038 transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
1039 {
1040         IndexStmt  *index;
1041         ListCell   *keys;
1042         IndexElem  *iparam;
1043
1044         Assert(constraint->contype == CONSTR_PRIMARY ||
1045                    constraint->contype == CONSTR_UNIQUE);
1046
1047         index = makeNode(IndexStmt);
1048         index->unique = true;
1049         index->primary = (constraint->contype == CONSTR_PRIMARY);
1050
1051         if (index->primary)
1052         {
1053                 if (cxt->pkey != NULL)
1054                         ereport(ERROR,
1055                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1056                          errmsg("multiple primary keys for table \"%s\" are not allowed",
1057                                         cxt->relation->relname)));
1058                 cxt->pkey = index;
1059
1060                 /*
1061                  * In ALTER TABLE case, a primary index might already exist, but
1062                  * DefineIndex will check for it.
1063                  */
1064         }
1065         index->isconstraint = true;
1066
1067         if (constraint->name != NULL)
1068                 index->idxname = pstrdup(constraint->name);
1069         else
1070                 index->idxname = NULL;  /* DefineIndex will choose name */
1071
1072         index->relation = cxt->relation;
1073         index->accessMethod = DEFAULT_INDEX_TYPE;
1074         index->options = constraint->options;
1075         index->tableSpace = constraint->indexspace;
1076         index->indexParams = NIL;
1077         index->whereClause = NULL;
1078         index->concurrent = false;
1079
1080         /*
1081          * Make sure referenced keys exist.  If we are making a PRIMARY KEY index,
1082          * also make sure they are NOT NULL, if possible. (Although we could leave
1083          * it to DefineIndex to mark the columns NOT NULL, it's more efficient to
1084          * get it right the first time.)
1085          */
1086         foreach(keys, constraint->keys)
1087         {
1088                 char       *key = strVal(lfirst(keys));
1089                 bool            found = false;
1090                 ColumnDef  *column = NULL;
1091                 ListCell   *columns;
1092
1093                 foreach(columns, cxt->columns)
1094                 {
1095                         column = (ColumnDef *) lfirst(columns);
1096                         Assert(IsA(column, ColumnDef));
1097                         if (strcmp(column->colname, key) == 0)
1098                         {
1099                                 found = true;
1100                                 break;
1101                         }
1102                 }
1103                 if (found)
1104                 {
1105                         /* found column in the new table; force it to be NOT NULL */
1106                         if (constraint->contype == CONSTR_PRIMARY)
1107                                 column->is_not_null = TRUE;
1108                 }
1109                 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1110                 {
1111                         /*
1112                          * column will be a system column in the new table, so accept it.
1113                          * System columns can't ever be null, so no need to worry about
1114                          * PRIMARY/NOT NULL constraint.
1115                          */
1116                         found = true;
1117                 }
1118                 else if (cxt->inhRelations)
1119                 {
1120                         /* try inherited tables */
1121                         ListCell   *inher;
1122
1123                         foreach(inher, cxt->inhRelations)
1124                         {
1125                                 RangeVar   *inh = (RangeVar *) lfirst(inher);
1126                                 Relation        rel;
1127                                 int                     count;
1128
1129                                 Assert(IsA(inh, RangeVar));
1130                                 rel = heap_openrv(inh, AccessShareLock);
1131                                 if (rel->rd_rel->relkind != RELKIND_RELATION)
1132                                         ereport(ERROR,
1133                                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1134                                                    errmsg("inherited relation \"%s\" is not a table",
1135                                                                   inh->relname)));
1136                                 for (count = 0; count < rel->rd_att->natts; count++)
1137                                 {
1138                                         Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1139                                         char       *inhname = NameStr(inhattr->attname);
1140
1141                                         if (inhattr->attisdropped)
1142                                                 continue;
1143                                         if (strcmp(key, inhname) == 0)
1144                                         {
1145                                                 found = true;
1146
1147                                                 /*
1148                                                  * We currently have no easy way to force an inherited
1149                                                  * column to be NOT NULL at creation, if its parent
1150                                                  * wasn't so already. We leave it to DefineIndex to
1151                                                  * fix things up in this case.
1152                                                  */
1153                                                 break;
1154                                         }
1155                                 }
1156                                 heap_close(rel, NoLock);
1157                                 if (found)
1158                                         break;
1159                         }
1160                 }
1161
1162                 /*
1163                  * In the ALTER TABLE case, don't complain about index keys not
1164                  * created in the command; they may well exist already. DefineIndex
1165                  * will complain about them if not, and will also take care of marking
1166                  * them NOT NULL.
1167                  */
1168                 if (!found && !cxt->isalter)
1169                         ereport(ERROR,
1170                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
1171                                          errmsg("column \"%s\" named in key does not exist",
1172                                                         key)));
1173
1174                 /* Check for PRIMARY KEY(foo, foo) */
1175                 foreach(columns, index->indexParams)
1176                 {
1177                         iparam = (IndexElem *) lfirst(columns);
1178                         if (iparam->name && strcmp(key, iparam->name) == 0)
1179                         {
1180                                 if (index->primary)
1181                                         ereport(ERROR,
1182                                                         (errcode(ERRCODE_DUPLICATE_COLUMN),
1183                                                          errmsg("column \"%s\" appears twice in primary key constraint",
1184                                                                         key)));
1185                                 else
1186                                         ereport(ERROR,
1187                                                         (errcode(ERRCODE_DUPLICATE_COLUMN),
1188                                         errmsg("column \"%s\" appears twice in unique constraint",
1189                                                    key)));
1190                         }
1191                 }
1192
1193                 /* OK, add it to the index definition */
1194                 iparam = makeNode(IndexElem);
1195                 iparam->name = pstrdup(key);
1196                 iparam->expr = NULL;
1197                 iparam->opclass = NIL;
1198                 iparam->ordering = SORTBY_DEFAULT;
1199                 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1200                 index->indexParams = lappend(index->indexParams, iparam);
1201         }
1202
1203         return index;
1204 }
1205
1206 /*
1207  * transformFKConstraints
1208  *              handle FOREIGN KEY constraints
1209  */
1210 static void
1211 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1212                                            bool skipValidation, bool isAddConstraint)
1213 {
1214         ListCell   *fkclist;
1215
1216         if (cxt->fkconstraints == NIL)
1217                 return;
1218
1219         /*
1220          * If CREATE TABLE or adding a column with NULL default, we can safely
1221          * skip validation of the constraint.
1222          */
1223         if (skipValidation)
1224         {
1225                 foreach(fkclist, cxt->fkconstraints)
1226                 {
1227                         FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1228
1229                         fkconstraint->skip_validation = true;
1230                 }
1231         }
1232
1233         /*
1234          * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1235          * CONSTRAINT command to execute after the basic command is complete. (If
1236          * called from ADD CONSTRAINT, that routine will add the FK constraints to
1237          * its own subcommand list.)
1238          *
1239          * Note: the ADD CONSTRAINT command must also execute after any index
1240          * creation commands.  Thus, this should run after
1241          * transformIndexConstraints, so that the CREATE INDEX commands are
1242          * already in cxt->alist.
1243          */
1244         if (!isAddConstraint)
1245         {
1246                 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1247
1248                 alterstmt->relation = cxt->relation;
1249                 alterstmt->cmds = NIL;
1250                 alterstmt->relkind = OBJECT_TABLE;
1251
1252                 foreach(fkclist, cxt->fkconstraints)
1253                 {
1254                         FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1255                         AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1256
1257                         altercmd->subtype = AT_ProcessedConstraint;
1258                         altercmd->name = NULL;
1259                         altercmd->def = (Node *) fkconstraint;
1260                         alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1261                 }
1262
1263                 cxt->alist = lappend(cxt->alist, alterstmt);
1264         }
1265 }
1266
1267 /*
1268  * transformIndexStmt - parse analysis for CREATE INDEX
1269  *
1270  * Note: this is a no-op for an index not using either index expressions or
1271  * a predicate expression.      There are several code paths that create indexes
1272  * without bothering to call this, because they know they don't have any
1273  * such expressions to deal with.
1274  */
1275 IndexStmt *
1276 transformIndexStmt(IndexStmt *stmt, const char *queryString)
1277 {
1278         Relation        rel;
1279         ParseState *pstate;
1280         RangeTblEntry *rte;
1281         ListCell   *l;
1282
1283         /*
1284          * We must not scribble on the passed-in IndexStmt, so copy it.  (This is
1285          * overkill, but easy.)
1286          */
1287         stmt = (IndexStmt *) copyObject(stmt);
1288
1289         /*
1290          * Open the parent table with appropriate locking.      We must do this
1291          * because addRangeTableEntry() would acquire only AccessShareLock,
1292          * leaving DefineIndex() needing to do a lock upgrade with consequent risk
1293          * of deadlock.  Make sure this stays in sync with the type of lock
1294          * DefineIndex() wants.
1295          */
1296         rel = heap_openrv(stmt->relation,
1297                                   (stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock));
1298
1299         /* Set up pstate */
1300         pstate = make_parsestate(NULL);
1301         pstate->p_sourcetext = queryString;
1302
1303         /*
1304          * Put the parent table into the rtable so that the expressions can refer
1305          * to its fields without qualification.
1306          */
1307         rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1308
1309         /* no to join list, yes to namespaces */
1310         addRTEtoQuery(pstate, rte, false, true, true);
1311
1312         /* take care of the where clause */
1313         if (stmt->whereClause)
1314                 stmt->whereClause = transformWhereClause(pstate,
1315                                                                                                  stmt->whereClause,
1316                                                                                                  "WHERE");
1317
1318         /* take care of any index expressions */
1319         foreach(l, stmt->indexParams)
1320         {
1321                 IndexElem  *ielem = (IndexElem *) lfirst(l);
1322
1323                 if (ielem->expr)
1324                 {
1325                         ielem->expr = transformExpr(pstate, ielem->expr);
1326
1327                         /*
1328                          * We check only that the result type is legitimate; this is for
1329                          * consistency with what transformWhereClause() checks for the
1330                          * predicate.  DefineIndex() will make more checks.
1331                          */
1332                         if (expression_returns_set(ielem->expr))
1333                                 ereport(ERROR,
1334                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1335                                                  errmsg("index expression cannot return a set")));
1336                 }
1337         }
1338
1339         /*
1340          * Check that only the base rel is mentioned.
1341          */
1342         if (list_length(pstate->p_rtable) != 1)
1343                 ereport(ERROR,
1344                                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1345                                  errmsg("index expressions and predicates can refer only to the table being indexed")));
1346
1347         free_parsestate(pstate);
1348
1349         /* Close relation, but keep the lock */
1350         heap_close(rel, NoLock);
1351
1352         return stmt;
1353 }
1354
1355
1356 /*
1357  * transformRuleStmt -
1358  *        transform a CREATE RULE Statement. The action is a list of parse
1359  *        trees which is transformed into a list of query trees, and we also
1360  *        transform the WHERE clause if any.
1361  *
1362  * actions and whereClause are output parameters that receive the
1363  * transformed results.
1364  *
1365  * Note that we must not scribble on the passed-in RuleStmt, so we do
1366  * copyObject() on the actions and WHERE clause.
1367  */
1368 void
1369 transformRuleStmt(RuleStmt *stmt, const char *queryString,
1370                                   List **actions, Node **whereClause)
1371 {
1372         Relation        rel;
1373         ParseState *pstate;
1374         RangeTblEntry *oldrte;
1375         RangeTblEntry *newrte;
1376
1377         /*
1378          * To avoid deadlock, make sure the first thing we do is grab
1379          * AccessExclusiveLock on the target relation.  This will be needed by
1380          * DefineQueryRewrite(), and we don't want to grab a lesser lock
1381          * beforehand.
1382          */
1383         rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1384
1385         /* Set up pstate */
1386         pstate = make_parsestate(NULL);
1387         pstate->p_sourcetext = queryString;
1388
1389         /*
1390          * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1391          * Set up their RTEs in the main pstate for use in parsing the rule
1392          * qualification.
1393          */
1394         oldrte = addRangeTableEntryForRelation(pstate, rel,
1395                                                                                    makeAlias("*OLD*", NIL),
1396                                                                                    false, false);
1397         newrte = addRangeTableEntryForRelation(pstate, rel,
1398                                                                                    makeAlias("*NEW*", NIL),
1399                                                                                    false, false);
1400         /* Must override addRangeTableEntry's default access-check flags */
1401         oldrte->requiredPerms = 0;
1402         newrte->requiredPerms = 0;
1403
1404         /*
1405          * They must be in the namespace too for lookup purposes, but only add the
1406          * one(s) that are relevant for the current kind of rule.  In an UPDATE
1407          * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1408          * there's no need to be so picky for INSERT & DELETE.  We do not add them
1409          * to the joinlist.
1410          */
1411         switch (stmt->event)
1412         {
1413                 case CMD_SELECT:
1414                         addRTEtoQuery(pstate, oldrte, false, true, true);
1415                         break;
1416                 case CMD_UPDATE:
1417                         addRTEtoQuery(pstate, oldrte, false, true, true);
1418                         addRTEtoQuery(pstate, newrte, false, true, true);
1419                         break;
1420                 case CMD_INSERT:
1421                         addRTEtoQuery(pstate, newrte, false, true, true);
1422                         break;
1423                 case CMD_DELETE:
1424                         addRTEtoQuery(pstate, oldrte, false, true, true);
1425                         break;
1426                 default:
1427                         elog(ERROR, "unrecognized event type: %d",
1428                                  (int) stmt->event);
1429                         break;
1430         }
1431
1432         /* take care of the where clause */
1433         *whereClause = transformWhereClause(pstate,
1434                                                                           (Node *) copyObject(stmt->whereClause),
1435                                                                                 "WHERE");
1436
1437         if (list_length(pstate->p_rtable) != 2)         /* naughty, naughty... */
1438                 ereport(ERROR,
1439                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1440                                  errmsg("rule WHERE condition cannot contain references to other relations")));
1441
1442         /* aggregates not allowed (but subselects are okay) */
1443         if (pstate->p_hasAggs)
1444                 ereport(ERROR,
1445                                 (errcode(ERRCODE_GROUPING_ERROR),
1446                    errmsg("cannot use aggregate function in rule WHERE condition")));
1447
1448         /*
1449          * 'instead nothing' rules with a qualification need a query rangetable so
1450          * the rewrite handler can add the negated rule qualification to the
1451          * original query. We create a query with the new command type CMD_NOTHING
1452          * here that is treated specially by the rewrite system.
1453          */
1454         if (stmt->actions == NIL)
1455         {
1456                 Query      *nothing_qry = makeNode(Query);
1457
1458                 nothing_qry->commandType = CMD_NOTHING;
1459                 nothing_qry->rtable = pstate->p_rtable;
1460                 nothing_qry->jointree = makeFromExpr(NIL, NULL);                /* no join wanted */
1461
1462                 *actions = list_make1(nothing_qry);
1463         }
1464         else
1465         {
1466                 ListCell   *l;
1467                 List       *newactions = NIL;
1468
1469                 /*
1470                  * transform each statement, like parse_sub_analyze()
1471                  */
1472                 foreach(l, stmt->actions)
1473                 {
1474                         Node       *action = (Node *) lfirst(l);
1475                         ParseState *sub_pstate = make_parsestate(NULL);
1476                         Query      *sub_qry,
1477                                            *top_subqry;
1478                         bool            has_old,
1479                                                 has_new;
1480
1481                         /*
1482                          * Since outer ParseState isn't parent of inner, have to pass down
1483                          * the query text by hand.
1484                          */
1485                         sub_pstate->p_sourcetext = queryString;
1486
1487                         /*
1488                          * Set up OLD/NEW in the rtable for this statement.  The entries
1489                          * are added only to relnamespace, not varnamespace, because we
1490                          * don't want them to be referred to by unqualified field names
1491                          * nor "*" in the rule actions.  We decide later whether to put
1492                          * them in the joinlist.
1493                          */
1494                         oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
1495                                                                                                    makeAlias("*OLD*", NIL),
1496                                                                                                    false, false);
1497                         newrte = addRangeTableEntryForRelation(sub_pstate, rel,
1498                                                                                                    makeAlias("*NEW*", NIL),
1499                                                                                                    false, false);
1500                         oldrte->requiredPerms = 0;
1501                         newrte->requiredPerms = 0;
1502                         addRTEtoQuery(sub_pstate, oldrte, false, true, false);
1503                         addRTEtoQuery(sub_pstate, newrte, false, true, false);
1504
1505                         /* Transform the rule action statement */
1506                         top_subqry = transformStmt(sub_pstate,
1507                                                                            (Node *) copyObject(action));
1508
1509                         /*
1510                          * We cannot support utility-statement actions (eg NOTIFY) with
1511                          * nonempty rule WHERE conditions, because there's no way to make
1512                          * the utility action execute conditionally.
1513                          */
1514                         if (top_subqry->commandType == CMD_UTILITY &&
1515                                 *whereClause != NULL)
1516                                 ereport(ERROR,
1517                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1518                                                  errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
1519
1520                         /*
1521                          * If the action is INSERT...SELECT, OLD/NEW have been pushed down
1522                          * into the SELECT, and that's what we need to look at. (Ugly
1523                          * kluge ... try to fix this when we redesign querytrees.)
1524                          */
1525                         sub_qry = getInsertSelectQuery(top_subqry, NULL);
1526
1527                         /*
1528                          * If the sub_qry is a setop, we cannot attach any qualifications
1529                          * to it, because the planner won't notice them.  This could
1530                          * perhaps be relaxed someday, but for now, we may as well reject
1531                          * such a rule immediately.
1532                          */
1533                         if (sub_qry->setOperations != NULL && *whereClause != NULL)
1534                                 ereport(ERROR,
1535                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1536                                                  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1537
1538                         /*
1539                          * Validate action's use of OLD/NEW, qual too
1540                          */
1541                         has_old =
1542                                 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1543                                 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
1544                         has_new =
1545                                 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1546                                 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
1547
1548                         switch (stmt->event)
1549                         {
1550                                 case CMD_SELECT:
1551                                         if (has_old)
1552                                                 ereport(ERROR,
1553                                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1554                                                                  errmsg("ON SELECT rule cannot use OLD")));
1555                                         if (has_new)
1556                                                 ereport(ERROR,
1557                                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1558                                                                  errmsg("ON SELECT rule cannot use NEW")));
1559                                         break;
1560                                 case CMD_UPDATE:
1561                                         /* both are OK */
1562                                         break;
1563                                 case CMD_INSERT:
1564                                         if (has_old)
1565                                                 ereport(ERROR,
1566                                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1567                                                                  errmsg("ON INSERT rule cannot use OLD")));
1568                                         break;
1569                                 case CMD_DELETE:
1570                                         if (has_new)
1571                                                 ereport(ERROR,
1572                                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1573                                                                  errmsg("ON DELETE rule cannot use NEW")));
1574                                         break;
1575                                 default:
1576                                         elog(ERROR, "unrecognized event type: %d",
1577                                                  (int) stmt->event);
1578                                         break;
1579                         }
1580
1581                         /*
1582                          * For efficiency's sake, add OLD to the rule action's jointree
1583                          * only if it was actually referenced in the statement or qual.
1584                          *
1585                          * For INSERT, NEW is not really a relation (only a reference to
1586                          * the to-be-inserted tuple) and should never be added to the
1587                          * jointree.
1588                          *
1589                          * For UPDATE, we treat NEW as being another kind of reference to
1590                          * OLD, because it represents references to *transformed* tuples
1591                          * of the existing relation.  It would be wrong to enter NEW
1592                          * separately in the jointree, since that would cause a double
1593                          * join of the updated relation.  It's also wrong to fail to make
1594                          * a jointree entry if only NEW and not OLD is mentioned.
1595                          */
1596                         if (has_old || (has_new && stmt->event == CMD_UPDATE))
1597                         {
1598                                 /*
1599                                  * If sub_qry is a setop, manipulating its jointree will do no
1600                                  * good at all, because the jointree is dummy. (This should be
1601                                  * a can't-happen case because of prior tests.)
1602                                  */
1603                                 if (sub_qry->setOperations != NULL)
1604                                         ereport(ERROR,
1605                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1606                                                          errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1607                                 /* hack so we can use addRTEtoQuery() */
1608                                 sub_pstate->p_rtable = sub_qry->rtable;
1609                                 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
1610                                 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
1611                                 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
1612                         }
1613
1614                         newactions = lappend(newactions, top_subqry);
1615
1616                         free_parsestate(sub_pstate);
1617                 }
1618
1619                 *actions = newactions;
1620         }
1621
1622         free_parsestate(pstate);
1623
1624         /* Close relation, but keep the exclusive lock */
1625         heap_close(rel, NoLock);
1626 }
1627
1628
1629 /*
1630  * transformAlterTableStmt -
1631  *              parse analysis for ALTER TABLE
1632  *
1633  * Returns a List of utility commands to be done in sequence.  One of these
1634  * will be the transformed AlterTableStmt, but there may be additional actions
1635  * to be done before and after the actual AlterTable() call.
1636  */
1637 List *
1638 transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
1639 {
1640         Relation        rel;
1641         ParseState *pstate;
1642         CreateStmtContext cxt;
1643         List       *result;
1644         List       *save_alist;
1645         ListCell   *lcmd,
1646                            *l;
1647         List       *newcmds = NIL;
1648         bool            skipValidation = true;
1649         AlterTableCmd *newcmd;
1650
1651         /*
1652          * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
1653          * is overkill, but easy.)
1654          */
1655         stmt = (AlterTableStmt *) copyObject(stmt);
1656
1657         /*
1658          * Acquire exclusive lock on the target relation, which will be held until
1659          * end of transaction.  This ensures any decisions we make here based on
1660          * the state of the relation will still be good at execution. We must get
1661          * exclusive lock now because execution will; taking a lower grade lock
1662          * now and trying to upgrade later risks deadlock.
1663          */
1664         rel = relation_openrv(stmt->relation, AccessExclusiveLock);
1665
1666         /* Set up pstate */
1667         pstate = make_parsestate(NULL);
1668         pstate->p_sourcetext = queryString;
1669
1670         cxt.stmtType = "ALTER TABLE";
1671         cxt.relation = stmt->relation;
1672         cxt.rel = rel;
1673         cxt.inhRelations = NIL;
1674         cxt.isalter = true;
1675         cxt.hasoids = false;            /* need not be right */
1676         cxt.columns = NIL;
1677         cxt.ckconstraints = NIL;
1678         cxt.fkconstraints = NIL;
1679         cxt.ixconstraints = NIL;
1680         cxt.inh_indexes = NIL;
1681         cxt.blist = NIL;
1682         cxt.alist = NIL;
1683         cxt.pkey = NULL;
1684
1685         /*
1686          * The only subtypes that currently require parse transformation handling
1687          * are ADD COLUMN and ADD CONSTRAINT.  These largely re-use code from
1688          * CREATE TABLE.
1689          */
1690         foreach(lcmd, stmt->cmds)
1691         {
1692                 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
1693
1694                 switch (cmd->subtype)
1695                 {
1696                         case AT_AddColumn:
1697                                 {
1698                                         ColumnDef  *def = (ColumnDef *) cmd->def;
1699
1700                                         Assert(IsA(cmd->def, ColumnDef));
1701                                         transformColumnDefinition(pstate, &cxt,
1702                                                                                           (ColumnDef *) cmd->def);
1703
1704                                         /*
1705                                          * If the column has a non-null default, we can't skip
1706                                          * validation of foreign keys.
1707                                          */
1708                                         if (((ColumnDef *) cmd->def)->raw_default != NULL)
1709                                                 skipValidation = false;
1710
1711                                         newcmds = lappend(newcmds, cmd);
1712
1713                                         /*
1714                                          * Convert an ADD COLUMN ... NOT NULL constraint to a
1715                                          * separate command
1716                                          */
1717                                         if (def->is_not_null)
1718                                         {
1719                                                 /* Remove NOT NULL from AddColumn */
1720                                                 def->is_not_null = false;
1721
1722                                                 /* Add as a separate AlterTableCmd */
1723                                                 newcmd = makeNode(AlterTableCmd);
1724                                                 newcmd->subtype = AT_SetNotNull;
1725                                                 newcmd->name = pstrdup(def->colname);
1726                                                 newcmds = lappend(newcmds, newcmd);
1727                                         }
1728
1729                                         /*
1730                                          * All constraints are processed in other ways. Remove the
1731                                          * original list
1732                                          */
1733                                         def->constraints = NIL;
1734
1735                                         break;
1736                                 }
1737                         case AT_AddConstraint:
1738
1739                                 /*
1740                                  * The original AddConstraint cmd node doesn't go to newcmds
1741                                  */
1742
1743                                 if (IsA(cmd->def, Constraint))
1744                                         transformTableConstraint(pstate, &cxt,
1745                                                                                          (Constraint *) cmd->def);
1746                                 else if (IsA(cmd->def, FkConstraint))
1747                                 {
1748                                         cxt.fkconstraints = lappend(cxt.fkconstraints, cmd->def);
1749                                         skipValidation = false;
1750                                 }
1751                                 else
1752                                         elog(ERROR, "unrecognized node type: %d",
1753                                                  (int) nodeTag(cmd->def));
1754                                 break;
1755
1756                         case AT_ProcessedConstraint:
1757
1758                                 /*
1759                                  * Already-transformed ADD CONSTRAINT, so just make it look
1760                                  * like the standard case.
1761                                  */
1762                                 cmd->subtype = AT_AddConstraint;
1763                                 newcmds = lappend(newcmds, cmd);
1764                                 break;
1765
1766                         default:
1767                                 newcmds = lappend(newcmds, cmd);
1768                                 break;
1769                 }
1770         }
1771
1772         /*
1773          * transformIndexConstraints wants cxt.alist to contain only index
1774          * statements, so transfer anything we already have into save_alist.
1775          * immediately.
1776          */
1777         save_alist = cxt.alist;
1778         cxt.alist = NIL;
1779
1780         /* Postprocess index and FK constraints */
1781         transformIndexConstraints(pstate, &cxt);
1782
1783         transformFKConstraints(pstate, &cxt, skipValidation, true);
1784
1785         /*
1786          * Push any index-creation commands into the ALTER, so that they can be
1787          * scheduled nicely by tablecmds.c.  Note that tablecmds.c assumes that
1788          * the IndexStmt attached to an AT_AddIndex subcommand has already been
1789          * through transformIndexStmt.
1790          */
1791         foreach(l, cxt.alist)
1792         {
1793                 Node       *idxstmt = (Node *) lfirst(l);
1794
1795                 Assert(IsA(idxstmt, IndexStmt));
1796                 newcmd = makeNode(AlterTableCmd);
1797                 newcmd->subtype = AT_AddIndex;
1798                 newcmd->def = (Node *) transformIndexStmt((IndexStmt *) idxstmt,
1799                                                                                                   queryString);
1800                 newcmds = lappend(newcmds, newcmd);
1801         }
1802         cxt.alist = NIL;
1803
1804         /* Append any CHECK or FK constraints to the commands list */
1805         foreach(l, cxt.ckconstraints)
1806         {
1807                 newcmd = makeNode(AlterTableCmd);
1808                 newcmd->subtype = AT_AddConstraint;
1809                 newcmd->def = (Node *) lfirst(l);
1810                 newcmds = lappend(newcmds, newcmd);
1811         }
1812         foreach(l, cxt.fkconstraints)
1813         {
1814                 newcmd = makeNode(AlterTableCmd);
1815                 newcmd->subtype = AT_AddConstraint;
1816                 newcmd->def = (Node *) lfirst(l);
1817                 newcmds = lappend(newcmds, newcmd);
1818         }
1819
1820         /* Close rel but keep lock */
1821         relation_close(rel, NoLock);
1822
1823         /*
1824          * Output results.
1825          */
1826         stmt->cmds = newcmds;
1827
1828         result = lappend(cxt.blist, stmt);
1829         result = list_concat(result, cxt.alist);
1830         result = list_concat(result, save_alist);
1831
1832         return result;
1833 }
1834
1835
1836 /*
1837  * Preprocess a list of column constraint clauses
1838  * to attach constraint attributes to their primary constraint nodes
1839  * and detect inconsistent/misplaced constraint attributes.
1840  *
1841  * NOTE: currently, attributes are only supported for FOREIGN KEY primary
1842  * constraints, but someday they ought to be supported for other constraints.
1843  */
1844 static void
1845 transformConstraintAttrs(List *constraintList)
1846 {
1847         Node       *lastprimarynode = NULL;
1848         bool            saw_deferrability = false;
1849         bool            saw_initially = false;
1850         ListCell   *clist;
1851
1852         foreach(clist, constraintList)
1853         {
1854                 Node       *node = lfirst(clist);
1855
1856                 if (!IsA(node, Constraint))
1857                 {
1858                         lastprimarynode = node;
1859                         /* reset flags for new primary node */
1860                         saw_deferrability = false;
1861                         saw_initially = false;
1862                 }
1863                 else
1864                 {
1865                         Constraint *con = (Constraint *) node;
1866
1867                         switch (con->contype)
1868                         {
1869                                 case CONSTR_ATTR_DEFERRABLE:
1870                                         if (lastprimarynode == NULL ||
1871                                                 !IsA(lastprimarynode, FkConstraint))
1872                                                 ereport(ERROR,
1873                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1874                                                                  errmsg("misplaced DEFERRABLE clause")));
1875                                         if (saw_deferrability)
1876                                                 ereport(ERROR,
1877                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1878                                                                  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
1879                                         saw_deferrability = true;
1880                                         ((FkConstraint *) lastprimarynode)->deferrable = true;
1881                                         break;
1882                                 case CONSTR_ATTR_NOT_DEFERRABLE:
1883                                         if (lastprimarynode == NULL ||
1884                                                 !IsA(lastprimarynode, FkConstraint))
1885                                                 ereport(ERROR,
1886                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1887                                                                  errmsg("misplaced NOT DEFERRABLE clause")));
1888                                         if (saw_deferrability)
1889                                                 ereport(ERROR,
1890                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1891                                                                  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
1892                                         saw_deferrability = true;
1893                                         ((FkConstraint *) lastprimarynode)->deferrable = false;
1894                                         if (saw_initially &&
1895                                                 ((FkConstraint *) lastprimarynode)->initdeferred)
1896                                                 ereport(ERROR,
1897                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1898                                                                  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
1899                                         break;
1900                                 case CONSTR_ATTR_DEFERRED:
1901                                         if (lastprimarynode == NULL ||
1902                                                 !IsA(lastprimarynode, FkConstraint))
1903                                                 ereport(ERROR,
1904                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1905                                                          errmsg("misplaced INITIALLY DEFERRED clause")));
1906                                         if (saw_initially)
1907                                                 ereport(ERROR,
1908                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1909                                                                  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
1910                                         saw_initially = true;
1911                                         ((FkConstraint *) lastprimarynode)->initdeferred = true;
1912
1913                                         /*
1914                                          * If only INITIALLY DEFERRED appears, assume DEFERRABLE
1915                                          */
1916                                         if (!saw_deferrability)
1917                                                 ((FkConstraint *) lastprimarynode)->deferrable = true;
1918                                         else if (!((FkConstraint *) lastprimarynode)->deferrable)
1919                                                 ereport(ERROR,
1920                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1921                                                                  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
1922                                         break;
1923                                 case CONSTR_ATTR_IMMEDIATE:
1924                                         if (lastprimarynode == NULL ||
1925                                                 !IsA(lastprimarynode, FkConstraint))
1926                                                 ereport(ERROR,
1927                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1928                                                         errmsg("misplaced INITIALLY IMMEDIATE clause")));
1929                                         if (saw_initially)
1930                                                 ereport(ERROR,
1931                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1932                                                                  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
1933                                         saw_initially = true;
1934                                         ((FkConstraint *) lastprimarynode)->initdeferred = false;
1935                                         break;
1936                                 default:
1937                                         /* Otherwise it's not an attribute */
1938                                         lastprimarynode = node;
1939                                         /* reset flags for new primary node */
1940                                         saw_deferrability = false;
1941                                         saw_initially = false;
1942                                         break;
1943                         }
1944                 }
1945         }
1946 }
1947
1948 /*
1949  * Special handling of type definition for a column
1950  */
1951 static void
1952 transformColumnType(ParseState *pstate, ColumnDef *column)
1953 {
1954         /*
1955          * All we really need to do here is verify that the type is valid.
1956          */
1957         Type            ctype = typenameType(pstate, column->typename, NULL);
1958
1959         ReleaseSysCache(ctype);
1960 }
1961
1962
1963 /*
1964  * transformCreateSchemaStmt -
1965  *        analyzes the CREATE SCHEMA statement
1966  *
1967  * Split the schema element list into individual commands and place
1968  * them in the result list in an order such that there are no forward
1969  * references (e.g. GRANT to a table created later in the list). Note
1970  * that the logic we use for determining forward references is
1971  * presently quite incomplete.
1972  *
1973  * SQL92 also allows constraints to make forward references, so thumb through
1974  * the table columns and move forward references to a posterior alter-table
1975  * command.
1976  *
1977  * The result is a list of parse nodes that still need to be analyzed ---
1978  * but we can't analyze the later commands until we've executed the earlier
1979  * ones, because of possible inter-object references.
1980  *
1981  * Note: this breaks the rules a little bit by modifying schema-name fields
1982  * within passed-in structs.  However, the transformation would be the same
1983  * if done over, so it should be all right to scribble on the input to this
1984  * extent.
1985  */
1986 List *
1987 transformCreateSchemaStmt(CreateSchemaStmt *stmt)
1988 {
1989         CreateSchemaStmtContext cxt;
1990         List       *result;
1991         ListCell   *elements;
1992
1993         cxt.stmtType = "CREATE SCHEMA";
1994         cxt.schemaname = stmt->schemaname;
1995         cxt.authid = stmt->authid;
1996         cxt.sequences = NIL;
1997         cxt.tables = NIL;
1998         cxt.views = NIL;
1999         cxt.indexes = NIL;
2000         cxt.triggers = NIL;
2001         cxt.grants = NIL;
2002
2003         /*
2004          * Run through each schema element in the schema element list. Separate
2005          * statements by type, and do preliminary analysis.
2006          */
2007         foreach(elements, stmt->schemaElts)
2008         {
2009                 Node       *element = lfirst(elements);
2010
2011                 switch (nodeTag(element))
2012                 {
2013                         case T_CreateSeqStmt:
2014                                 {
2015                                         CreateSeqStmt *elp = (CreateSeqStmt *) element;
2016
2017                                         setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
2018                                         cxt.sequences = lappend(cxt.sequences, element);
2019                                 }
2020                                 break;
2021
2022                         case T_CreateStmt:
2023                                 {
2024                                         CreateStmt *elp = (CreateStmt *) element;
2025
2026                                         setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2027
2028                                         /*
2029                                          * XXX todo: deal with constraints
2030                                          */
2031                                         cxt.tables = lappend(cxt.tables, element);
2032                                 }
2033                                 break;
2034
2035                         case T_ViewStmt:
2036                                 {
2037                                         ViewStmt   *elp = (ViewStmt *) element;
2038
2039                                         setSchemaName(cxt.schemaname, &elp->view->schemaname);
2040
2041                                         /*
2042                                          * XXX todo: deal with references between views
2043                                          */
2044                                         cxt.views = lappend(cxt.views, element);
2045                                 }
2046                                 break;
2047
2048                         case T_IndexStmt:
2049                                 {
2050                                         IndexStmt  *elp = (IndexStmt *) element;
2051
2052                                         setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2053                                         cxt.indexes = lappend(cxt.indexes, element);
2054                                 }
2055                                 break;
2056
2057                         case T_CreateTrigStmt:
2058                                 {
2059                                         CreateTrigStmt *elp = (CreateTrigStmt *) element;
2060
2061                                         setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2062                                         cxt.triggers = lappend(cxt.triggers, element);
2063                                 }
2064                                 break;
2065
2066                         case T_GrantStmt:
2067                                 cxt.grants = lappend(cxt.grants, element);
2068                                 break;
2069
2070                         default:
2071                                 elog(ERROR, "unrecognized node type: %d",
2072                                          (int) nodeTag(element));
2073                 }
2074         }
2075
2076         result = NIL;
2077         result = list_concat(result, cxt.sequences);
2078         result = list_concat(result, cxt.tables);
2079         result = list_concat(result, cxt.views);
2080         result = list_concat(result, cxt.indexes);
2081         result = list_concat(result, cxt.triggers);
2082         result = list_concat(result, cxt.grants);
2083
2084         return result;
2085 }
2086
2087 /*
2088  * setSchemaName
2089  *              Set or check schema name in an element of a CREATE SCHEMA command
2090  */
2091 static void
2092 setSchemaName(char *context_schema, char **stmt_schema_name)
2093 {
2094         if (*stmt_schema_name == NULL)
2095                 *stmt_schema_name = context_schema;
2096         else if (strcmp(context_schema, *stmt_schema_name) != 0)
2097                 ereport(ERROR,
2098                                 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
2099                                  errmsg("CREATE specifies a schema (%s) "
2100                                                 "different from the one being created (%s)",
2101                                                 *stmt_schema_name, context_schema)));
2102 }