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-2011, PostgreSQL Global Development Group
20 * Portions Copyright (c) 1994, Regents of the University of California
22 * src/backend/parser/parse_utilcmd.c
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_operator.h"
39 #include "catalog/pg_type.h"
40 #include "commands/comment.h"
41 #include "commands/defrem.h"
42 #include "commands/tablecmds.h"
43 #include "commands/tablespace.h"
44 #include "miscadmin.h"
45 #include "nodes/makefuncs.h"
46 #include "nodes/nodeFuncs.h"
47 #include "parser/analyze.h"
48 #include "parser/parse_clause.h"
49 #include "parser/parse_expr.h"
50 #include "parser/parse_relation.h"
51 #include "parser/parse_target.h"
52 #include "parser/parse_type.h"
53 #include "parser/parse_utilcmd.h"
54 #include "parser/parser.h"
55 #include "rewrite/rewriteManip.h"
56 #include "storage/lock.h"
57 #include "utils/acl.h"
58 #include "utils/builtins.h"
59 #include "utils/lsyscache.h"
60 #include "utils/relcache.h"
61 #include "utils/syscache.h"
62 #include "utils/typcache.h"
65 /* State shared by transformCreateStmt and its subroutines */
68 ParseState *pstate; /* overall parser state */
69 const char *stmtType; /* "CREATE [FOREIGN] TABLE" or "ALTER TABLE" */
70 RangeVar *relation; /* relation to create */
71 Relation rel; /* opened/locked rel, if ALTER */
72 List *inhRelations; /* relations to inherit from */
73 bool isalter; /* true if altering existing table */
74 bool hasoids; /* does relation have an OID column? */
75 List *columns; /* ColumnDef items */
76 List *ckconstraints; /* CHECK constraints */
77 List *fkconstraints; /* FOREIGN KEY constraints */
78 List *ixconstraints; /* index-creating constraints */
79 List *inh_indexes; /* cloned indexes from INCLUDING INDEXES */
80 List *blist; /* "before list" of things to do before
81 * creating the table */
82 List *alist; /* "after list" of things to do after creating
84 IndexStmt *pkey; /* PRIMARY KEY index, if any */
87 /* State shared by transformCreateSchemaStmt and its subroutines */
90 const char *stmtType; /* "CREATE SCHEMA" or "ALTER SCHEMA" */
91 char *schemaname; /* name of schema */
92 char *authid; /* owner of schema */
93 List *sequences; /* CREATE SEQUENCE items */
94 List *tables; /* CREATE TABLE items */
95 List *views; /* CREATE VIEW items */
96 List *indexes; /* CREATE INDEX items */
97 List *triggers; /* CREATE TRIGGER items */
98 List *grants; /* GRANT items */
99 } CreateSchemaStmtContext;
102 static void transformColumnDefinition(CreateStmtContext *cxt,
104 static void transformTableConstraint(CreateStmtContext *cxt,
105 Constraint *constraint);
106 static void transformInhRelation(CreateStmtContext *cxt,
107 InhRelation *inhrelation);
108 static void transformOfType(CreateStmtContext *cxt,
109 TypeName *ofTypename);
110 static char *chooseIndexName(const RangeVar *relation, IndexStmt *index_stmt);
111 static IndexStmt *generateClonedIndexStmt(CreateStmtContext *cxt,
112 Relation parent_index, AttrNumber *attmap);
113 static List *get_opclass(Oid opclass, Oid actual_datatype);
114 static void transformIndexConstraints(CreateStmtContext *cxt);
115 static IndexStmt *transformIndexConstraint(Constraint *constraint,
116 CreateStmtContext *cxt);
117 static void transformFKConstraints(CreateStmtContext *cxt,
119 bool isAddConstraint);
120 static void transformConstraintAttrs(CreateStmtContext *cxt,
121 List *constraintList);
122 static void transformColumnType(CreateStmtContext *cxt, ColumnDef *column);
123 static void setSchemaName(char *context_schema, char **stmt_schema_name);
127 * transformCreateStmt -
128 * parse analysis for CREATE TABLE
130 * Returns a List of utility commands to be done in sequence. One of these
131 * will be the transformed CreateStmt, but there may be additional actions
132 * to be done before and after the actual DefineRelation() call.
134 * SQL92 allows constraints to be scattered all over, so thumb through
135 * the columns and collect all constraints into one place.
136 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
137 * then expand those into multiple IndexStmt blocks.
138 * - thomas 1997-12-02
141 transformCreateStmt(CreateStmt *stmt, const char *queryString)
144 CreateStmtContext cxt;
150 * We must not scribble on the passed-in CreateStmt, so copy it. (This is
151 * overkill, but easy.)
153 stmt = (CreateStmt *) copyObject(stmt);
156 * If the target relation name isn't schema-qualified, make it so. This
157 * prevents some corner cases in which added-on rewritten commands might
158 * think they should apply to other relations that have the same name and
159 * are earlier in the search path. But a local temp table is effectively
160 * specified to be in pg_temp, so no need for anything extra in that case.
162 if (stmt->relation->schemaname == NULL
163 && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
165 Oid namespaceid = RangeVarGetCreationNamespace(stmt->relation);
167 stmt->relation->schemaname = get_namespace_name(namespaceid);
170 /* Set up pstate and CreateStmtContext */
171 pstate = make_parsestate(NULL);
172 pstate->p_sourcetext = queryString;
175 if (IsA(stmt, CreateForeignTableStmt))
176 cxt.stmtType = "CREATE FOREIGN TABLE";
178 cxt.stmtType = "CREATE TABLE";
179 cxt.relation = stmt->relation;
181 cxt.inhRelations = stmt->inhRelations;
184 cxt.ckconstraints = NIL;
185 cxt.fkconstraints = NIL;
186 cxt.ixconstraints = NIL;
187 cxt.inh_indexes = NIL;
191 cxt.hasoids = interpretOidsOption(stmt->options);
193 Assert(!stmt->ofTypename || !stmt->inhRelations); /* grammar enforces */
195 if (stmt->ofTypename)
196 transformOfType(&cxt, stmt->ofTypename);
199 * Run through each primary element in the table creation clause. Separate
200 * column defs from constraints, and do preliminary analysis.
202 foreach(elements, stmt->tableElts)
204 Node *element = lfirst(elements);
206 switch (nodeTag(element))
209 transformColumnDefinition(&cxt, (ColumnDef *) element);
213 transformTableConstraint(&cxt, (Constraint *) element);
217 transformInhRelation(&cxt, (InhRelation *) element);
221 elog(ERROR, "unrecognized node type: %d",
222 (int) nodeTag(element));
228 * transformIndexConstraints wants cxt.alist to contain only index
229 * statements, so transfer anything we already have into save_alist.
231 save_alist = cxt.alist;
234 Assert(stmt->constraints == NIL);
237 * Postprocess constraints that give rise to index definitions.
239 transformIndexConstraints(&cxt);
242 * Postprocess foreign-key constraints.
244 transformFKConstraints(&cxt, true, false);
249 stmt->tableElts = cxt.columns;
250 stmt->constraints = cxt.ckconstraints;
252 result = lappend(cxt.blist, stmt);
253 result = list_concat(result, cxt.alist);
254 result = list_concat(result, save_alist);
260 * transformColumnDefinition -
261 * transform a single ColumnDef within CREATE TABLE
262 * Also used in ALTER TABLE ADD COLUMN
265 transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
270 Constraint *constraint;
273 cxt->columns = lappend(cxt->columns, column);
275 /* Check for SERIAL pseudo-types */
278 && list_length(column->typeName->names) == 1
279 && !column->typeName->pct_type)
281 char *typname = strVal(linitial(column->typeName->names));
283 if (strcmp(typname, "serial") == 0 ||
284 strcmp(typname, "serial4") == 0)
287 column->typeName->names = NIL;
288 column->typeName->typeOid = INT4OID;
290 else if (strcmp(typname, "bigserial") == 0 ||
291 strcmp(typname, "serial8") == 0)
294 column->typeName->names = NIL;
295 column->typeName->typeOid = INT8OID;
299 * We have to reject "serial[]" explicitly, because once we've set
300 * typeid, LookupTypeName won't notice arrayBounds. We don't need any
301 * special coding for serial(typmod) though.
303 if (is_serial && column->typeName->arrayBounds != NIL)
305 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
306 errmsg("array of serial is not implemented"),
307 parser_errposition(cxt->pstate,
308 column->typeName->location)));
311 /* Do necessary work on the column type declaration */
312 if (column->typeName)
313 transformColumnType(cxt, column);
315 /* Special actions for SERIAL pseudo-types */
324 FuncCall *funccallnode;
325 CreateSeqStmt *seqstmt;
326 AlterSeqStmt *altseqstmt;
330 * Determine namespace and name to use for the sequence.
332 * Although we use ChooseRelationName, it's not guaranteed that the
333 * selected sequence name won't conflict; given sufficiently long
334 * field names, two different serial columns in the same table could
335 * be assigned the same sequence name, and we'd not notice since we
336 * aren't creating the sequence quite yet. In practice this seems
337 * quite unlikely to be a problem, especially since few people would
338 * need two serial columns in one table.
341 snamespaceid = RelationGetNamespace(cxt->rel);
343 snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
344 snamespace = get_namespace_name(snamespaceid);
345 sname = ChooseRelationName(cxt->relation->relname,
351 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
352 cxt->stmtType, sname,
353 cxt->relation->relname, column->colname)));
356 * Build a CREATE SEQUENCE command to create the sequence object, and
357 * add it to the list of things to be done before this CREATE/ALTER
360 seqstmt = makeNode(CreateSeqStmt);
361 seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
362 seqstmt->options = NIL;
365 * If this is ALTER ADD COLUMN, make sure the sequence will be owned
366 * by the table's owner. The current user might be someone else
367 * (perhaps a superuser, or someone who's only a member of the owning
368 * role), but the SEQUENCE OWNED BY mechanisms will bleat unless
369 * table and sequence have exactly the same owning role.
372 seqstmt->ownerId = cxt->rel->rd_rel->relowner;
374 seqstmt->ownerId = InvalidOid;
376 cxt->blist = lappend(cxt->blist, seqstmt);
379 * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence
380 * as owned by this column, and add it to the list of things to be
381 * done after this CREATE/ALTER TABLE.
383 altseqstmt = makeNode(AlterSeqStmt);
384 altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
385 attnamelist = list_make3(makeString(snamespace),
386 makeString(cxt->relation->relname),
387 makeString(column->colname));
388 altseqstmt->options = list_make1(makeDefElem("owned_by",
389 (Node *) attnamelist));
391 cxt->alist = lappend(cxt->alist, altseqstmt);
394 * Create appropriate constraints for SERIAL. We do this in full,
395 * rather than shortcutting, so that we will detect any conflicting
396 * constraints the user wrote (like a different DEFAULT).
398 * Create an expression tree representing the function call
399 * nextval('sequencename'). We cannot reduce the raw tree to cooked
400 * form until after the sequence is created, but there's no need to do
403 qstring = quote_qualified_identifier(snamespace, sname);
404 snamenode = makeNode(A_Const);
405 snamenode->val.type = T_String;
406 snamenode->val.val.str = qstring;
407 snamenode->location = -1;
408 castnode = makeNode(TypeCast);
409 castnode->typeName = SystemTypeName("regclass");
410 castnode->arg = (Node *) snamenode;
411 castnode->location = -1;
412 funccallnode = makeNode(FuncCall);
413 funccallnode->funcname = SystemFuncName("nextval");
414 funccallnode->args = list_make1(castnode);
415 funccallnode->agg_order = NIL;
416 funccallnode->agg_star = false;
417 funccallnode->agg_distinct = false;
418 funccallnode->func_variadic = false;
419 funccallnode->over = NULL;
420 funccallnode->location = -1;
422 constraint = makeNode(Constraint);
423 constraint->contype = CONSTR_DEFAULT;
424 constraint->location = -1;
425 constraint->raw_expr = (Node *) funccallnode;
426 constraint->cooked_expr = NULL;
427 column->constraints = lappend(column->constraints, constraint);
429 constraint = makeNode(Constraint);
430 constraint->contype = CONSTR_NOTNULL;
431 constraint->location = -1;
432 column->constraints = lappend(column->constraints, constraint);
435 /* Process column constraints, if any... */
436 transformConstraintAttrs(cxt, column->constraints);
438 saw_nullable = false;
441 foreach(clist, column->constraints)
443 constraint = lfirst(clist);
444 Assert(IsA(constraint, Constraint));
446 switch (constraint->contype)
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 parser_errposition(cxt->pstate,
455 constraint->location)));
456 column->is_not_null = FALSE;
461 if (saw_nullable && !column->is_not_null)
463 (errcode(ERRCODE_SYNTAX_ERROR),
464 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
465 column->colname, cxt->relation->relname),
466 parser_errposition(cxt->pstate,
467 constraint->location)));
468 column->is_not_null = TRUE;
475 (errcode(ERRCODE_SYNTAX_ERROR),
476 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
477 column->colname, cxt->relation->relname),
478 parser_errposition(cxt->pstate,
479 constraint->location)));
480 column->raw_default = constraint->raw_expr;
481 Assert(constraint->cooked_expr == NULL);
486 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
491 if (constraint->keys == NIL)
492 constraint->keys = list_make1(makeString(column->colname));
493 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
496 case CONSTR_EXCLUSION:
497 /* grammar does not allow EXCLUDE as a column constraint */
498 elog(ERROR, "column exclusion constraints are not supported");
504 * Fill in the current attribute's name and throw it into the
505 * list of FK constraints to be processed later.
507 constraint->fk_attrs = list_make1(makeString(column->colname));
508 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
511 case CONSTR_ATTR_DEFERRABLE:
512 case CONSTR_ATTR_NOT_DEFERRABLE:
513 case CONSTR_ATTR_DEFERRED:
514 case CONSTR_ATTR_IMMEDIATE:
515 /* transformConstraintAttrs took care of these */
519 elog(ERROR, "unrecognized constraint type: %d",
520 constraint->contype);
527 * transformTableConstraint
528 * transform a Constraint node within CREATE TABLE or ALTER TABLE
531 transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
533 switch (constraint->contype)
537 case CONSTR_EXCLUSION:
538 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
542 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
546 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
552 case CONSTR_ATTR_DEFERRABLE:
553 case CONSTR_ATTR_NOT_DEFERRABLE:
554 case CONSTR_ATTR_DEFERRED:
555 case CONSTR_ATTR_IMMEDIATE:
556 elog(ERROR, "invalid context for constraint type %d",
557 constraint->contype);
561 elog(ERROR, "unrecognized constraint type: %d",
562 constraint->contype);
568 * transformInhRelation
570 * Change the LIKE <subtable> portion of a CREATE TABLE statement into
571 * column definitions which recreate the user defined column portions of
575 transformInhRelation(CreateStmtContext *cxt, InhRelation *inhRelation)
577 AttrNumber parent_attno;
584 relation = parserOpenTable(cxt->pstate, inhRelation->relation,
587 if (relation->rd_rel->relkind != RELKIND_RELATION)
589 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
590 errmsg("inherited relation \"%s\" is not a table",
591 inhRelation->relation->relname)));
594 * Check for SELECT privilages
596 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
598 if (aclresult != ACLCHECK_OK)
599 aclcheck_error(aclresult, ACL_KIND_CLASS,
600 RelationGetRelationName(relation));
602 tupleDesc = RelationGetDescr(relation);
603 constr = tupleDesc->constr;
606 * Insert the copied attributes into the cxt for the new table definition.
608 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
611 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
612 char *attributeName = NameStr(attribute->attname);
616 * Ignore dropped columns in the parent.
618 if (attribute->attisdropped)
622 * Create a new column, which is marked as NOT inherited.
624 * For constraints, ONLY the NOT NULL constraint is inherited by the
625 * new column definition per SQL99.
627 def = makeNode(ColumnDef);
628 def->colname = pstrdup(attributeName);
629 def->typeName = makeTypeNameFromOid(attribute->atttypid,
630 attribute->atttypmod);
632 def->is_local = true;
633 def->is_not_null = attribute->attnotnull;
634 def->raw_default = NULL;
635 def->cooked_default = NULL;
636 def->constraints = NIL;
641 cxt->columns = lappend(cxt->columns, def);
644 * Copy default, if present and the default has been requested
646 if (attribute->atthasdef &&
647 (inhRelation->options & CREATE_TABLE_LIKE_DEFAULTS))
649 Node *this_default = NULL;
650 AttrDefault *attrdef;
653 /* Find default in constraint structure */
654 Assert(constr != NULL);
655 attrdef = constr->defval;
656 for (i = 0; i < constr->num_defval; i++)
658 if (attrdef[i].adnum == parent_attno)
660 this_default = stringToNode(attrdef[i].adbin);
664 Assert(this_default != NULL);
667 * If default expr could contain any vars, we'd need to fix 'em,
668 * but it can't; so default is ready to apply to child.
671 def->cooked_default = this_default;
674 /* Likewise, copy storage if requested */
675 if (inhRelation->options & CREATE_TABLE_LIKE_STORAGE)
676 def->storage = attribute->attstorage;
680 /* Likewise, copy comment if requested */
681 if ((inhRelation->options & CREATE_TABLE_LIKE_COMMENTS) &&
682 (comment = GetComment(attribute->attrelid,
684 attribute->attnum)) != NULL)
686 CommentStmt *stmt = makeNode(CommentStmt);
688 stmt->objtype = OBJECT_COLUMN;
689 stmt->objname = list_make3(makeString(cxt->relation->schemaname),
690 makeString(cxt->relation->relname),
691 makeString(def->colname));
693 stmt->comment = comment;
695 cxt->alist = lappend(cxt->alist, stmt);
700 * Copy CHECK constraints if requested, being careful to adjust attribute
703 if ((inhRelation->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
706 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
709 for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
711 char *ccname = tupleDesc->constr->check[ccnum].ccname;
712 char *ccbin = tupleDesc->constr->check[ccnum].ccbin;
713 Node *ccbin_node = stringToNode(ccbin);
714 Constraint *n = makeNode(Constraint);
716 change_varattnos_of_a_node(ccbin_node, attmap);
718 n->contype = CONSTR_CHECK;
720 n->conname = pstrdup(ccname);
722 n->cooked_expr = nodeToString(ccbin_node);
723 cxt->ckconstraints = lappend(cxt->ckconstraints, n);
725 /* Copy comment on constraint */
726 if ((inhRelation->options & CREATE_TABLE_LIKE_COMMENTS) &&
727 (comment = GetComment(get_constraint_oid(RelationGetRelid(relation),
729 ConstraintRelationId,
732 CommentStmt *stmt = makeNode(CommentStmt);
734 stmt->objtype = OBJECT_CONSTRAINT;
735 stmt->objname = list_make3(makeString(cxt->relation->schemaname),
736 makeString(cxt->relation->relname),
737 makeString(n->conname));
739 stmt->comment = comment;
741 cxt->alist = lappend(cxt->alist, stmt);
747 * Likewise, copy indexes if requested
749 if ((inhRelation->options & CREATE_TABLE_LIKE_INDEXES) &&
750 relation->rd_rel->relhasindex)
752 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
753 List *parent_indexes;
756 parent_indexes = RelationGetIndexList(relation);
758 foreach(l, parent_indexes)
760 Oid parent_index_oid = lfirst_oid(l);
761 Relation parent_index;
762 IndexStmt *index_stmt;
764 parent_index = index_open(parent_index_oid, AccessShareLock);
766 /* Build CREATE INDEX statement to recreate the parent_index */
767 index_stmt = generateClonedIndexStmt(cxt, parent_index, attmap);
769 /* Copy comment on index */
770 if (inhRelation->options & CREATE_TABLE_LIKE_COMMENTS)
772 comment = GetComment(parent_index_oid, RelationRelationId, 0);
779 * We have to assign the index a name now, so that we can
780 * reference it in CommentStmt.
782 if (index_stmt->idxname == NULL)
783 index_stmt->idxname = chooseIndexName(cxt->relation,
786 stmt = makeNode(CommentStmt);
787 stmt->objtype = OBJECT_INDEX;
789 list_make2(makeString(cxt->relation->schemaname),
790 makeString(index_stmt->idxname));
792 stmt->comment = comment;
794 cxt->alist = lappend(cxt->alist, stmt);
798 /* Save it in the inh_indexes list for the time being */
799 cxt->inh_indexes = lappend(cxt->inh_indexes, index_stmt);
801 index_close(parent_index, AccessShareLock);
806 * Close the parent rel, but keep our AccessShareLock on it until xact
807 * commit. That will prevent someone else from deleting or ALTERing the
808 * parent before the child is committed.
810 heap_close(relation, NoLock);
814 transformOfType(CreateStmtContext *cxt, TypeName *ofTypename)
822 AssertArg(ofTypename);
824 tuple = typenameType(NULL, ofTypename, NULL);
825 typ = (Form_pg_type) GETSTRUCT(tuple);
826 ofTypeId = HeapTupleGetOid(tuple);
827 ofTypename->typeOid = ofTypeId; /* cached for later */
829 if (typ->typtype != TYPTYPE_COMPOSITE)
831 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
832 errmsg("type %s is not a composite type",
833 format_type_be(ofTypeId))));
835 tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
836 for (i = 0; i < tupdesc->natts; i++)
838 Form_pg_attribute attr = tupdesc->attrs[i];
839 ColumnDef *n = makeNode(ColumnDef);
841 if (attr->attisdropped)
844 n->colname = pstrdup(NameStr(attr->attname));
845 n->typeName = makeTypeNameFromOid(attr->atttypid, attr->atttypmod);
846 n->constraints = NULL;
848 n->is_from_type = true;
849 cxt->columns = lappend(cxt->columns, n);
851 DecrTupleDescRefCount(tupdesc);
853 ReleaseSysCache(tuple);
859 * Compute name for an index. This must match code in indexcmds.c.
861 * XXX this is inherently broken because the indexes aren't created
862 * immediately, so we fail to resolve conflicts when the same name is
863 * derived for multiple indexes. However, that's a reasonably uncommon
864 * situation, so we'll live with it for now.
867 chooseIndexName(const RangeVar *relation, IndexStmt *index_stmt)
872 namespaceId = RangeVarGetCreationNamespace(relation);
873 colnames = ChooseIndexColumnNames(index_stmt->indexParams);
874 return ChooseIndexName(relation->relname, namespaceId,
875 colnames, index_stmt->excludeOpNames,
876 index_stmt->primary, index_stmt->isconstraint);
880 * Generate an IndexStmt node using information from an already existing index
881 * "source_idx". Attribute numbers should be adjusted according to attmap.
884 generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
887 Oid source_relid = RelationGetRelid(source_idx);
888 Form_pg_attribute *attrs = RelationGetDescr(source_idx)->attrs;
891 Form_pg_class idxrelrec;
892 Form_pg_index idxrec;
897 ListCell *indexpr_item;
905 * Fetch pg_class tuple of source index. We can't use the copy in the
906 * relcache entry because it doesn't include optional fields.
908 ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
909 if (!HeapTupleIsValid(ht_idxrel))
910 elog(ERROR, "cache lookup failed for relation %u", source_relid);
911 idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
913 /* Fetch pg_index tuple for source index from relcache entry */
914 ht_idx = source_idx->rd_indextuple;
915 idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
916 indrelid = idxrec->indrelid;
918 /* Fetch pg_am tuple for source index from relcache entry */
919 amrec = source_idx->rd_am;
921 /* Extract indclass from the pg_index tuple */
922 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
923 Anum_pg_index_indclass, &isnull);
925 indclass = (oidvector *) DatumGetPointer(datum);
927 /* Begin building the IndexStmt */
928 index = makeNode(IndexStmt);
929 index->relation = cxt->relation;
930 index->accessMethod = pstrdup(NameStr(amrec->amname));
931 if (OidIsValid(idxrelrec->reltablespace))
932 index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
934 index->tableSpace = NULL;
935 index->indexOid = InvalidOid;
936 index->unique = idxrec->indisunique;
937 index->primary = idxrec->indisprimary;
938 index->concurrent = false;
941 * We don't try to preserve the name of the source index; instead, just
942 * let DefineIndex() choose a reasonable name.
944 index->idxname = NULL;
947 * If the index is marked PRIMARY or has an exclusion condition, it's
948 * certainly from a constraint; else, if it's not marked UNIQUE, it
949 * certainly isn't. If it is or might be from a constraint, we have to
950 * fetch the pg_constraint record.
952 if (index->primary || index->unique || idxrelrec->relhasexclusion)
954 Oid constraintId = get_index_constraint(source_relid);
956 if (OidIsValid(constraintId))
959 Form_pg_constraint conrec;
961 ht_constr = SearchSysCache1(CONSTROID,
962 ObjectIdGetDatum(constraintId));
963 if (!HeapTupleIsValid(ht_constr))
964 elog(ERROR, "cache lookup failed for constraint %u",
966 conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
968 index->isconstraint = true;
969 index->deferrable = conrec->condeferrable;
970 index->initdeferred = conrec->condeferred;
972 /* If it's an exclusion constraint, we need the operator names */
973 if (idxrelrec->relhasexclusion)
979 Assert(conrec->contype == CONSTRAINT_EXCLUSION);
980 /* Extract operator OIDs from the pg_constraint tuple */
981 datum = SysCacheGetAttr(CONSTROID, ht_constr,
982 Anum_pg_constraint_conexclop,
985 elog(ERROR, "null conexclop for constraint %u",
988 deconstruct_array(DatumGetArrayTypeP(datum),
989 OIDOID, sizeof(Oid), true, 'i',
990 &elems, NULL, &nElems);
992 for (i = 0; i < nElems; i++)
994 Oid operid = DatumGetObjectId(elems[i]);
996 Form_pg_operator operform;
1001 opertup = SearchSysCache1(OPEROID,
1002 ObjectIdGetDatum(operid));
1003 if (!HeapTupleIsValid(opertup))
1004 elog(ERROR, "cache lookup failed for operator %u",
1006 operform = (Form_pg_operator) GETSTRUCT(opertup);
1007 oprname = pstrdup(NameStr(operform->oprname));
1008 /* For simplicity we always schema-qualify the op name */
1009 nspname = get_namespace_name(operform->oprnamespace);
1010 namelist = list_make2(makeString(nspname),
1011 makeString(oprname));
1012 index->excludeOpNames = lappend(index->excludeOpNames,
1014 ReleaseSysCache(opertup);
1018 ReleaseSysCache(ht_constr);
1021 index->isconstraint = false;
1024 index->isconstraint = false;
1026 /* Get the index expressions, if any */
1027 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1028 Anum_pg_index_indexprs, &isnull);
1033 exprsString = TextDatumGetCString(datum);
1034 indexprs = (List *) stringToNode(exprsString);
1039 /* Build the list of IndexElem */
1040 index->indexParams = NIL;
1042 indexpr_item = list_head(indexprs);
1043 for (keyno = 0; keyno < idxrec->indnatts; keyno++)
1046 AttrNumber attnum = idxrec->indkey.values[keyno];
1047 int16 opt = source_idx->rd_indoption[keyno];
1049 iparam = makeNode(IndexElem);
1051 if (AttributeNumberIsValid(attnum))
1053 /* Simple index column */
1056 attname = get_relid_attribute_name(indrelid, attnum);
1057 keycoltype = get_atttype(indrelid, attnum);
1059 iparam->name = attname;
1060 iparam->expr = NULL;
1064 /* Expressional index */
1067 if (indexpr_item == NULL)
1068 elog(ERROR, "too few entries in indexprs list");
1069 indexkey = (Node *) lfirst(indexpr_item);
1070 indexpr_item = lnext(indexpr_item);
1072 /* OK to modify indexkey since we are working on a private copy */
1073 change_varattnos_of_a_node(indexkey, attmap);
1075 iparam->name = NULL;
1076 iparam->expr = indexkey;
1078 keycoltype = exprType(indexkey);
1081 /* Copy the original index column name */
1082 iparam->indexcolname = pstrdup(NameStr(attrs[keyno]->attname));
1084 /* Add the operator class name, if non-default */
1085 iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1087 iparam->ordering = SORTBY_DEFAULT;
1088 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1090 /* Adjust options if necessary */
1091 if (amrec->amcanorder)
1094 * If it supports sort ordering, copy DESC and NULLS opts. Don't
1095 * set non-default settings unnecessarily, though, so as to
1096 * improve the chance of recognizing equivalence to constraint
1099 if (opt & INDOPTION_DESC)
1101 iparam->ordering = SORTBY_DESC;
1102 if ((opt & INDOPTION_NULLS_FIRST) == 0)
1103 iparam->nulls_ordering = SORTBY_NULLS_LAST;
1107 if (opt & INDOPTION_NULLS_FIRST)
1108 iparam->nulls_ordering = SORTBY_NULLS_FIRST;
1112 index->indexParams = lappend(index->indexParams, iparam);
1115 /* Copy reloptions if any */
1116 datum = SysCacheGetAttr(RELOID, ht_idxrel,
1117 Anum_pg_class_reloptions, &isnull);
1119 index->options = untransformRelOptions(datum);
1121 /* If it's a partial index, decompile and append the predicate */
1122 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1123 Anum_pg_index_indpred, &isnull);
1128 /* Convert text string to node tree */
1129 pred_str = TextDatumGetCString(datum);
1130 index->whereClause = (Node *) stringToNode(pred_str);
1131 /* Adjust attribute numbers */
1132 change_varattnos_of_a_node(index->whereClause, attmap);
1136 ReleaseSysCache(ht_idxrel);
1142 * get_opclass - fetch name of an index operator class
1144 * If the opclass is the default for the given actual_datatype, then
1145 * the return value is NIL.
1148 get_opclass(Oid opclass, Oid actual_datatype)
1151 Form_pg_opclass opc_rec;
1154 ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1155 if (!HeapTupleIsValid(ht_opc))
1156 elog(ERROR, "cache lookup failed for opclass %u", opclass);
1157 opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
1159 if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
1161 /* For simplicity, we always schema-qualify the name */
1162 char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
1163 char *opc_name = pstrdup(NameStr(opc_rec->opcname));
1165 result = list_make2(makeString(nsp_name), makeString(opc_name));
1168 ReleaseSysCache(ht_opc);
1174 * transformIndexConstraints
1175 * Handle UNIQUE, PRIMARY KEY, EXCLUDE constraints, which create indexes.
1176 * We also merge in any index definitions arising from
1177 * LIKE ... INCLUDING INDEXES.
1180 transformIndexConstraints(CreateStmtContext *cxt)
1183 List *indexlist = NIL;
1187 * Run through the constraints that need to generate an index. For PRIMARY
1188 * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
1189 * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
1192 foreach(lc, cxt->ixconstraints)
1194 Constraint *constraint = (Constraint *) lfirst(lc);
1196 Assert(IsA(constraint, Constraint));
1197 Assert(constraint->contype == CONSTR_PRIMARY ||
1198 constraint->contype == CONSTR_UNIQUE ||
1199 constraint->contype == CONSTR_EXCLUSION);
1201 index = transformIndexConstraint(constraint, cxt);
1203 indexlist = lappend(indexlist, index);
1206 /* Add in any indexes defined by LIKE ... INCLUDING INDEXES */
1207 foreach(lc, cxt->inh_indexes)
1209 index = (IndexStmt *) lfirst(lc);
1213 if (cxt->pkey != NULL)
1215 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1216 errmsg("multiple primary keys for table \"%s\" are not allowed",
1217 cxt->relation->relname)));
1221 indexlist = lappend(indexlist, index);
1225 * Scan the index list and remove any redundant index specifications. This
1226 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1227 * strict reading of SQL92 would suggest raising an error instead, but
1228 * that strikes me as too anal-retentive. - tgl 2001-02-14
1230 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1231 * pre-existing indexes, too.
1233 Assert(cxt->alist == NIL);
1234 if (cxt->pkey != NULL)
1236 /* Make sure we keep the PKEY index in preference to others... */
1237 cxt->alist = list_make1(cxt->pkey);
1240 foreach(lc, indexlist)
1247 /* if it's pkey, it's already in cxt->alist */
1248 if (index == cxt->pkey)
1251 foreach(k, cxt->alist)
1253 IndexStmt *priorindex = lfirst(k);
1255 if (equal(index->indexParams, priorindex->indexParams) &&
1256 equal(index->whereClause, priorindex->whereClause) &&
1257 equal(index->excludeOpNames, priorindex->excludeOpNames) &&
1258 strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
1259 index->deferrable == priorindex->deferrable &&
1260 index->initdeferred == priorindex->initdeferred)
1262 priorindex->unique |= index->unique;
1265 * If the prior index is as yet unnamed, and this one is
1266 * named, then transfer the name to the prior index. This
1267 * ensures that if we have named and unnamed constraints,
1268 * we'll use (at least one of) the names for the index.
1270 if (priorindex->idxname == NULL)
1271 priorindex->idxname = index->idxname;
1278 cxt->alist = lappend(cxt->alist, index);
1283 * transformIndexConstraint
1284 * Transform one UNIQUE, PRIMARY KEY, or EXCLUDE constraint for
1285 * transformIndexConstraints.
1288 transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
1293 index = makeNode(IndexStmt);
1295 index->unique = (constraint->contype != CONSTR_EXCLUSION);
1296 index->primary = (constraint->contype == CONSTR_PRIMARY);
1299 if (cxt->pkey != NULL)
1301 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1302 errmsg("multiple primary keys for table \"%s\" are not allowed",
1303 cxt->relation->relname),
1304 parser_errposition(cxt->pstate, constraint->location)));
1308 * In ALTER TABLE case, a primary index might already exist, but
1309 * DefineIndex will check for it.
1312 index->isconstraint = true;
1313 index->deferrable = constraint->deferrable;
1314 index->initdeferred = constraint->initdeferred;
1316 if (constraint->conname != NULL)
1317 index->idxname = pstrdup(constraint->conname);
1319 index->idxname = NULL; /* DefineIndex will choose name */
1321 index->relation = cxt->relation;
1322 index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
1323 index->options = constraint->options;
1324 index->tableSpace = constraint->indexspace;
1325 index->whereClause = constraint->where_clause;
1326 index->indexParams = NIL;
1327 index->excludeOpNames = NIL;
1328 index->indexOid = InvalidOid;
1329 index->concurrent = false;
1332 * If it's ALTER TABLE ADD CONSTRAINT USING INDEX, look up the index and
1333 * verify it's usable, then extract the implied column name list. (We
1334 * will not actually need the column name list at runtime, but we need
1335 * it now to check for duplicate column entries below.)
1337 if (constraint->indexname != NULL)
1339 char *index_name = constraint->indexname;
1340 Relation heap_rel = cxt->rel;
1343 Form_pg_index index_form;
1344 oidvector *indclass;
1345 Datum indclassDatum;
1349 /* Grammar should not allow this with explicit column list */
1350 Assert(constraint->keys == NIL);
1352 /* Grammar should only allow PRIMARY and UNIQUE constraints */
1353 Assert(constraint->contype == CONSTR_PRIMARY ||
1354 constraint->contype == CONSTR_UNIQUE);
1356 /* Must be ALTER, not CREATE, but grammar doesn't enforce that */
1359 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1360 errmsg("cannot use an existing index in CREATE TABLE"),
1361 parser_errposition(cxt->pstate, constraint->location)));
1363 /* Look for the index in the same schema as the table */
1364 index_oid = get_relname_relid(index_name, RelationGetNamespace(heap_rel));
1366 if (!OidIsValid(index_oid))
1368 (errcode(ERRCODE_UNDEFINED_OBJECT),
1369 errmsg("index \"%s\" does not exist", index_name),
1370 parser_errposition(cxt->pstate, constraint->location)));
1372 /* Open the index (this will throw an error if it is not an index) */
1373 index_rel = index_open(index_oid, AccessShareLock);
1374 index_form = index_rel->rd_index;
1376 /* Check that it does not have an associated constraint already */
1377 if (OidIsValid(get_index_constraint(index_oid)))
1379 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1380 errmsg("index \"%s\" is already associated with a constraint",
1382 parser_errposition(cxt->pstate, constraint->location)));
1384 /* Perform validity checks on the index */
1385 if (index_form->indrelid != RelationGetRelid(heap_rel))
1387 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1388 errmsg("index \"%s\" does not belong to table \"%s\"",
1389 index_name, RelationGetRelationName(heap_rel)),
1390 parser_errposition(cxt->pstate, constraint->location)));
1392 if (!index_form->indisvalid)
1394 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1395 errmsg("index \"%s\" is not valid", index_name),
1396 parser_errposition(cxt->pstate, constraint->location)));
1398 if (!index_form->indisready)
1400 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1401 errmsg("index \"%s\" is not ready", index_name),
1402 parser_errposition(cxt->pstate, constraint->location)));
1404 if (!index_form->indisunique)
1406 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1407 errmsg("\"%s\" is not a unique index", index_name),
1408 errdetail("Cannot create a PRIMARY KEY or UNIQUE constraint using such an index."),
1409 parser_errposition(cxt->pstate, constraint->location)));
1411 if (RelationGetIndexExpressions(index_rel) != NIL)
1413 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1414 errmsg("index \"%s\" contains expressions", index_name),
1415 errdetail("Cannot create a PRIMARY KEY or UNIQUE constraint using such an index."),
1416 parser_errposition(cxt->pstate, constraint->location)));
1418 if (RelationGetIndexPredicate(index_rel) != NIL)
1420 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1421 errmsg("\"%s\" is a partial index", index_name),
1422 errdetail("Cannot create a PRIMARY KEY or UNIQUE constraint using such an index."),
1423 parser_errposition(cxt->pstate, constraint->location)));
1426 * It's probably unsafe to change a deferred index to non-deferred.
1427 * (A non-constraint index couldn't be deferred anyway, so this case
1428 * should never occur; no need to sweat, but let's check it.)
1430 if (!index_form->indimmediate && !constraint->deferrable)
1432 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1433 errmsg("\"%s\" is a deferrable index", index_name),
1434 errdetail("Cannot create a non-deferrable constraint using a deferrable index."),
1435 parser_errposition(cxt->pstate, constraint->location)));
1438 * Insist on it being a btree. That's the only kind that supports
1439 * uniqueness at the moment anyway; but we must have an index that
1440 * exactly matches what you'd get from plain ADD CONSTRAINT syntax,
1441 * else dump and reload will produce a different index (breaking
1442 * pg_upgrade in particular).
1444 if (index_rel->rd_rel->relam != get_am_oid(DEFAULT_INDEX_TYPE, false))
1446 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1447 errmsg("index \"%s\" is not a b-tree", index_name),
1448 parser_errposition(cxt->pstate, constraint->location)));
1450 /* Must get indclass the hard way */
1451 indclassDatum = SysCacheGetAttr(INDEXRELID, index_rel->rd_indextuple,
1452 Anum_pg_index_indclass, &isnull);
1454 indclass = (oidvector *) DatumGetPointer(indclassDatum);
1456 for (i = 0; i < index_form->indnatts; i++)
1458 int2 attnum = index_form->indkey.values[i];
1459 Form_pg_attribute attform;
1464 * We shouldn't see attnum == 0 here, since we already rejected
1465 * expression indexes. If we do, SystemAttributeDefinition
1466 * will throw an error.
1470 Assert(attnum <= heap_rel->rd_att->natts);
1471 attform = heap_rel->rd_att->attrs[attnum - 1];
1474 attform = SystemAttributeDefinition(attnum,
1475 heap_rel->rd_rel->relhasoids);
1476 attname = pstrdup(NameStr(attform->attname));
1479 * Insist on default opclass and sort options. While the index
1480 * would still work as a constraint with non-default settings, it
1481 * might not provide exactly the same uniqueness semantics as
1482 * you'd get from a normally-created constraint; and there's also
1483 * the dump/reload problem mentioned above.
1485 defopclass = GetDefaultOpClass(attform->atttypid,
1486 index_rel->rd_rel->relam);
1487 if (indclass->values[i] != defopclass ||
1488 index_rel->rd_indoption[i] != 0)
1490 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1491 errmsg("index \"%s\" does not have default sorting behavior", index_name),
1492 errdetail("Cannot create a PRIMARY KEY or UNIQUE constraint using such an index."),
1493 parser_errposition(cxt->pstate, constraint->location)));
1495 constraint->keys = lappend(constraint->keys, makeString(attname));
1498 /* Close the index relation but keep the lock */
1499 relation_close(index_rel, NoLock);
1501 index->indexOid = index_oid;
1505 * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
1506 * IndexElems and operator names. We have to break that apart into
1509 if (constraint->contype == CONSTR_EXCLUSION)
1511 foreach(lc, constraint->exclusions)
1513 List *pair = (List *) lfirst(lc);
1517 Assert(list_length(pair) == 2);
1518 elem = (IndexElem *) linitial(pair);
1519 Assert(IsA(elem, IndexElem));
1520 opname = (List *) lsecond(pair);
1521 Assert(IsA(opname, List));
1523 index->indexParams = lappend(index->indexParams, elem);
1524 index->excludeOpNames = lappend(index->excludeOpNames, opname);
1531 * For UNIQUE and PRIMARY KEY, we just have a list of column names.
1533 * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
1534 * also make sure they are NOT NULL, if possible. (Although we could leave
1535 * it to DefineIndex to mark the columns NOT NULL, it's more efficient to
1536 * get it right the first time.)
1538 foreach(lc, constraint->keys)
1540 char *key = strVal(lfirst(lc));
1542 ColumnDef *column = NULL;
1546 foreach(columns, cxt->columns)
1548 column = (ColumnDef *) lfirst(columns);
1549 Assert(IsA(column, ColumnDef));
1550 if (strcmp(column->colname, key) == 0)
1558 /* found column in the new table; force it to be NOT NULL */
1559 if (constraint->contype == CONSTR_PRIMARY)
1560 column->is_not_null = TRUE;
1562 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1565 * column will be a system column in the new table, so accept it.
1566 * System columns can't ever be null, so no need to worry about
1567 * PRIMARY/NOT NULL constraint.
1571 else if (cxt->inhRelations)
1573 /* try inherited tables */
1576 foreach(inher, cxt->inhRelations)
1578 RangeVar *inh = (RangeVar *) lfirst(inher);
1582 Assert(IsA(inh, RangeVar));
1583 rel = heap_openrv(inh, AccessShareLock);
1584 if (rel->rd_rel->relkind != RELKIND_RELATION)
1586 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1587 errmsg("inherited relation \"%s\" is not a table",
1589 for (count = 0; count < rel->rd_att->natts; count++)
1591 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1592 char *inhname = NameStr(inhattr->attname);
1594 if (inhattr->attisdropped)
1596 if (strcmp(key, inhname) == 0)
1601 * We currently have no easy way to force an inherited
1602 * column to be NOT NULL at creation, if its parent
1603 * wasn't so already. We leave it to DefineIndex to
1604 * fix things up in this case.
1609 heap_close(rel, NoLock);
1616 * In the ALTER TABLE case, don't complain about index keys not
1617 * created in the command; they may well exist already. DefineIndex
1618 * will complain about them if not, and will also take care of marking
1621 if (!found && !cxt->isalter)
1623 (errcode(ERRCODE_UNDEFINED_COLUMN),
1624 errmsg("column \"%s\" named in key does not exist", key),
1625 parser_errposition(cxt->pstate, constraint->location)));
1627 /* Check for PRIMARY KEY(foo, foo) */
1628 foreach(columns, index->indexParams)
1630 iparam = (IndexElem *) lfirst(columns);
1631 if (iparam->name && strcmp(key, iparam->name) == 0)
1635 (errcode(ERRCODE_DUPLICATE_COLUMN),
1636 errmsg("column \"%s\" appears twice in primary key constraint",
1638 parser_errposition(cxt->pstate, constraint->location)));
1641 (errcode(ERRCODE_DUPLICATE_COLUMN),
1642 errmsg("column \"%s\" appears twice in unique constraint",
1644 parser_errposition(cxt->pstate, constraint->location)));
1648 /* OK, add it to the index definition */
1649 iparam = makeNode(IndexElem);
1650 iparam->name = pstrdup(key);
1651 iparam->expr = NULL;
1652 iparam->indexcolname = NULL;
1653 iparam->opclass = NIL;
1654 iparam->ordering = SORTBY_DEFAULT;
1655 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1656 index->indexParams = lappend(index->indexParams, iparam);
1663 * transformFKConstraints
1664 * handle FOREIGN KEY constraints
1667 transformFKConstraints(CreateStmtContext *cxt,
1668 bool skipValidation, bool isAddConstraint)
1672 if (cxt->fkconstraints == NIL)
1676 * If CREATE TABLE or adding a column with NULL default, we can safely
1677 * skip validation of the constraint.
1681 foreach(fkclist, cxt->fkconstraints)
1683 Constraint *constraint = (Constraint *) lfirst(fkclist);
1685 constraint->skip_validation = true;
1690 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1691 * CONSTRAINT command to execute after the basic command is complete. (If
1692 * called from ADD CONSTRAINT, that routine will add the FK constraints to
1693 * its own subcommand list.)
1695 * Note: the ADD CONSTRAINT command must also execute after any index
1696 * creation commands. Thus, this should run after
1697 * transformIndexConstraints, so that the CREATE INDEX commands are
1698 * already in cxt->alist.
1700 if (!isAddConstraint)
1702 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1704 alterstmt->relation = cxt->relation;
1705 alterstmt->cmds = NIL;
1706 alterstmt->relkind = OBJECT_TABLE;
1708 foreach(fkclist, cxt->fkconstraints)
1710 Constraint *constraint = (Constraint *) lfirst(fkclist);
1711 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1713 altercmd->subtype = AT_ProcessedConstraint;
1714 altercmd->name = NULL;
1715 altercmd->def = (Node *) constraint;
1716 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1719 cxt->alist = lappend(cxt->alist, alterstmt);
1724 * transformIndexStmt - parse analysis for CREATE INDEX and ALTER TABLE
1726 * Note: this is a no-op for an index not using either index expressions or
1727 * a predicate expression. There are several code paths that create indexes
1728 * without bothering to call this, because they know they don't have any
1729 * such expressions to deal with.
1732 transformIndexStmt(IndexStmt *stmt, const char *queryString)
1740 * We must not scribble on the passed-in IndexStmt, so copy it. (This is
1741 * overkill, but easy.)
1743 stmt = (IndexStmt *) copyObject(stmt);
1746 * Open the parent table with appropriate locking. We must do this
1747 * because addRangeTableEntry() would acquire only AccessShareLock,
1748 * leaving DefineIndex() needing to do a lock upgrade with consequent risk
1749 * of deadlock. Make sure this stays in sync with the type of lock
1750 * DefineIndex() wants. If we are being called by ALTER TABLE, we will
1751 * already hold a higher lock.
1753 rel = heap_openrv(stmt->relation,
1754 (stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock));
1757 pstate = make_parsestate(NULL);
1758 pstate->p_sourcetext = queryString;
1761 * Put the parent table into the rtable so that the expressions can refer
1762 * to its fields without qualification.
1764 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1766 /* no to join list, yes to namespaces */
1767 addRTEtoQuery(pstate, rte, false, true, true);
1769 /* take care of the where clause */
1770 if (stmt->whereClause)
1771 stmt->whereClause = transformWhereClause(pstate,
1775 /* take care of any index expressions */
1776 foreach(l, stmt->indexParams)
1778 IndexElem *ielem = (IndexElem *) lfirst(l);
1782 /* Extract preliminary index col name before transforming expr */
1783 if (ielem->indexcolname == NULL)
1784 ielem->indexcolname = FigureIndexColname(ielem->expr);
1786 /* Now do parse transformation of the expression */
1787 ielem->expr = transformExpr(pstate, ielem->expr);
1790 * We check only that the result type is legitimate; this is for
1791 * consistency with what transformWhereClause() checks for the
1792 * predicate. DefineIndex() will make more checks.
1794 if (expression_returns_set(ielem->expr))
1796 (errcode(ERRCODE_DATATYPE_MISMATCH),
1797 errmsg("index expression cannot return a set")));
1802 * Check that only the base rel is mentioned.
1804 if (list_length(pstate->p_rtable) != 1)
1806 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1807 errmsg("index expressions and predicates can refer only to the table being indexed")));
1809 free_parsestate(pstate);
1811 /* Close relation, but keep the lock */
1812 heap_close(rel, NoLock);
1819 * transformRuleStmt -
1820 * transform a CREATE RULE Statement. The action is a list of parse
1821 * trees which is transformed into a list of query trees, and we also
1822 * transform the WHERE clause if any.
1824 * actions and whereClause are output parameters that receive the
1825 * transformed results.
1827 * Note that we must not scribble on the passed-in RuleStmt, so we do
1828 * copyObject() on the actions and WHERE clause.
1831 transformRuleStmt(RuleStmt *stmt, const char *queryString,
1832 List **actions, Node **whereClause)
1836 RangeTblEntry *oldrte;
1837 RangeTblEntry *newrte;
1840 * To avoid deadlock, make sure the first thing we do is grab
1841 * AccessExclusiveLock on the target relation. This will be needed by
1842 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1845 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1848 pstate = make_parsestate(NULL);
1849 pstate->p_sourcetext = queryString;
1852 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1853 * Set up their RTEs in the main pstate for use in parsing the rule
1856 oldrte = addRangeTableEntryForRelation(pstate, rel,
1857 makeAlias("old", NIL),
1859 newrte = addRangeTableEntryForRelation(pstate, rel,
1860 makeAlias("new", NIL),
1862 /* Must override addRangeTableEntry's default access-check flags */
1863 oldrte->requiredPerms = 0;
1864 newrte->requiredPerms = 0;
1867 * They must be in the namespace too for lookup purposes, but only add the
1868 * one(s) that are relevant for the current kind of rule. In an UPDATE
1869 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1870 * there's no need to be so picky for INSERT & DELETE. We do not add them
1873 switch (stmt->event)
1876 addRTEtoQuery(pstate, oldrte, false, true, true);
1879 addRTEtoQuery(pstate, oldrte, false, true, true);
1880 addRTEtoQuery(pstate, newrte, false, true, true);
1883 addRTEtoQuery(pstate, newrte, false, true, true);
1886 addRTEtoQuery(pstate, oldrte, false, true, true);
1889 elog(ERROR, "unrecognized event type: %d",
1894 /* take care of the where clause */
1895 *whereClause = transformWhereClause(pstate,
1896 (Node *) copyObject(stmt->whereClause),
1899 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
1901 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1902 errmsg("rule WHERE condition cannot contain references to other relations")));
1904 /* aggregates not allowed (but subselects are okay) */
1905 if (pstate->p_hasAggs)
1907 (errcode(ERRCODE_GROUPING_ERROR),
1908 errmsg("cannot use aggregate function in rule WHERE condition")));
1909 if (pstate->p_hasWindowFuncs)
1911 (errcode(ERRCODE_WINDOWING_ERROR),
1912 errmsg("cannot use window function in rule WHERE condition")));
1915 * 'instead nothing' rules with a qualification need a query rangetable so
1916 * the rewrite handler can add the negated rule qualification to the
1917 * original query. We create a query with the new command type CMD_NOTHING
1918 * here that is treated specially by the rewrite system.
1920 if (stmt->actions == NIL)
1922 Query *nothing_qry = makeNode(Query);
1924 nothing_qry->commandType = CMD_NOTHING;
1925 nothing_qry->rtable = pstate->p_rtable;
1926 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1928 *actions = list_make1(nothing_qry);
1933 List *newactions = NIL;
1936 * transform each statement, like parse_sub_analyze()
1938 foreach(l, stmt->actions)
1940 Node *action = (Node *) lfirst(l);
1941 ParseState *sub_pstate = make_parsestate(NULL);
1948 * Since outer ParseState isn't parent of inner, have to pass down
1949 * the query text by hand.
1951 sub_pstate->p_sourcetext = queryString;
1954 * Set up OLD/NEW in the rtable for this statement. The entries
1955 * are added only to relnamespace, not varnamespace, because we
1956 * don't want them to be referred to by unqualified field names
1957 * nor "*" in the rule actions. We decide later whether to put
1958 * them in the joinlist.
1960 oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
1961 makeAlias("old", NIL),
1963 newrte = addRangeTableEntryForRelation(sub_pstate, rel,
1964 makeAlias("new", NIL),
1966 oldrte->requiredPerms = 0;
1967 newrte->requiredPerms = 0;
1968 addRTEtoQuery(sub_pstate, oldrte, false, true, false);
1969 addRTEtoQuery(sub_pstate, newrte, false, true, false);
1971 /* Transform the rule action statement */
1972 top_subqry = transformStmt(sub_pstate,
1973 (Node *) copyObject(action));
1976 * We cannot support utility-statement actions (eg NOTIFY) with
1977 * nonempty rule WHERE conditions, because there's no way to make
1978 * the utility action execute conditionally.
1980 if (top_subqry->commandType == CMD_UTILITY &&
1981 *whereClause != NULL)
1983 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1984 errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
1987 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
1988 * into the SELECT, and that's what we need to look at. (Ugly
1989 * kluge ... try to fix this when we redesign querytrees.)
1991 sub_qry = getInsertSelectQuery(top_subqry, NULL);
1994 * If the sub_qry is a setop, we cannot attach any qualifications
1995 * to it, because the planner won't notice them. This could
1996 * perhaps be relaxed someday, but for now, we may as well reject
1997 * such a rule immediately.
1999 if (sub_qry->setOperations != NULL && *whereClause != NULL)
2001 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2002 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2005 * Validate action's use of OLD/NEW, qual too
2008 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
2009 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
2011 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
2012 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
2014 switch (stmt->event)
2019 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2020 errmsg("ON SELECT rule cannot use OLD")));
2023 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2024 errmsg("ON SELECT rule cannot use NEW")));
2032 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2033 errmsg("ON INSERT rule cannot use OLD")));
2038 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2039 errmsg("ON DELETE rule cannot use NEW")));
2042 elog(ERROR, "unrecognized event type: %d",
2048 * OLD/NEW are not allowed in WITH queries, because they would
2049 * amount to outer references for the WITH, which we disallow.
2050 * However, they were already in the outer rangetable when we
2051 * analyzed the query, so we have to check.
2053 * Note that in the INSERT...SELECT case, we need to examine
2054 * the CTE lists of both top_subqry and sub_qry.
2056 * Note that we aren't digging into the body of the query
2057 * looking for WITHs in nested sub-SELECTs. A WITH down there
2058 * can legitimately refer to OLD/NEW, because it'd be an
2059 * indirect-correlated outer reference.
2061 if (rangeTableEntry_used((Node *) top_subqry->cteList,
2062 PRS2_OLD_VARNO, 0) ||
2063 rangeTableEntry_used((Node *) sub_qry->cteList,
2066 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2067 errmsg("cannot refer to OLD within WITH query")));
2068 if (rangeTableEntry_used((Node *) top_subqry->cteList,
2069 PRS2_NEW_VARNO, 0) ||
2070 rangeTableEntry_used((Node *) sub_qry->cteList,
2073 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2074 errmsg("cannot refer to NEW within WITH query")));
2077 * For efficiency's sake, add OLD to the rule action's jointree
2078 * only if it was actually referenced in the statement or qual.
2080 * For INSERT, NEW is not really a relation (only a reference to
2081 * the to-be-inserted tuple) and should never be added to the
2084 * For UPDATE, we treat NEW as being another kind of reference to
2085 * OLD, because it represents references to *transformed* tuples
2086 * of the existing relation. It would be wrong to enter NEW
2087 * separately in the jointree, since that would cause a double
2088 * join of the updated relation. It's also wrong to fail to make
2089 * a jointree entry if only NEW and not OLD is mentioned.
2091 if (has_old || (has_new && stmt->event == CMD_UPDATE))
2094 * If sub_qry is a setop, manipulating its jointree will do no
2095 * good at all, because the jointree is dummy. (This should be
2096 * a can't-happen case because of prior tests.)
2098 if (sub_qry->setOperations != NULL)
2100 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2101 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2102 /* hack so we can use addRTEtoQuery() */
2103 sub_pstate->p_rtable = sub_qry->rtable;
2104 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
2105 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
2106 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
2109 newactions = lappend(newactions, top_subqry);
2111 free_parsestate(sub_pstate);
2114 *actions = newactions;
2117 free_parsestate(pstate);
2119 /* Close relation, but keep the exclusive lock */
2120 heap_close(rel, NoLock);
2125 * transformAlterTableStmt -
2126 * parse analysis for ALTER TABLE
2128 * Returns a List of utility commands to be done in sequence. One of these
2129 * will be the transformed AlterTableStmt, but there may be additional actions
2130 * to be done before and after the actual AlterTable() call.
2133 transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
2137 CreateStmtContext cxt;
2142 List *newcmds = NIL;
2143 bool skipValidation = true;
2144 AlterTableCmd *newcmd;
2148 * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
2149 * is overkill, but easy.)
2151 stmt = (AlterTableStmt *) copyObject(stmt);
2154 * Determine the appropriate lock level for this list of subcommands.
2156 lockmode = AlterTableGetLockLevel(stmt->cmds);
2159 * Acquire appropriate lock on the target relation, which will be held until
2160 * end of transaction. This ensures any decisions we make here based on
2161 * the state of the relation will still be good at execution. We must get
2162 * lock now because execution will later require it; taking a lower grade lock
2163 * now and trying to upgrade later risks deadlock. Any new commands we add
2164 * after this must not upgrade the lock level requested here.
2166 rel = relation_openrv(stmt->relation, lockmode);
2168 /* Set up pstate and CreateStmtContext */
2169 pstate = make_parsestate(NULL);
2170 pstate->p_sourcetext = queryString;
2172 cxt.pstate = pstate;
2173 cxt.stmtType = "ALTER TABLE";
2174 cxt.relation = stmt->relation;
2176 cxt.inhRelations = NIL;
2178 cxt.hasoids = false; /* need not be right */
2180 cxt.ckconstraints = NIL;
2181 cxt.fkconstraints = NIL;
2182 cxt.ixconstraints = NIL;
2183 cxt.inh_indexes = NIL;
2189 * The only subtypes that currently require parse transformation handling
2190 * are ADD COLUMN and ADD CONSTRAINT. These largely re-use code from
2193 foreach(lcmd, stmt->cmds)
2195 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2197 switch (cmd->subtype)
2200 case AT_AddColumnToView:
2202 ColumnDef *def = (ColumnDef *) cmd->def;
2204 Assert(IsA(def, ColumnDef));
2205 transformColumnDefinition(&cxt, def);
2208 * If the column has a non-null default, we can't skip
2209 * validation of foreign keys.
2211 if (def->raw_default != NULL)
2212 skipValidation = false;
2215 * All constraints are processed in other ways. Remove the
2218 def->constraints = NIL;
2220 newcmds = lappend(newcmds, cmd);
2223 case AT_AddConstraint:
2226 * The original AddConstraint cmd node doesn't go to newcmds
2228 if (IsA(cmd->def, Constraint))
2230 transformTableConstraint(&cxt, (Constraint *) cmd->def);
2231 if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
2232 skipValidation = false;
2235 elog(ERROR, "unrecognized node type: %d",
2236 (int) nodeTag(cmd->def));
2239 case AT_ProcessedConstraint:
2242 * Already-transformed ADD CONSTRAINT, so just make it look
2243 * like the standard case.
2245 cmd->subtype = AT_AddConstraint;
2246 newcmds = lappend(newcmds, cmd);
2250 newcmds = lappend(newcmds, cmd);
2256 * transformIndexConstraints wants cxt.alist to contain only index
2257 * statements, so transfer anything we already have into save_alist
2260 save_alist = cxt.alist;
2263 /* Postprocess index and FK constraints */
2264 transformIndexConstraints(&cxt);
2266 transformFKConstraints(&cxt, skipValidation, true);
2269 * Push any index-creation commands into the ALTER, so that they can be
2270 * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
2271 * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
2272 * subcommand has already been through transformIndexStmt.
2274 foreach(l, cxt.alist)
2276 IndexStmt *idxstmt = (IndexStmt *) lfirst(l);
2278 Assert(IsA(idxstmt, IndexStmt));
2279 idxstmt = transformIndexStmt(idxstmt, queryString);
2280 newcmd = makeNode(AlterTableCmd);
2281 newcmd->subtype = OidIsValid(idxstmt->indexOid) ? AT_AddIndexConstraint : AT_AddIndex;
2282 newcmd->def = (Node *) idxstmt;
2283 newcmds = lappend(newcmds, newcmd);
2287 /* Append any CHECK or FK constraints to the commands list */
2288 foreach(l, cxt.ckconstraints)
2290 newcmd = makeNode(AlterTableCmd);
2291 newcmd->subtype = AT_AddConstraint;
2292 newcmd->def = (Node *) lfirst(l);
2293 newcmds = lappend(newcmds, newcmd);
2295 foreach(l, cxt.fkconstraints)
2297 newcmd = makeNode(AlterTableCmd);
2298 newcmd->subtype = AT_AddConstraint;
2299 newcmd->def = (Node *) lfirst(l);
2300 newcmds = lappend(newcmds, newcmd);
2303 /* Close rel but keep lock */
2304 relation_close(rel, NoLock);
2309 stmt->cmds = newcmds;
2311 result = lappend(cxt.blist, stmt);
2312 result = list_concat(result, cxt.alist);
2313 result = list_concat(result, save_alist);
2320 * Preprocess a list of column constraint clauses
2321 * to attach constraint attributes to their primary constraint nodes
2322 * and detect inconsistent/misplaced constraint attributes.
2324 * NOTE: currently, attributes are only supported for FOREIGN KEY, UNIQUE,
2325 * and PRIMARY KEY constraints, but someday they ought to be supported
2326 * for other constraint types.
2329 transformConstraintAttrs(CreateStmtContext *cxt, List *constraintList)
2331 Constraint *lastprimarycon = NULL;
2332 bool saw_deferrability = false;
2333 bool saw_initially = false;
2336 #define SUPPORTS_ATTRS(node) \
2337 ((node) != NULL && \
2338 ((node)->contype == CONSTR_PRIMARY || \
2339 (node)->contype == CONSTR_UNIQUE || \
2340 (node)->contype == CONSTR_EXCLUSION || \
2341 (node)->contype == CONSTR_FOREIGN))
2343 foreach(clist, constraintList)
2345 Constraint *con = (Constraint *) lfirst(clist);
2347 if (!IsA(con, Constraint))
2348 elog(ERROR, "unrecognized node type: %d",
2349 (int) nodeTag(con));
2350 switch (con->contype)
2352 case CONSTR_ATTR_DEFERRABLE:
2353 if (!SUPPORTS_ATTRS(lastprimarycon))
2355 (errcode(ERRCODE_SYNTAX_ERROR),
2356 errmsg("misplaced DEFERRABLE clause"),
2357 parser_errposition(cxt->pstate, con->location)));
2358 if (saw_deferrability)
2360 (errcode(ERRCODE_SYNTAX_ERROR),
2361 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2362 parser_errposition(cxt->pstate, con->location)));
2363 saw_deferrability = true;
2364 lastprimarycon->deferrable = true;
2367 case CONSTR_ATTR_NOT_DEFERRABLE:
2368 if (!SUPPORTS_ATTRS(lastprimarycon))
2370 (errcode(ERRCODE_SYNTAX_ERROR),
2371 errmsg("misplaced NOT DEFERRABLE clause"),
2372 parser_errposition(cxt->pstate, con->location)));
2373 if (saw_deferrability)
2375 (errcode(ERRCODE_SYNTAX_ERROR),
2376 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2377 parser_errposition(cxt->pstate, con->location)));
2378 saw_deferrability = true;
2379 lastprimarycon->deferrable = false;
2380 if (saw_initially &&
2381 lastprimarycon->initdeferred)
2383 (errcode(ERRCODE_SYNTAX_ERROR),
2384 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2385 parser_errposition(cxt->pstate, con->location)));
2388 case CONSTR_ATTR_DEFERRED:
2389 if (!SUPPORTS_ATTRS(lastprimarycon))
2391 (errcode(ERRCODE_SYNTAX_ERROR),
2392 errmsg("misplaced INITIALLY DEFERRED clause"),
2393 parser_errposition(cxt->pstate, con->location)));
2396 (errcode(ERRCODE_SYNTAX_ERROR),
2397 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2398 parser_errposition(cxt->pstate, con->location)));
2399 saw_initially = true;
2400 lastprimarycon->initdeferred = true;
2403 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
2405 if (!saw_deferrability)
2406 lastprimarycon->deferrable = true;
2407 else if (!lastprimarycon->deferrable)
2409 (errcode(ERRCODE_SYNTAX_ERROR),
2410 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2411 parser_errposition(cxt->pstate, con->location)));
2414 case CONSTR_ATTR_IMMEDIATE:
2415 if (!SUPPORTS_ATTRS(lastprimarycon))
2417 (errcode(ERRCODE_SYNTAX_ERROR),
2418 errmsg("misplaced INITIALLY IMMEDIATE clause"),
2419 parser_errposition(cxt->pstate, con->location)));
2422 (errcode(ERRCODE_SYNTAX_ERROR),
2423 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2424 parser_errposition(cxt->pstate, con->location)));
2425 saw_initially = true;
2426 lastprimarycon->initdeferred = false;
2430 /* Otherwise it's not an attribute */
2431 lastprimarycon = con;
2432 /* reset flags for new primary node */
2433 saw_deferrability = false;
2434 saw_initially = false;
2441 * Special handling of type definition for a column
2444 transformColumnType(CreateStmtContext *cxt, ColumnDef *column)
2447 * All we really need to do here is verify that the type is valid.
2449 Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
2451 ReleaseSysCache(ctype);
2456 * transformCreateSchemaStmt -
2457 * analyzes the CREATE SCHEMA statement
2459 * Split the schema element list into individual commands and place
2460 * them in the result list in an order such that there are no forward
2461 * references (e.g. GRANT to a table created later in the list). Note
2462 * that the logic we use for determining forward references is
2463 * presently quite incomplete.
2465 * SQL92 also allows constraints to make forward references, so thumb through
2466 * the table columns and move forward references to a posterior alter-table
2469 * The result is a list of parse nodes that still need to be analyzed ---
2470 * but we can't analyze the later commands until we've executed the earlier
2471 * ones, because of possible inter-object references.
2473 * Note: this breaks the rules a little bit by modifying schema-name fields
2474 * within passed-in structs. However, the transformation would be the same
2475 * if done over, so it should be all right to scribble on the input to this
2479 transformCreateSchemaStmt(CreateSchemaStmt *stmt)
2481 CreateSchemaStmtContext cxt;
2485 cxt.stmtType = "CREATE SCHEMA";
2486 cxt.schemaname = stmt->schemaname;
2487 cxt.authid = stmt->authid;
2488 cxt.sequences = NIL;
2496 * Run through each schema element in the schema element list. Separate
2497 * statements by type, and do preliminary analysis.
2499 foreach(elements, stmt->schemaElts)
2501 Node *element = lfirst(elements);
2503 switch (nodeTag(element))
2505 case T_CreateSeqStmt:
2507 CreateSeqStmt *elp = (CreateSeqStmt *) element;
2509 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
2510 cxt.sequences = lappend(cxt.sequences, element);
2516 CreateStmt *elp = (CreateStmt *) element;
2518 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2521 * XXX todo: deal with constraints
2523 cxt.tables = lappend(cxt.tables, element);
2529 ViewStmt *elp = (ViewStmt *) element;
2531 setSchemaName(cxt.schemaname, &elp->view->schemaname);
2534 * XXX todo: deal with references between views
2536 cxt.views = lappend(cxt.views, element);
2542 IndexStmt *elp = (IndexStmt *) element;
2544 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2545 cxt.indexes = lappend(cxt.indexes, element);
2549 case T_CreateTrigStmt:
2551 CreateTrigStmt *elp = (CreateTrigStmt *) element;
2553 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2554 cxt.triggers = lappend(cxt.triggers, element);
2559 cxt.grants = lappend(cxt.grants, element);
2563 elog(ERROR, "unrecognized node type: %d",
2564 (int) nodeTag(element));
2569 result = list_concat(result, cxt.sequences);
2570 result = list_concat(result, cxt.tables);
2571 result = list_concat(result, cxt.views);
2572 result = list_concat(result, cxt.indexes);
2573 result = list_concat(result, cxt.triggers);
2574 result = list_concat(result, cxt.grants);
2581 * Set or check schema name in an element of a CREATE SCHEMA command
2584 setSchemaName(char *context_schema, char **stmt_schema_name)
2586 if (*stmt_schema_name == NULL)
2587 *stmt_schema_name = context_schema;
2588 else if (strcmp(context_schema, *stmt_schema_name) != 0)
2590 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
2591 errmsg("CREATE specifies a schema (%s) "
2592 "different from the one being created (%s)",
2593 *stmt_schema_name, context_schema)));