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->is_from_type = false;
636 def->raw_default = NULL;
637 def->cooked_default = NULL;
638 def->collClause = NULL;
639 def->collOid = attribute->attcollation;
640 def->constraints = NIL;
645 cxt->columns = lappend(cxt->columns, def);
648 * Copy default, if present and the default has been requested
650 if (attribute->atthasdef &&
651 (inhRelation->options & CREATE_TABLE_LIKE_DEFAULTS))
653 Node *this_default = NULL;
654 AttrDefault *attrdef;
657 /* Find default in constraint structure */
658 Assert(constr != NULL);
659 attrdef = constr->defval;
660 for (i = 0; i < constr->num_defval; i++)
662 if (attrdef[i].adnum == parent_attno)
664 this_default = stringToNode(attrdef[i].adbin);
668 Assert(this_default != NULL);
671 * If default expr could contain any vars, we'd need to fix 'em,
672 * but it can't; so default is ready to apply to child.
675 def->cooked_default = this_default;
678 /* Likewise, copy storage if requested */
679 if (inhRelation->options & CREATE_TABLE_LIKE_STORAGE)
680 def->storage = attribute->attstorage;
684 /* Likewise, copy comment if requested */
685 if ((inhRelation->options & CREATE_TABLE_LIKE_COMMENTS) &&
686 (comment = GetComment(attribute->attrelid,
688 attribute->attnum)) != NULL)
690 CommentStmt *stmt = makeNode(CommentStmt);
692 stmt->objtype = OBJECT_COLUMN;
693 stmt->objname = list_make3(makeString(cxt->relation->schemaname),
694 makeString(cxt->relation->relname),
695 makeString(def->colname));
697 stmt->comment = comment;
699 cxt->alist = lappend(cxt->alist, stmt);
704 * Copy CHECK constraints if requested, being careful to adjust attribute
707 if ((inhRelation->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
710 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
713 for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
715 char *ccname = tupleDesc->constr->check[ccnum].ccname;
716 char *ccbin = tupleDesc->constr->check[ccnum].ccbin;
717 Node *ccbin_node = stringToNode(ccbin);
718 Constraint *n = makeNode(Constraint);
720 change_varattnos_of_a_node(ccbin_node, attmap);
722 n->contype = CONSTR_CHECK;
724 n->conname = pstrdup(ccname);
726 n->cooked_expr = nodeToString(ccbin_node);
727 cxt->ckconstraints = lappend(cxt->ckconstraints, n);
729 /* Copy comment on constraint */
730 if ((inhRelation->options & CREATE_TABLE_LIKE_COMMENTS) &&
731 (comment = GetComment(get_constraint_oid(RelationGetRelid(relation),
733 ConstraintRelationId,
736 CommentStmt *stmt = makeNode(CommentStmt);
738 stmt->objtype = OBJECT_CONSTRAINT;
739 stmt->objname = list_make3(makeString(cxt->relation->schemaname),
740 makeString(cxt->relation->relname),
741 makeString(n->conname));
743 stmt->comment = comment;
745 cxt->alist = lappend(cxt->alist, stmt);
751 * Likewise, copy indexes if requested
753 if ((inhRelation->options & CREATE_TABLE_LIKE_INDEXES) &&
754 relation->rd_rel->relhasindex)
756 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
757 List *parent_indexes;
760 parent_indexes = RelationGetIndexList(relation);
762 foreach(l, parent_indexes)
764 Oid parent_index_oid = lfirst_oid(l);
765 Relation parent_index;
766 IndexStmt *index_stmt;
768 parent_index = index_open(parent_index_oid, AccessShareLock);
770 /* Build CREATE INDEX statement to recreate the parent_index */
771 index_stmt = generateClonedIndexStmt(cxt, parent_index, attmap);
773 /* Copy comment on index */
774 if (inhRelation->options & CREATE_TABLE_LIKE_COMMENTS)
776 comment = GetComment(parent_index_oid, RelationRelationId, 0);
783 * We have to assign the index a name now, so that we can
784 * reference it in CommentStmt.
786 if (index_stmt->idxname == NULL)
787 index_stmt->idxname = chooseIndexName(cxt->relation,
790 stmt = makeNode(CommentStmt);
791 stmt->objtype = OBJECT_INDEX;
793 list_make2(makeString(cxt->relation->schemaname),
794 makeString(index_stmt->idxname));
796 stmt->comment = comment;
798 cxt->alist = lappend(cxt->alist, stmt);
802 /* Save it in the inh_indexes list for the time being */
803 cxt->inh_indexes = lappend(cxt->inh_indexes, index_stmt);
805 index_close(parent_index, AccessShareLock);
810 * Close the parent rel, but keep our AccessShareLock on it until xact
811 * commit. That will prevent someone else from deleting or ALTERing the
812 * parent before the child is committed.
814 heap_close(relation, NoLock);
818 transformOfType(CreateStmtContext *cxt, TypeName *ofTypename)
826 AssertArg(ofTypename);
828 tuple = typenameType(NULL, ofTypename, NULL);
829 typ = (Form_pg_type) GETSTRUCT(tuple);
830 ofTypeId = HeapTupleGetOid(tuple);
831 ofTypename->typeOid = ofTypeId; /* cached for later */
833 if (typ->typtype != TYPTYPE_COMPOSITE)
835 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
836 errmsg("type %s is not a composite type",
837 format_type_be(ofTypeId))));
839 tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
840 for (i = 0; i < tupdesc->natts; i++)
842 Form_pg_attribute attr = tupdesc->attrs[i];
845 if (attr->attisdropped)
848 n = makeNode(ColumnDef);
849 n->colname = pstrdup(NameStr(attr->attname));
850 n->typeName = makeTypeNameFromOid(attr->atttypid, attr->atttypmod);
853 n->is_not_null = false;
854 n->is_from_type = true;
856 n->raw_default = NULL;
857 n->cooked_default = NULL;
858 n->collClause = NULL;
859 n->collOid = attr->attcollation;
860 n->constraints = NIL;
861 cxt->columns = lappend(cxt->columns, n);
863 DecrTupleDescRefCount(tupdesc);
865 ReleaseSysCache(tuple);
871 * Compute name for an index. This must match code in indexcmds.c.
873 * XXX this is inherently broken because the indexes aren't created
874 * immediately, so we fail to resolve conflicts when the same name is
875 * derived for multiple indexes. However, that's a reasonably uncommon
876 * situation, so we'll live with it for now.
879 chooseIndexName(const RangeVar *relation, IndexStmt *index_stmt)
884 namespaceId = RangeVarGetCreationNamespace(relation);
885 colnames = ChooseIndexColumnNames(index_stmt->indexParams);
886 return ChooseIndexName(relation->relname, namespaceId,
887 colnames, index_stmt->excludeOpNames,
888 index_stmt->primary, index_stmt->isconstraint);
892 * Generate an IndexStmt node using information from an already existing index
893 * "source_idx". Attribute numbers should be adjusted according to attmap.
896 generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
899 Oid source_relid = RelationGetRelid(source_idx);
900 Form_pg_attribute *attrs = RelationGetDescr(source_idx)->attrs;
903 Form_pg_class idxrelrec;
904 Form_pg_index idxrec;
909 ListCell *indexpr_item;
917 * Fetch pg_class tuple of source index. We can't use the copy in the
918 * relcache entry because it doesn't include optional fields.
920 ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
921 if (!HeapTupleIsValid(ht_idxrel))
922 elog(ERROR, "cache lookup failed for relation %u", source_relid);
923 idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
925 /* Fetch pg_index tuple for source index from relcache entry */
926 ht_idx = source_idx->rd_indextuple;
927 idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
928 indrelid = idxrec->indrelid;
930 /* Fetch pg_am tuple for source index from relcache entry */
931 amrec = source_idx->rd_am;
933 /* Extract indclass from the pg_index tuple */
934 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
935 Anum_pg_index_indclass, &isnull);
937 indclass = (oidvector *) DatumGetPointer(datum);
939 /* Begin building the IndexStmt */
940 index = makeNode(IndexStmt);
941 index->relation = cxt->relation;
942 index->accessMethod = pstrdup(NameStr(amrec->amname));
943 if (OidIsValid(idxrelrec->reltablespace))
944 index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
946 index->tableSpace = NULL;
947 index->indexOid = InvalidOid;
948 index->unique = idxrec->indisunique;
949 index->primary = idxrec->indisprimary;
950 index->concurrent = false;
953 * We don't try to preserve the name of the source index; instead, just
954 * let DefineIndex() choose a reasonable name.
956 index->idxname = NULL;
959 * If the index is marked PRIMARY or has an exclusion condition, it's
960 * certainly from a constraint; else, if it's not marked UNIQUE, it
961 * certainly isn't. If it is or might be from a constraint, we have to
962 * fetch the pg_constraint record.
964 if (index->primary || index->unique || idxrec->indisexclusion)
966 Oid constraintId = get_index_constraint(source_relid);
968 if (OidIsValid(constraintId))
971 Form_pg_constraint conrec;
973 ht_constr = SearchSysCache1(CONSTROID,
974 ObjectIdGetDatum(constraintId));
975 if (!HeapTupleIsValid(ht_constr))
976 elog(ERROR, "cache lookup failed for constraint %u",
978 conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
980 index->isconstraint = true;
981 index->deferrable = conrec->condeferrable;
982 index->initdeferred = conrec->condeferred;
984 /* If it's an exclusion constraint, we need the operator names */
985 if (idxrec->indisexclusion)
991 Assert(conrec->contype == CONSTRAINT_EXCLUSION);
992 /* Extract operator OIDs from the pg_constraint tuple */
993 datum = SysCacheGetAttr(CONSTROID, ht_constr,
994 Anum_pg_constraint_conexclop,
997 elog(ERROR, "null conexclop for constraint %u",
1000 deconstruct_array(DatumGetArrayTypeP(datum),
1001 OIDOID, sizeof(Oid), true, 'i',
1002 &elems, NULL, &nElems);
1004 for (i = 0; i < nElems; i++)
1006 Oid operid = DatumGetObjectId(elems[i]);
1008 Form_pg_operator operform;
1013 opertup = SearchSysCache1(OPEROID,
1014 ObjectIdGetDatum(operid));
1015 if (!HeapTupleIsValid(opertup))
1016 elog(ERROR, "cache lookup failed for operator %u",
1018 operform = (Form_pg_operator) GETSTRUCT(opertup);
1019 oprname = pstrdup(NameStr(operform->oprname));
1020 /* For simplicity we always schema-qualify the op name */
1021 nspname = get_namespace_name(operform->oprnamespace);
1022 namelist = list_make2(makeString(nspname),
1023 makeString(oprname));
1024 index->excludeOpNames = lappend(index->excludeOpNames,
1026 ReleaseSysCache(opertup);
1030 ReleaseSysCache(ht_constr);
1033 index->isconstraint = false;
1036 index->isconstraint = false;
1038 /* Get the index expressions, if any */
1039 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1040 Anum_pg_index_indexprs, &isnull);
1045 exprsString = TextDatumGetCString(datum);
1046 indexprs = (List *) stringToNode(exprsString);
1051 /* Build the list of IndexElem */
1052 index->indexParams = NIL;
1054 indexpr_item = list_head(indexprs);
1055 for (keyno = 0; keyno < idxrec->indnatts; keyno++)
1058 AttrNumber attnum = idxrec->indkey.values[keyno];
1059 int16 opt = source_idx->rd_indoption[keyno];
1061 iparam = makeNode(IndexElem);
1063 if (AttributeNumberIsValid(attnum))
1065 /* Simple index column */
1068 attname = get_relid_attribute_name(indrelid, attnum);
1069 keycoltype = get_atttype(indrelid, attnum);
1071 iparam->name = attname;
1072 iparam->expr = NULL;
1076 /* Expressional index */
1079 if (indexpr_item == NULL)
1080 elog(ERROR, "too few entries in indexprs list");
1081 indexkey = (Node *) lfirst(indexpr_item);
1082 indexpr_item = lnext(indexpr_item);
1084 /* OK to modify indexkey since we are working on a private copy */
1085 change_varattnos_of_a_node(indexkey, attmap);
1087 iparam->name = NULL;
1088 iparam->expr = indexkey;
1090 keycoltype = exprType(indexkey);
1093 /* Copy the original index column name */
1094 iparam->indexcolname = pstrdup(NameStr(attrs[keyno]->attname));
1096 /* Add the operator class name, if non-default */
1097 iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1099 iparam->ordering = SORTBY_DEFAULT;
1100 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1102 /* Adjust options if necessary */
1103 if (amrec->amcanorder)
1106 * If it supports sort ordering, copy DESC and NULLS opts. Don't
1107 * set non-default settings unnecessarily, though, so as to
1108 * improve the chance of recognizing equivalence to constraint
1111 if (opt & INDOPTION_DESC)
1113 iparam->ordering = SORTBY_DESC;
1114 if ((opt & INDOPTION_NULLS_FIRST) == 0)
1115 iparam->nulls_ordering = SORTBY_NULLS_LAST;
1119 if (opt & INDOPTION_NULLS_FIRST)
1120 iparam->nulls_ordering = SORTBY_NULLS_FIRST;
1124 index->indexParams = lappend(index->indexParams, iparam);
1127 /* Copy reloptions if any */
1128 datum = SysCacheGetAttr(RELOID, ht_idxrel,
1129 Anum_pg_class_reloptions, &isnull);
1131 index->options = untransformRelOptions(datum);
1133 /* If it's a partial index, decompile and append the predicate */
1134 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1135 Anum_pg_index_indpred, &isnull);
1140 /* Convert text string to node tree */
1141 pred_str = TextDatumGetCString(datum);
1142 index->whereClause = (Node *) stringToNode(pred_str);
1143 /* Adjust attribute numbers */
1144 change_varattnos_of_a_node(index->whereClause, attmap);
1148 ReleaseSysCache(ht_idxrel);
1154 * get_opclass - fetch name of an index operator class
1156 * If the opclass is the default for the given actual_datatype, then
1157 * the return value is NIL.
1160 get_opclass(Oid opclass, Oid actual_datatype)
1163 Form_pg_opclass opc_rec;
1166 ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1167 if (!HeapTupleIsValid(ht_opc))
1168 elog(ERROR, "cache lookup failed for opclass %u", opclass);
1169 opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
1171 if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
1173 /* For simplicity, we always schema-qualify the name */
1174 char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
1175 char *opc_name = pstrdup(NameStr(opc_rec->opcname));
1177 result = list_make2(makeString(nsp_name), makeString(opc_name));
1180 ReleaseSysCache(ht_opc);
1186 * transformIndexConstraints
1187 * Handle UNIQUE, PRIMARY KEY, EXCLUDE constraints, which create indexes.
1188 * We also merge in any index definitions arising from
1189 * LIKE ... INCLUDING INDEXES.
1192 transformIndexConstraints(CreateStmtContext *cxt)
1195 List *indexlist = NIL;
1199 * Run through the constraints that need to generate an index. For PRIMARY
1200 * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
1201 * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
1204 foreach(lc, cxt->ixconstraints)
1206 Constraint *constraint = (Constraint *) lfirst(lc);
1208 Assert(IsA(constraint, Constraint));
1209 Assert(constraint->contype == CONSTR_PRIMARY ||
1210 constraint->contype == CONSTR_UNIQUE ||
1211 constraint->contype == CONSTR_EXCLUSION);
1213 index = transformIndexConstraint(constraint, cxt);
1215 indexlist = lappend(indexlist, index);
1218 /* Add in any indexes defined by LIKE ... INCLUDING INDEXES */
1219 foreach(lc, cxt->inh_indexes)
1221 index = (IndexStmt *) lfirst(lc);
1225 if (cxt->pkey != NULL)
1227 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1228 errmsg("multiple primary keys for table \"%s\" are not allowed",
1229 cxt->relation->relname)));
1233 indexlist = lappend(indexlist, index);
1237 * Scan the index list and remove any redundant index specifications. This
1238 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1239 * strict reading of SQL92 would suggest raising an error instead, but
1240 * that strikes me as too anal-retentive. - tgl 2001-02-14
1242 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1243 * pre-existing indexes, too.
1245 Assert(cxt->alist == NIL);
1246 if (cxt->pkey != NULL)
1248 /* Make sure we keep the PKEY index in preference to others... */
1249 cxt->alist = list_make1(cxt->pkey);
1252 foreach(lc, indexlist)
1259 /* if it's pkey, it's already in cxt->alist */
1260 if (index == cxt->pkey)
1263 foreach(k, cxt->alist)
1265 IndexStmt *priorindex = lfirst(k);
1267 if (equal(index->indexParams, priorindex->indexParams) &&
1268 equal(index->whereClause, priorindex->whereClause) &&
1269 equal(index->excludeOpNames, priorindex->excludeOpNames) &&
1270 strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
1271 index->deferrable == priorindex->deferrable &&
1272 index->initdeferred == priorindex->initdeferred)
1274 priorindex->unique |= index->unique;
1277 * If the prior index is as yet unnamed, and this one is
1278 * named, then transfer the name to the prior index. This
1279 * ensures that if we have named and unnamed constraints,
1280 * we'll use (at least one of) the names for the index.
1282 if (priorindex->idxname == NULL)
1283 priorindex->idxname = index->idxname;
1290 cxt->alist = lappend(cxt->alist, index);
1295 * transformIndexConstraint
1296 * Transform one UNIQUE, PRIMARY KEY, or EXCLUDE constraint for
1297 * transformIndexConstraints.
1300 transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
1305 index = makeNode(IndexStmt);
1307 index->unique = (constraint->contype != CONSTR_EXCLUSION);
1308 index->primary = (constraint->contype == CONSTR_PRIMARY);
1311 if (cxt->pkey != NULL)
1313 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1314 errmsg("multiple primary keys for table \"%s\" are not allowed",
1315 cxt->relation->relname),
1316 parser_errposition(cxt->pstate, constraint->location)));
1320 * In ALTER TABLE case, a primary index might already exist, but
1321 * DefineIndex will check for it.
1324 index->isconstraint = true;
1325 index->deferrable = constraint->deferrable;
1326 index->initdeferred = constraint->initdeferred;
1328 if (constraint->conname != NULL)
1329 index->idxname = pstrdup(constraint->conname);
1331 index->idxname = NULL; /* DefineIndex will choose name */
1333 index->relation = cxt->relation;
1334 index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
1335 index->options = constraint->options;
1336 index->tableSpace = constraint->indexspace;
1337 index->whereClause = constraint->where_clause;
1338 index->indexParams = NIL;
1339 index->excludeOpNames = NIL;
1340 index->indexOid = InvalidOid;
1341 index->concurrent = false;
1344 * If it's ALTER TABLE ADD CONSTRAINT USING INDEX, look up the index and
1345 * verify it's usable, then extract the implied column name list. (We
1346 * will not actually need the column name list at runtime, but we need
1347 * it now to check for duplicate column entries below.)
1349 if (constraint->indexname != NULL)
1351 char *index_name = constraint->indexname;
1352 Relation heap_rel = cxt->rel;
1355 Form_pg_index index_form;
1356 oidvector *indclass;
1357 Datum indclassDatum;
1361 /* Grammar should not allow this with explicit column list */
1362 Assert(constraint->keys == NIL);
1364 /* Grammar should only allow PRIMARY and UNIQUE constraints */
1365 Assert(constraint->contype == CONSTR_PRIMARY ||
1366 constraint->contype == CONSTR_UNIQUE);
1368 /* Must be ALTER, not CREATE, but grammar doesn't enforce that */
1371 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1372 errmsg("cannot use an existing index in CREATE TABLE"),
1373 parser_errposition(cxt->pstate, constraint->location)));
1375 /* Look for the index in the same schema as the table */
1376 index_oid = get_relname_relid(index_name, RelationGetNamespace(heap_rel));
1378 if (!OidIsValid(index_oid))
1380 (errcode(ERRCODE_UNDEFINED_OBJECT),
1381 errmsg("index \"%s\" does not exist", index_name),
1382 parser_errposition(cxt->pstate, constraint->location)));
1384 /* Open the index (this will throw an error if it is not an index) */
1385 index_rel = index_open(index_oid, AccessShareLock);
1386 index_form = index_rel->rd_index;
1388 /* Check that it does not have an associated constraint already */
1389 if (OidIsValid(get_index_constraint(index_oid)))
1391 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1392 errmsg("index \"%s\" is already associated with a constraint",
1394 parser_errposition(cxt->pstate, constraint->location)));
1396 /* Perform validity checks on the index */
1397 if (index_form->indrelid != RelationGetRelid(heap_rel))
1399 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1400 errmsg("index \"%s\" does not belong to table \"%s\"",
1401 index_name, RelationGetRelationName(heap_rel)),
1402 parser_errposition(cxt->pstate, constraint->location)));
1404 if (!index_form->indisvalid)
1406 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1407 errmsg("index \"%s\" is not valid", index_name),
1408 parser_errposition(cxt->pstate, constraint->location)));
1410 if (!index_form->indisready)
1412 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1413 errmsg("index \"%s\" is not ready", index_name),
1414 parser_errposition(cxt->pstate, constraint->location)));
1416 if (!index_form->indisunique)
1418 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1419 errmsg("\"%s\" is not a unique index", index_name),
1420 errdetail("Cannot create a PRIMARY KEY or UNIQUE constraint using such an index."),
1421 parser_errposition(cxt->pstate, constraint->location)));
1423 if (RelationGetIndexExpressions(index_rel) != NIL)
1425 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1426 errmsg("index \"%s\" contains expressions", index_name),
1427 errdetail("Cannot create a PRIMARY KEY or UNIQUE constraint using such an index."),
1428 parser_errposition(cxt->pstate, constraint->location)));
1430 if (RelationGetIndexPredicate(index_rel) != NIL)
1432 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1433 errmsg("\"%s\" is a partial index", index_name),
1434 errdetail("Cannot create a PRIMARY KEY or UNIQUE constraint using such an index."),
1435 parser_errposition(cxt->pstate, constraint->location)));
1438 * It's probably unsafe to change a deferred index to non-deferred.
1439 * (A non-constraint index couldn't be deferred anyway, so this case
1440 * should never occur; no need to sweat, but let's check it.)
1442 if (!index_form->indimmediate && !constraint->deferrable)
1444 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1445 errmsg("\"%s\" is a deferrable index", index_name),
1446 errdetail("Cannot create a non-deferrable constraint using a deferrable index."),
1447 parser_errposition(cxt->pstate, constraint->location)));
1450 * Insist on it being a btree. That's the only kind that supports
1451 * uniqueness at the moment anyway; but we must have an index that
1452 * exactly matches what you'd get from plain ADD CONSTRAINT syntax,
1453 * else dump and reload will produce a different index (breaking
1454 * pg_upgrade in particular).
1456 if (index_rel->rd_rel->relam != get_am_oid(DEFAULT_INDEX_TYPE, false))
1458 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1459 errmsg("index \"%s\" is not a b-tree", index_name),
1460 parser_errposition(cxt->pstate, constraint->location)));
1462 /* Must get indclass the hard way */
1463 indclassDatum = SysCacheGetAttr(INDEXRELID, index_rel->rd_indextuple,
1464 Anum_pg_index_indclass, &isnull);
1466 indclass = (oidvector *) DatumGetPointer(indclassDatum);
1468 for (i = 0; i < index_form->indnatts; i++)
1470 int2 attnum = index_form->indkey.values[i];
1471 Form_pg_attribute attform;
1476 * We shouldn't see attnum == 0 here, since we already rejected
1477 * expression indexes. If we do, SystemAttributeDefinition
1478 * will throw an error.
1482 Assert(attnum <= heap_rel->rd_att->natts);
1483 attform = heap_rel->rd_att->attrs[attnum - 1];
1486 attform = SystemAttributeDefinition(attnum,
1487 heap_rel->rd_rel->relhasoids);
1488 attname = pstrdup(NameStr(attform->attname));
1491 * Insist on default opclass and sort options. While the index
1492 * would still work as a constraint with non-default settings, it
1493 * might not provide exactly the same uniqueness semantics as
1494 * you'd get from a normally-created constraint; and there's also
1495 * the dump/reload problem mentioned above.
1497 defopclass = GetDefaultOpClass(attform->atttypid,
1498 index_rel->rd_rel->relam);
1499 if (indclass->values[i] != defopclass ||
1500 index_rel->rd_indoption[i] != 0)
1502 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1503 errmsg("index \"%s\" does not have default sorting behavior", index_name),
1504 errdetail("Cannot create a PRIMARY KEY or UNIQUE constraint using such an index."),
1505 parser_errposition(cxt->pstate, constraint->location)));
1507 constraint->keys = lappend(constraint->keys, makeString(attname));
1510 /* Close the index relation but keep the lock */
1511 relation_close(index_rel, NoLock);
1513 index->indexOid = index_oid;
1517 * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
1518 * IndexElems and operator names. We have to break that apart into
1521 if (constraint->contype == CONSTR_EXCLUSION)
1523 foreach(lc, constraint->exclusions)
1525 List *pair = (List *) lfirst(lc);
1529 Assert(list_length(pair) == 2);
1530 elem = (IndexElem *) linitial(pair);
1531 Assert(IsA(elem, IndexElem));
1532 opname = (List *) lsecond(pair);
1533 Assert(IsA(opname, List));
1535 index->indexParams = lappend(index->indexParams, elem);
1536 index->excludeOpNames = lappend(index->excludeOpNames, opname);
1543 * For UNIQUE and PRIMARY KEY, we just have a list of column names.
1545 * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
1546 * also make sure they are NOT NULL, if possible. (Although we could leave
1547 * it to DefineIndex to mark the columns NOT NULL, it's more efficient to
1548 * get it right the first time.)
1550 foreach(lc, constraint->keys)
1552 char *key = strVal(lfirst(lc));
1554 ColumnDef *column = NULL;
1558 foreach(columns, cxt->columns)
1560 column = (ColumnDef *) lfirst(columns);
1561 Assert(IsA(column, ColumnDef));
1562 if (strcmp(column->colname, key) == 0)
1570 /* found column in the new table; force it to be NOT NULL */
1571 if (constraint->contype == CONSTR_PRIMARY)
1572 column->is_not_null = TRUE;
1574 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1577 * column will be a system column in the new table, so accept it.
1578 * System columns can't ever be null, so no need to worry about
1579 * PRIMARY/NOT NULL constraint.
1583 else if (cxt->inhRelations)
1585 /* try inherited tables */
1588 foreach(inher, cxt->inhRelations)
1590 RangeVar *inh = (RangeVar *) lfirst(inher);
1594 Assert(IsA(inh, RangeVar));
1595 rel = heap_openrv(inh, AccessShareLock);
1596 if (rel->rd_rel->relkind != RELKIND_RELATION)
1598 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1599 errmsg("inherited relation \"%s\" is not a table",
1601 for (count = 0; count < rel->rd_att->natts; count++)
1603 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1604 char *inhname = NameStr(inhattr->attname);
1606 if (inhattr->attisdropped)
1608 if (strcmp(key, inhname) == 0)
1613 * We currently have no easy way to force an inherited
1614 * column to be NOT NULL at creation, if its parent
1615 * wasn't so already. We leave it to DefineIndex to
1616 * fix things up in this case.
1621 heap_close(rel, NoLock);
1628 * In the ALTER TABLE case, don't complain about index keys not
1629 * created in the command; they may well exist already. DefineIndex
1630 * will complain about them if not, and will also take care of marking
1633 if (!found && !cxt->isalter)
1635 (errcode(ERRCODE_UNDEFINED_COLUMN),
1636 errmsg("column \"%s\" named in key does not exist", key),
1637 parser_errposition(cxt->pstate, constraint->location)));
1639 /* Check for PRIMARY KEY(foo, foo) */
1640 foreach(columns, index->indexParams)
1642 iparam = (IndexElem *) lfirst(columns);
1643 if (iparam->name && strcmp(key, iparam->name) == 0)
1647 (errcode(ERRCODE_DUPLICATE_COLUMN),
1648 errmsg("column \"%s\" appears twice in primary key constraint",
1650 parser_errposition(cxt->pstate, constraint->location)));
1653 (errcode(ERRCODE_DUPLICATE_COLUMN),
1654 errmsg("column \"%s\" appears twice in unique constraint",
1656 parser_errposition(cxt->pstate, constraint->location)));
1660 /* OK, add it to the index definition */
1661 iparam = makeNode(IndexElem);
1662 iparam->name = pstrdup(key);
1663 iparam->expr = NULL;
1664 iparam->indexcolname = NULL;
1665 iparam->opclass = NIL;
1666 iparam->ordering = SORTBY_DEFAULT;
1667 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1668 index->indexParams = lappend(index->indexParams, iparam);
1675 * transformFKConstraints
1676 * handle FOREIGN KEY constraints
1679 transformFKConstraints(CreateStmtContext *cxt,
1680 bool skipValidation, bool isAddConstraint)
1684 if (cxt->fkconstraints == NIL)
1688 * If CREATE TABLE or adding a column with NULL default, we can safely
1689 * skip validation of the constraint.
1693 foreach(fkclist, cxt->fkconstraints)
1695 Constraint *constraint = (Constraint *) lfirst(fkclist);
1697 constraint->skip_validation = true;
1702 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1703 * CONSTRAINT command to execute after the basic command is complete. (If
1704 * called from ADD CONSTRAINT, that routine will add the FK constraints to
1705 * its own subcommand list.)
1707 * Note: the ADD CONSTRAINT command must also execute after any index
1708 * creation commands. Thus, this should run after
1709 * transformIndexConstraints, so that the CREATE INDEX commands are
1710 * already in cxt->alist.
1712 if (!isAddConstraint)
1714 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1716 alterstmt->relation = cxt->relation;
1717 alterstmt->cmds = NIL;
1718 alterstmt->relkind = OBJECT_TABLE;
1720 foreach(fkclist, cxt->fkconstraints)
1722 Constraint *constraint = (Constraint *) lfirst(fkclist);
1723 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1725 altercmd->subtype = AT_ProcessedConstraint;
1726 altercmd->name = NULL;
1727 altercmd->def = (Node *) constraint;
1728 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1731 cxt->alist = lappend(cxt->alist, alterstmt);
1736 * transformIndexStmt - parse analysis for CREATE INDEX and ALTER TABLE
1738 * Note: this is a no-op for an index not using either index expressions or
1739 * a predicate expression. There are several code paths that create indexes
1740 * without bothering to call this, because they know they don't have any
1741 * such expressions to deal with.
1744 transformIndexStmt(IndexStmt *stmt, const char *queryString)
1752 * We must not scribble on the passed-in IndexStmt, so copy it. (This is
1753 * overkill, but easy.)
1755 stmt = (IndexStmt *) copyObject(stmt);
1758 * Open the parent table with appropriate locking. We must do this
1759 * because addRangeTableEntry() would acquire only AccessShareLock,
1760 * leaving DefineIndex() needing to do a lock upgrade with consequent risk
1761 * of deadlock. Make sure this stays in sync with the type of lock
1762 * DefineIndex() wants. If we are being called by ALTER TABLE, we will
1763 * already hold a higher lock.
1765 rel = heap_openrv(stmt->relation,
1766 (stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock));
1769 pstate = make_parsestate(NULL);
1770 pstate->p_sourcetext = queryString;
1773 * Put the parent table into the rtable so that the expressions can refer
1774 * to its fields without qualification.
1776 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1778 /* no to join list, yes to namespaces */
1779 addRTEtoQuery(pstate, rte, false, true, true);
1781 /* take care of the where clause */
1782 if (stmt->whereClause)
1783 stmt->whereClause = transformWhereClause(pstate,
1787 /* take care of any index expressions */
1788 foreach(l, stmt->indexParams)
1790 IndexElem *ielem = (IndexElem *) lfirst(l);
1794 /* Extract preliminary index col name before transforming expr */
1795 if (ielem->indexcolname == NULL)
1796 ielem->indexcolname = FigureIndexColname(ielem->expr);
1798 /* Now do parse transformation of the expression */
1799 ielem->expr = transformExpr(pstate, ielem->expr);
1802 * We check only that the result type is legitimate; this is for
1803 * consistency with what transformWhereClause() checks for the
1804 * predicate. DefineIndex() will make more checks.
1806 if (expression_returns_set(ielem->expr))
1808 (errcode(ERRCODE_DATATYPE_MISMATCH),
1809 errmsg("index expression cannot return a set")));
1814 * Check that only the base rel is mentioned.
1816 if (list_length(pstate->p_rtable) != 1)
1818 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1819 errmsg("index expressions and predicates can refer only to the table being indexed")));
1821 free_parsestate(pstate);
1823 /* Close relation, but keep the lock */
1824 heap_close(rel, NoLock);
1831 * transformRuleStmt -
1832 * transform a CREATE RULE Statement. The action is a list of parse
1833 * trees which is transformed into a list of query trees, and we also
1834 * transform the WHERE clause if any.
1836 * actions and whereClause are output parameters that receive the
1837 * transformed results.
1839 * Note that we must not scribble on the passed-in RuleStmt, so we do
1840 * copyObject() on the actions and WHERE clause.
1843 transformRuleStmt(RuleStmt *stmt, const char *queryString,
1844 List **actions, Node **whereClause)
1848 RangeTblEntry *oldrte;
1849 RangeTblEntry *newrte;
1852 * To avoid deadlock, make sure the first thing we do is grab
1853 * AccessExclusiveLock on the target relation. This will be needed by
1854 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1857 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1860 pstate = make_parsestate(NULL);
1861 pstate->p_sourcetext = queryString;
1864 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1865 * Set up their RTEs in the main pstate for use in parsing the rule
1868 oldrte = addRangeTableEntryForRelation(pstate, rel,
1869 makeAlias("old", NIL),
1871 newrte = addRangeTableEntryForRelation(pstate, rel,
1872 makeAlias("new", NIL),
1874 /* Must override addRangeTableEntry's default access-check flags */
1875 oldrte->requiredPerms = 0;
1876 newrte->requiredPerms = 0;
1879 * They must be in the namespace too for lookup purposes, but only add the
1880 * one(s) that are relevant for the current kind of rule. In an UPDATE
1881 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1882 * there's no need to be so picky for INSERT & DELETE. We do not add them
1885 switch (stmt->event)
1888 addRTEtoQuery(pstate, oldrte, false, true, true);
1891 addRTEtoQuery(pstate, oldrte, false, true, true);
1892 addRTEtoQuery(pstate, newrte, false, true, true);
1895 addRTEtoQuery(pstate, newrte, false, true, true);
1898 addRTEtoQuery(pstate, oldrte, false, true, true);
1901 elog(ERROR, "unrecognized event type: %d",
1906 /* take care of the where clause */
1907 *whereClause = transformWhereClause(pstate,
1908 (Node *) copyObject(stmt->whereClause),
1911 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
1913 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1914 errmsg("rule WHERE condition cannot contain references to other relations")));
1916 /* aggregates not allowed (but subselects are okay) */
1917 if (pstate->p_hasAggs)
1919 (errcode(ERRCODE_GROUPING_ERROR),
1920 errmsg("cannot use aggregate function in rule WHERE condition")));
1921 if (pstate->p_hasWindowFuncs)
1923 (errcode(ERRCODE_WINDOWING_ERROR),
1924 errmsg("cannot use window function in rule WHERE condition")));
1927 * 'instead nothing' rules with a qualification need a query rangetable so
1928 * the rewrite handler can add the negated rule qualification to the
1929 * original query. We create a query with the new command type CMD_NOTHING
1930 * here that is treated specially by the rewrite system.
1932 if (stmt->actions == NIL)
1934 Query *nothing_qry = makeNode(Query);
1936 nothing_qry->commandType = CMD_NOTHING;
1937 nothing_qry->rtable = pstate->p_rtable;
1938 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1940 *actions = list_make1(nothing_qry);
1945 List *newactions = NIL;
1948 * transform each statement, like parse_sub_analyze()
1950 foreach(l, stmt->actions)
1952 Node *action = (Node *) lfirst(l);
1953 ParseState *sub_pstate = make_parsestate(NULL);
1960 * Since outer ParseState isn't parent of inner, have to pass down
1961 * the query text by hand.
1963 sub_pstate->p_sourcetext = queryString;
1966 * Set up OLD/NEW in the rtable for this statement. The entries
1967 * are added only to relnamespace, not varnamespace, because we
1968 * don't want them to be referred to by unqualified field names
1969 * nor "*" in the rule actions. We decide later whether to put
1970 * them in the joinlist.
1972 oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
1973 makeAlias("old", NIL),
1975 newrte = addRangeTableEntryForRelation(sub_pstate, rel,
1976 makeAlias("new", NIL),
1978 oldrte->requiredPerms = 0;
1979 newrte->requiredPerms = 0;
1980 addRTEtoQuery(sub_pstate, oldrte, false, true, false);
1981 addRTEtoQuery(sub_pstate, newrte, false, true, false);
1983 /* Transform the rule action statement */
1984 top_subqry = transformStmt(sub_pstate,
1985 (Node *) copyObject(action));
1988 * We cannot support utility-statement actions (eg NOTIFY) with
1989 * nonempty rule WHERE conditions, because there's no way to make
1990 * the utility action execute conditionally.
1992 if (top_subqry->commandType == CMD_UTILITY &&
1993 *whereClause != NULL)
1995 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1996 errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
1999 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
2000 * into the SELECT, and that's what we need to look at. (Ugly
2001 * kluge ... try to fix this when we redesign querytrees.)
2003 sub_qry = getInsertSelectQuery(top_subqry, NULL);
2006 * If the sub_qry is a setop, we cannot attach any qualifications
2007 * to it, because the planner won't notice them. This could
2008 * perhaps be relaxed someday, but for now, we may as well reject
2009 * such a rule immediately.
2011 if (sub_qry->setOperations != NULL && *whereClause != NULL)
2013 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2014 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2017 * Validate action's use of OLD/NEW, qual too
2020 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
2021 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
2023 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
2024 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
2026 switch (stmt->event)
2031 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2032 errmsg("ON SELECT rule cannot use OLD")));
2035 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2036 errmsg("ON SELECT rule cannot use NEW")));
2044 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2045 errmsg("ON INSERT rule cannot use OLD")));
2050 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2051 errmsg("ON DELETE rule cannot use NEW")));
2054 elog(ERROR, "unrecognized event type: %d",
2060 * OLD/NEW are not allowed in WITH queries, because they would
2061 * amount to outer references for the WITH, which we disallow.
2062 * However, they were already in the outer rangetable when we
2063 * analyzed the query, so we have to check.
2065 * Note that in the INSERT...SELECT case, we need to examine
2066 * the CTE lists of both top_subqry and sub_qry.
2068 * Note that we aren't digging into the body of the query
2069 * looking for WITHs in nested sub-SELECTs. A WITH down there
2070 * can legitimately refer to OLD/NEW, because it'd be an
2071 * indirect-correlated outer reference.
2073 if (rangeTableEntry_used((Node *) top_subqry->cteList,
2074 PRS2_OLD_VARNO, 0) ||
2075 rangeTableEntry_used((Node *) sub_qry->cteList,
2078 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2079 errmsg("cannot refer to OLD within WITH query")));
2080 if (rangeTableEntry_used((Node *) top_subqry->cteList,
2081 PRS2_NEW_VARNO, 0) ||
2082 rangeTableEntry_used((Node *) sub_qry->cteList,
2085 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2086 errmsg("cannot refer to NEW within WITH query")));
2089 * For efficiency's sake, add OLD to the rule action's jointree
2090 * only if it was actually referenced in the statement or qual.
2092 * For INSERT, NEW is not really a relation (only a reference to
2093 * the to-be-inserted tuple) and should never be added to the
2096 * For UPDATE, we treat NEW as being another kind of reference to
2097 * OLD, because it represents references to *transformed* tuples
2098 * of the existing relation. It would be wrong to enter NEW
2099 * separately in the jointree, since that would cause a double
2100 * join of the updated relation. It's also wrong to fail to make
2101 * a jointree entry if only NEW and not OLD is mentioned.
2103 if (has_old || (has_new && stmt->event == CMD_UPDATE))
2106 * If sub_qry is a setop, manipulating its jointree will do no
2107 * good at all, because the jointree is dummy. (This should be
2108 * a can't-happen case because of prior tests.)
2110 if (sub_qry->setOperations != NULL)
2112 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2113 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2114 /* hack so we can use addRTEtoQuery() */
2115 sub_pstate->p_rtable = sub_qry->rtable;
2116 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
2117 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
2118 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
2121 newactions = lappend(newactions, top_subqry);
2123 free_parsestate(sub_pstate);
2126 *actions = newactions;
2129 free_parsestate(pstate);
2131 /* Close relation, but keep the exclusive lock */
2132 heap_close(rel, NoLock);
2137 * transformAlterTableStmt -
2138 * parse analysis for ALTER TABLE
2140 * Returns a List of utility commands to be done in sequence. One of these
2141 * will be the transformed AlterTableStmt, but there may be additional actions
2142 * to be done before and after the actual AlterTable() call.
2145 transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
2149 CreateStmtContext cxt;
2154 List *newcmds = NIL;
2155 bool skipValidation = true;
2156 AlterTableCmd *newcmd;
2160 * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
2161 * is overkill, but easy.)
2163 stmt = (AlterTableStmt *) copyObject(stmt);
2166 * Determine the appropriate lock level for this list of subcommands.
2168 lockmode = AlterTableGetLockLevel(stmt->cmds);
2171 * Acquire appropriate lock on the target relation, which will be held until
2172 * end of transaction. This ensures any decisions we make here based on
2173 * the state of the relation will still be good at execution. We must get
2174 * lock now because execution will later require it; taking a lower grade lock
2175 * now and trying to upgrade later risks deadlock. Any new commands we add
2176 * after this must not upgrade the lock level requested here.
2178 rel = relation_openrv(stmt->relation, lockmode);
2180 /* Set up pstate and CreateStmtContext */
2181 pstate = make_parsestate(NULL);
2182 pstate->p_sourcetext = queryString;
2184 cxt.pstate = pstate;
2185 cxt.stmtType = "ALTER TABLE";
2186 cxt.relation = stmt->relation;
2188 cxt.inhRelations = NIL;
2190 cxt.hasoids = false; /* need not be right */
2192 cxt.ckconstraints = NIL;
2193 cxt.fkconstraints = NIL;
2194 cxt.ixconstraints = NIL;
2195 cxt.inh_indexes = NIL;
2201 * The only subtypes that currently require parse transformation handling
2202 * are ADD COLUMN and ADD CONSTRAINT. These largely re-use code from
2205 foreach(lcmd, stmt->cmds)
2207 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2209 switch (cmd->subtype)
2212 case AT_AddColumnToView:
2214 ColumnDef *def = (ColumnDef *) cmd->def;
2216 Assert(IsA(def, ColumnDef));
2217 transformColumnDefinition(&cxt, def);
2220 * If the column has a non-null default, we can't skip
2221 * validation of foreign keys.
2223 if (def->raw_default != NULL)
2224 skipValidation = false;
2227 * All constraints are processed in other ways. Remove the
2230 def->constraints = NIL;
2232 newcmds = lappend(newcmds, cmd);
2235 case AT_AddConstraint:
2238 * The original AddConstraint cmd node doesn't go to newcmds
2240 if (IsA(cmd->def, Constraint))
2242 transformTableConstraint(&cxt, (Constraint *) cmd->def);
2243 if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
2244 skipValidation = false;
2247 elog(ERROR, "unrecognized node type: %d",
2248 (int) nodeTag(cmd->def));
2251 case AT_ProcessedConstraint:
2254 * Already-transformed ADD CONSTRAINT, so just make it look
2255 * like the standard case.
2257 cmd->subtype = AT_AddConstraint;
2258 newcmds = lappend(newcmds, cmd);
2262 newcmds = lappend(newcmds, cmd);
2268 * transformIndexConstraints wants cxt.alist to contain only index
2269 * statements, so transfer anything we already have into save_alist
2272 save_alist = cxt.alist;
2275 /* Postprocess index and FK constraints */
2276 transformIndexConstraints(&cxt);
2278 transformFKConstraints(&cxt, skipValidation, true);
2281 * Push any index-creation commands into the ALTER, so that they can be
2282 * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
2283 * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
2284 * subcommand has already been through transformIndexStmt.
2286 foreach(l, cxt.alist)
2288 IndexStmt *idxstmt = (IndexStmt *) lfirst(l);
2290 Assert(IsA(idxstmt, IndexStmt));
2291 idxstmt = transformIndexStmt(idxstmt, queryString);
2292 newcmd = makeNode(AlterTableCmd);
2293 newcmd->subtype = OidIsValid(idxstmt->indexOid) ? AT_AddIndexConstraint : AT_AddIndex;
2294 newcmd->def = (Node *) idxstmt;
2295 newcmds = lappend(newcmds, newcmd);
2299 /* Append any CHECK or FK constraints to the commands list */
2300 foreach(l, cxt.ckconstraints)
2302 newcmd = makeNode(AlterTableCmd);
2303 newcmd->subtype = AT_AddConstraint;
2304 newcmd->def = (Node *) lfirst(l);
2305 newcmds = lappend(newcmds, newcmd);
2307 foreach(l, cxt.fkconstraints)
2309 newcmd = makeNode(AlterTableCmd);
2310 newcmd->subtype = AT_AddConstraint;
2311 newcmd->def = (Node *) lfirst(l);
2312 newcmds = lappend(newcmds, newcmd);
2315 /* Close rel but keep lock */
2316 relation_close(rel, NoLock);
2321 stmt->cmds = newcmds;
2323 result = lappend(cxt.blist, stmt);
2324 result = list_concat(result, cxt.alist);
2325 result = list_concat(result, save_alist);
2332 * Preprocess a list of column constraint clauses
2333 * to attach constraint attributes to their primary constraint nodes
2334 * and detect inconsistent/misplaced constraint attributes.
2336 * NOTE: currently, attributes are only supported for FOREIGN KEY, UNIQUE,
2337 * and PRIMARY KEY constraints, but someday they ought to be supported
2338 * for other constraint types.
2341 transformConstraintAttrs(CreateStmtContext *cxt, List *constraintList)
2343 Constraint *lastprimarycon = NULL;
2344 bool saw_deferrability = false;
2345 bool saw_initially = false;
2348 #define SUPPORTS_ATTRS(node) \
2349 ((node) != NULL && \
2350 ((node)->contype == CONSTR_PRIMARY || \
2351 (node)->contype == CONSTR_UNIQUE || \
2352 (node)->contype == CONSTR_EXCLUSION || \
2353 (node)->contype == CONSTR_FOREIGN))
2355 foreach(clist, constraintList)
2357 Constraint *con = (Constraint *) lfirst(clist);
2359 if (!IsA(con, Constraint))
2360 elog(ERROR, "unrecognized node type: %d",
2361 (int) nodeTag(con));
2362 switch (con->contype)
2364 case CONSTR_ATTR_DEFERRABLE:
2365 if (!SUPPORTS_ATTRS(lastprimarycon))
2367 (errcode(ERRCODE_SYNTAX_ERROR),
2368 errmsg("misplaced DEFERRABLE clause"),
2369 parser_errposition(cxt->pstate, con->location)));
2370 if (saw_deferrability)
2372 (errcode(ERRCODE_SYNTAX_ERROR),
2373 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2374 parser_errposition(cxt->pstate, con->location)));
2375 saw_deferrability = true;
2376 lastprimarycon->deferrable = true;
2379 case CONSTR_ATTR_NOT_DEFERRABLE:
2380 if (!SUPPORTS_ATTRS(lastprimarycon))
2382 (errcode(ERRCODE_SYNTAX_ERROR),
2383 errmsg("misplaced NOT DEFERRABLE clause"),
2384 parser_errposition(cxt->pstate, con->location)));
2385 if (saw_deferrability)
2387 (errcode(ERRCODE_SYNTAX_ERROR),
2388 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2389 parser_errposition(cxt->pstate, con->location)));
2390 saw_deferrability = true;
2391 lastprimarycon->deferrable = false;
2392 if (saw_initially &&
2393 lastprimarycon->initdeferred)
2395 (errcode(ERRCODE_SYNTAX_ERROR),
2396 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2397 parser_errposition(cxt->pstate, con->location)));
2400 case CONSTR_ATTR_DEFERRED:
2401 if (!SUPPORTS_ATTRS(lastprimarycon))
2403 (errcode(ERRCODE_SYNTAX_ERROR),
2404 errmsg("misplaced INITIALLY DEFERRED clause"),
2405 parser_errposition(cxt->pstate, con->location)));
2408 (errcode(ERRCODE_SYNTAX_ERROR),
2409 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2410 parser_errposition(cxt->pstate, con->location)));
2411 saw_initially = true;
2412 lastprimarycon->initdeferred = true;
2415 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
2417 if (!saw_deferrability)
2418 lastprimarycon->deferrable = true;
2419 else if (!lastprimarycon->deferrable)
2421 (errcode(ERRCODE_SYNTAX_ERROR),
2422 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2423 parser_errposition(cxt->pstate, con->location)));
2426 case CONSTR_ATTR_IMMEDIATE:
2427 if (!SUPPORTS_ATTRS(lastprimarycon))
2429 (errcode(ERRCODE_SYNTAX_ERROR),
2430 errmsg("misplaced INITIALLY IMMEDIATE clause"),
2431 parser_errposition(cxt->pstate, con->location)));
2434 (errcode(ERRCODE_SYNTAX_ERROR),
2435 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2436 parser_errposition(cxt->pstate, con->location)));
2437 saw_initially = true;
2438 lastprimarycon->initdeferred = false;
2442 /* Otherwise it's not an attribute */
2443 lastprimarycon = con;
2444 /* reset flags for new primary node */
2445 saw_deferrability = false;
2446 saw_initially = false;
2453 * Special handling of type definition for a column
2456 transformColumnType(CreateStmtContext *cxt, ColumnDef *column)
2459 * All we really need to do here is verify that the type is valid,
2460 * including any collation spec that might be present.
2462 Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
2464 if (column->collClause)
2466 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
2469 collOid = LookupCollation(cxt->pstate,
2470 column->collClause->collnames,
2471 column->collClause->location);
2472 /* Complain if COLLATE is applied to an uncollatable type */
2473 if (!OidIsValid(typtup->typcollation))
2475 (errcode(ERRCODE_DATATYPE_MISMATCH),
2476 errmsg("collations are not supported by type %s",
2477 format_type_be(HeapTupleGetOid(ctype))),
2478 parser_errposition(cxt->pstate,
2479 column->collClause->location)));
2482 ReleaseSysCache(ctype);
2487 * transformCreateSchemaStmt -
2488 * analyzes the CREATE SCHEMA statement
2490 * Split the schema element list into individual commands and place
2491 * them in the result list in an order such that there are no forward
2492 * references (e.g. GRANT to a table created later in the list). Note
2493 * that the logic we use for determining forward references is
2494 * presently quite incomplete.
2496 * SQL92 also allows constraints to make forward references, so thumb through
2497 * the table columns and move forward references to a posterior alter-table
2500 * The result is a list of parse nodes that still need to be analyzed ---
2501 * but we can't analyze the later commands until we've executed the earlier
2502 * ones, because of possible inter-object references.
2504 * Note: this breaks the rules a little bit by modifying schema-name fields
2505 * within passed-in structs. However, the transformation would be the same
2506 * if done over, so it should be all right to scribble on the input to this
2510 transformCreateSchemaStmt(CreateSchemaStmt *stmt)
2512 CreateSchemaStmtContext cxt;
2516 cxt.stmtType = "CREATE SCHEMA";
2517 cxt.schemaname = stmt->schemaname;
2518 cxt.authid = stmt->authid;
2519 cxt.sequences = NIL;
2527 * Run through each schema element in the schema element list. Separate
2528 * statements by type, and do preliminary analysis.
2530 foreach(elements, stmt->schemaElts)
2532 Node *element = lfirst(elements);
2534 switch (nodeTag(element))
2536 case T_CreateSeqStmt:
2538 CreateSeqStmt *elp = (CreateSeqStmt *) element;
2540 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
2541 cxt.sequences = lappend(cxt.sequences, element);
2547 CreateStmt *elp = (CreateStmt *) element;
2549 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2552 * XXX todo: deal with constraints
2554 cxt.tables = lappend(cxt.tables, element);
2560 ViewStmt *elp = (ViewStmt *) element;
2562 setSchemaName(cxt.schemaname, &elp->view->schemaname);
2565 * XXX todo: deal with references between views
2567 cxt.views = lappend(cxt.views, element);
2573 IndexStmt *elp = (IndexStmt *) element;
2575 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2576 cxt.indexes = lappend(cxt.indexes, element);
2580 case T_CreateTrigStmt:
2582 CreateTrigStmt *elp = (CreateTrigStmt *) element;
2584 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2585 cxt.triggers = lappend(cxt.triggers, element);
2590 cxt.grants = lappend(cxt.grants, element);
2594 elog(ERROR, "unrecognized node type: %d",
2595 (int) nodeTag(element));
2600 result = list_concat(result, cxt.sequences);
2601 result = list_concat(result, cxt.tables);
2602 result = list_concat(result, cxt.views);
2603 result = list_concat(result, cxt.indexes);
2604 result = list_concat(result, cxt.triggers);
2605 result = list_concat(result, cxt.grants);
2612 * Set or check schema name in an element of a CREATE SCHEMA command
2615 setSchemaName(char *context_schema, char **stmt_schema_name)
2617 if (*stmt_schema_name == NULL)
2618 *stmt_schema_name = context_schema;
2619 else if (strcmp(context_schema, *stmt_schema_name) != 0)
2621 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
2622 errmsg("CREATE specifies a schema (%s) "
2623 "different from the one being created (%s)",
2624 *stmt_schema_name, context_schema)));