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_collation.h"
37 #include "catalog/pg_constraint.h"
38 #include "catalog/pg_opclass.h"
39 #include "catalog/pg_operator.h"
40 #include "catalog/pg_type.h"
41 #include "commands/comment.h"
42 #include "commands/defrem.h"
43 #include "commands/tablecmds.h"
44 #include "commands/tablespace.h"
45 #include "miscadmin.h"
46 #include "nodes/makefuncs.h"
47 #include "nodes/nodeFuncs.h"
48 #include "parser/analyze.h"
49 #include "parser/parse_clause.h"
50 #include "parser/parse_collate.h"
51 #include "parser/parse_expr.h"
52 #include "parser/parse_relation.h"
53 #include "parser/parse_target.h"
54 #include "parser/parse_type.h"
55 #include "parser/parse_utilcmd.h"
56 #include "parser/parser.h"
57 #include "rewrite/rewriteManip.h"
58 #include "storage/lock.h"
59 #include "utils/acl.h"
60 #include "utils/builtins.h"
61 #include "utils/lsyscache.h"
62 #include "utils/relcache.h"
63 #include "utils/syscache.h"
64 #include "utils/typcache.h"
67 /* State shared by transformCreateStmt and its subroutines */
70 ParseState *pstate; /* overall parser state */
71 const char *stmtType; /* "CREATE [FOREIGN] TABLE" or "ALTER TABLE" */
72 RangeVar *relation; /* relation to create */
73 Relation rel; /* opened/locked rel, if ALTER */
74 List *inhRelations; /* relations to inherit from */
75 bool isalter; /* true if altering existing table */
76 bool hasoids; /* does relation have an OID column? */
77 List *columns; /* ColumnDef items */
78 List *ckconstraints; /* CHECK constraints */
79 List *fkconstraints; /* FOREIGN KEY constraints */
80 List *ixconstraints; /* index-creating constraints */
81 List *inh_indexes; /* cloned indexes from INCLUDING INDEXES */
82 List *blist; /* "before list" of things to do before
83 * creating the table */
84 List *alist; /* "after list" of things to do after creating
86 IndexStmt *pkey; /* PRIMARY KEY index, if any */
89 /* State shared by transformCreateSchemaStmt and its subroutines */
92 const char *stmtType; /* "CREATE SCHEMA" or "ALTER SCHEMA" */
93 char *schemaname; /* name of schema */
94 char *authid; /* owner of schema */
95 List *sequences; /* CREATE SEQUENCE items */
96 List *tables; /* CREATE TABLE items */
97 List *views; /* CREATE VIEW items */
98 List *indexes; /* CREATE INDEX items */
99 List *triggers; /* CREATE TRIGGER items */
100 List *grants; /* GRANT items */
101 } CreateSchemaStmtContext;
104 static void transformColumnDefinition(CreateStmtContext *cxt,
106 static void transformTableConstraint(CreateStmtContext *cxt,
107 Constraint *constraint);
108 static void transformInhRelation(CreateStmtContext *cxt,
109 InhRelation *inhrelation);
110 static void transformOfType(CreateStmtContext *cxt,
111 TypeName *ofTypename);
112 static char *chooseIndexName(const RangeVar *relation, IndexStmt *index_stmt);
113 static IndexStmt *generateClonedIndexStmt(CreateStmtContext *cxt,
114 Relation parent_index, AttrNumber *attmap);
115 static List *get_collation(Oid collation, Oid actual_datatype);
116 static List *get_opclass(Oid opclass, Oid actual_datatype);
117 static void transformIndexConstraints(CreateStmtContext *cxt);
118 static IndexStmt *transformIndexConstraint(Constraint *constraint,
119 CreateStmtContext *cxt);
120 static void transformFKConstraints(CreateStmtContext *cxt,
122 bool isAddConstraint);
123 static void transformConstraintAttrs(CreateStmtContext *cxt,
124 List *constraintList);
125 static void transformColumnType(CreateStmtContext *cxt, ColumnDef *column);
126 static void setSchemaName(char *context_schema, char **stmt_schema_name);
130 * transformCreateStmt -
131 * parse analysis for CREATE TABLE
133 * Returns a List of utility commands to be done in sequence. One of these
134 * will be the transformed CreateStmt, but there may be additional actions
135 * to be done before and after the actual DefineRelation() call.
137 * SQL92 allows constraints to be scattered all over, so thumb through
138 * the columns and collect all constraints into one place.
139 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
140 * then expand those into multiple IndexStmt blocks.
141 * - thomas 1997-12-02
144 transformCreateStmt(CreateStmt *stmt, const char *queryString)
147 CreateStmtContext cxt;
153 * We must not scribble on the passed-in CreateStmt, so copy it. (This is
154 * overkill, but easy.)
156 stmt = (CreateStmt *) copyObject(stmt);
159 * If the target relation name isn't schema-qualified, make it so. This
160 * prevents some corner cases in which added-on rewritten commands might
161 * think they should apply to other relations that have the same name and
162 * are earlier in the search path. But a local temp table is effectively
163 * specified to be in pg_temp, so no need for anything extra in that case.
165 if (stmt->relation->schemaname == NULL
166 && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
168 Oid namespaceid = RangeVarGetCreationNamespace(stmt->relation);
170 stmt->relation->schemaname = get_namespace_name(namespaceid);
173 /* Set up pstate and CreateStmtContext */
174 pstate = make_parsestate(NULL);
175 pstate->p_sourcetext = queryString;
178 if (IsA(stmt, CreateForeignTableStmt))
179 cxt.stmtType = "CREATE FOREIGN TABLE";
181 cxt.stmtType = "CREATE TABLE";
182 cxt.relation = stmt->relation;
184 cxt.inhRelations = stmt->inhRelations;
187 cxt.ckconstraints = NIL;
188 cxt.fkconstraints = NIL;
189 cxt.ixconstraints = NIL;
190 cxt.inh_indexes = NIL;
194 cxt.hasoids = interpretOidsOption(stmt->options);
196 Assert(!stmt->ofTypename || !stmt->inhRelations); /* grammar enforces */
198 if (stmt->ofTypename)
199 transformOfType(&cxt, stmt->ofTypename);
202 * Run through each primary element in the table creation clause. Separate
203 * column defs from constraints, and do preliminary analysis.
205 foreach(elements, stmt->tableElts)
207 Node *element = lfirst(elements);
209 switch (nodeTag(element))
212 transformColumnDefinition(&cxt, (ColumnDef *) element);
216 transformTableConstraint(&cxt, (Constraint *) element);
220 transformInhRelation(&cxt, (InhRelation *) element);
224 elog(ERROR, "unrecognized node type: %d",
225 (int) nodeTag(element));
231 * transformIndexConstraints wants cxt.alist to contain only index
232 * statements, so transfer anything we already have into save_alist.
234 save_alist = cxt.alist;
237 Assert(stmt->constraints == NIL);
240 * Postprocess constraints that give rise to index definitions.
242 transformIndexConstraints(&cxt);
245 * Postprocess foreign-key constraints.
247 transformFKConstraints(&cxt, true, false);
252 stmt->tableElts = cxt.columns;
253 stmt->constraints = cxt.ckconstraints;
255 result = lappend(cxt.blist, stmt);
256 result = list_concat(result, cxt.alist);
257 result = list_concat(result, save_alist);
263 * transformColumnDefinition -
264 * transform a single ColumnDef within CREATE TABLE
265 * Also used in ALTER TABLE ADD COLUMN
268 transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
273 Constraint *constraint;
276 cxt->columns = lappend(cxt->columns, column);
278 /* Check for SERIAL pseudo-types */
281 && list_length(column->typeName->names) == 1
282 && !column->typeName->pct_type)
284 char *typname = strVal(linitial(column->typeName->names));
286 if (strcmp(typname, "serial") == 0 ||
287 strcmp(typname, "serial4") == 0)
290 column->typeName->names = NIL;
291 column->typeName->typeOid = INT4OID;
293 else if (strcmp(typname, "bigserial") == 0 ||
294 strcmp(typname, "serial8") == 0)
297 column->typeName->names = NIL;
298 column->typeName->typeOid = INT8OID;
302 * We have to reject "serial[]" explicitly, because once we've set
303 * typeid, LookupTypeName won't notice arrayBounds. We don't need any
304 * special coding for serial(typmod) though.
306 if (is_serial && column->typeName->arrayBounds != NIL)
308 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
309 errmsg("array of serial is not implemented"),
310 parser_errposition(cxt->pstate,
311 column->typeName->location)));
314 /* Do necessary work on the column type declaration */
315 if (column->typeName)
316 transformColumnType(cxt, column);
318 /* Special actions for SERIAL pseudo-types */
327 FuncCall *funccallnode;
328 CreateSeqStmt *seqstmt;
329 AlterSeqStmt *altseqstmt;
333 * Determine namespace and name to use for the sequence.
335 * Although we use ChooseRelationName, it's not guaranteed that the
336 * selected sequence name won't conflict; given sufficiently long
337 * field names, two different serial columns in the same table could
338 * be assigned the same sequence name, and we'd not notice since we
339 * aren't creating the sequence quite yet. In practice this seems
340 * quite unlikely to be a problem, especially since few people would
341 * need two serial columns in one table.
344 snamespaceid = RelationGetNamespace(cxt->rel);
346 snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
347 snamespace = get_namespace_name(snamespaceid);
348 sname = ChooseRelationName(cxt->relation->relname,
354 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
355 cxt->stmtType, sname,
356 cxt->relation->relname, column->colname)));
359 * Build a CREATE SEQUENCE command to create the sequence object, and
360 * add it to the list of things to be done before this CREATE/ALTER
363 seqstmt = makeNode(CreateSeqStmt);
364 seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
365 seqstmt->options = NIL;
368 * If this is ALTER ADD COLUMN, make sure the sequence will be owned
369 * by the table's owner. The current user might be someone else
370 * (perhaps a superuser, or someone who's only a member of the owning
371 * role), but the SEQUENCE OWNED BY mechanisms will bleat unless table
372 * and sequence have exactly the same owning role.
375 seqstmt->ownerId = cxt->rel->rd_rel->relowner;
377 seqstmt->ownerId = InvalidOid;
379 cxt->blist = lappend(cxt->blist, seqstmt);
382 * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence
383 * as owned by this column, and add it to the list of things to be
384 * done after this CREATE/ALTER TABLE.
386 altseqstmt = makeNode(AlterSeqStmt);
387 altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
388 attnamelist = list_make3(makeString(snamespace),
389 makeString(cxt->relation->relname),
390 makeString(column->colname));
391 altseqstmt->options = list_make1(makeDefElem("owned_by",
392 (Node *) attnamelist));
394 cxt->alist = lappend(cxt->alist, altseqstmt);
397 * Create appropriate constraints for SERIAL. We do this in full,
398 * rather than shortcutting, so that we will detect any conflicting
399 * constraints the user wrote (like a different DEFAULT).
401 * Create an expression tree representing the function call
402 * nextval('sequencename'). We cannot reduce the raw tree to cooked
403 * form until after the sequence is created, but there's no need to do
406 qstring = quote_qualified_identifier(snamespace, sname);
407 snamenode = makeNode(A_Const);
408 snamenode->val.type = T_String;
409 snamenode->val.val.str = qstring;
410 snamenode->location = -1;
411 castnode = makeNode(TypeCast);
412 castnode->typeName = SystemTypeName("regclass");
413 castnode->arg = (Node *) snamenode;
414 castnode->location = -1;
415 funccallnode = makeNode(FuncCall);
416 funccallnode->funcname = SystemFuncName("nextval");
417 funccallnode->args = list_make1(castnode);
418 funccallnode->agg_order = NIL;
419 funccallnode->agg_star = false;
420 funccallnode->agg_distinct = false;
421 funccallnode->func_variadic = false;
422 funccallnode->over = NULL;
423 funccallnode->location = -1;
425 constraint = makeNode(Constraint);
426 constraint->contype = CONSTR_DEFAULT;
427 constraint->location = -1;
428 constraint->raw_expr = (Node *) funccallnode;
429 constraint->cooked_expr = NULL;
430 column->constraints = lappend(column->constraints, constraint);
432 constraint = makeNode(Constraint);
433 constraint->contype = CONSTR_NOTNULL;
434 constraint->location = -1;
435 column->constraints = lappend(column->constraints, constraint);
438 /* Process column constraints, if any... */
439 transformConstraintAttrs(cxt, column->constraints);
441 saw_nullable = false;
444 foreach(clist, column->constraints)
446 constraint = lfirst(clist);
447 Assert(IsA(constraint, Constraint));
449 switch (constraint->contype)
452 if (saw_nullable && column->is_not_null)
454 (errcode(ERRCODE_SYNTAX_ERROR),
455 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
456 column->colname, cxt->relation->relname),
457 parser_errposition(cxt->pstate,
458 constraint->location)));
459 column->is_not_null = FALSE;
464 if (saw_nullable && !column->is_not_null)
466 (errcode(ERRCODE_SYNTAX_ERROR),
467 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
468 column->colname, cxt->relation->relname),
469 parser_errposition(cxt->pstate,
470 constraint->location)));
471 column->is_not_null = TRUE;
478 (errcode(ERRCODE_SYNTAX_ERROR),
479 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
480 column->colname, cxt->relation->relname),
481 parser_errposition(cxt->pstate,
482 constraint->location)));
483 column->raw_default = constraint->raw_expr;
484 Assert(constraint->cooked_expr == NULL);
489 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
494 if (constraint->keys == NIL)
495 constraint->keys = list_make1(makeString(column->colname));
496 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
499 case CONSTR_EXCLUSION:
500 /* grammar does not allow EXCLUDE as a column constraint */
501 elog(ERROR, "column exclusion constraints are not supported");
507 * Fill in the current attribute's name and throw it into the
508 * list of FK constraints to be processed later.
510 constraint->fk_attrs = list_make1(makeString(column->colname));
511 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
514 case CONSTR_ATTR_DEFERRABLE:
515 case CONSTR_ATTR_NOT_DEFERRABLE:
516 case CONSTR_ATTR_DEFERRED:
517 case CONSTR_ATTR_IMMEDIATE:
518 /* transformConstraintAttrs took care of these */
522 elog(ERROR, "unrecognized constraint type: %d",
523 constraint->contype);
530 * transformTableConstraint
531 * transform a Constraint node within CREATE TABLE or ALTER TABLE
534 transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
536 switch (constraint->contype)
540 case CONSTR_EXCLUSION:
541 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
545 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
549 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
555 case CONSTR_ATTR_DEFERRABLE:
556 case CONSTR_ATTR_NOT_DEFERRABLE:
557 case CONSTR_ATTR_DEFERRED:
558 case CONSTR_ATTR_IMMEDIATE:
559 elog(ERROR, "invalid context for constraint type %d",
560 constraint->contype);
564 elog(ERROR, "unrecognized constraint type: %d",
565 constraint->contype);
571 * transformInhRelation
573 * Change the LIKE <subtable> portion of a CREATE TABLE statement into
574 * column definitions which recreate the user defined column portions of
578 transformInhRelation(CreateStmtContext *cxt, InhRelation *inhRelation)
580 AttrNumber parent_attno;
587 relation = parserOpenTable(cxt->pstate, inhRelation->relation,
590 if (relation->rd_rel->relkind != RELKIND_RELATION)
592 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
593 errmsg("inherited relation \"%s\" is not a table",
594 inhRelation->relation->relname)));
597 * Check for SELECT privilages
599 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
601 if (aclresult != ACLCHECK_OK)
602 aclcheck_error(aclresult, ACL_KIND_CLASS,
603 RelationGetRelationName(relation));
605 tupleDesc = RelationGetDescr(relation);
606 constr = tupleDesc->constr;
609 * Insert the copied attributes into the cxt for the new table definition.
611 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
614 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
615 char *attributeName = NameStr(attribute->attname);
619 * Ignore dropped columns in the parent.
621 if (attribute->attisdropped)
625 * Create a new column, which is marked as NOT inherited.
627 * For constraints, ONLY the NOT NULL constraint is inherited by the
628 * new column definition per SQL99.
630 def = makeNode(ColumnDef);
631 def->colname = pstrdup(attributeName);
632 def->typeName = makeTypeNameFromOid(attribute->atttypid,
633 attribute->atttypmod);
635 def->is_local = true;
636 def->is_not_null = attribute->attnotnull;
637 def->is_from_type = false;
639 def->raw_default = NULL;
640 def->cooked_default = NULL;
641 def->collClause = NULL;
642 def->collOid = attribute->attcollation;
643 def->constraints = NIL;
648 cxt->columns = lappend(cxt->columns, def);
651 * Copy default, if present and the default has been requested
653 if (attribute->atthasdef &&
654 (inhRelation->options & CREATE_TABLE_LIKE_DEFAULTS))
656 Node *this_default = NULL;
657 AttrDefault *attrdef;
660 /* Find default in constraint structure */
661 Assert(constr != NULL);
662 attrdef = constr->defval;
663 for (i = 0; i < constr->num_defval; i++)
665 if (attrdef[i].adnum == parent_attno)
667 this_default = stringToNode(attrdef[i].adbin);
671 Assert(this_default != NULL);
674 * If default expr could contain any vars, we'd need to fix 'em,
675 * but it can't; so default is ready to apply to child.
678 def->cooked_default = this_default;
681 /* Likewise, copy storage if requested */
682 if (inhRelation->options & CREATE_TABLE_LIKE_STORAGE)
683 def->storage = attribute->attstorage;
687 /* Likewise, copy comment if requested */
688 if ((inhRelation->options & CREATE_TABLE_LIKE_COMMENTS) &&
689 (comment = GetComment(attribute->attrelid,
691 attribute->attnum)) != NULL)
693 CommentStmt *stmt = makeNode(CommentStmt);
695 stmt->objtype = OBJECT_COLUMN;
696 stmt->objname = list_make3(makeString(cxt->relation->schemaname),
697 makeString(cxt->relation->relname),
698 makeString(def->colname));
700 stmt->comment = comment;
702 cxt->alist = lappend(cxt->alist, stmt);
707 * Copy CHECK constraints if requested, being careful to adjust attribute
710 if ((inhRelation->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
713 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
716 for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
718 char *ccname = tupleDesc->constr->check[ccnum].ccname;
719 char *ccbin = tupleDesc->constr->check[ccnum].ccbin;
720 Node *ccbin_node = stringToNode(ccbin);
721 Constraint *n = makeNode(Constraint);
723 change_varattnos_of_a_node(ccbin_node, attmap);
725 n->contype = CONSTR_CHECK;
727 n->conname = pstrdup(ccname);
729 n->cooked_expr = nodeToString(ccbin_node);
730 cxt->ckconstraints = lappend(cxt->ckconstraints, n);
732 /* Copy comment on constraint */
733 if ((inhRelation->options & CREATE_TABLE_LIKE_COMMENTS) &&
734 (comment = GetComment(get_constraint_oid(RelationGetRelid(relation),
736 ConstraintRelationId,
739 CommentStmt *stmt = makeNode(CommentStmt);
741 stmt->objtype = OBJECT_CONSTRAINT;
742 stmt->objname = list_make3(makeString(cxt->relation->schemaname),
743 makeString(cxt->relation->relname),
744 makeString(n->conname));
746 stmt->comment = comment;
748 cxt->alist = lappend(cxt->alist, stmt);
754 * Likewise, copy indexes if requested
756 if ((inhRelation->options & CREATE_TABLE_LIKE_INDEXES) &&
757 relation->rd_rel->relhasindex)
759 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
760 List *parent_indexes;
763 parent_indexes = RelationGetIndexList(relation);
765 foreach(l, parent_indexes)
767 Oid parent_index_oid = lfirst_oid(l);
768 Relation parent_index;
769 IndexStmt *index_stmt;
771 parent_index = index_open(parent_index_oid, AccessShareLock);
773 /* Build CREATE INDEX statement to recreate the parent_index */
774 index_stmt = generateClonedIndexStmt(cxt, parent_index, attmap);
776 /* Copy comment on index */
777 if (inhRelation->options & CREATE_TABLE_LIKE_COMMENTS)
779 comment = GetComment(parent_index_oid, RelationRelationId, 0);
786 * We have to assign the index a name now, so that we can
787 * reference it in CommentStmt.
789 if (index_stmt->idxname == NULL)
790 index_stmt->idxname = chooseIndexName(cxt->relation,
793 stmt = makeNode(CommentStmt);
794 stmt->objtype = OBJECT_INDEX;
796 list_make2(makeString(cxt->relation->schemaname),
797 makeString(index_stmt->idxname));
799 stmt->comment = comment;
801 cxt->alist = lappend(cxt->alist, stmt);
805 /* Save it in the inh_indexes list for the time being */
806 cxt->inh_indexes = lappend(cxt->inh_indexes, index_stmt);
808 index_close(parent_index, AccessShareLock);
813 * Close the parent rel, but keep our AccessShareLock on it until xact
814 * commit. That will prevent someone else from deleting or ALTERing the
815 * parent before the child is committed.
817 heap_close(relation, NoLock);
821 transformOfType(CreateStmtContext *cxt, TypeName *ofTypename)
829 AssertArg(ofTypename);
831 tuple = typenameType(NULL, ofTypename, NULL);
832 typ = (Form_pg_type) GETSTRUCT(tuple);
833 ofTypeId = HeapTupleGetOid(tuple);
834 ofTypename->typeOid = ofTypeId; /* cached for later */
836 if (typ->typtype != TYPTYPE_COMPOSITE)
838 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
839 errmsg("type %s is not a composite type",
840 format_type_be(ofTypeId))));
842 tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
843 for (i = 0; i < tupdesc->natts; i++)
845 Form_pg_attribute attr = tupdesc->attrs[i];
848 if (attr->attisdropped)
851 n = makeNode(ColumnDef);
852 n->colname = pstrdup(NameStr(attr->attname));
853 n->typeName = makeTypeNameFromOid(attr->atttypid, attr->atttypmod);
856 n->is_not_null = false;
857 n->is_from_type = true;
859 n->raw_default = NULL;
860 n->cooked_default = NULL;
861 n->collClause = NULL;
862 n->collOid = attr->attcollation;
863 n->constraints = NIL;
864 cxt->columns = lappend(cxt->columns, n);
866 DecrTupleDescRefCount(tupdesc);
868 ReleaseSysCache(tuple);
874 * Compute name for an index. This must match code in indexcmds.c.
876 * XXX this is inherently broken because the indexes aren't created
877 * immediately, so we fail to resolve conflicts when the same name is
878 * derived for multiple indexes. However, that's a reasonably uncommon
879 * situation, so we'll live with it for now.
882 chooseIndexName(const RangeVar *relation, IndexStmt *index_stmt)
887 namespaceId = RangeVarGetCreationNamespace(relation);
888 colnames = ChooseIndexColumnNames(index_stmt->indexParams);
889 return ChooseIndexName(relation->relname, namespaceId,
890 colnames, index_stmt->excludeOpNames,
891 index_stmt->primary, index_stmt->isconstraint);
895 * Generate an IndexStmt node using information from an already existing index
896 * "source_idx". Attribute numbers should be adjusted according to attmap.
899 generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
902 Oid source_relid = RelationGetRelid(source_idx);
903 Form_pg_attribute *attrs = RelationGetDescr(source_idx)->attrs;
906 Form_pg_class idxrelrec;
907 Form_pg_index idxrec;
909 oidvector *indcollation;
913 ListCell *indexpr_item;
921 * Fetch pg_class tuple of source index. We can't use the copy in the
922 * relcache entry because it doesn't include optional fields.
924 ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
925 if (!HeapTupleIsValid(ht_idxrel))
926 elog(ERROR, "cache lookup failed for relation %u", source_relid);
927 idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
929 /* Fetch pg_index tuple for source index from relcache entry */
930 ht_idx = source_idx->rd_indextuple;
931 idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
932 indrelid = idxrec->indrelid;
934 /* Fetch pg_am tuple for source index from relcache entry */
935 amrec = source_idx->rd_am;
937 /* Extract indcollation from the pg_index tuple */
938 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
939 Anum_pg_index_indcollation, &isnull);
941 indcollation = (oidvector *) DatumGetPointer(datum);
943 /* Extract indclass from the pg_index tuple */
944 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
945 Anum_pg_index_indclass, &isnull);
947 indclass = (oidvector *) DatumGetPointer(datum);
949 /* Begin building the IndexStmt */
950 index = makeNode(IndexStmt);
951 index->relation = cxt->relation;
952 index->accessMethod = pstrdup(NameStr(amrec->amname));
953 if (OidIsValid(idxrelrec->reltablespace))
954 index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
956 index->tableSpace = NULL;
957 index->indexOid = InvalidOid;
958 index->unique = idxrec->indisunique;
959 index->primary = idxrec->indisprimary;
960 index->concurrent = false;
963 * We don't try to preserve the name of the source index; instead, just
964 * let DefineIndex() choose a reasonable name.
966 index->idxname = NULL;
969 * If the index is marked PRIMARY or has an exclusion condition, it's
970 * certainly from a constraint; else, if it's not marked UNIQUE, it
971 * certainly isn't. If it is or might be from a constraint, we have to
972 * fetch the pg_constraint record.
974 if (index->primary || index->unique || idxrec->indisexclusion)
976 Oid constraintId = get_index_constraint(source_relid);
978 if (OidIsValid(constraintId))
981 Form_pg_constraint conrec;
983 ht_constr = SearchSysCache1(CONSTROID,
984 ObjectIdGetDatum(constraintId));
985 if (!HeapTupleIsValid(ht_constr))
986 elog(ERROR, "cache lookup failed for constraint %u",
988 conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
990 index->isconstraint = true;
991 index->deferrable = conrec->condeferrable;
992 index->initdeferred = conrec->condeferred;
994 /* If it's an exclusion constraint, we need the operator names */
995 if (idxrec->indisexclusion)
1001 Assert(conrec->contype == CONSTRAINT_EXCLUSION);
1002 /* Extract operator OIDs from the pg_constraint tuple */
1003 datum = SysCacheGetAttr(CONSTROID, ht_constr,
1004 Anum_pg_constraint_conexclop,
1007 elog(ERROR, "null conexclop for constraint %u",
1010 deconstruct_array(DatumGetArrayTypeP(datum),
1011 OIDOID, sizeof(Oid), true, 'i',
1012 &elems, NULL, &nElems);
1014 for (i = 0; i < nElems; i++)
1016 Oid operid = DatumGetObjectId(elems[i]);
1018 Form_pg_operator operform;
1023 opertup = SearchSysCache1(OPEROID,
1024 ObjectIdGetDatum(operid));
1025 if (!HeapTupleIsValid(opertup))
1026 elog(ERROR, "cache lookup failed for operator %u",
1028 operform = (Form_pg_operator) GETSTRUCT(opertup);
1029 oprname = pstrdup(NameStr(operform->oprname));
1030 /* For simplicity we always schema-qualify the op name */
1031 nspname = get_namespace_name(operform->oprnamespace);
1032 namelist = list_make2(makeString(nspname),
1033 makeString(oprname));
1034 index->excludeOpNames = lappend(index->excludeOpNames,
1036 ReleaseSysCache(opertup);
1040 ReleaseSysCache(ht_constr);
1043 index->isconstraint = false;
1046 index->isconstraint = false;
1048 /* Get the index expressions, if any */
1049 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1050 Anum_pg_index_indexprs, &isnull);
1055 exprsString = TextDatumGetCString(datum);
1056 indexprs = (List *) stringToNode(exprsString);
1061 /* Build the list of IndexElem */
1062 index->indexParams = NIL;
1064 indexpr_item = list_head(indexprs);
1065 for (keyno = 0; keyno < idxrec->indnatts; keyno++)
1068 AttrNumber attnum = idxrec->indkey.values[keyno];
1069 int16 opt = source_idx->rd_indoption[keyno];
1071 iparam = makeNode(IndexElem);
1073 if (AttributeNumberIsValid(attnum))
1075 /* Simple index column */
1078 attname = get_relid_attribute_name(indrelid, attnum);
1079 keycoltype = get_atttype(indrelid, attnum);
1081 iparam->name = attname;
1082 iparam->expr = NULL;
1086 /* Expressional index */
1089 if (indexpr_item == NULL)
1090 elog(ERROR, "too few entries in indexprs list");
1091 indexkey = (Node *) lfirst(indexpr_item);
1092 indexpr_item = lnext(indexpr_item);
1094 /* OK to modify indexkey since we are working on a private copy */
1095 change_varattnos_of_a_node(indexkey, attmap);
1097 iparam->name = NULL;
1098 iparam->expr = indexkey;
1100 keycoltype = exprType(indexkey);
1103 /* Copy the original index column name */
1104 iparam->indexcolname = pstrdup(NameStr(attrs[keyno]->attname));
1106 /* Add the collation name, if non-default */
1107 iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
1109 /* Add the operator class name, if non-default */
1110 iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1112 iparam->ordering = SORTBY_DEFAULT;
1113 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1115 /* Adjust options if necessary */
1116 if (amrec->amcanorder)
1119 * If it supports sort ordering, copy DESC and NULLS opts. Don't
1120 * set non-default settings unnecessarily, though, so as to
1121 * improve the chance of recognizing equivalence to constraint
1124 if (opt & INDOPTION_DESC)
1126 iparam->ordering = SORTBY_DESC;
1127 if ((opt & INDOPTION_NULLS_FIRST) == 0)
1128 iparam->nulls_ordering = SORTBY_NULLS_LAST;
1132 if (opt & INDOPTION_NULLS_FIRST)
1133 iparam->nulls_ordering = SORTBY_NULLS_FIRST;
1137 index->indexParams = lappend(index->indexParams, iparam);
1140 /* Copy reloptions if any */
1141 datum = SysCacheGetAttr(RELOID, ht_idxrel,
1142 Anum_pg_class_reloptions, &isnull);
1144 index->options = untransformRelOptions(datum);
1146 /* If it's a partial index, decompile and append the predicate */
1147 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1148 Anum_pg_index_indpred, &isnull);
1153 /* Convert text string to node tree */
1154 pred_str = TextDatumGetCString(datum);
1155 index->whereClause = (Node *) stringToNode(pred_str);
1156 /* Adjust attribute numbers */
1157 change_varattnos_of_a_node(index->whereClause, attmap);
1161 ReleaseSysCache(ht_idxrel);
1167 * get_collation - fetch qualified name of a collation
1169 * If collation is InvalidOid or is the default for the given actual_datatype,
1170 * then the return value is NIL.
1173 get_collation(Oid collation, Oid actual_datatype)
1177 Form_pg_collation coll_rec;
1181 if (!OidIsValid(collation))
1182 return NIL; /* easy case */
1183 if (collation == get_typcollation(actual_datatype))
1184 return NIL; /* just let it default */
1186 ht_coll = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
1187 if (!HeapTupleIsValid(ht_coll))
1188 elog(ERROR, "cache lookup failed for collation %u", collation);
1189 coll_rec = (Form_pg_collation) GETSTRUCT(ht_coll);
1191 /* For simplicity, we always schema-qualify the name */
1192 nsp_name = get_namespace_name(coll_rec->collnamespace);
1193 coll_name = pstrdup(NameStr(coll_rec->collname));
1194 result = list_make2(makeString(nsp_name), makeString(coll_name));
1196 ReleaseSysCache(ht_coll);
1201 * get_opclass - fetch qualified name of an index operator class
1203 * If the opclass is the default for the given actual_datatype, then
1204 * the return value is NIL.
1207 get_opclass(Oid opclass, Oid actual_datatype)
1211 Form_pg_opclass opc_rec;
1213 ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1214 if (!HeapTupleIsValid(ht_opc))
1215 elog(ERROR, "cache lookup failed for opclass %u", opclass);
1216 opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
1218 if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
1220 /* For simplicity, we always schema-qualify the name */
1221 char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
1222 char *opc_name = pstrdup(NameStr(opc_rec->opcname));
1224 result = list_make2(makeString(nsp_name), makeString(opc_name));
1227 ReleaseSysCache(ht_opc);
1233 * transformIndexConstraints
1234 * Handle UNIQUE, PRIMARY KEY, EXCLUDE constraints, which create indexes.
1235 * We also merge in any index definitions arising from
1236 * LIKE ... INCLUDING INDEXES.
1239 transformIndexConstraints(CreateStmtContext *cxt)
1242 List *indexlist = NIL;
1246 * Run through the constraints that need to generate an index. For PRIMARY
1247 * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
1248 * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
1251 foreach(lc, cxt->ixconstraints)
1253 Constraint *constraint = (Constraint *) lfirst(lc);
1255 Assert(IsA(constraint, Constraint));
1256 Assert(constraint->contype == CONSTR_PRIMARY ||
1257 constraint->contype == CONSTR_UNIQUE ||
1258 constraint->contype == CONSTR_EXCLUSION);
1260 index = transformIndexConstraint(constraint, cxt);
1262 indexlist = lappend(indexlist, index);
1265 /* Add in any indexes defined by LIKE ... INCLUDING INDEXES */
1266 foreach(lc, cxt->inh_indexes)
1268 index = (IndexStmt *) lfirst(lc);
1272 if (cxt->pkey != NULL)
1274 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1275 errmsg("multiple primary keys for table \"%s\" are not allowed",
1276 cxt->relation->relname)));
1280 indexlist = lappend(indexlist, index);
1284 * Scan the index list and remove any redundant index specifications. This
1285 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1286 * strict reading of SQL92 would suggest raising an error instead, but
1287 * that strikes me as too anal-retentive. - tgl 2001-02-14
1289 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1290 * pre-existing indexes, too.
1292 Assert(cxt->alist == NIL);
1293 if (cxt->pkey != NULL)
1295 /* Make sure we keep the PKEY index in preference to others... */
1296 cxt->alist = list_make1(cxt->pkey);
1299 foreach(lc, indexlist)
1306 /* if it's pkey, it's already in cxt->alist */
1307 if (index == cxt->pkey)
1310 foreach(k, cxt->alist)
1312 IndexStmt *priorindex = lfirst(k);
1314 if (equal(index->indexParams, priorindex->indexParams) &&
1315 equal(index->whereClause, priorindex->whereClause) &&
1316 equal(index->excludeOpNames, priorindex->excludeOpNames) &&
1317 strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
1318 index->deferrable == priorindex->deferrable &&
1319 index->initdeferred == priorindex->initdeferred)
1321 priorindex->unique |= index->unique;
1324 * If the prior index is as yet unnamed, and this one is
1325 * named, then transfer the name to the prior index. This
1326 * ensures that if we have named and unnamed constraints,
1327 * we'll use (at least one of) the names for the index.
1329 if (priorindex->idxname == NULL)
1330 priorindex->idxname = index->idxname;
1337 cxt->alist = lappend(cxt->alist, index);
1342 * transformIndexConstraint
1343 * Transform one UNIQUE, PRIMARY KEY, or EXCLUDE constraint for
1344 * transformIndexConstraints.
1347 transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
1352 index = makeNode(IndexStmt);
1354 index->unique = (constraint->contype != CONSTR_EXCLUSION);
1355 index->primary = (constraint->contype == CONSTR_PRIMARY);
1358 if (cxt->pkey != NULL)
1360 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1361 errmsg("multiple primary keys for table \"%s\" are not allowed",
1362 cxt->relation->relname),
1363 parser_errposition(cxt->pstate, constraint->location)));
1367 * In ALTER TABLE case, a primary index might already exist, but
1368 * DefineIndex will check for it.
1371 index->isconstraint = true;
1372 index->deferrable = constraint->deferrable;
1373 index->initdeferred = constraint->initdeferred;
1375 if (constraint->conname != NULL)
1376 index->idxname = pstrdup(constraint->conname);
1378 index->idxname = NULL; /* DefineIndex will choose name */
1380 index->relation = cxt->relation;
1381 index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
1382 index->options = constraint->options;
1383 index->tableSpace = constraint->indexspace;
1384 index->whereClause = constraint->where_clause;
1385 index->indexParams = NIL;
1386 index->excludeOpNames = NIL;
1387 index->indexOid = InvalidOid;
1388 index->concurrent = false;
1391 * If it's ALTER TABLE ADD CONSTRAINT USING INDEX, look up the index and
1392 * verify it's usable, then extract the implied column name list. (We
1393 * will not actually need the column name list at runtime, but we need it
1394 * now to check for duplicate column entries below.)
1396 if (constraint->indexname != NULL)
1398 char *index_name = constraint->indexname;
1399 Relation heap_rel = cxt->rel;
1402 Form_pg_index index_form;
1403 oidvector *indclass;
1404 Datum indclassDatum;
1408 /* Grammar should not allow this with explicit column list */
1409 Assert(constraint->keys == NIL);
1411 /* Grammar should only allow PRIMARY and UNIQUE constraints */
1412 Assert(constraint->contype == CONSTR_PRIMARY ||
1413 constraint->contype == CONSTR_UNIQUE);
1415 /* Must be ALTER, not CREATE, but grammar doesn't enforce that */
1418 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1419 errmsg("cannot use an existing index in CREATE TABLE"),
1420 parser_errposition(cxt->pstate, constraint->location)));
1422 /* Look for the index in the same schema as the table */
1423 index_oid = get_relname_relid(index_name, RelationGetNamespace(heap_rel));
1425 if (!OidIsValid(index_oid))
1427 (errcode(ERRCODE_UNDEFINED_OBJECT),
1428 errmsg("index \"%s\" does not exist", index_name),
1429 parser_errposition(cxt->pstate, constraint->location)));
1431 /* Open the index (this will throw an error if it is not an index) */
1432 index_rel = index_open(index_oid, AccessShareLock);
1433 index_form = index_rel->rd_index;
1435 /* Check that it does not have an associated constraint already */
1436 if (OidIsValid(get_index_constraint(index_oid)))
1438 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1439 errmsg("index \"%s\" is already associated with a constraint",
1441 parser_errposition(cxt->pstate, constraint->location)));
1443 /* Perform validity checks on the index */
1444 if (index_form->indrelid != RelationGetRelid(heap_rel))
1446 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1447 errmsg("index \"%s\" does not belong to table \"%s\"",
1448 index_name, RelationGetRelationName(heap_rel)),
1449 parser_errposition(cxt->pstate, constraint->location)));
1451 if (!index_form->indisvalid)
1453 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1454 errmsg("index \"%s\" is not valid", index_name),
1455 parser_errposition(cxt->pstate, constraint->location)));
1457 if (!index_form->indisready)
1459 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1460 errmsg("index \"%s\" is not ready", index_name),
1461 parser_errposition(cxt->pstate, constraint->location)));
1463 if (!index_form->indisunique)
1465 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1466 errmsg("\"%s\" is not a unique index", index_name),
1467 errdetail("Cannot create a PRIMARY KEY or UNIQUE constraint using such an index."),
1468 parser_errposition(cxt->pstate, constraint->location)));
1470 if (RelationGetIndexExpressions(index_rel) != NIL)
1472 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1473 errmsg("index \"%s\" contains expressions", index_name),
1474 errdetail("Cannot create a PRIMARY KEY or UNIQUE constraint using such an index."),
1475 parser_errposition(cxt->pstate, constraint->location)));
1477 if (RelationGetIndexPredicate(index_rel) != NIL)
1479 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1480 errmsg("\"%s\" is a partial index", index_name),
1481 errdetail("Cannot create a PRIMARY KEY or UNIQUE constraint using such an index."),
1482 parser_errposition(cxt->pstate, constraint->location)));
1485 * It's probably unsafe to change a deferred index to non-deferred. (A
1486 * non-constraint index couldn't be deferred anyway, so this case
1487 * should never occur; no need to sweat, but let's check it.)
1489 if (!index_form->indimmediate && !constraint->deferrable)
1491 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1492 errmsg("\"%s\" is a deferrable index", index_name),
1493 errdetail("Cannot create a non-deferrable constraint using a deferrable index."),
1494 parser_errposition(cxt->pstate, constraint->location)));
1497 * Insist on it being a btree. That's the only kind that supports
1498 * uniqueness at the moment anyway; but we must have an index that
1499 * exactly matches what you'd get from plain ADD CONSTRAINT syntax,
1500 * else dump and reload will produce a different index (breaking
1501 * pg_upgrade in particular).
1503 if (index_rel->rd_rel->relam != get_am_oid(DEFAULT_INDEX_TYPE, false))
1505 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1506 errmsg("index \"%s\" is not a b-tree", index_name),
1507 parser_errposition(cxt->pstate, constraint->location)));
1509 /* Must get indclass the hard way */
1510 indclassDatum = SysCacheGetAttr(INDEXRELID, index_rel->rd_indextuple,
1511 Anum_pg_index_indclass, &isnull);
1513 indclass = (oidvector *) DatumGetPointer(indclassDatum);
1515 for (i = 0; i < index_form->indnatts; i++)
1517 int2 attnum = index_form->indkey.values[i];
1518 Form_pg_attribute attform;
1523 * We shouldn't see attnum == 0 here, since we already rejected
1524 * expression indexes. If we do, SystemAttributeDefinition will
1529 Assert(attnum <= heap_rel->rd_att->natts);
1530 attform = heap_rel->rd_att->attrs[attnum - 1];
1533 attform = SystemAttributeDefinition(attnum,
1534 heap_rel->rd_rel->relhasoids);
1535 attname = pstrdup(NameStr(attform->attname));
1538 * Insist on default opclass and sort options. While the index
1539 * would still work as a constraint with non-default settings, it
1540 * might not provide exactly the same uniqueness semantics as
1541 * you'd get from a normally-created constraint; and there's also
1542 * the dump/reload problem mentioned above.
1544 defopclass = GetDefaultOpClass(attform->atttypid,
1545 index_rel->rd_rel->relam);
1546 if (indclass->values[i] != defopclass ||
1547 index_rel->rd_indoption[i] != 0)
1549 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1550 errmsg("index \"%s\" does not have default sorting behavior", index_name),
1551 errdetail("Cannot create a PRIMARY KEY or UNIQUE constraint using such an index."),
1552 parser_errposition(cxt->pstate, constraint->location)));
1554 constraint->keys = lappend(constraint->keys, makeString(attname));
1557 /* Close the index relation but keep the lock */
1558 relation_close(index_rel, NoLock);
1560 index->indexOid = index_oid;
1564 * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
1565 * IndexElems and operator names. We have to break that apart into
1568 if (constraint->contype == CONSTR_EXCLUSION)
1570 foreach(lc, constraint->exclusions)
1572 List *pair = (List *) lfirst(lc);
1576 Assert(list_length(pair) == 2);
1577 elem = (IndexElem *) linitial(pair);
1578 Assert(IsA(elem, IndexElem));
1579 opname = (List *) lsecond(pair);
1580 Assert(IsA(opname, List));
1582 index->indexParams = lappend(index->indexParams, elem);
1583 index->excludeOpNames = lappend(index->excludeOpNames, opname);
1590 * For UNIQUE and PRIMARY KEY, we just have a list of column names.
1592 * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
1593 * also make sure they are NOT NULL, if possible. (Although we could leave
1594 * it to DefineIndex to mark the columns NOT NULL, it's more efficient to
1595 * get it right the first time.)
1597 foreach(lc, constraint->keys)
1599 char *key = strVal(lfirst(lc));
1601 ColumnDef *column = NULL;
1605 foreach(columns, cxt->columns)
1607 column = (ColumnDef *) lfirst(columns);
1608 Assert(IsA(column, ColumnDef));
1609 if (strcmp(column->colname, key) == 0)
1617 /* found column in the new table; force it to be NOT NULL */
1618 if (constraint->contype == CONSTR_PRIMARY)
1619 column->is_not_null = TRUE;
1621 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1624 * column will be a system column in the new table, so accept it.
1625 * System columns can't ever be null, so no need to worry about
1626 * PRIMARY/NOT NULL constraint.
1630 else if (cxt->inhRelations)
1632 /* try inherited tables */
1635 foreach(inher, cxt->inhRelations)
1637 RangeVar *inh = (RangeVar *) lfirst(inher);
1641 Assert(IsA(inh, RangeVar));
1642 rel = heap_openrv(inh, AccessShareLock);
1643 if (rel->rd_rel->relkind != RELKIND_RELATION)
1645 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1646 errmsg("inherited relation \"%s\" is not a table",
1648 for (count = 0; count < rel->rd_att->natts; count++)
1650 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1651 char *inhname = NameStr(inhattr->attname);
1653 if (inhattr->attisdropped)
1655 if (strcmp(key, inhname) == 0)
1660 * We currently have no easy way to force an inherited
1661 * column to be NOT NULL at creation, if its parent
1662 * wasn't so already. We leave it to DefineIndex to
1663 * fix things up in this case.
1668 heap_close(rel, NoLock);
1675 * In the ALTER TABLE case, don't complain about index keys not
1676 * created in the command; they may well exist already. DefineIndex
1677 * will complain about them if not, and will also take care of marking
1680 if (!found && !cxt->isalter)
1682 (errcode(ERRCODE_UNDEFINED_COLUMN),
1683 errmsg("column \"%s\" named in key does not exist", key),
1684 parser_errposition(cxt->pstate, constraint->location)));
1686 /* Check for PRIMARY KEY(foo, foo) */
1687 foreach(columns, index->indexParams)
1689 iparam = (IndexElem *) lfirst(columns);
1690 if (iparam->name && strcmp(key, iparam->name) == 0)
1694 (errcode(ERRCODE_DUPLICATE_COLUMN),
1695 errmsg("column \"%s\" appears twice in primary key constraint",
1697 parser_errposition(cxt->pstate, constraint->location)));
1700 (errcode(ERRCODE_DUPLICATE_COLUMN),
1701 errmsg("column \"%s\" appears twice in unique constraint",
1703 parser_errposition(cxt->pstate, constraint->location)));
1707 /* OK, add it to the index definition */
1708 iparam = makeNode(IndexElem);
1709 iparam->name = pstrdup(key);
1710 iparam->expr = NULL;
1711 iparam->indexcolname = NULL;
1712 iparam->collation = NIL;
1713 iparam->opclass = NIL;
1714 iparam->ordering = SORTBY_DEFAULT;
1715 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1716 index->indexParams = lappend(index->indexParams, iparam);
1723 * transformFKConstraints
1724 * handle FOREIGN KEY constraints
1727 transformFKConstraints(CreateStmtContext *cxt,
1728 bool skipValidation, bool isAddConstraint)
1732 if (cxt->fkconstraints == NIL)
1736 * If CREATE TABLE or adding a column with NULL default, we can safely
1737 * skip validation of the constraint.
1741 foreach(fkclist, cxt->fkconstraints)
1743 Constraint *constraint = (Constraint *) lfirst(fkclist);
1745 constraint->skip_validation = true;
1746 constraint->initially_valid = true;
1751 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1752 * CONSTRAINT command to execute after the basic command is complete. (If
1753 * called from ADD CONSTRAINT, that routine will add the FK constraints to
1754 * its own subcommand list.)
1756 * Note: the ADD CONSTRAINT command must also execute after any index
1757 * creation commands. Thus, this should run after
1758 * transformIndexConstraints, so that the CREATE INDEX commands are
1759 * already in cxt->alist.
1761 if (!isAddConstraint)
1763 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1765 alterstmt->relation = cxt->relation;
1766 alterstmt->cmds = NIL;
1767 alterstmt->relkind = OBJECT_TABLE;
1769 foreach(fkclist, cxt->fkconstraints)
1771 Constraint *constraint = (Constraint *) lfirst(fkclist);
1772 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1774 altercmd->subtype = AT_ProcessedConstraint;
1775 altercmd->name = NULL;
1776 altercmd->def = (Node *) constraint;
1777 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1780 cxt->alist = lappend(cxt->alist, alterstmt);
1785 * transformIndexStmt - parse analysis for CREATE INDEX and ALTER TABLE
1787 * Note: this is a no-op for an index not using either index expressions or
1788 * a predicate expression. There are several code paths that create indexes
1789 * without bothering to call this, because they know they don't have any
1790 * such expressions to deal with.
1793 transformIndexStmt(IndexStmt *stmt, const char *queryString)
1801 * We must not scribble on the passed-in IndexStmt, so copy it. (This is
1802 * overkill, but easy.)
1804 stmt = (IndexStmt *) copyObject(stmt);
1807 * Open the parent table with appropriate locking. We must do this
1808 * because addRangeTableEntry() would acquire only AccessShareLock,
1809 * leaving DefineIndex() needing to do a lock upgrade with consequent risk
1810 * of deadlock. Make sure this stays in sync with the type of lock
1811 * DefineIndex() wants. If we are being called by ALTER TABLE, we will
1812 * already hold a higher lock.
1814 rel = heap_openrv(stmt->relation,
1815 (stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock));
1818 pstate = make_parsestate(NULL);
1819 pstate->p_sourcetext = queryString;
1822 * Put the parent table into the rtable so that the expressions can refer
1823 * to its fields without qualification.
1825 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1827 /* no to join list, yes to namespaces */
1828 addRTEtoQuery(pstate, rte, false, true, true);
1830 /* take care of the where clause */
1831 if (stmt->whereClause)
1833 stmt->whereClause = transformWhereClause(pstate,
1836 /* we have to fix its collations too */
1837 assign_expr_collations(pstate, stmt->whereClause);
1840 /* take care of any index expressions */
1841 foreach(l, stmt->indexParams)
1843 IndexElem *ielem = (IndexElem *) lfirst(l);
1847 /* Extract preliminary index col name before transforming expr */
1848 if (ielem->indexcolname == NULL)
1849 ielem->indexcolname = FigureIndexColname(ielem->expr);
1851 /* Now do parse transformation of the expression */
1852 ielem->expr = transformExpr(pstate, ielem->expr);
1854 /* We have to fix its collations too */
1855 assign_expr_collations(pstate, ielem->expr);
1858 * We check only that the result type is legitimate; this is for
1859 * consistency with what transformWhereClause() checks for the
1860 * predicate. DefineIndex() will make more checks.
1862 if (expression_returns_set(ielem->expr))
1864 (errcode(ERRCODE_DATATYPE_MISMATCH),
1865 errmsg("index expression cannot return a set")));
1870 * Check that only the base rel is mentioned.
1872 if (list_length(pstate->p_rtable) != 1)
1874 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1875 errmsg("index expressions and predicates can refer only to the table being indexed")));
1877 free_parsestate(pstate);
1879 /* Close relation, but keep the lock */
1880 heap_close(rel, NoLock);
1887 * transformRuleStmt -
1888 * transform a CREATE RULE Statement. The action is a list of parse
1889 * trees which is transformed into a list of query trees, and we also
1890 * transform the WHERE clause if any.
1892 * actions and whereClause are output parameters that receive the
1893 * transformed results.
1895 * Note that we must not scribble on the passed-in RuleStmt, so we do
1896 * copyObject() on the actions and WHERE clause.
1899 transformRuleStmt(RuleStmt *stmt, const char *queryString,
1900 List **actions, Node **whereClause)
1904 RangeTblEntry *oldrte;
1905 RangeTblEntry *newrte;
1908 * To avoid deadlock, make sure the first thing we do is grab
1909 * AccessExclusiveLock on the target relation. This will be needed by
1910 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1913 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1916 pstate = make_parsestate(NULL);
1917 pstate->p_sourcetext = queryString;
1920 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1921 * Set up their RTEs in the main pstate for use in parsing the rule
1924 oldrte = addRangeTableEntryForRelation(pstate, rel,
1925 makeAlias("old", NIL),
1927 newrte = addRangeTableEntryForRelation(pstate, rel,
1928 makeAlias("new", NIL),
1930 /* Must override addRangeTableEntry's default access-check flags */
1931 oldrte->requiredPerms = 0;
1932 newrte->requiredPerms = 0;
1935 * They must be in the namespace too for lookup purposes, but only add the
1936 * one(s) that are relevant for the current kind of rule. In an UPDATE
1937 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1938 * there's no need to be so picky for INSERT & DELETE. We do not add them
1941 switch (stmt->event)
1944 addRTEtoQuery(pstate, oldrte, false, true, true);
1947 addRTEtoQuery(pstate, oldrte, false, true, true);
1948 addRTEtoQuery(pstate, newrte, false, true, true);
1951 addRTEtoQuery(pstate, newrte, false, true, true);
1954 addRTEtoQuery(pstate, oldrte, false, true, true);
1957 elog(ERROR, "unrecognized event type: %d",
1962 /* take care of the where clause */
1963 *whereClause = transformWhereClause(pstate,
1964 (Node *) copyObject(stmt->whereClause),
1966 /* we have to fix its collations too */
1967 assign_expr_collations(pstate, *whereClause);
1969 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
1971 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1972 errmsg("rule WHERE condition cannot contain references to other relations")));
1974 /* aggregates not allowed (but subselects are okay) */
1975 if (pstate->p_hasAggs)
1977 (errcode(ERRCODE_GROUPING_ERROR),
1978 errmsg("cannot use aggregate function in rule WHERE condition")));
1979 if (pstate->p_hasWindowFuncs)
1981 (errcode(ERRCODE_WINDOWING_ERROR),
1982 errmsg("cannot use window function in rule WHERE condition")));
1985 * 'instead nothing' rules with a qualification need a query rangetable so
1986 * the rewrite handler can add the negated rule qualification to the
1987 * original query. We create a query with the new command type CMD_NOTHING
1988 * here that is treated specially by the rewrite system.
1990 if (stmt->actions == NIL)
1992 Query *nothing_qry = makeNode(Query);
1994 nothing_qry->commandType = CMD_NOTHING;
1995 nothing_qry->rtable = pstate->p_rtable;
1996 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1998 *actions = list_make1(nothing_qry);
2003 List *newactions = NIL;
2006 * transform each statement, like parse_sub_analyze()
2008 foreach(l, stmt->actions)
2010 Node *action = (Node *) lfirst(l);
2011 ParseState *sub_pstate = make_parsestate(NULL);
2018 * Since outer ParseState isn't parent of inner, have to pass down
2019 * the query text by hand.
2021 sub_pstate->p_sourcetext = queryString;
2024 * Set up OLD/NEW in the rtable for this statement. The entries
2025 * are added only to relnamespace, not varnamespace, because we
2026 * don't want them to be referred to by unqualified field names
2027 * nor "*" in the rule actions. We decide later whether to put
2028 * them in the joinlist.
2030 oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
2031 makeAlias("old", NIL),
2033 newrte = addRangeTableEntryForRelation(sub_pstate, rel,
2034 makeAlias("new", NIL),
2036 oldrte->requiredPerms = 0;
2037 newrte->requiredPerms = 0;
2038 addRTEtoQuery(sub_pstate, oldrte, false, true, false);
2039 addRTEtoQuery(sub_pstate, newrte, false, true, false);
2041 /* Transform the rule action statement */
2042 top_subqry = transformStmt(sub_pstate,
2043 (Node *) copyObject(action));
2046 * We cannot support utility-statement actions (eg NOTIFY) with
2047 * nonempty rule WHERE conditions, because there's no way to make
2048 * the utility action execute conditionally.
2050 if (top_subqry->commandType == CMD_UTILITY &&
2051 *whereClause != NULL)
2053 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2054 errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
2057 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
2058 * into the SELECT, and that's what we need to look at. (Ugly
2059 * kluge ... try to fix this when we redesign querytrees.)
2061 sub_qry = getInsertSelectQuery(top_subqry, NULL);
2064 * If the sub_qry is a setop, we cannot attach any qualifications
2065 * to it, because the planner won't notice them. This could
2066 * perhaps be relaxed someday, but for now, we may as well reject
2067 * such a rule immediately.
2069 if (sub_qry->setOperations != NULL && *whereClause != NULL)
2071 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2072 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2075 * Validate action's use of OLD/NEW, qual too
2078 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
2079 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
2081 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
2082 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
2084 switch (stmt->event)
2089 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2090 errmsg("ON SELECT rule cannot use OLD")));
2093 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2094 errmsg("ON SELECT rule cannot use NEW")));
2102 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2103 errmsg("ON INSERT rule cannot use OLD")));
2108 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2109 errmsg("ON DELETE rule cannot use NEW")));
2112 elog(ERROR, "unrecognized event type: %d",
2118 * OLD/NEW are not allowed in WITH queries, because they would
2119 * amount to outer references for the WITH, which we disallow.
2120 * However, they were already in the outer rangetable when we
2121 * analyzed the query, so we have to check.
2123 * Note that in the INSERT...SELECT case, we need to examine the
2124 * CTE lists of both top_subqry and sub_qry.
2126 * Note that we aren't digging into the body of the query looking
2127 * for WITHs in nested sub-SELECTs. A WITH down there can
2128 * legitimately refer to OLD/NEW, because it'd be an
2129 * indirect-correlated outer reference.
2131 if (rangeTableEntry_used((Node *) top_subqry->cteList,
2132 PRS2_OLD_VARNO, 0) ||
2133 rangeTableEntry_used((Node *) sub_qry->cteList,
2136 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2137 errmsg("cannot refer to OLD within WITH query")));
2138 if (rangeTableEntry_used((Node *) top_subqry->cteList,
2139 PRS2_NEW_VARNO, 0) ||
2140 rangeTableEntry_used((Node *) sub_qry->cteList,
2143 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2144 errmsg("cannot refer to NEW within WITH query")));
2147 * For efficiency's sake, add OLD to the rule action's jointree
2148 * only if it was actually referenced in the statement or qual.
2150 * For INSERT, NEW is not really a relation (only a reference to
2151 * the to-be-inserted tuple) and should never be added to the
2154 * For UPDATE, we treat NEW as being another kind of reference to
2155 * OLD, because it represents references to *transformed* tuples
2156 * of the existing relation. It would be wrong to enter NEW
2157 * separately in the jointree, since that would cause a double
2158 * join of the updated relation. It's also wrong to fail to make
2159 * a jointree entry if only NEW and not OLD is mentioned.
2161 if (has_old || (has_new && stmt->event == CMD_UPDATE))
2164 * If sub_qry is a setop, manipulating its jointree will do no
2165 * good at all, because the jointree is dummy. (This should be
2166 * a can't-happen case because of prior tests.)
2168 if (sub_qry->setOperations != NULL)
2170 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2171 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2172 /* hack so we can use addRTEtoQuery() */
2173 sub_pstate->p_rtable = sub_qry->rtable;
2174 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
2175 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
2176 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
2179 newactions = lappend(newactions, top_subqry);
2181 free_parsestate(sub_pstate);
2184 *actions = newactions;
2187 free_parsestate(pstate);
2189 /* Close relation, but keep the exclusive lock */
2190 heap_close(rel, NoLock);
2195 * transformAlterTableStmt -
2196 * parse analysis for ALTER TABLE
2198 * Returns a List of utility commands to be done in sequence. One of these
2199 * will be the transformed AlterTableStmt, but there may be additional actions
2200 * to be done before and after the actual AlterTable() call.
2203 transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
2207 CreateStmtContext cxt;
2212 List *newcmds = NIL;
2213 bool skipValidation = true;
2214 AlterTableCmd *newcmd;
2218 * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
2219 * is overkill, but easy.)
2221 stmt = (AlterTableStmt *) copyObject(stmt);
2224 * Determine the appropriate lock level for this list of subcommands.
2226 lockmode = AlterTableGetLockLevel(stmt->cmds);
2229 * Acquire appropriate lock on the target relation, which will be held
2230 * until end of transaction. This ensures any decisions we make here
2231 * based on the state of the relation will still be good at execution. We
2232 * must get lock now because execution will later require it; taking a
2233 * lower grade lock now and trying to upgrade later risks deadlock. Any
2234 * new commands we add after this must not upgrade the lock level
2237 rel = relation_openrv(stmt->relation, lockmode);
2239 /* Set up pstate and CreateStmtContext */
2240 pstate = make_parsestate(NULL);
2241 pstate->p_sourcetext = queryString;
2243 cxt.pstate = pstate;
2244 cxt.stmtType = "ALTER TABLE";
2245 cxt.relation = stmt->relation;
2247 cxt.inhRelations = NIL;
2249 cxt.hasoids = false; /* need not be right */
2251 cxt.ckconstraints = NIL;
2252 cxt.fkconstraints = NIL;
2253 cxt.ixconstraints = NIL;
2254 cxt.inh_indexes = NIL;
2260 * The only subtypes that currently require parse transformation handling
2261 * are ADD COLUMN and ADD CONSTRAINT. These largely re-use code from
2264 foreach(lcmd, stmt->cmds)
2266 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2268 switch (cmd->subtype)
2271 case AT_AddColumnToView:
2273 ColumnDef *def = (ColumnDef *) cmd->def;
2275 Assert(IsA(def, ColumnDef));
2276 transformColumnDefinition(&cxt, def);
2279 * If the column has a non-null default, we can't skip
2280 * validation of foreign keys.
2282 if (def->raw_default != NULL)
2283 skipValidation = false;
2286 * All constraints are processed in other ways. Remove the
2289 def->constraints = NIL;
2291 newcmds = lappend(newcmds, cmd);
2294 case AT_AddConstraint:
2297 * The original AddConstraint cmd node doesn't go to newcmds
2299 if (IsA(cmd->def, Constraint))
2301 transformTableConstraint(&cxt, (Constraint *) cmd->def);
2302 if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
2303 skipValidation = false;
2306 elog(ERROR, "unrecognized node type: %d",
2307 (int) nodeTag(cmd->def));
2310 case AT_ProcessedConstraint:
2313 * Already-transformed ADD CONSTRAINT, so just make it look
2314 * like the standard case.
2316 cmd->subtype = AT_AddConstraint;
2317 newcmds = lappend(newcmds, cmd);
2321 newcmds = lappend(newcmds, cmd);
2327 * transformIndexConstraints wants cxt.alist to contain only index
2328 * statements, so transfer anything we already have into save_alist
2331 save_alist = cxt.alist;
2334 /* Postprocess index and FK constraints */
2335 transformIndexConstraints(&cxt);
2337 transformFKConstraints(&cxt, skipValidation, true);
2340 * Push any index-creation commands into the ALTER, so that they can be
2341 * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
2342 * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
2343 * subcommand has already been through transformIndexStmt.
2345 foreach(l, cxt.alist)
2347 IndexStmt *idxstmt = (IndexStmt *) lfirst(l);
2349 Assert(IsA(idxstmt, IndexStmt));
2350 idxstmt = transformIndexStmt(idxstmt, queryString);
2351 newcmd = makeNode(AlterTableCmd);
2352 newcmd->subtype = OidIsValid(idxstmt->indexOid) ? AT_AddIndexConstraint : AT_AddIndex;
2353 newcmd->def = (Node *) idxstmt;
2354 newcmds = lappend(newcmds, newcmd);
2358 /* Append any CHECK or FK constraints to the commands list */
2359 foreach(l, cxt.ckconstraints)
2361 newcmd = makeNode(AlterTableCmd);
2362 newcmd->subtype = AT_AddConstraint;
2363 newcmd->def = (Node *) lfirst(l);
2364 newcmds = lappend(newcmds, newcmd);
2366 foreach(l, cxt.fkconstraints)
2368 newcmd = makeNode(AlterTableCmd);
2369 newcmd->subtype = AT_AddConstraint;
2370 newcmd->def = (Node *) lfirst(l);
2371 newcmds = lappend(newcmds, newcmd);
2374 /* Close rel but keep lock */
2375 relation_close(rel, NoLock);
2380 stmt->cmds = newcmds;
2382 result = lappend(cxt.blist, stmt);
2383 result = list_concat(result, cxt.alist);
2384 result = list_concat(result, save_alist);
2391 * Preprocess a list of column constraint clauses
2392 * to attach constraint attributes to their primary constraint nodes
2393 * and detect inconsistent/misplaced constraint attributes.
2395 * NOTE: currently, attributes are only supported for FOREIGN KEY, UNIQUE,
2396 * and PRIMARY KEY constraints, but someday they ought to be supported
2397 * for other constraint types.
2400 transformConstraintAttrs(CreateStmtContext *cxt, List *constraintList)
2402 Constraint *lastprimarycon = NULL;
2403 bool saw_deferrability = false;
2404 bool saw_initially = false;
2407 #define SUPPORTS_ATTRS(node) \
2408 ((node) != NULL && \
2409 ((node)->contype == CONSTR_PRIMARY || \
2410 (node)->contype == CONSTR_UNIQUE || \
2411 (node)->contype == CONSTR_EXCLUSION || \
2412 (node)->contype == CONSTR_FOREIGN))
2414 foreach(clist, constraintList)
2416 Constraint *con = (Constraint *) lfirst(clist);
2418 if (!IsA(con, Constraint))
2419 elog(ERROR, "unrecognized node type: %d",
2420 (int) nodeTag(con));
2421 switch (con->contype)
2423 case CONSTR_ATTR_DEFERRABLE:
2424 if (!SUPPORTS_ATTRS(lastprimarycon))
2426 (errcode(ERRCODE_SYNTAX_ERROR),
2427 errmsg("misplaced DEFERRABLE clause"),
2428 parser_errposition(cxt->pstate, con->location)));
2429 if (saw_deferrability)
2431 (errcode(ERRCODE_SYNTAX_ERROR),
2432 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2433 parser_errposition(cxt->pstate, con->location)));
2434 saw_deferrability = true;
2435 lastprimarycon->deferrable = true;
2438 case CONSTR_ATTR_NOT_DEFERRABLE:
2439 if (!SUPPORTS_ATTRS(lastprimarycon))
2441 (errcode(ERRCODE_SYNTAX_ERROR),
2442 errmsg("misplaced NOT DEFERRABLE clause"),
2443 parser_errposition(cxt->pstate, con->location)));
2444 if (saw_deferrability)
2446 (errcode(ERRCODE_SYNTAX_ERROR),
2447 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2448 parser_errposition(cxt->pstate, con->location)));
2449 saw_deferrability = true;
2450 lastprimarycon->deferrable = false;
2451 if (saw_initially &&
2452 lastprimarycon->initdeferred)
2454 (errcode(ERRCODE_SYNTAX_ERROR),
2455 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2456 parser_errposition(cxt->pstate, con->location)));
2459 case CONSTR_ATTR_DEFERRED:
2460 if (!SUPPORTS_ATTRS(lastprimarycon))
2462 (errcode(ERRCODE_SYNTAX_ERROR),
2463 errmsg("misplaced INITIALLY DEFERRED clause"),
2464 parser_errposition(cxt->pstate, con->location)));
2467 (errcode(ERRCODE_SYNTAX_ERROR),
2468 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2469 parser_errposition(cxt->pstate, con->location)));
2470 saw_initially = true;
2471 lastprimarycon->initdeferred = true;
2474 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
2476 if (!saw_deferrability)
2477 lastprimarycon->deferrable = true;
2478 else if (!lastprimarycon->deferrable)
2480 (errcode(ERRCODE_SYNTAX_ERROR),
2481 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2482 parser_errposition(cxt->pstate, con->location)));
2485 case CONSTR_ATTR_IMMEDIATE:
2486 if (!SUPPORTS_ATTRS(lastprimarycon))
2488 (errcode(ERRCODE_SYNTAX_ERROR),
2489 errmsg("misplaced INITIALLY IMMEDIATE clause"),
2490 parser_errposition(cxt->pstate, con->location)));
2493 (errcode(ERRCODE_SYNTAX_ERROR),
2494 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2495 parser_errposition(cxt->pstate, con->location)));
2496 saw_initially = true;
2497 lastprimarycon->initdeferred = false;
2501 /* Otherwise it's not an attribute */
2502 lastprimarycon = con;
2503 /* reset flags for new primary node */
2504 saw_deferrability = false;
2505 saw_initially = false;
2512 * Special handling of type definition for a column
2515 transformColumnType(CreateStmtContext *cxt, ColumnDef *column)
2518 * All we really need to do here is verify that the type is valid,
2519 * including any collation spec that might be present.
2521 Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
2523 if (column->collClause)
2525 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
2528 collOid = LookupCollation(cxt->pstate,
2529 column->collClause->collname,
2530 column->collClause->location);
2531 /* Complain if COLLATE is applied to an uncollatable type */
2532 if (!OidIsValid(typtup->typcollation))
2534 (errcode(ERRCODE_DATATYPE_MISMATCH),
2535 errmsg("collations are not supported by type %s",
2536 format_type_be(HeapTupleGetOid(ctype))),
2537 parser_errposition(cxt->pstate,
2538 column->collClause->location)));
2541 ReleaseSysCache(ctype);
2546 * transformCreateSchemaStmt -
2547 * analyzes the CREATE SCHEMA statement
2549 * Split the schema element list into individual commands and place
2550 * them in the result list in an order such that there are no forward
2551 * references (e.g. GRANT to a table created later in the list). Note
2552 * that the logic we use for determining forward references is
2553 * presently quite incomplete.
2555 * SQL92 also allows constraints to make forward references, so thumb through
2556 * the table columns and move forward references to a posterior alter-table
2559 * The result is a list of parse nodes that still need to be analyzed ---
2560 * but we can't analyze the later commands until we've executed the earlier
2561 * ones, because of possible inter-object references.
2563 * Note: this breaks the rules a little bit by modifying schema-name fields
2564 * within passed-in structs. However, the transformation would be the same
2565 * if done over, so it should be all right to scribble on the input to this
2569 transformCreateSchemaStmt(CreateSchemaStmt *stmt)
2571 CreateSchemaStmtContext cxt;
2575 cxt.stmtType = "CREATE SCHEMA";
2576 cxt.schemaname = stmt->schemaname;
2577 cxt.authid = stmt->authid;
2578 cxt.sequences = NIL;
2586 * Run through each schema element in the schema element list. Separate
2587 * statements by type, and do preliminary analysis.
2589 foreach(elements, stmt->schemaElts)
2591 Node *element = lfirst(elements);
2593 switch (nodeTag(element))
2595 case T_CreateSeqStmt:
2597 CreateSeqStmt *elp = (CreateSeqStmt *) element;
2599 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
2600 cxt.sequences = lappend(cxt.sequences, element);
2606 CreateStmt *elp = (CreateStmt *) element;
2608 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2611 * XXX todo: deal with constraints
2613 cxt.tables = lappend(cxt.tables, element);
2619 ViewStmt *elp = (ViewStmt *) element;
2621 setSchemaName(cxt.schemaname, &elp->view->schemaname);
2624 * XXX todo: deal with references between views
2626 cxt.views = lappend(cxt.views, element);
2632 IndexStmt *elp = (IndexStmt *) element;
2634 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2635 cxt.indexes = lappend(cxt.indexes, element);
2639 case T_CreateTrigStmt:
2641 CreateTrigStmt *elp = (CreateTrigStmt *) element;
2643 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2644 cxt.triggers = lappend(cxt.triggers, element);
2649 cxt.grants = lappend(cxt.grants, element);
2653 elog(ERROR, "unrecognized node type: %d",
2654 (int) nodeTag(element));
2659 result = list_concat(result, cxt.sequences);
2660 result = list_concat(result, cxt.tables);
2661 result = list_concat(result, cxt.views);
2662 result = list_concat(result, cxt.indexes);
2663 result = list_concat(result, cxt.triggers);
2664 result = list_concat(result, cxt.grants);
2671 * Set or check schema name in an element of a CREATE SCHEMA command
2674 setSchemaName(char *context_schema, char **stmt_schema_name)
2676 if (*stmt_schema_name == NULL)
2677 *stmt_schema_name = context_schema;
2678 else if (strcmp(context_schema, *stmt_schema_name) != 0)
2680 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
2681 errmsg("CREATE specifies a schema (%s) "
2682 "different from the one being created (%s)",
2683 *stmt_schema_name, context_schema)));