1 /*-------------------------------------------------------------------------
4 * Perform parse analysis work for various utility commands
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.
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.
19 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
20 * Portions Copyright (c) 1994, Regents of the University of California
22 * $PostgreSQL: pgsql/src/backend/parser/parse_utilcmd.c,v 2.24 2009/07/29 20:56:19 tgl Exp $
24 *-------------------------------------------------------------------------
29 #include "access/genam.h"
30 #include "access/heapam.h"
31 #include "access/reloptions.h"
32 #include "catalog/dependency.h"
33 #include "catalog/heap.h"
34 #include "catalog/index.h"
35 #include "catalog/namespace.h"
36 #include "catalog/pg_constraint.h"
37 #include "catalog/pg_opclass.h"
38 #include "catalog/pg_type.h"
39 #include "commands/defrem.h"
40 #include "commands/tablecmds.h"
41 #include "commands/tablespace.h"
42 #include "miscadmin.h"
43 #include "nodes/makefuncs.h"
44 #include "nodes/nodeFuncs.h"
45 #include "parser/analyze.h"
46 #include "parser/parse_clause.h"
47 #include "parser/parse_expr.h"
48 #include "parser/parse_relation.h"
49 #include "parser/parse_type.h"
50 #include "parser/parse_utilcmd.h"
51 #include "parser/parser.h"
52 #include "rewrite/rewriteManip.h"
53 #include "utils/acl.h"
54 #include "utils/builtins.h"
55 #include "utils/lsyscache.h"
56 #include "utils/relcache.h"
57 #include "utils/syscache.h"
60 /* State shared by transformCreateStmt and its subroutines */
63 const char *stmtType; /* "CREATE TABLE" or "ALTER TABLE" */
64 RangeVar *relation; /* relation to create */
65 Relation rel; /* opened/locked rel, if ALTER */
66 List *inhRelations; /* relations to inherit from */
67 bool isalter; /* true if altering existing table */
68 bool hasoids; /* does relation have an OID column? */
69 List *columns; /* ColumnDef items */
70 List *ckconstraints; /* CHECK constraints */
71 List *fkconstraints; /* FOREIGN KEY constraints */
72 List *ixconstraints; /* index-creating constraints */
73 List *inh_indexes; /* cloned indexes from INCLUDING INDEXES */
74 List *blist; /* "before list" of things to do before
75 * creating the table */
76 List *alist; /* "after list" of things to do after creating
78 IndexStmt *pkey; /* PRIMARY KEY index, if any */
81 /* State shared by transformCreateSchemaStmt and its subroutines */
84 const char *stmtType; /* "CREATE SCHEMA" or "ALTER SCHEMA" */
85 char *schemaname; /* name of schema */
86 char *authid; /* owner of schema */
87 List *sequences; /* CREATE SEQUENCE items */
88 List *tables; /* CREATE TABLE items */
89 List *views; /* CREATE VIEW items */
90 List *indexes; /* CREATE INDEX items */
91 List *triggers; /* CREATE TRIGGER items */
92 List *grants; /* GRANT items */
93 } CreateSchemaStmtContext;
96 static void transformColumnDefinition(ParseState *pstate,
97 CreateStmtContext *cxt,
99 static void transformTableConstraint(ParseState *pstate,
100 CreateStmtContext *cxt,
101 Constraint *constraint);
102 static void transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
103 InhRelation *inhrelation);
104 static IndexStmt *generateClonedIndexStmt(CreateStmtContext *cxt,
105 Relation parent_index, AttrNumber *attmap);
106 static List *get_opclass(Oid opclass, Oid actual_datatype);
107 static void transformIndexConstraints(ParseState *pstate,
108 CreateStmtContext *cxt);
109 static IndexStmt *transformIndexConstraint(Constraint *constraint,
110 CreateStmtContext *cxt);
111 static void transformFKConstraints(ParseState *pstate,
112 CreateStmtContext *cxt,
114 bool isAddConstraint);
115 static void transformConstraintAttrs(List *constraintList);
116 static void transformColumnType(ParseState *pstate, ColumnDef *column);
117 static void setSchemaName(char *context_schema, char **stmt_schema_name);
121 * transformCreateStmt -
122 * parse analysis for CREATE TABLE
124 * Returns a List of utility commands to be done in sequence. One of these
125 * will be the transformed CreateStmt, but there may be additional actions
126 * to be done before and after the actual DefineRelation() call.
128 * SQL92 allows constraints to be scattered all over, so thumb through
129 * the columns and collect all constraints into one place.
130 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
131 * then expand those into multiple IndexStmt blocks.
132 * - thomas 1997-12-02
135 transformCreateStmt(CreateStmt *stmt, const char *queryString)
138 CreateStmtContext cxt;
144 * We must not scribble on the passed-in CreateStmt, so copy it. (This is
145 * overkill, but easy.)
147 stmt = (CreateStmt *) copyObject(stmt);
150 * If the target relation name isn't schema-qualified, make it so. This
151 * prevents some corner cases in which added-on rewritten commands might
152 * think they should apply to other relations that have the same name and
153 * are earlier in the search path. "istemp" is equivalent to a
154 * specification of pg_temp, so no need for anything extra in that case.
156 if (stmt->relation->schemaname == NULL && !stmt->relation->istemp)
158 Oid namespaceid = RangeVarGetCreationNamespace(stmt->relation);
160 stmt->relation->schemaname = get_namespace_name(namespaceid);
164 pstate = make_parsestate(NULL);
165 pstate->p_sourcetext = queryString;
167 cxt.stmtType = "CREATE TABLE";
168 cxt.relation = stmt->relation;
170 cxt.inhRelations = stmt->inhRelations;
173 cxt.ckconstraints = NIL;
174 cxt.fkconstraints = NIL;
175 cxt.ixconstraints = NIL;
176 cxt.inh_indexes = NIL;
180 cxt.hasoids = interpretOidsOption(stmt->options);
183 * Run through each primary element in the table creation clause. Separate
184 * column defs from constraints, and do preliminary analysis.
186 foreach(elements, stmt->tableElts)
188 Node *element = lfirst(elements);
190 switch (nodeTag(element))
193 transformColumnDefinition(pstate, &cxt,
194 (ColumnDef *) element);
198 transformTableConstraint(pstate, &cxt,
199 (Constraint *) element);
203 /* No pre-transformation needed */
204 cxt.fkconstraints = lappend(cxt.fkconstraints, element);
208 transformInhRelation(pstate, &cxt,
209 (InhRelation *) element);
213 elog(ERROR, "unrecognized node type: %d",
214 (int) nodeTag(element));
220 * transformIndexConstraints wants cxt.alist to contain only index
221 * statements, so transfer anything we already have into save_alist.
223 save_alist = cxt.alist;
226 Assert(stmt->constraints == NIL);
229 * Postprocess constraints that give rise to index definitions.
231 transformIndexConstraints(pstate, &cxt);
234 * Postprocess foreign-key constraints.
236 transformFKConstraints(pstate, &cxt, true, false);
241 stmt->tableElts = cxt.columns;
242 stmt->constraints = cxt.ckconstraints;
244 result = lappend(cxt.blist, stmt);
245 result = list_concat(result, cxt.alist);
246 result = list_concat(result, save_alist);
252 * transformColumnDefinition -
253 * transform a single ColumnDef within CREATE TABLE
254 * Also used in ALTER TABLE ADD COLUMN
257 transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
263 Constraint *constraint;
266 cxt->columns = lappend(cxt->columns, column);
268 /* Check for SERIAL pseudo-types */
270 if (list_length(column->typeName->names) == 1 &&
271 !column->typeName->pct_type)
273 char *typname = strVal(linitial(column->typeName->names));
275 if (strcmp(typname, "serial") == 0 ||
276 strcmp(typname, "serial4") == 0)
279 column->typeName->names = NIL;
280 column->typeName->typeOid = INT4OID;
282 else if (strcmp(typname, "bigserial") == 0 ||
283 strcmp(typname, "serial8") == 0)
286 column->typeName->names = NIL;
287 column->typeName->typeOid = INT8OID;
291 * We have to reject "serial[]" explicitly, because once we've set
292 * typeid, LookupTypeName won't notice arrayBounds. We don't need any
293 * special coding for serial(typmod) though.
295 if (is_serial && column->typeName->arrayBounds != NIL)
297 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
298 errmsg("array of serial is not implemented")));
301 /* Do necessary work on the column type declaration */
302 transformColumnType(pstate, column);
304 /* Special actions for SERIAL pseudo-types */
313 FuncCall *funccallnode;
314 CreateSeqStmt *seqstmt;
315 AlterSeqStmt *altseqstmt;
319 * Determine namespace and name to use for the sequence.
321 * Although we use ChooseRelationName, it's not guaranteed that the
322 * selected sequence name won't conflict; given sufficiently long
323 * field names, two different serial columns in the same table could
324 * be assigned the same sequence name, and we'd not notice since we
325 * aren't creating the sequence quite yet. In practice this seems
326 * quite unlikely to be a problem, especially since few people would
327 * need two serial columns in one table.
330 snamespaceid = RelationGetNamespace(cxt->rel);
332 snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
333 snamespace = get_namespace_name(snamespaceid);
334 sname = ChooseRelationName(cxt->relation->relname,
340 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
341 cxt->stmtType, sname,
342 cxt->relation->relname, column->colname)));
345 * Build a CREATE SEQUENCE command to create the sequence object, and
346 * add it to the list of things to be done before this CREATE/ALTER
349 seqstmt = makeNode(CreateSeqStmt);
350 seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
351 seqstmt->options = NIL;
353 cxt->blist = lappend(cxt->blist, seqstmt);
356 * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence
357 * as owned by this column, and add it to the list of things to be
358 * done after this CREATE/ALTER TABLE.
360 altseqstmt = makeNode(AlterSeqStmt);
361 altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
362 attnamelist = list_make3(makeString(snamespace),
363 makeString(cxt->relation->relname),
364 makeString(column->colname));
365 altseqstmt->options = list_make1(makeDefElem("owned_by",
366 (Node *) attnamelist));
368 cxt->alist = lappend(cxt->alist, altseqstmt);
371 * Create appropriate constraints for SERIAL. We do this in full,
372 * rather than shortcutting, so that we will detect any conflicting
373 * constraints the user wrote (like a different DEFAULT).
375 * Create an expression tree representing the function call
376 * nextval('sequencename'). We cannot reduce the raw tree to cooked
377 * form until after the sequence is created, but there's no need to do
380 qstring = quote_qualified_identifier(snamespace, sname);
381 snamenode = makeNode(A_Const);
382 snamenode->val.type = T_String;
383 snamenode->val.val.str = qstring;
384 snamenode->location = -1;
385 castnode = makeNode(TypeCast);
386 castnode->typeName = SystemTypeName("regclass");
387 castnode->arg = (Node *) snamenode;
388 castnode->location = -1;
389 funccallnode = makeNode(FuncCall);
390 funccallnode->funcname = SystemFuncName("nextval");
391 funccallnode->args = list_make1(castnode);
392 funccallnode->agg_star = false;
393 funccallnode->agg_distinct = false;
394 funccallnode->func_variadic = false;
395 funccallnode->over = NULL;
396 funccallnode->location = -1;
398 constraint = makeNode(Constraint);
399 constraint->contype = CONSTR_DEFAULT;
400 constraint->raw_expr = (Node *) funccallnode;
401 constraint->cooked_expr = NULL;
402 constraint->keys = NIL;
403 column->constraints = lappend(column->constraints, constraint);
405 constraint = makeNode(Constraint);
406 constraint->contype = CONSTR_NOTNULL;
407 column->constraints = lappend(column->constraints, constraint);
410 /* Process column constraints, if any... */
411 transformConstraintAttrs(column->constraints);
413 saw_nullable = false;
416 foreach(clist, column->constraints)
418 constraint = lfirst(clist);
421 * If this column constraint is a FOREIGN KEY constraint, then we fill
422 * in the current attribute's name and throw it into the list of FK
423 * constraints to be processed later.
425 if (IsA(constraint, FkConstraint))
427 FkConstraint *fkconstraint = (FkConstraint *) constraint;
429 fkconstraint->fk_attrs = list_make1(makeString(column->colname));
430 cxt->fkconstraints = lappend(cxt->fkconstraints, fkconstraint);
434 Assert(IsA(constraint, Constraint));
436 switch (constraint->contype)
439 if (saw_nullable && column->is_not_null)
441 (errcode(ERRCODE_SYNTAX_ERROR),
442 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
443 column->colname, cxt->relation->relname)));
444 column->is_not_null = FALSE;
449 if (saw_nullable && !column->is_not_null)
451 (errcode(ERRCODE_SYNTAX_ERROR),
452 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
453 column->colname, cxt->relation->relname)));
454 column->is_not_null = TRUE;
461 (errcode(ERRCODE_SYNTAX_ERROR),
462 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
463 column->colname, cxt->relation->relname)));
464 column->raw_default = constraint->raw_expr;
465 Assert(constraint->cooked_expr == NULL);
471 if (constraint->keys == NIL)
472 constraint->keys = list_make1(makeString(column->colname));
473 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
477 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
480 case CONSTR_ATTR_DEFERRABLE:
481 case CONSTR_ATTR_NOT_DEFERRABLE:
482 case CONSTR_ATTR_DEFERRED:
483 case CONSTR_ATTR_IMMEDIATE:
484 /* transformConstraintAttrs took care of these */
488 elog(ERROR, "unrecognized constraint type: %d",
489 constraint->contype);
496 * transformTableConstraint
497 * transform a Constraint node within CREATE TABLE or ALTER TABLE
500 transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt,
501 Constraint *constraint)
503 switch (constraint->contype)
507 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
511 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
517 case CONSTR_ATTR_DEFERRABLE:
518 case CONSTR_ATTR_NOT_DEFERRABLE:
519 case CONSTR_ATTR_DEFERRED:
520 case CONSTR_ATTR_IMMEDIATE:
521 elog(ERROR, "invalid context for constraint type %d",
522 constraint->contype);
526 elog(ERROR, "unrecognized constraint type: %d",
527 constraint->contype);
533 * transformInhRelation
535 * Change the LIKE <subtable> portion of a CREATE TABLE statement into
536 * column definitions which recreate the user defined column portions of
540 transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
541 InhRelation *inhRelation)
543 AttrNumber parent_attno;
548 bool including_defaults = false;
549 bool including_constraints = false;
550 bool including_indexes = false;
553 relation = parserOpenTable(pstate, inhRelation->relation, AccessShareLock);
555 if (relation->rd_rel->relkind != RELKIND_RELATION)
557 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
558 errmsg("inherited relation \"%s\" is not a table",
559 inhRelation->relation->relname)));
562 * Check for SELECT privilages
564 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
566 if (aclresult != ACLCHECK_OK)
567 aclcheck_error(aclresult, ACL_KIND_CLASS,
568 RelationGetRelationName(relation));
570 tupleDesc = RelationGetDescr(relation);
571 constr = tupleDesc->constr;
573 foreach(elem, inhRelation->options)
575 int option = lfirst_int(elem);
579 case CREATE_TABLE_LIKE_INCLUDING_DEFAULTS:
580 including_defaults = true;
582 case CREATE_TABLE_LIKE_EXCLUDING_DEFAULTS:
583 including_defaults = false;
585 case CREATE_TABLE_LIKE_INCLUDING_CONSTRAINTS:
586 including_constraints = true;
588 case CREATE_TABLE_LIKE_EXCLUDING_CONSTRAINTS:
589 including_constraints = false;
591 case CREATE_TABLE_LIKE_INCLUDING_INDEXES:
592 including_indexes = true;
594 case CREATE_TABLE_LIKE_EXCLUDING_INDEXES:
595 including_indexes = false;
598 elog(ERROR, "unrecognized CREATE TABLE LIKE option: %d",
604 * Insert the copied attributes into the cxt for the new table definition.
606 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
609 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
610 char *attributeName = NameStr(attribute->attname);
614 * Ignore dropped columns in the parent.
616 if (attribute->attisdropped)
620 * Create a new column, which is marked as NOT inherited.
622 * For constraints, ONLY the NOT NULL constraint is inherited by the
623 * new column definition per SQL99.
625 def = makeNode(ColumnDef);
626 def->colname = pstrdup(attributeName);
627 def->typeName = makeTypeNameFromOid(attribute->atttypid,
628 attribute->atttypmod);
630 def->is_local = true;
631 def->is_not_null = attribute->attnotnull;
632 def->raw_default = NULL;
633 def->cooked_default = NULL;
634 def->constraints = NIL;
639 cxt->columns = lappend(cxt->columns, def);
642 * Copy default, if present and the default has been requested
644 if (attribute->atthasdef && including_defaults)
646 char *this_default = NULL;
647 AttrDefault *attrdef;
650 /* Find default in constraint structure */
651 Assert(constr != NULL);
652 attrdef = constr->defval;
653 for (i = 0; i < constr->num_defval; i++)
655 if (attrdef[i].adnum == parent_attno)
657 this_default = attrdef[i].adbin;
661 Assert(this_default != NULL);
664 * If default expr could contain any vars, we'd need to fix 'em,
665 * but it can't; so default is ready to apply to child.
668 def->cooked_default = pstrdup(this_default);
673 * Copy CHECK constraints if requested, being careful to adjust attribute
676 if (including_constraints && tupleDesc->constr)
678 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
681 for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
683 char *ccname = tupleDesc->constr->check[ccnum].ccname;
684 char *ccbin = tupleDesc->constr->check[ccnum].ccbin;
685 Node *ccbin_node = stringToNode(ccbin);
686 Constraint *n = makeNode(Constraint);
688 change_varattnos_of_a_node(ccbin_node, attmap);
690 n->contype = CONSTR_CHECK;
691 n->name = pstrdup(ccname);
693 n->cooked_expr = nodeToString(ccbin_node);
694 n->indexspace = NULL;
695 cxt->ckconstraints = lappend(cxt->ckconstraints, (Node *) n);
700 * Likewise, copy indexes if requested
702 if (including_indexes && relation->rd_rel->relhasindex)
704 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
705 List *parent_indexes;
708 parent_indexes = RelationGetIndexList(relation);
710 foreach(l, parent_indexes)
712 Oid parent_index_oid = lfirst_oid(l);
713 Relation parent_index;
714 IndexStmt *index_stmt;
716 parent_index = index_open(parent_index_oid, AccessShareLock);
718 /* Build CREATE INDEX statement to recreate the parent_index */
719 index_stmt = generateClonedIndexStmt(cxt, parent_index, attmap);
721 /* Save it in the inh_indexes list for the time being */
722 cxt->inh_indexes = lappend(cxt->inh_indexes, index_stmt);
724 index_close(parent_index, AccessShareLock);
729 * Close the parent rel, but keep our AccessShareLock on it until xact
730 * commit. That will prevent someone else from deleting or ALTERing the
731 * parent before the child is committed.
733 heap_close(relation, NoLock);
737 * Generate an IndexStmt node using information from an already existing index
738 * "source_idx". Attribute numbers should be adjusted according to attmap.
741 generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
744 Oid source_relid = RelationGetRelid(source_idx);
747 Form_pg_class idxrelrec;
748 Form_pg_index idxrec;
753 ListCell *indexpr_item;
761 * Fetch pg_class tuple of source index. We can't use the copy in the
762 * relcache entry because it doesn't include optional fields.
764 ht_idxrel = SearchSysCache(RELOID,
765 ObjectIdGetDatum(source_relid),
767 if (!HeapTupleIsValid(ht_idxrel))
768 elog(ERROR, "cache lookup failed for relation %u", source_relid);
769 idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
771 /* Fetch pg_index tuple for source index from relcache entry */
772 ht_idx = source_idx->rd_indextuple;
773 idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
774 indrelid = idxrec->indrelid;
776 /* Fetch pg_am tuple for source index from relcache entry */
777 amrec = source_idx->rd_am;
779 /* Must get indclass the hard way, since it's not stored in relcache */
780 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
781 Anum_pg_index_indclass, &isnull);
783 indclass = (oidvector *) DatumGetPointer(datum);
785 /* Begin building the IndexStmt */
786 index = makeNode(IndexStmt);
787 index->relation = cxt->relation;
788 index->accessMethod = pstrdup(NameStr(amrec->amname));
789 if (OidIsValid(idxrelrec->reltablespace))
790 index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
792 index->tableSpace = NULL;
793 index->unique = idxrec->indisunique;
794 index->primary = idxrec->indisprimary;
795 index->concurrent = false;
798 * We don't try to preserve the name of the source index; instead, just
799 * let DefineIndex() choose a reasonable name.
801 index->idxname = NULL;
804 * If the index is marked PRIMARY, it's certainly from a constraint; else,
805 * if it's not marked UNIQUE, it certainly isn't. If it is or might be
806 * from a constraint, we have to fetch the constraint to check for
807 * deferrability attributes.
809 if (index->primary || index->unique)
811 Oid constraintId = get_index_constraint(source_relid);
813 if (OidIsValid(constraintId))
816 Form_pg_constraint conrec;
818 ht_constr = SearchSysCache(CONSTROID,
819 ObjectIdGetDatum(constraintId),
821 if (!HeapTupleIsValid(ht_constr))
822 elog(ERROR, "cache lookup failed for constraint %u",
824 conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
826 index->isconstraint = true;
827 index->deferrable = conrec->condeferrable;
828 index->initdeferred = conrec->condeferred;
830 ReleaseSysCache(ht_constr);
833 index->isconstraint = false;
836 index->isconstraint = false;
838 /* Get the index expressions, if any */
839 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
840 Anum_pg_index_indexprs, &isnull);
845 exprsString = TextDatumGetCString(datum);
846 indexprs = (List *) stringToNode(exprsString);
851 /* Build the list of IndexElem */
852 index->indexParams = NIL;
854 indexpr_item = list_head(indexprs);
855 for (keyno = 0; keyno < idxrec->indnatts; keyno++)
858 AttrNumber attnum = idxrec->indkey.values[keyno];
859 int16 opt = source_idx->rd_indoption[keyno];
861 iparam = makeNode(IndexElem);
863 if (AttributeNumberIsValid(attnum))
865 /* Simple index column */
868 attname = get_relid_attribute_name(indrelid, attnum);
869 keycoltype = get_atttype(indrelid, attnum);
871 iparam->name = attname;
876 /* Expressional index */
879 if (indexpr_item == NULL)
880 elog(ERROR, "too few entries in indexprs list");
881 indexkey = (Node *) lfirst(indexpr_item);
882 indexpr_item = lnext(indexpr_item);
884 /* OK to modify indexkey since we are working on a private copy */
885 change_varattnos_of_a_node(indexkey, attmap);
888 iparam->expr = indexkey;
890 keycoltype = exprType(indexkey);
893 /* Add the operator class name, if non-default */
894 iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
896 iparam->ordering = SORTBY_DEFAULT;
897 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
899 /* Adjust options if necessary */
900 if (amrec->amcanorder)
903 * If it supports sort ordering, copy DESC and NULLS opts. Don't
904 * set non-default settings unnecessarily, though, so as to
905 * improve the chance of recognizing equivalence to constraint
908 if (opt & INDOPTION_DESC)
910 iparam->ordering = SORTBY_DESC;
911 if ((opt & INDOPTION_NULLS_FIRST) == 0)
912 iparam->nulls_ordering = SORTBY_NULLS_LAST;
916 if (opt & INDOPTION_NULLS_FIRST)
917 iparam->nulls_ordering = SORTBY_NULLS_FIRST;
921 index->indexParams = lappend(index->indexParams, iparam);
924 /* Copy reloptions if any */
925 datum = SysCacheGetAttr(RELOID, ht_idxrel,
926 Anum_pg_class_reloptions, &isnull);
928 index->options = untransformRelOptions(datum);
930 /* If it's a partial index, decompile and append the predicate */
931 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
932 Anum_pg_index_indpred, &isnull);
937 /* Convert text string to node tree */
938 pred_str = TextDatumGetCString(datum);
939 index->whereClause = (Node *) stringToNode(pred_str);
940 /* Adjust attribute numbers */
941 change_varattnos_of_a_node(index->whereClause, attmap);
945 ReleaseSysCache(ht_idxrel);
951 * get_opclass - fetch name of an index operator class
953 * If the opclass is the default for the given actual_datatype, then
954 * the return value is NIL.
957 get_opclass(Oid opclass, Oid actual_datatype)
960 Form_pg_opclass opc_rec;
963 ht_opc = SearchSysCache(CLAOID,
964 ObjectIdGetDatum(opclass),
966 if (!HeapTupleIsValid(ht_opc))
967 elog(ERROR, "cache lookup failed for opclass %u", opclass);
968 opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
970 if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
972 /* For simplicity, we always schema-qualify the name */
973 char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
974 char *opc_name = pstrdup(NameStr(opc_rec->opcname));
976 result = list_make2(makeString(nsp_name), makeString(opc_name));
979 ReleaseSysCache(ht_opc);
985 * transformIndexConstraints
986 * Handle UNIQUE and PRIMARY KEY constraints, which create indexes.
987 * We also merge in any index definitions arising from
988 * LIKE ... INCLUDING INDEXES.
991 transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
994 List *indexlist = NIL;
998 * Run through the constraints that need to generate an index. For PRIMARY
999 * KEY, mark each column as NOT NULL and create an index. For UNIQUE,
1000 * create an index as for PRIMARY KEY, but do not insist on NOT NULL.
1002 foreach(lc, cxt->ixconstraints)
1004 Constraint *constraint = (Constraint *) lfirst(lc);
1006 Assert(IsA(constraint, Constraint));
1007 Assert(constraint->contype == CONSTR_PRIMARY ||
1008 constraint->contype == CONSTR_UNIQUE);
1010 index = transformIndexConstraint(constraint, cxt);
1012 indexlist = lappend(indexlist, index);
1015 /* Add in any indexes defined by LIKE ... INCLUDING INDEXES */
1016 foreach(lc, cxt->inh_indexes)
1018 index = (IndexStmt *) lfirst(lc);
1022 if (cxt->pkey != NULL)
1024 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1025 errmsg("multiple primary keys for table \"%s\" are not allowed",
1026 cxt->relation->relname)));
1030 indexlist = lappend(indexlist, index);
1034 * Scan the index list and remove any redundant index specifications. This
1035 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1036 * strict reading of SQL92 would suggest raising an error instead, but
1037 * that strikes me as too anal-retentive. - tgl 2001-02-14
1039 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1040 * pre-existing indexes, too.
1042 Assert(cxt->alist == NIL);
1043 if (cxt->pkey != NULL)
1045 /* Make sure we keep the PKEY index in preference to others... */
1046 cxt->alist = list_make1(cxt->pkey);
1049 foreach(lc, indexlist)
1056 /* if it's pkey, it's already in cxt->alist */
1057 if (index == cxt->pkey)
1060 foreach(k, cxt->alist)
1062 IndexStmt *priorindex = lfirst(k);
1064 if (equal(index->indexParams, priorindex->indexParams) &&
1065 equal(index->whereClause, priorindex->whereClause) &&
1066 strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
1067 index->deferrable == priorindex->deferrable &&
1068 index->initdeferred == priorindex->initdeferred)
1070 priorindex->unique |= index->unique;
1073 * If the prior index is as yet unnamed, and this one is
1074 * named, then transfer the name to the prior index. This
1075 * ensures that if we have named and unnamed constraints,
1076 * we'll use (at least one of) the names for the index.
1078 if (priorindex->idxname == NULL)
1079 priorindex->idxname = index->idxname;
1086 cxt->alist = lappend(cxt->alist, index);
1091 * transformIndexConstraint
1092 * Transform one UNIQUE or PRIMARY KEY constraint for
1093 * transformIndexConstraints.
1096 transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
1102 index = makeNode(IndexStmt);
1104 index->unique = true;
1105 index->primary = (constraint->contype == CONSTR_PRIMARY);
1108 if (cxt->pkey != NULL)
1110 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1111 errmsg("multiple primary keys for table \"%s\" are not allowed",
1112 cxt->relation->relname)));
1116 * In ALTER TABLE case, a primary index might already exist, but
1117 * DefineIndex will check for it.
1120 index->isconstraint = true;
1121 index->deferrable = constraint->deferrable;
1122 index->initdeferred = constraint->initdeferred;
1124 if (constraint->name != NULL)
1125 index->idxname = pstrdup(constraint->name);
1127 index->idxname = NULL; /* DefineIndex will choose name */
1129 index->relation = cxt->relation;
1130 index->accessMethod = DEFAULT_INDEX_TYPE;
1131 index->options = constraint->options;
1132 index->tableSpace = constraint->indexspace;
1133 index->indexParams = NIL;
1134 index->whereClause = NULL;
1135 index->concurrent = false;
1138 * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
1139 * also make sure they are NOT NULL, if possible. (Although we could leave
1140 * it to DefineIndex to mark the columns NOT NULL, it's more efficient to
1141 * get it right the first time.)
1143 foreach(keys, constraint->keys)
1145 char *key = strVal(lfirst(keys));
1147 ColumnDef *column = NULL;
1150 foreach(columns, cxt->columns)
1152 column = (ColumnDef *) lfirst(columns);
1153 Assert(IsA(column, ColumnDef));
1154 if (strcmp(column->colname, key) == 0)
1162 /* found column in the new table; force it to be NOT NULL */
1163 if (constraint->contype == CONSTR_PRIMARY)
1164 column->is_not_null = TRUE;
1166 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1169 * column will be a system column in the new table, so accept it.
1170 * System columns can't ever be null, so no need to worry about
1171 * PRIMARY/NOT NULL constraint.
1175 else if (cxt->inhRelations)
1177 /* try inherited tables */
1180 foreach(inher, cxt->inhRelations)
1182 RangeVar *inh = (RangeVar *) lfirst(inher);
1186 Assert(IsA(inh, RangeVar));
1187 rel = heap_openrv(inh, AccessShareLock);
1188 if (rel->rd_rel->relkind != RELKIND_RELATION)
1190 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1191 errmsg("inherited relation \"%s\" is not a table",
1193 for (count = 0; count < rel->rd_att->natts; count++)
1195 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1196 char *inhname = NameStr(inhattr->attname);
1198 if (inhattr->attisdropped)
1200 if (strcmp(key, inhname) == 0)
1205 * We currently have no easy way to force an inherited
1206 * column to be NOT NULL at creation, if its parent
1207 * wasn't so already. We leave it to DefineIndex to
1208 * fix things up in this case.
1213 heap_close(rel, NoLock);
1220 * In the ALTER TABLE case, don't complain about index keys not
1221 * created in the command; they may well exist already. DefineIndex
1222 * will complain about them if not, and will also take care of marking
1225 if (!found && !cxt->isalter)
1227 (errcode(ERRCODE_UNDEFINED_COLUMN),
1228 errmsg("column \"%s\" named in key does not exist",
1231 /* Check for PRIMARY KEY(foo, foo) */
1232 foreach(columns, index->indexParams)
1234 iparam = (IndexElem *) lfirst(columns);
1235 if (iparam->name && strcmp(key, iparam->name) == 0)
1239 (errcode(ERRCODE_DUPLICATE_COLUMN),
1240 errmsg("column \"%s\" appears twice in primary key constraint",
1244 (errcode(ERRCODE_DUPLICATE_COLUMN),
1245 errmsg("column \"%s\" appears twice in unique constraint",
1250 /* OK, add it to the index definition */
1251 iparam = makeNode(IndexElem);
1252 iparam->name = pstrdup(key);
1253 iparam->expr = NULL;
1254 iparam->opclass = NIL;
1255 iparam->ordering = SORTBY_DEFAULT;
1256 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1257 index->indexParams = lappend(index->indexParams, iparam);
1264 * transformFKConstraints
1265 * handle FOREIGN KEY constraints
1268 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1269 bool skipValidation, bool isAddConstraint)
1273 if (cxt->fkconstraints == NIL)
1277 * If CREATE TABLE or adding a column with NULL default, we can safely
1278 * skip validation of the constraint.
1282 foreach(fkclist, cxt->fkconstraints)
1284 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1286 fkconstraint->skip_validation = true;
1291 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1292 * CONSTRAINT command to execute after the basic command is complete. (If
1293 * called from ADD CONSTRAINT, that routine will add the FK constraints to
1294 * its own subcommand list.)
1296 * Note: the ADD CONSTRAINT command must also execute after any index
1297 * creation commands. Thus, this should run after
1298 * transformIndexConstraints, so that the CREATE INDEX commands are
1299 * already in cxt->alist.
1301 if (!isAddConstraint)
1303 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1305 alterstmt->relation = cxt->relation;
1306 alterstmt->cmds = NIL;
1307 alterstmt->relkind = OBJECT_TABLE;
1309 foreach(fkclist, cxt->fkconstraints)
1311 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1312 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1314 altercmd->subtype = AT_ProcessedConstraint;
1315 altercmd->name = NULL;
1316 altercmd->def = (Node *) fkconstraint;
1317 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1320 cxt->alist = lappend(cxt->alist, alterstmt);
1325 * transformIndexStmt - parse analysis for CREATE INDEX
1327 * Note: this is a no-op for an index not using either index expressions or
1328 * a predicate expression. There are several code paths that create indexes
1329 * without bothering to call this, because they know they don't have any
1330 * such expressions to deal with.
1333 transformIndexStmt(IndexStmt *stmt, const char *queryString)
1341 * We must not scribble on the passed-in IndexStmt, so copy it. (This is
1342 * overkill, but easy.)
1344 stmt = (IndexStmt *) copyObject(stmt);
1347 * Open the parent table with appropriate locking. We must do this
1348 * because addRangeTableEntry() would acquire only AccessShareLock,
1349 * leaving DefineIndex() needing to do a lock upgrade with consequent risk
1350 * of deadlock. Make sure this stays in sync with the type of lock
1351 * DefineIndex() wants.
1353 rel = heap_openrv(stmt->relation,
1354 (stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock));
1357 pstate = make_parsestate(NULL);
1358 pstate->p_sourcetext = queryString;
1361 * Put the parent table into the rtable so that the expressions can refer
1362 * to its fields without qualification.
1364 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1366 /* no to join list, yes to namespaces */
1367 addRTEtoQuery(pstate, rte, false, true, true);
1369 /* take care of the where clause */
1370 if (stmt->whereClause)
1371 stmt->whereClause = transformWhereClause(pstate,
1375 /* take care of any index expressions */
1376 foreach(l, stmt->indexParams)
1378 IndexElem *ielem = (IndexElem *) lfirst(l);
1382 ielem->expr = transformExpr(pstate, ielem->expr);
1385 * We check only that the result type is legitimate; this is for
1386 * consistency with what transformWhereClause() checks for the
1387 * predicate. DefineIndex() will make more checks.
1389 if (expression_returns_set(ielem->expr))
1391 (errcode(ERRCODE_DATATYPE_MISMATCH),
1392 errmsg("index expression cannot return a set")));
1397 * Check that only the base rel is mentioned.
1399 if (list_length(pstate->p_rtable) != 1)
1401 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1402 errmsg("index expressions and predicates can refer only to the table being indexed")));
1404 free_parsestate(pstate);
1406 /* Close relation, but keep the lock */
1407 heap_close(rel, NoLock);
1414 * transformRuleStmt -
1415 * transform a CREATE RULE Statement. The action is a list of parse
1416 * trees which is transformed into a list of query trees, and we also
1417 * transform the WHERE clause if any.
1419 * actions and whereClause are output parameters that receive the
1420 * transformed results.
1422 * Note that we must not scribble on the passed-in RuleStmt, so we do
1423 * copyObject() on the actions and WHERE clause.
1426 transformRuleStmt(RuleStmt *stmt, const char *queryString,
1427 List **actions, Node **whereClause)
1431 RangeTblEntry *oldrte;
1432 RangeTblEntry *newrte;
1435 * To avoid deadlock, make sure the first thing we do is grab
1436 * AccessExclusiveLock on the target relation. This will be needed by
1437 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1440 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1443 pstate = make_parsestate(NULL);
1444 pstate->p_sourcetext = queryString;
1447 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1448 * Set up their RTEs in the main pstate for use in parsing the rule
1451 oldrte = addRangeTableEntryForRelation(pstate, rel,
1452 makeAlias("*OLD*", NIL),
1454 newrte = addRangeTableEntryForRelation(pstate, rel,
1455 makeAlias("*NEW*", NIL),
1457 /* Must override addRangeTableEntry's default access-check flags */
1458 oldrte->requiredPerms = 0;
1459 newrte->requiredPerms = 0;
1462 * They must be in the namespace too for lookup purposes, but only add the
1463 * one(s) that are relevant for the current kind of rule. In an UPDATE
1464 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1465 * there's no need to be so picky for INSERT & DELETE. We do not add them
1468 switch (stmt->event)
1471 addRTEtoQuery(pstate, oldrte, false, true, true);
1474 addRTEtoQuery(pstate, oldrte, false, true, true);
1475 addRTEtoQuery(pstate, newrte, false, true, true);
1478 addRTEtoQuery(pstate, newrte, false, true, true);
1481 addRTEtoQuery(pstate, oldrte, false, true, true);
1484 elog(ERROR, "unrecognized event type: %d",
1489 /* take care of the where clause */
1490 *whereClause = transformWhereClause(pstate,
1491 (Node *) copyObject(stmt->whereClause),
1494 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
1496 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1497 errmsg("rule WHERE condition cannot contain references to other relations")));
1499 /* aggregates not allowed (but subselects are okay) */
1500 if (pstate->p_hasAggs)
1502 (errcode(ERRCODE_GROUPING_ERROR),
1503 errmsg("cannot use aggregate function in rule WHERE condition")));
1504 if (pstate->p_hasWindowFuncs)
1506 (errcode(ERRCODE_WINDOWING_ERROR),
1507 errmsg("cannot use window function in rule WHERE condition")));
1510 * 'instead nothing' rules with a qualification need a query rangetable so
1511 * the rewrite handler can add the negated rule qualification to the
1512 * original query. We create a query with the new command type CMD_NOTHING
1513 * here that is treated specially by the rewrite system.
1515 if (stmt->actions == NIL)
1517 Query *nothing_qry = makeNode(Query);
1519 nothing_qry->commandType = CMD_NOTHING;
1520 nothing_qry->rtable = pstate->p_rtable;
1521 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1523 *actions = list_make1(nothing_qry);
1528 List *newactions = NIL;
1531 * transform each statement, like parse_sub_analyze()
1533 foreach(l, stmt->actions)
1535 Node *action = (Node *) lfirst(l);
1536 ParseState *sub_pstate = make_parsestate(NULL);
1543 * Since outer ParseState isn't parent of inner, have to pass down
1544 * the query text by hand.
1546 sub_pstate->p_sourcetext = queryString;
1549 * Set up OLD/NEW in the rtable for this statement. The entries
1550 * are added only to relnamespace, not varnamespace, because we
1551 * don't want them to be referred to by unqualified field names
1552 * nor "*" in the rule actions. We decide later whether to put
1553 * them in the joinlist.
1555 oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
1556 makeAlias("*OLD*", NIL),
1558 newrte = addRangeTableEntryForRelation(sub_pstate, rel,
1559 makeAlias("*NEW*", NIL),
1561 oldrte->requiredPerms = 0;
1562 newrte->requiredPerms = 0;
1563 addRTEtoQuery(sub_pstate, oldrte, false, true, false);
1564 addRTEtoQuery(sub_pstate, newrte, false, true, false);
1566 /* Transform the rule action statement */
1567 top_subqry = transformStmt(sub_pstate,
1568 (Node *) copyObject(action));
1571 * We cannot support utility-statement actions (eg NOTIFY) with
1572 * nonempty rule WHERE conditions, because there's no way to make
1573 * the utility action execute conditionally.
1575 if (top_subqry->commandType == CMD_UTILITY &&
1576 *whereClause != NULL)
1578 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1579 errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
1582 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
1583 * into the SELECT, and that's what we need to look at. (Ugly
1584 * kluge ... try to fix this when we redesign querytrees.)
1586 sub_qry = getInsertSelectQuery(top_subqry, NULL);
1589 * If the sub_qry is a setop, we cannot attach any qualifications
1590 * to it, because the planner won't notice them. This could
1591 * perhaps be relaxed someday, but for now, we may as well reject
1592 * such a rule immediately.
1594 if (sub_qry->setOperations != NULL && *whereClause != NULL)
1596 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1597 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1600 * Validate action's use of OLD/NEW, qual too
1603 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1604 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
1606 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1607 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
1609 switch (stmt->event)
1614 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1615 errmsg("ON SELECT rule cannot use OLD")));
1618 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1619 errmsg("ON SELECT rule cannot use NEW")));
1627 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1628 errmsg("ON INSERT rule cannot use OLD")));
1633 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1634 errmsg("ON DELETE rule cannot use NEW")));
1637 elog(ERROR, "unrecognized event type: %d",
1643 * For efficiency's sake, add OLD to the rule action's jointree
1644 * only if it was actually referenced in the statement or qual.
1646 * For INSERT, NEW is not really a relation (only a reference to
1647 * the to-be-inserted tuple) and should never be added to the
1650 * For UPDATE, we treat NEW as being another kind of reference to
1651 * OLD, because it represents references to *transformed* tuples
1652 * of the existing relation. It would be wrong to enter NEW
1653 * separately in the jointree, since that would cause a double
1654 * join of the updated relation. It's also wrong to fail to make
1655 * a jointree entry if only NEW and not OLD is mentioned.
1657 if (has_old || (has_new && stmt->event == CMD_UPDATE))
1660 * If sub_qry is a setop, manipulating its jointree will do no
1661 * good at all, because the jointree is dummy. (This should be
1662 * a can't-happen case because of prior tests.)
1664 if (sub_qry->setOperations != NULL)
1666 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1667 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1668 /* hack so we can use addRTEtoQuery() */
1669 sub_pstate->p_rtable = sub_qry->rtable;
1670 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
1671 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
1672 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
1675 newactions = lappend(newactions, top_subqry);
1677 free_parsestate(sub_pstate);
1680 *actions = newactions;
1683 free_parsestate(pstate);
1685 /* Close relation, but keep the exclusive lock */
1686 heap_close(rel, NoLock);
1691 * transformAlterTableStmt -
1692 * parse analysis for ALTER TABLE
1694 * Returns a List of utility commands to be done in sequence. One of these
1695 * will be the transformed AlterTableStmt, but there may be additional actions
1696 * to be done before and after the actual AlterTable() call.
1699 transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
1703 CreateStmtContext cxt;
1708 List *newcmds = NIL;
1709 bool skipValidation = true;
1710 AlterTableCmd *newcmd;
1713 * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
1714 * is overkill, but easy.)
1716 stmt = (AlterTableStmt *) copyObject(stmt);
1719 * Acquire exclusive lock on the target relation, which will be held until
1720 * end of transaction. This ensures any decisions we make here based on
1721 * the state of the relation will still be good at execution. We must get
1722 * exclusive lock now because execution will; taking a lower grade lock
1723 * now and trying to upgrade later risks deadlock.
1725 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
1728 pstate = make_parsestate(NULL);
1729 pstate->p_sourcetext = queryString;
1731 cxt.stmtType = "ALTER TABLE";
1732 cxt.relation = stmt->relation;
1734 cxt.inhRelations = NIL;
1736 cxt.hasoids = false; /* need not be right */
1738 cxt.ckconstraints = NIL;
1739 cxt.fkconstraints = NIL;
1740 cxt.ixconstraints = NIL;
1741 cxt.inh_indexes = NIL;
1747 * The only subtypes that currently require parse transformation handling
1748 * are ADD COLUMN and ADD CONSTRAINT. These largely re-use code from
1751 foreach(lcmd, stmt->cmds)
1753 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
1755 switch (cmd->subtype)
1758 case AT_AddColumnToView:
1760 ColumnDef *def = (ColumnDef *) cmd->def;
1762 Assert(IsA(def, ColumnDef));
1763 transformColumnDefinition(pstate, &cxt, def);
1766 * If the column has a non-null default, we can't skip
1767 * validation of foreign keys.
1769 if (def->raw_default != NULL)
1770 skipValidation = false;
1773 * All constraints are processed in other ways. Remove the
1776 def->constraints = NIL;
1778 newcmds = lappend(newcmds, cmd);
1781 case AT_AddConstraint:
1784 * The original AddConstraint cmd node doesn't go to newcmds
1786 if (IsA(cmd->def, Constraint))
1787 transformTableConstraint(pstate, &cxt,
1788 (Constraint *) cmd->def);
1789 else if (IsA(cmd->def, FkConstraint))
1791 cxt.fkconstraints = lappend(cxt.fkconstraints, cmd->def);
1792 skipValidation = false;
1795 elog(ERROR, "unrecognized node type: %d",
1796 (int) nodeTag(cmd->def));
1799 case AT_ProcessedConstraint:
1802 * Already-transformed ADD CONSTRAINT, so just make it look
1803 * like the standard case.
1805 cmd->subtype = AT_AddConstraint;
1806 newcmds = lappend(newcmds, cmd);
1810 newcmds = lappend(newcmds, cmd);
1816 * transformIndexConstraints wants cxt.alist to contain only index
1817 * statements, so transfer anything we already have into save_alist
1820 save_alist = cxt.alist;
1823 /* Postprocess index and FK constraints */
1824 transformIndexConstraints(pstate, &cxt);
1826 transformFKConstraints(pstate, &cxt, skipValidation, true);
1829 * Push any index-creation commands into the ALTER, so that they can be
1830 * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
1831 * the IndexStmt attached to an AT_AddIndex subcommand has already been
1832 * through transformIndexStmt.
1834 foreach(l, cxt.alist)
1836 Node *idxstmt = (Node *) lfirst(l);
1838 Assert(IsA(idxstmt, IndexStmt));
1839 newcmd = makeNode(AlterTableCmd);
1840 newcmd->subtype = AT_AddIndex;
1841 newcmd->def = (Node *) transformIndexStmt((IndexStmt *) idxstmt,
1843 newcmds = lappend(newcmds, newcmd);
1847 /* Append any CHECK or FK constraints to the commands list */
1848 foreach(l, cxt.ckconstraints)
1850 newcmd = makeNode(AlterTableCmd);
1851 newcmd->subtype = AT_AddConstraint;
1852 newcmd->def = (Node *) lfirst(l);
1853 newcmds = lappend(newcmds, newcmd);
1855 foreach(l, cxt.fkconstraints)
1857 newcmd = makeNode(AlterTableCmd);
1858 newcmd->subtype = AT_AddConstraint;
1859 newcmd->def = (Node *) lfirst(l);
1860 newcmds = lappend(newcmds, newcmd);
1863 /* Close rel but keep lock */
1864 relation_close(rel, NoLock);
1869 stmt->cmds = newcmds;
1871 result = lappend(cxt.blist, stmt);
1872 result = list_concat(result, cxt.alist);
1873 result = list_concat(result, save_alist);
1880 * Preprocess a list of column constraint clauses
1881 * to attach constraint attributes to their primary constraint nodes
1882 * and detect inconsistent/misplaced constraint attributes.
1884 * NOTE: currently, attributes are only supported for FOREIGN KEY, UNIQUE,
1885 * and PRIMARY KEY constraints, but someday they ought to be supported
1886 * for other constraint types.
1889 transformConstraintAttrs(List *constraintList)
1891 Node *lastprimarynode = NULL;
1892 bool saw_deferrability = false;
1893 bool saw_initially = false;
1896 #define SUPPORTS_ATTRS(node) \
1897 ((node) != NULL && \
1898 (IsA((node), FkConstraint) || \
1899 (IsA((node), Constraint) && \
1900 (((Constraint *) (node))->contype == CONSTR_PRIMARY || \
1901 ((Constraint *) (node))->contype == CONSTR_UNIQUE))))
1903 foreach(clist, constraintList)
1905 Node *node = lfirst(clist);
1907 if (!IsA(node, Constraint))
1909 lastprimarynode = node;
1910 /* reset flags for new primary node */
1911 saw_deferrability = false;
1912 saw_initially = false;
1916 Constraint *con = (Constraint *) node;
1918 switch (con->contype)
1920 case CONSTR_ATTR_DEFERRABLE:
1921 if (!SUPPORTS_ATTRS(lastprimarynode))
1923 (errcode(ERRCODE_SYNTAX_ERROR),
1924 errmsg("misplaced DEFERRABLE clause")));
1925 if (saw_deferrability)
1927 (errcode(ERRCODE_SYNTAX_ERROR),
1928 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
1929 saw_deferrability = true;
1930 if (IsA(lastprimarynode, FkConstraint))
1931 ((FkConstraint *) lastprimarynode)->deferrable = true;
1933 ((Constraint *) lastprimarynode)->deferrable = true;
1936 case CONSTR_ATTR_NOT_DEFERRABLE:
1937 if (!SUPPORTS_ATTRS(lastprimarynode))
1939 (errcode(ERRCODE_SYNTAX_ERROR),
1940 errmsg("misplaced NOT DEFERRABLE clause")));
1941 if (saw_deferrability)
1943 (errcode(ERRCODE_SYNTAX_ERROR),
1944 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
1945 saw_deferrability = true;
1946 if (IsA(lastprimarynode, FkConstraint))
1948 ((FkConstraint *) lastprimarynode)->deferrable = false;
1949 if (saw_initially &&
1950 ((FkConstraint *) lastprimarynode)->initdeferred)
1952 (errcode(ERRCODE_SYNTAX_ERROR),
1953 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
1957 ((Constraint *) lastprimarynode)->deferrable = false;
1958 if (saw_initially &&
1959 ((Constraint *) lastprimarynode)->initdeferred)
1961 (errcode(ERRCODE_SYNTAX_ERROR),
1962 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
1966 case CONSTR_ATTR_DEFERRED:
1967 if (!SUPPORTS_ATTRS(lastprimarynode))
1969 (errcode(ERRCODE_SYNTAX_ERROR),
1970 errmsg("misplaced INITIALLY DEFERRED clause")));
1973 (errcode(ERRCODE_SYNTAX_ERROR),
1974 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
1975 saw_initially = true;
1978 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
1980 if (IsA(lastprimarynode, FkConstraint))
1982 ((FkConstraint *) lastprimarynode)->initdeferred = true;
1984 if (!saw_deferrability)
1985 ((FkConstraint *) lastprimarynode)->deferrable = true;
1986 else if (!((FkConstraint *) lastprimarynode)->deferrable)
1988 (errcode(ERRCODE_SYNTAX_ERROR),
1989 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
1993 ((Constraint *) lastprimarynode)->initdeferred = true;
1995 if (!saw_deferrability)
1996 ((Constraint *) lastprimarynode)->deferrable = true;
1997 else if (!((Constraint *) lastprimarynode)->deferrable)
1999 (errcode(ERRCODE_SYNTAX_ERROR),
2000 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
2004 case CONSTR_ATTR_IMMEDIATE:
2005 if (!SUPPORTS_ATTRS(lastprimarynode))
2007 (errcode(ERRCODE_SYNTAX_ERROR),
2008 errmsg("misplaced INITIALLY IMMEDIATE clause")));
2011 (errcode(ERRCODE_SYNTAX_ERROR),
2012 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
2013 saw_initially = true;
2014 if (IsA(lastprimarynode, FkConstraint))
2015 ((FkConstraint *) lastprimarynode)->initdeferred = false;
2017 ((Constraint *) lastprimarynode)->initdeferred = false;
2021 /* Otherwise it's not an attribute */
2022 lastprimarynode = node;
2023 /* reset flags for new primary node */
2024 saw_deferrability = false;
2025 saw_initially = false;
2033 * Special handling of type definition for a column
2036 transformColumnType(ParseState *pstate, ColumnDef *column)
2039 * All we really need to do here is verify that the type is valid.
2041 Type ctype = typenameType(pstate, column->typeName, NULL);
2043 ReleaseSysCache(ctype);
2048 * transformCreateSchemaStmt -
2049 * analyzes the CREATE SCHEMA statement
2051 * Split the schema element list into individual commands and place
2052 * them in the result list in an order such that there are no forward
2053 * references (e.g. GRANT to a table created later in the list). Note
2054 * that the logic we use for determining forward references is
2055 * presently quite incomplete.
2057 * SQL92 also allows constraints to make forward references, so thumb through
2058 * the table columns and move forward references to a posterior alter-table
2061 * The result is a list of parse nodes that still need to be analyzed ---
2062 * but we can't analyze the later commands until we've executed the earlier
2063 * ones, because of possible inter-object references.
2065 * Note: this breaks the rules a little bit by modifying schema-name fields
2066 * within passed-in structs. However, the transformation would be the same
2067 * if done over, so it should be all right to scribble on the input to this
2071 transformCreateSchemaStmt(CreateSchemaStmt *stmt)
2073 CreateSchemaStmtContext cxt;
2077 cxt.stmtType = "CREATE SCHEMA";
2078 cxt.schemaname = stmt->schemaname;
2079 cxt.authid = stmt->authid;
2080 cxt.sequences = NIL;
2088 * Run through each schema element in the schema element list. Separate
2089 * statements by type, and do preliminary analysis.
2091 foreach(elements, stmt->schemaElts)
2093 Node *element = lfirst(elements);
2095 switch (nodeTag(element))
2097 case T_CreateSeqStmt:
2099 CreateSeqStmt *elp = (CreateSeqStmt *) element;
2101 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
2102 cxt.sequences = lappend(cxt.sequences, element);
2108 CreateStmt *elp = (CreateStmt *) element;
2110 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2113 * XXX todo: deal with constraints
2115 cxt.tables = lappend(cxt.tables, element);
2121 ViewStmt *elp = (ViewStmt *) element;
2123 setSchemaName(cxt.schemaname, &elp->view->schemaname);
2126 * XXX todo: deal with references between views
2128 cxt.views = lappend(cxt.views, element);
2134 IndexStmt *elp = (IndexStmt *) element;
2136 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2137 cxt.indexes = lappend(cxt.indexes, element);
2141 case T_CreateTrigStmt:
2143 CreateTrigStmt *elp = (CreateTrigStmt *) element;
2145 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2146 cxt.triggers = lappend(cxt.triggers, element);
2151 cxt.grants = lappend(cxt.grants, element);
2155 elog(ERROR, "unrecognized node type: %d",
2156 (int) nodeTag(element));
2161 result = list_concat(result, cxt.sequences);
2162 result = list_concat(result, cxt.tables);
2163 result = list_concat(result, cxt.views);
2164 result = list_concat(result, cxt.indexes);
2165 result = list_concat(result, cxt.triggers);
2166 result = list_concat(result, cxt.grants);
2173 * Set or check schema name in an element of a CREATE SCHEMA command
2176 setSchemaName(char *context_schema, char **stmt_schema_name)
2178 if (*stmt_schema_name == NULL)
2179 *stmt_schema_name = context_schema;
2180 else if (strcmp(context_schema, *stmt_schema_name) != 0)
2182 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
2183 errmsg("CREATE specifies a schema (%s) "
2184 "different from the one being created (%s)",
2185 *stmt_schema_name, context_schema)));