OSDN Git Service

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