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_collate.h"
50 #include "parser/parse_expr.h"
51 #include "parser/parse_relation.h"
52 #include "parser/parse_target.h"
53 #include "parser/parse_type.h"
54 #include "parser/parse_utilcmd.h"
55 #include "parser/parser.h"
56 #include "rewrite/rewriteManip.h"
57 #include "storage/lock.h"
58 #include "utils/acl.h"
59 #include "utils/builtins.h"
60 #include "utils/lsyscache.h"
61 #include "utils/relcache.h"
62 #include "utils/syscache.h"
63 #include "utils/typcache.h"
66 /* State shared by transformCreateStmt and its subroutines */
69 ParseState *pstate; /* overall parser state */
70 const char *stmtType; /* "CREATE [FOREIGN] TABLE" or "ALTER TABLE" */
71 RangeVar *relation; /* relation to create */
72 Relation rel; /* opened/locked rel, if ALTER */
73 List *inhRelations; /* relations to inherit from */
74 bool isalter; /* true if altering existing table */
75 bool hasoids; /* does relation have an OID column? */
76 List *columns; /* ColumnDef items */
77 List *ckconstraints; /* CHECK constraints */
78 List *fkconstraints; /* FOREIGN KEY constraints */
79 List *ixconstraints; /* index-creating constraints */
80 List *inh_indexes; /* cloned indexes from INCLUDING INDEXES */
81 List *blist; /* "before list" of things to do before
82 * creating the table */
83 List *alist; /* "after list" of things to do after creating
85 IndexStmt *pkey; /* PRIMARY KEY index, if any */
88 /* State shared by transformCreateSchemaStmt and its subroutines */
91 const char *stmtType; /* "CREATE SCHEMA" or "ALTER SCHEMA" */
92 char *schemaname; /* name of schema */
93 char *authid; /* owner of schema */
94 List *sequences; /* CREATE SEQUENCE items */
95 List *tables; /* CREATE TABLE items */
96 List *views; /* CREATE VIEW items */
97 List *indexes; /* CREATE INDEX items */
98 List *triggers; /* CREATE TRIGGER items */
99 List *grants; /* GRANT items */
100 } CreateSchemaStmtContext;
103 static void transformColumnDefinition(CreateStmtContext *cxt,
105 static void transformTableConstraint(CreateStmtContext *cxt,
106 Constraint *constraint);
107 static void transformInhRelation(CreateStmtContext *cxt,
108 InhRelation *inhrelation);
109 static void transformOfType(CreateStmtContext *cxt,
110 TypeName *ofTypename);
111 static char *chooseIndexName(const RangeVar *relation, IndexStmt *index_stmt);
112 static IndexStmt *generateClonedIndexStmt(CreateStmtContext *cxt,
113 Relation parent_index, AttrNumber *attmap);
114 static List *get_opclass(Oid opclass, Oid actual_datatype);
115 static void transformIndexConstraints(CreateStmtContext *cxt);
116 static IndexStmt *transformIndexConstraint(Constraint *constraint,
117 CreateStmtContext *cxt);
118 static void transformFKConstraints(CreateStmtContext *cxt,
120 bool isAddConstraint);
121 static void transformConstraintAttrs(CreateStmtContext *cxt,
122 List *constraintList);
123 static void transformColumnType(CreateStmtContext *cxt, ColumnDef *column);
124 static void setSchemaName(char *context_schema, char **stmt_schema_name);
128 * transformCreateStmt -
129 * parse analysis for CREATE TABLE
131 * Returns a List of utility commands to be done in sequence. One of these
132 * will be the transformed CreateStmt, but there may be additional actions
133 * to be done before and after the actual DefineRelation() call.
135 * SQL92 allows constraints to be scattered all over, so thumb through
136 * the columns and collect all constraints into one place.
137 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
138 * then expand those into multiple IndexStmt blocks.
139 * - thomas 1997-12-02
142 transformCreateStmt(CreateStmt *stmt, const char *queryString)
145 CreateStmtContext cxt;
151 * We must not scribble on the passed-in CreateStmt, so copy it. (This is
152 * overkill, but easy.)
154 stmt = (CreateStmt *) copyObject(stmt);
157 * If the target relation name isn't schema-qualified, make it so. This
158 * prevents some corner cases in which added-on rewritten commands might
159 * think they should apply to other relations that have the same name and
160 * are earlier in the search path. But a local temp table is effectively
161 * specified to be in pg_temp, so no need for anything extra in that case.
163 if (stmt->relation->schemaname == NULL
164 && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
166 Oid namespaceid = RangeVarGetCreationNamespace(stmt->relation);
168 stmt->relation->schemaname = get_namespace_name(namespaceid);
171 /* Set up pstate and CreateStmtContext */
172 pstate = make_parsestate(NULL);
173 pstate->p_sourcetext = queryString;
176 if (IsA(stmt, CreateForeignTableStmt))
177 cxt.stmtType = "CREATE FOREIGN TABLE";
179 cxt.stmtType = "CREATE TABLE";
180 cxt.relation = stmt->relation;
182 cxt.inhRelations = stmt->inhRelations;
185 cxt.ckconstraints = NIL;
186 cxt.fkconstraints = NIL;
187 cxt.ixconstraints = NIL;
188 cxt.inh_indexes = NIL;
192 cxt.hasoids = interpretOidsOption(stmt->options);
194 Assert(!stmt->ofTypename || !stmt->inhRelations); /* grammar enforces */
196 if (stmt->ofTypename)
197 transformOfType(&cxt, stmt->ofTypename);
200 * Run through each primary element in the table creation clause. Separate
201 * column defs from constraints, and do preliminary analysis.
203 foreach(elements, stmt->tableElts)
205 Node *element = lfirst(elements);
207 switch (nodeTag(element))
210 transformColumnDefinition(&cxt, (ColumnDef *) element);
214 transformTableConstraint(&cxt, (Constraint *) element);
218 transformInhRelation(&cxt, (InhRelation *) element);
222 elog(ERROR, "unrecognized node type: %d",
223 (int) nodeTag(element));
229 * transformIndexConstraints wants cxt.alist to contain only index
230 * statements, so transfer anything we already have into save_alist.
232 save_alist = cxt.alist;
235 Assert(stmt->constraints == NIL);
238 * Postprocess constraints that give rise to index definitions.
240 transformIndexConstraints(&cxt);
243 * Postprocess foreign-key constraints.
245 transformFKConstraints(&cxt, true, false);
250 stmt->tableElts = cxt.columns;
251 stmt->constraints = cxt.ckconstraints;
253 result = lappend(cxt.blist, stmt);
254 result = list_concat(result, cxt.alist);
255 result = list_concat(result, save_alist);
261 * transformColumnDefinition -
262 * transform a single ColumnDef within CREATE TABLE
263 * Also used in ALTER TABLE ADD COLUMN
266 transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
271 Constraint *constraint;
274 cxt->columns = lappend(cxt->columns, column);
276 /* Check for SERIAL pseudo-types */
279 && list_length(column->typeName->names) == 1
280 && !column->typeName->pct_type)
282 char *typname = strVal(linitial(column->typeName->names));
284 if (strcmp(typname, "serial") == 0 ||
285 strcmp(typname, "serial4") == 0)
288 column->typeName->names = NIL;
289 column->typeName->typeOid = INT4OID;
291 else if (strcmp(typname, "bigserial") == 0 ||
292 strcmp(typname, "serial8") == 0)
295 column->typeName->names = NIL;
296 column->typeName->typeOid = INT8OID;
300 * We have to reject "serial[]" explicitly, because once we've set
301 * typeid, LookupTypeName won't notice arrayBounds. We don't need any
302 * special coding for serial(typmod) though.
304 if (is_serial && column->typeName->arrayBounds != NIL)
306 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
307 errmsg("array of serial is not implemented"),
308 parser_errposition(cxt->pstate,
309 column->typeName->location)));
312 /* Do necessary work on the column type declaration */
313 if (column->typeName)
314 transformColumnType(cxt, column);
316 /* Special actions for SERIAL pseudo-types */
325 FuncCall *funccallnode;
326 CreateSeqStmt *seqstmt;
327 AlterSeqStmt *altseqstmt;
331 * Determine namespace and name to use for the sequence.
333 * Although we use ChooseRelationName, it's not guaranteed that the
334 * selected sequence name won't conflict; given sufficiently long
335 * field names, two different serial columns in the same table could
336 * be assigned the same sequence name, and we'd not notice since we
337 * aren't creating the sequence quite yet. In practice this seems
338 * quite unlikely to be a problem, especially since few people would
339 * need two serial columns in one table.
342 snamespaceid = RelationGetNamespace(cxt->rel);
344 snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
345 snamespace = get_namespace_name(snamespaceid);
346 sname = ChooseRelationName(cxt->relation->relname,
352 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
353 cxt->stmtType, sname,
354 cxt->relation->relname, column->colname)));
357 * Build a CREATE SEQUENCE command to create the sequence object, and
358 * add it to the list of things to be done before this CREATE/ALTER
361 seqstmt = makeNode(CreateSeqStmt);
362 seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
363 seqstmt->options = NIL;
366 * If this is ALTER ADD COLUMN, make sure the sequence will be owned
367 * by the table's owner. The current user might be someone else
368 * (perhaps a superuser, or someone who's only a member of the owning
369 * role), but the SEQUENCE OWNED BY mechanisms will bleat unless
370 * table and sequence have exactly the same owning role.
373 seqstmt->ownerId = cxt->rel->rd_rel->relowner;
375 seqstmt->ownerId = InvalidOid;
377 cxt->blist = lappend(cxt->blist, seqstmt);
380 * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence
381 * as owned by this column, and add it to the list of things to be
382 * done after this CREATE/ALTER TABLE.
384 altseqstmt = makeNode(AlterSeqStmt);
385 altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
386 attnamelist = list_make3(makeString(snamespace),
387 makeString(cxt->relation->relname),
388 makeString(column->colname));
389 altseqstmt->options = list_make1(makeDefElem("owned_by",
390 (Node *) attnamelist));
392 cxt->alist = lappend(cxt->alist, altseqstmt);
395 * Create appropriate constraints for SERIAL. We do this in full,
396 * rather than shortcutting, so that we will detect any conflicting
397 * constraints the user wrote (like a different DEFAULT).
399 * Create an expression tree representing the function call
400 * nextval('sequencename'). We cannot reduce the raw tree to cooked
401 * form until after the sequence is created, but there's no need to do
404 qstring = quote_qualified_identifier(snamespace, sname);
405 snamenode = makeNode(A_Const);
406 snamenode->val.type = T_String;
407 snamenode->val.val.str = qstring;
408 snamenode->location = -1;
409 castnode = makeNode(TypeCast);
410 castnode->typeName = SystemTypeName("regclass");
411 castnode->arg = (Node *) snamenode;
412 castnode->location = -1;
413 funccallnode = makeNode(FuncCall);
414 funccallnode->funcname = SystemFuncName("nextval");
415 funccallnode->args = list_make1(castnode);
416 funccallnode->agg_order = NIL;
417 funccallnode->agg_star = false;
418 funccallnode->agg_distinct = false;
419 funccallnode->func_variadic = false;
420 funccallnode->over = NULL;
421 funccallnode->location = -1;
423 constraint = makeNode(Constraint);
424 constraint->contype = CONSTR_DEFAULT;
425 constraint->location = -1;
426 constraint->raw_expr = (Node *) funccallnode;
427 constraint->cooked_expr = NULL;
428 column->constraints = lappend(column->constraints, constraint);
430 constraint = makeNode(Constraint);
431 constraint->contype = CONSTR_NOTNULL;
432 constraint->location = -1;
433 column->constraints = lappend(column->constraints, constraint);
436 /* Process column constraints, if any... */
437 transformConstraintAttrs(cxt, column->constraints);
439 saw_nullable = false;
442 foreach(clist, column->constraints)
444 constraint = lfirst(clist);
445 Assert(IsA(constraint, Constraint));
447 switch (constraint->contype)
450 if (saw_nullable && column->is_not_null)
452 (errcode(ERRCODE_SYNTAX_ERROR),
453 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
454 column->colname, cxt->relation->relname),
455 parser_errposition(cxt->pstate,
456 constraint->location)));
457 column->is_not_null = FALSE;
462 if (saw_nullable && !column->is_not_null)
464 (errcode(ERRCODE_SYNTAX_ERROR),
465 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
466 column->colname, cxt->relation->relname),
467 parser_errposition(cxt->pstate,
468 constraint->location)));
469 column->is_not_null = TRUE;
476 (errcode(ERRCODE_SYNTAX_ERROR),
477 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
478 column->colname, cxt->relation->relname),
479 parser_errposition(cxt->pstate,
480 constraint->location)));
481 column->raw_default = constraint->raw_expr;
482 Assert(constraint->cooked_expr == NULL);
487 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
492 if (constraint->keys == NIL)
493 constraint->keys = list_make1(makeString(column->colname));
494 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
497 case CONSTR_EXCLUSION:
498 /* grammar does not allow EXCLUDE as a column constraint */
499 elog(ERROR, "column exclusion constraints are not supported");
505 * Fill in the current attribute's name and throw it into the
506 * list of FK constraints to be processed later.
508 constraint->fk_attrs = list_make1(makeString(column->colname));
509 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
512 case CONSTR_ATTR_DEFERRABLE:
513 case CONSTR_ATTR_NOT_DEFERRABLE:
514 case CONSTR_ATTR_DEFERRED:
515 case CONSTR_ATTR_IMMEDIATE:
516 /* transformConstraintAttrs took care of these */
520 elog(ERROR, "unrecognized constraint type: %d",
521 constraint->contype);
528 * transformTableConstraint
529 * transform a Constraint node within CREATE TABLE or ALTER TABLE
532 transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
534 switch (constraint->contype)
538 case CONSTR_EXCLUSION:
539 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
543 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
547 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
553 case CONSTR_ATTR_DEFERRABLE:
554 case CONSTR_ATTR_NOT_DEFERRABLE:
555 case CONSTR_ATTR_DEFERRED:
556 case CONSTR_ATTR_IMMEDIATE:
557 elog(ERROR, "invalid context for constraint type %d",
558 constraint->contype);
562 elog(ERROR, "unrecognized constraint type: %d",
563 constraint->contype);
569 * transformInhRelation
571 * Change the LIKE <subtable> portion of a CREATE TABLE statement into
572 * column definitions which recreate the user defined column portions of
576 transformInhRelation(CreateStmtContext *cxt, InhRelation *inhRelation)
578 AttrNumber parent_attno;
585 relation = parserOpenTable(cxt->pstate, inhRelation->relation,
588 if (relation->rd_rel->relkind != RELKIND_RELATION)
590 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
591 errmsg("inherited relation \"%s\" is not a table",
592 inhRelation->relation->relname)));
595 * Check for SELECT privilages
597 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
599 if (aclresult != ACLCHECK_OK)
600 aclcheck_error(aclresult, ACL_KIND_CLASS,
601 RelationGetRelationName(relation));
603 tupleDesc = RelationGetDescr(relation);
604 constr = tupleDesc->constr;
607 * Insert the copied attributes into the cxt for the new table definition.
609 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
612 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
613 char *attributeName = NameStr(attribute->attname);
617 * Ignore dropped columns in the parent.
619 if (attribute->attisdropped)
623 * Create a new column, which is marked as NOT inherited.
625 * For constraints, ONLY the NOT NULL constraint is inherited by the
626 * new column definition per SQL99.
628 def = makeNode(ColumnDef);
629 def->colname = pstrdup(attributeName);
630 def->typeName = makeTypeNameFromOid(attribute->atttypid,
631 attribute->atttypmod);
633 def->is_local = true;
634 def->is_not_null = attribute->attnotnull;
635 def->is_from_type = false;
637 def->raw_default = NULL;
638 def->cooked_default = NULL;
639 def->collClause = NULL;
640 def->collOid = attribute->attcollation;
641 def->constraints = NIL;
646 cxt->columns = lappend(cxt->columns, def);
649 * Copy default, if present and the default has been requested
651 if (attribute->atthasdef &&
652 (inhRelation->options & CREATE_TABLE_LIKE_DEFAULTS))
654 Node *this_default = NULL;
655 AttrDefault *attrdef;
658 /* Find default in constraint structure */
659 Assert(constr != NULL);
660 attrdef = constr->defval;
661 for (i = 0; i < constr->num_defval; i++)
663 if (attrdef[i].adnum == parent_attno)
665 this_default = stringToNode(attrdef[i].adbin);
669 Assert(this_default != NULL);
672 * If default expr could contain any vars, we'd need to fix 'em,
673 * but it can't; so default is ready to apply to child.
676 def->cooked_default = this_default;
679 /* Likewise, copy storage if requested */
680 if (inhRelation->options & CREATE_TABLE_LIKE_STORAGE)
681 def->storage = attribute->attstorage;
685 /* Likewise, copy comment if requested */
686 if ((inhRelation->options & CREATE_TABLE_LIKE_COMMENTS) &&
687 (comment = GetComment(attribute->attrelid,
689 attribute->attnum)) != NULL)
691 CommentStmt *stmt = makeNode(CommentStmt);
693 stmt->objtype = OBJECT_COLUMN;
694 stmt->objname = list_make3(makeString(cxt->relation->schemaname),
695 makeString(cxt->relation->relname),
696 makeString(def->colname));
698 stmt->comment = comment;
700 cxt->alist = lappend(cxt->alist, stmt);
705 * Copy CHECK constraints if requested, being careful to adjust attribute
708 if ((inhRelation->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
711 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
714 for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
716 char *ccname = tupleDesc->constr->check[ccnum].ccname;
717 char *ccbin = tupleDesc->constr->check[ccnum].ccbin;
718 Node *ccbin_node = stringToNode(ccbin);
719 Constraint *n = makeNode(Constraint);
721 change_varattnos_of_a_node(ccbin_node, attmap);
723 n->contype = CONSTR_CHECK;
725 n->conname = pstrdup(ccname);
727 n->cooked_expr = nodeToString(ccbin_node);
728 cxt->ckconstraints = lappend(cxt->ckconstraints, n);
730 /* Copy comment on constraint */
731 if ((inhRelation->options & CREATE_TABLE_LIKE_COMMENTS) &&
732 (comment = GetComment(get_constraint_oid(RelationGetRelid(relation),
734 ConstraintRelationId,
737 CommentStmt *stmt = makeNode(CommentStmt);
739 stmt->objtype = OBJECT_CONSTRAINT;
740 stmt->objname = list_make3(makeString(cxt->relation->schemaname),
741 makeString(cxt->relation->relname),
742 makeString(n->conname));
744 stmt->comment = comment;
746 cxt->alist = lappend(cxt->alist, stmt);
752 * Likewise, copy indexes if requested
754 if ((inhRelation->options & CREATE_TABLE_LIKE_INDEXES) &&
755 relation->rd_rel->relhasindex)
757 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
758 List *parent_indexes;
761 parent_indexes = RelationGetIndexList(relation);
763 foreach(l, parent_indexes)
765 Oid parent_index_oid = lfirst_oid(l);
766 Relation parent_index;
767 IndexStmt *index_stmt;
769 parent_index = index_open(parent_index_oid, AccessShareLock);
771 /* Build CREATE INDEX statement to recreate the parent_index */
772 index_stmt = generateClonedIndexStmt(cxt, parent_index, attmap);
774 /* Copy comment on index */
775 if (inhRelation->options & CREATE_TABLE_LIKE_COMMENTS)
777 comment = GetComment(parent_index_oid, RelationRelationId, 0);
784 * We have to assign the index a name now, so that we can
785 * reference it in CommentStmt.
787 if (index_stmt->idxname == NULL)
788 index_stmt->idxname = chooseIndexName(cxt->relation,
791 stmt = makeNode(CommentStmt);
792 stmt->objtype = OBJECT_INDEX;
794 list_make2(makeString(cxt->relation->schemaname),
795 makeString(index_stmt->idxname));
797 stmt->comment = comment;
799 cxt->alist = lappend(cxt->alist, stmt);
803 /* Save it in the inh_indexes list for the time being */
804 cxt->inh_indexes = lappend(cxt->inh_indexes, index_stmt);
806 index_close(parent_index, AccessShareLock);
811 * Close the parent rel, but keep our AccessShareLock on it until xact
812 * commit. That will prevent someone else from deleting or ALTERing the
813 * parent before the child is committed.
815 heap_close(relation, NoLock);
819 transformOfType(CreateStmtContext *cxt, TypeName *ofTypename)
827 AssertArg(ofTypename);
829 tuple = typenameType(NULL, ofTypename, NULL);
830 typ = (Form_pg_type) GETSTRUCT(tuple);
831 ofTypeId = HeapTupleGetOid(tuple);
832 ofTypename->typeOid = ofTypeId; /* cached for later */
834 if (typ->typtype != TYPTYPE_COMPOSITE)
836 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
837 errmsg("type %s is not a composite type",
838 format_type_be(ofTypeId))));
840 tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
841 for (i = 0; i < tupdesc->natts; i++)
843 Form_pg_attribute attr = tupdesc->attrs[i];
846 if (attr->attisdropped)
849 n = makeNode(ColumnDef);
850 n->colname = pstrdup(NameStr(attr->attname));
851 n->typeName = makeTypeNameFromOid(attr->atttypid, attr->atttypmod);
854 n->is_not_null = false;
855 n->is_from_type = true;
857 n->raw_default = NULL;
858 n->cooked_default = NULL;
859 n->collClause = NULL;
860 n->collOid = attr->attcollation;
861 n->constraints = NIL;
862 cxt->columns = lappend(cxt->columns, n);
864 DecrTupleDescRefCount(tupdesc);
866 ReleaseSysCache(tuple);
872 * Compute name for an index. This must match code in indexcmds.c.
874 * XXX this is inherently broken because the indexes aren't created
875 * immediately, so we fail to resolve conflicts when the same name is
876 * derived for multiple indexes. However, that's a reasonably uncommon
877 * situation, so we'll live with it for now.
880 chooseIndexName(const RangeVar *relation, IndexStmt *index_stmt)
885 namespaceId = RangeVarGetCreationNamespace(relation);
886 colnames = ChooseIndexColumnNames(index_stmt->indexParams);
887 return ChooseIndexName(relation->relname, namespaceId,
888 colnames, index_stmt->excludeOpNames,
889 index_stmt->primary, index_stmt->isconstraint);
893 * Generate an IndexStmt node using information from an already existing index
894 * "source_idx". Attribute numbers should be adjusted according to attmap.
897 generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
900 Oid source_relid = RelationGetRelid(source_idx);
901 Form_pg_attribute *attrs = RelationGetDescr(source_idx)->attrs;
904 Form_pg_class idxrelrec;
905 Form_pg_index idxrec;
910 ListCell *indexpr_item;
918 * Fetch pg_class tuple of source index. We can't use the copy in the
919 * relcache entry because it doesn't include optional fields.
921 ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
922 if (!HeapTupleIsValid(ht_idxrel))
923 elog(ERROR, "cache lookup failed for relation %u", source_relid);
924 idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
926 /* Fetch pg_index tuple for source index from relcache entry */
927 ht_idx = source_idx->rd_indextuple;
928 idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
929 indrelid = idxrec->indrelid;
931 /* Fetch pg_am tuple for source index from relcache entry */
932 amrec = source_idx->rd_am;
934 /* Extract indclass from the pg_index tuple */
935 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
936 Anum_pg_index_indclass, &isnull);
938 indclass = (oidvector *) DatumGetPointer(datum);
940 /* Begin building the IndexStmt */
941 index = makeNode(IndexStmt);
942 index->relation = cxt->relation;
943 index->accessMethod = pstrdup(NameStr(amrec->amname));
944 if (OidIsValid(idxrelrec->reltablespace))
945 index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
947 index->tableSpace = NULL;
948 index->indexOid = InvalidOid;
949 index->unique = idxrec->indisunique;
950 index->primary = idxrec->indisprimary;
951 index->concurrent = false;
954 * We don't try to preserve the name of the source index; instead, just
955 * let DefineIndex() choose a reasonable name.
957 index->idxname = NULL;
960 * If the index is marked PRIMARY or has an exclusion condition, it's
961 * certainly from a constraint; else, if it's not marked UNIQUE, it
962 * certainly isn't. If it is or might be from a constraint, we have to
963 * fetch the pg_constraint record.
965 if (index->primary || index->unique || idxrec->indisexclusion)
967 Oid constraintId = get_index_constraint(source_relid);
969 if (OidIsValid(constraintId))
972 Form_pg_constraint conrec;
974 ht_constr = SearchSysCache1(CONSTROID,
975 ObjectIdGetDatum(constraintId));
976 if (!HeapTupleIsValid(ht_constr))
977 elog(ERROR, "cache lookup failed for constraint %u",
979 conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
981 index->isconstraint = true;
982 index->deferrable = conrec->condeferrable;
983 index->initdeferred = conrec->condeferred;
985 /* If it's an exclusion constraint, we need the operator names */
986 if (idxrec->indisexclusion)
992 Assert(conrec->contype == CONSTRAINT_EXCLUSION);
993 /* Extract operator OIDs from the pg_constraint tuple */
994 datum = SysCacheGetAttr(CONSTROID, ht_constr,
995 Anum_pg_constraint_conexclop,
998 elog(ERROR, "null conexclop for constraint %u",
1001 deconstruct_array(DatumGetArrayTypeP(datum),
1002 OIDOID, sizeof(Oid), true, 'i',
1003 &elems, NULL, &nElems);
1005 for (i = 0; i < nElems; i++)
1007 Oid operid = DatumGetObjectId(elems[i]);
1009 Form_pg_operator operform;
1014 opertup = SearchSysCache1(OPEROID,
1015 ObjectIdGetDatum(operid));
1016 if (!HeapTupleIsValid(opertup))
1017 elog(ERROR, "cache lookup failed for operator %u",
1019 operform = (Form_pg_operator) GETSTRUCT(opertup);
1020 oprname = pstrdup(NameStr(operform->oprname));
1021 /* For simplicity we always schema-qualify the op name */
1022 nspname = get_namespace_name(operform->oprnamespace);
1023 namelist = list_make2(makeString(nspname),
1024 makeString(oprname));
1025 index->excludeOpNames = lappend(index->excludeOpNames,
1027 ReleaseSysCache(opertup);
1031 ReleaseSysCache(ht_constr);
1034 index->isconstraint = false;
1037 index->isconstraint = false;
1039 /* Get the index expressions, if any */
1040 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1041 Anum_pg_index_indexprs, &isnull);
1046 exprsString = TextDatumGetCString(datum);
1047 indexprs = (List *) stringToNode(exprsString);
1052 /* Build the list of IndexElem */
1053 index->indexParams = NIL;
1055 indexpr_item = list_head(indexprs);
1056 for (keyno = 0; keyno < idxrec->indnatts; keyno++)
1059 AttrNumber attnum = idxrec->indkey.values[keyno];
1060 int16 opt = source_idx->rd_indoption[keyno];
1062 iparam = makeNode(IndexElem);
1064 if (AttributeNumberIsValid(attnum))
1066 /* Simple index column */
1069 attname = get_relid_attribute_name(indrelid, attnum);
1070 keycoltype = get_atttype(indrelid, attnum);
1072 iparam->name = attname;
1073 iparam->expr = NULL;
1077 /* Expressional index */
1080 if (indexpr_item == NULL)
1081 elog(ERROR, "too few entries in indexprs list");
1082 indexkey = (Node *) lfirst(indexpr_item);
1083 indexpr_item = lnext(indexpr_item);
1085 /* OK to modify indexkey since we are working on a private copy */
1086 change_varattnos_of_a_node(indexkey, attmap);
1088 iparam->name = NULL;
1089 iparam->expr = indexkey;
1091 keycoltype = exprType(indexkey);
1094 /* Copy the original index column name */
1095 iparam->indexcolname = pstrdup(NameStr(attrs[keyno]->attname));
1097 /* Add the operator class name, if non-default */
1098 iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1100 iparam->ordering = SORTBY_DEFAULT;
1101 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1103 /* Adjust options if necessary */
1104 if (amrec->amcanorder)
1107 * If it supports sort ordering, copy DESC and NULLS opts. Don't
1108 * set non-default settings unnecessarily, though, so as to
1109 * improve the chance of recognizing equivalence to constraint
1112 if (opt & INDOPTION_DESC)
1114 iparam->ordering = SORTBY_DESC;
1115 if ((opt & INDOPTION_NULLS_FIRST) == 0)
1116 iparam->nulls_ordering = SORTBY_NULLS_LAST;
1120 if (opt & INDOPTION_NULLS_FIRST)
1121 iparam->nulls_ordering = SORTBY_NULLS_FIRST;
1125 index->indexParams = lappend(index->indexParams, iparam);
1128 /* Copy reloptions if any */
1129 datum = SysCacheGetAttr(RELOID, ht_idxrel,
1130 Anum_pg_class_reloptions, &isnull);
1132 index->options = untransformRelOptions(datum);
1134 /* If it's a partial index, decompile and append the predicate */
1135 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1136 Anum_pg_index_indpred, &isnull);
1141 /* Convert text string to node tree */
1142 pred_str = TextDatumGetCString(datum);
1143 index->whereClause = (Node *) stringToNode(pred_str);
1144 /* Adjust attribute numbers */
1145 change_varattnos_of_a_node(index->whereClause, attmap);
1149 ReleaseSysCache(ht_idxrel);
1155 * get_opclass - fetch name of an index operator class
1157 * If the opclass is the default for the given actual_datatype, then
1158 * the return value is NIL.
1161 get_opclass(Oid opclass, Oid actual_datatype)
1164 Form_pg_opclass opc_rec;
1167 ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1168 if (!HeapTupleIsValid(ht_opc))
1169 elog(ERROR, "cache lookup failed for opclass %u", opclass);
1170 opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
1172 if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
1174 /* For simplicity, we always schema-qualify the name */
1175 char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
1176 char *opc_name = pstrdup(NameStr(opc_rec->opcname));
1178 result = list_make2(makeString(nsp_name), makeString(opc_name));
1181 ReleaseSysCache(ht_opc);
1187 * transformIndexConstraints
1188 * Handle UNIQUE, PRIMARY KEY, EXCLUDE constraints, which create indexes.
1189 * We also merge in any index definitions arising from
1190 * LIKE ... INCLUDING INDEXES.
1193 transformIndexConstraints(CreateStmtContext *cxt)
1196 List *indexlist = NIL;
1200 * Run through the constraints that need to generate an index. For PRIMARY
1201 * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
1202 * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
1205 foreach(lc, cxt->ixconstraints)
1207 Constraint *constraint = (Constraint *) lfirst(lc);
1209 Assert(IsA(constraint, Constraint));
1210 Assert(constraint->contype == CONSTR_PRIMARY ||
1211 constraint->contype == CONSTR_UNIQUE ||
1212 constraint->contype == CONSTR_EXCLUSION);
1214 index = transformIndexConstraint(constraint, cxt);
1216 indexlist = lappend(indexlist, index);
1219 /* Add in any indexes defined by LIKE ... INCLUDING INDEXES */
1220 foreach(lc, cxt->inh_indexes)
1222 index = (IndexStmt *) lfirst(lc);
1226 if (cxt->pkey != NULL)
1228 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1229 errmsg("multiple primary keys for table \"%s\" are not allowed",
1230 cxt->relation->relname)));
1234 indexlist = lappend(indexlist, index);
1238 * Scan the index list and remove any redundant index specifications. This
1239 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1240 * strict reading of SQL92 would suggest raising an error instead, but
1241 * that strikes me as too anal-retentive. - tgl 2001-02-14
1243 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1244 * pre-existing indexes, too.
1246 Assert(cxt->alist == NIL);
1247 if (cxt->pkey != NULL)
1249 /* Make sure we keep the PKEY index in preference to others... */
1250 cxt->alist = list_make1(cxt->pkey);
1253 foreach(lc, indexlist)
1260 /* if it's pkey, it's already in cxt->alist */
1261 if (index == cxt->pkey)
1264 foreach(k, cxt->alist)
1266 IndexStmt *priorindex = lfirst(k);
1268 if (equal(index->indexParams, priorindex->indexParams) &&
1269 equal(index->whereClause, priorindex->whereClause) &&
1270 equal(index->excludeOpNames, priorindex->excludeOpNames) &&
1271 strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
1272 index->deferrable == priorindex->deferrable &&
1273 index->initdeferred == priorindex->initdeferred)
1275 priorindex->unique |= index->unique;
1278 * If the prior index is as yet unnamed, and this one is
1279 * named, then transfer the name to the prior index. This
1280 * ensures that if we have named and unnamed constraints,
1281 * we'll use (at least one of) the names for the index.
1283 if (priorindex->idxname == NULL)
1284 priorindex->idxname = index->idxname;
1291 cxt->alist = lappend(cxt->alist, index);
1296 * transformIndexConstraint
1297 * Transform one UNIQUE, PRIMARY KEY, or EXCLUDE constraint for
1298 * transformIndexConstraints.
1301 transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
1306 index = makeNode(IndexStmt);
1308 index->unique = (constraint->contype != CONSTR_EXCLUSION);
1309 index->primary = (constraint->contype == CONSTR_PRIMARY);
1312 if (cxt->pkey != NULL)
1314 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1315 errmsg("multiple primary keys for table \"%s\" are not allowed",
1316 cxt->relation->relname),
1317 parser_errposition(cxt->pstate, constraint->location)));
1321 * In ALTER TABLE case, a primary index might already exist, but
1322 * DefineIndex will check for it.
1325 index->isconstraint = true;
1326 index->deferrable = constraint->deferrable;
1327 index->initdeferred = constraint->initdeferred;
1329 if (constraint->conname != NULL)
1330 index->idxname = pstrdup(constraint->conname);
1332 index->idxname = NULL; /* DefineIndex will choose name */
1334 index->relation = cxt->relation;
1335 index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
1336 index->options = constraint->options;
1337 index->tableSpace = constraint->indexspace;
1338 index->whereClause = constraint->where_clause;
1339 index->indexParams = NIL;
1340 index->excludeOpNames = NIL;
1341 index->indexOid = InvalidOid;
1342 index->concurrent = false;
1345 * If it's ALTER TABLE ADD CONSTRAINT USING INDEX, look up the index and
1346 * verify it's usable, then extract the implied column name list. (We
1347 * will not actually need the column name list at runtime, but we need
1348 * it now to check for duplicate column entries below.)
1350 if (constraint->indexname != NULL)
1352 char *index_name = constraint->indexname;
1353 Relation heap_rel = cxt->rel;
1356 Form_pg_index index_form;
1357 oidvector *indclass;
1358 Datum indclassDatum;
1362 /* Grammar should not allow this with explicit column list */
1363 Assert(constraint->keys == NIL);
1365 /* Grammar should only allow PRIMARY and UNIQUE constraints */
1366 Assert(constraint->contype == CONSTR_PRIMARY ||
1367 constraint->contype == CONSTR_UNIQUE);
1369 /* Must be ALTER, not CREATE, but grammar doesn't enforce that */
1372 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1373 errmsg("cannot use an existing index in CREATE TABLE"),
1374 parser_errposition(cxt->pstate, constraint->location)));
1376 /* Look for the index in the same schema as the table */
1377 index_oid = get_relname_relid(index_name, RelationGetNamespace(heap_rel));
1379 if (!OidIsValid(index_oid))
1381 (errcode(ERRCODE_UNDEFINED_OBJECT),
1382 errmsg("index \"%s\" does not exist", index_name),
1383 parser_errposition(cxt->pstate, constraint->location)));
1385 /* Open the index (this will throw an error if it is not an index) */
1386 index_rel = index_open(index_oid, AccessShareLock);
1387 index_form = index_rel->rd_index;
1389 /* Check that it does not have an associated constraint already */
1390 if (OidIsValid(get_index_constraint(index_oid)))
1392 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1393 errmsg("index \"%s\" is already associated with a constraint",
1395 parser_errposition(cxt->pstate, constraint->location)));
1397 /* Perform validity checks on the index */
1398 if (index_form->indrelid != RelationGetRelid(heap_rel))
1400 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1401 errmsg("index \"%s\" does not belong to table \"%s\"",
1402 index_name, RelationGetRelationName(heap_rel)),
1403 parser_errposition(cxt->pstate, constraint->location)));
1405 if (!index_form->indisvalid)
1407 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1408 errmsg("index \"%s\" is not valid", index_name),
1409 parser_errposition(cxt->pstate, constraint->location)));
1411 if (!index_form->indisready)
1413 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1414 errmsg("index \"%s\" is not ready", index_name),
1415 parser_errposition(cxt->pstate, constraint->location)));
1417 if (!index_form->indisunique)
1419 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1420 errmsg("\"%s\" is not a unique index", index_name),
1421 errdetail("Cannot create a PRIMARY KEY or UNIQUE constraint using such an index."),
1422 parser_errposition(cxt->pstate, constraint->location)));
1424 if (RelationGetIndexExpressions(index_rel) != NIL)
1426 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1427 errmsg("index \"%s\" contains expressions", index_name),
1428 errdetail("Cannot create a PRIMARY KEY or UNIQUE constraint using such an index."),
1429 parser_errposition(cxt->pstate, constraint->location)));
1431 if (RelationGetIndexPredicate(index_rel) != NIL)
1433 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1434 errmsg("\"%s\" is a partial index", index_name),
1435 errdetail("Cannot create a PRIMARY KEY or UNIQUE constraint using such an index."),
1436 parser_errposition(cxt->pstate, constraint->location)));
1439 * It's probably unsafe to change a deferred index to non-deferred.
1440 * (A non-constraint index couldn't be deferred anyway, so this case
1441 * should never occur; no need to sweat, but let's check it.)
1443 if (!index_form->indimmediate && !constraint->deferrable)
1445 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1446 errmsg("\"%s\" is a deferrable index", index_name),
1447 errdetail("Cannot create a non-deferrable constraint using a deferrable index."),
1448 parser_errposition(cxt->pstate, constraint->location)));
1451 * Insist on it being a btree. That's the only kind that supports
1452 * uniqueness at the moment anyway; but we must have an index that
1453 * exactly matches what you'd get from plain ADD CONSTRAINT syntax,
1454 * else dump and reload will produce a different index (breaking
1455 * pg_upgrade in particular).
1457 if (index_rel->rd_rel->relam != get_am_oid(DEFAULT_INDEX_TYPE, false))
1459 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1460 errmsg("index \"%s\" is not a b-tree", index_name),
1461 parser_errposition(cxt->pstate, constraint->location)));
1463 /* Must get indclass the hard way */
1464 indclassDatum = SysCacheGetAttr(INDEXRELID, index_rel->rd_indextuple,
1465 Anum_pg_index_indclass, &isnull);
1467 indclass = (oidvector *) DatumGetPointer(indclassDatum);
1469 for (i = 0; i < index_form->indnatts; i++)
1471 int2 attnum = index_form->indkey.values[i];
1472 Form_pg_attribute attform;
1477 * We shouldn't see attnum == 0 here, since we already rejected
1478 * expression indexes. If we do, SystemAttributeDefinition
1479 * will throw an error.
1483 Assert(attnum <= heap_rel->rd_att->natts);
1484 attform = heap_rel->rd_att->attrs[attnum - 1];
1487 attform = SystemAttributeDefinition(attnum,
1488 heap_rel->rd_rel->relhasoids);
1489 attname = pstrdup(NameStr(attform->attname));
1492 * Insist on default opclass and sort options. While the index
1493 * would still work as a constraint with non-default settings, it
1494 * might not provide exactly the same uniqueness semantics as
1495 * you'd get from a normally-created constraint; and there's also
1496 * the dump/reload problem mentioned above.
1498 defopclass = GetDefaultOpClass(attform->atttypid,
1499 index_rel->rd_rel->relam);
1500 if (indclass->values[i] != defopclass ||
1501 index_rel->rd_indoption[i] != 0)
1503 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1504 errmsg("index \"%s\" does not have default sorting behavior", index_name),
1505 errdetail("Cannot create a PRIMARY KEY or UNIQUE constraint using such an index."),
1506 parser_errposition(cxt->pstate, constraint->location)));
1508 constraint->keys = lappend(constraint->keys, makeString(attname));
1511 /* Close the index relation but keep the lock */
1512 relation_close(index_rel, NoLock);
1514 index->indexOid = index_oid;
1518 * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
1519 * IndexElems and operator names. We have to break that apart into
1522 if (constraint->contype == CONSTR_EXCLUSION)
1524 foreach(lc, constraint->exclusions)
1526 List *pair = (List *) lfirst(lc);
1530 Assert(list_length(pair) == 2);
1531 elem = (IndexElem *) linitial(pair);
1532 Assert(IsA(elem, IndexElem));
1533 opname = (List *) lsecond(pair);
1534 Assert(IsA(opname, List));
1536 index->indexParams = lappend(index->indexParams, elem);
1537 index->excludeOpNames = lappend(index->excludeOpNames, opname);
1544 * For UNIQUE and PRIMARY KEY, we just have a list of column names.
1546 * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
1547 * also make sure they are NOT NULL, if possible. (Although we could leave
1548 * it to DefineIndex to mark the columns NOT NULL, it's more efficient to
1549 * get it right the first time.)
1551 foreach(lc, constraint->keys)
1553 char *key = strVal(lfirst(lc));
1555 ColumnDef *column = NULL;
1559 foreach(columns, cxt->columns)
1561 column = (ColumnDef *) lfirst(columns);
1562 Assert(IsA(column, ColumnDef));
1563 if (strcmp(column->colname, key) == 0)
1571 /* found column in the new table; force it to be NOT NULL */
1572 if (constraint->contype == CONSTR_PRIMARY)
1573 column->is_not_null = TRUE;
1575 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1578 * column will be a system column in the new table, so accept it.
1579 * System columns can't ever be null, so no need to worry about
1580 * PRIMARY/NOT NULL constraint.
1584 else if (cxt->inhRelations)
1586 /* try inherited tables */
1589 foreach(inher, cxt->inhRelations)
1591 RangeVar *inh = (RangeVar *) lfirst(inher);
1595 Assert(IsA(inh, RangeVar));
1596 rel = heap_openrv(inh, AccessShareLock);
1597 if (rel->rd_rel->relkind != RELKIND_RELATION)
1599 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1600 errmsg("inherited relation \"%s\" is not a table",
1602 for (count = 0; count < rel->rd_att->natts; count++)
1604 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1605 char *inhname = NameStr(inhattr->attname);
1607 if (inhattr->attisdropped)
1609 if (strcmp(key, inhname) == 0)
1614 * We currently have no easy way to force an inherited
1615 * column to be NOT NULL at creation, if its parent
1616 * wasn't so already. We leave it to DefineIndex to
1617 * fix things up in this case.
1622 heap_close(rel, NoLock);
1629 * In the ALTER TABLE case, don't complain about index keys not
1630 * created in the command; they may well exist already. DefineIndex
1631 * will complain about them if not, and will also take care of marking
1634 if (!found && !cxt->isalter)
1636 (errcode(ERRCODE_UNDEFINED_COLUMN),
1637 errmsg("column \"%s\" named in key does not exist", key),
1638 parser_errposition(cxt->pstate, constraint->location)));
1640 /* Check for PRIMARY KEY(foo, foo) */
1641 foreach(columns, index->indexParams)
1643 iparam = (IndexElem *) lfirst(columns);
1644 if (iparam->name && strcmp(key, iparam->name) == 0)
1648 (errcode(ERRCODE_DUPLICATE_COLUMN),
1649 errmsg("column \"%s\" appears twice in primary key constraint",
1651 parser_errposition(cxt->pstate, constraint->location)));
1654 (errcode(ERRCODE_DUPLICATE_COLUMN),
1655 errmsg("column \"%s\" appears twice in unique constraint",
1657 parser_errposition(cxt->pstate, constraint->location)));
1661 /* OK, add it to the index definition */
1662 iparam = makeNode(IndexElem);
1663 iparam->name = pstrdup(key);
1664 iparam->expr = NULL;
1665 iparam->indexcolname = NULL;
1666 iparam->opclass = NIL;
1667 iparam->ordering = SORTBY_DEFAULT;
1668 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1669 index->indexParams = lappend(index->indexParams, iparam);
1676 * transformFKConstraints
1677 * handle FOREIGN KEY constraints
1680 transformFKConstraints(CreateStmtContext *cxt,
1681 bool skipValidation, bool isAddConstraint)
1685 if (cxt->fkconstraints == NIL)
1689 * If CREATE TABLE or adding a column with NULL default, we can safely
1690 * skip validation of the constraint.
1694 foreach(fkclist, cxt->fkconstraints)
1696 Constraint *constraint = (Constraint *) lfirst(fkclist);
1698 constraint->skip_validation = true;
1703 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1704 * CONSTRAINT command to execute after the basic command is complete. (If
1705 * called from ADD CONSTRAINT, that routine will add the FK constraints to
1706 * its own subcommand list.)
1708 * Note: the ADD CONSTRAINT command must also execute after any index
1709 * creation commands. Thus, this should run after
1710 * transformIndexConstraints, so that the CREATE INDEX commands are
1711 * already in cxt->alist.
1713 if (!isAddConstraint)
1715 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1717 alterstmt->relation = cxt->relation;
1718 alterstmt->cmds = NIL;
1719 alterstmt->relkind = OBJECT_TABLE;
1721 foreach(fkclist, cxt->fkconstraints)
1723 Constraint *constraint = (Constraint *) lfirst(fkclist);
1724 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1726 altercmd->subtype = AT_ProcessedConstraint;
1727 altercmd->name = NULL;
1728 altercmd->def = (Node *) constraint;
1729 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1732 cxt->alist = lappend(cxt->alist, alterstmt);
1737 * transformIndexStmt - parse analysis for CREATE INDEX and ALTER TABLE
1739 * Note: this is a no-op for an index not using either index expressions or
1740 * a predicate expression. There are several code paths that create indexes
1741 * without bothering to call this, because they know they don't have any
1742 * such expressions to deal with.
1745 transformIndexStmt(IndexStmt *stmt, const char *queryString)
1753 * We must not scribble on the passed-in IndexStmt, so copy it. (This is
1754 * overkill, but easy.)
1756 stmt = (IndexStmt *) copyObject(stmt);
1759 * Open the parent table with appropriate locking. We must do this
1760 * because addRangeTableEntry() would acquire only AccessShareLock,
1761 * leaving DefineIndex() needing to do a lock upgrade with consequent risk
1762 * of deadlock. Make sure this stays in sync with the type of lock
1763 * DefineIndex() wants. If we are being called by ALTER TABLE, we will
1764 * already hold a higher lock.
1766 rel = heap_openrv(stmt->relation,
1767 (stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock));
1770 pstate = make_parsestate(NULL);
1771 pstate->p_sourcetext = queryString;
1774 * Put the parent table into the rtable so that the expressions can refer
1775 * to its fields without qualification.
1777 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1779 /* no to join list, yes to namespaces */
1780 addRTEtoQuery(pstate, rte, false, true, true);
1782 /* take care of the where clause */
1783 if (stmt->whereClause)
1784 stmt->whereClause = transformWhereClause(pstate,
1788 /* take care of any index expressions */
1789 foreach(l, stmt->indexParams)
1791 IndexElem *ielem = (IndexElem *) lfirst(l);
1795 /* Extract preliminary index col name before transforming expr */
1796 if (ielem->indexcolname == NULL)
1797 ielem->indexcolname = FigureIndexColname(ielem->expr);
1799 /* Now do parse transformation of the expression */
1800 ielem->expr = transformExpr(pstate, ielem->expr);
1802 /* We have to fix its collations too */
1803 assign_expr_collations(pstate, ielem->expr);
1806 * We check only that the result type is legitimate; this is for
1807 * consistency with what transformWhereClause() checks for the
1808 * predicate. DefineIndex() will make more checks.
1810 if (expression_returns_set(ielem->expr))
1812 (errcode(ERRCODE_DATATYPE_MISMATCH),
1813 errmsg("index expression cannot return a set")));
1818 * Check that only the base rel is mentioned.
1820 if (list_length(pstate->p_rtable) != 1)
1822 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1823 errmsg("index expressions and predicates can refer only to the table being indexed")));
1825 free_parsestate(pstate);
1827 /* Close relation, but keep the lock */
1828 heap_close(rel, NoLock);
1835 * transformRuleStmt -
1836 * transform a CREATE RULE Statement. The action is a list of parse
1837 * trees which is transformed into a list of query trees, and we also
1838 * transform the WHERE clause if any.
1840 * actions and whereClause are output parameters that receive the
1841 * transformed results.
1843 * Note that we must not scribble on the passed-in RuleStmt, so we do
1844 * copyObject() on the actions and WHERE clause.
1847 transformRuleStmt(RuleStmt *stmt, const char *queryString,
1848 List **actions, Node **whereClause)
1852 RangeTblEntry *oldrte;
1853 RangeTblEntry *newrte;
1856 * To avoid deadlock, make sure the first thing we do is grab
1857 * AccessExclusiveLock on the target relation. This will be needed by
1858 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1861 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1864 pstate = make_parsestate(NULL);
1865 pstate->p_sourcetext = queryString;
1868 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1869 * Set up their RTEs in the main pstate for use in parsing the rule
1872 oldrte = addRangeTableEntryForRelation(pstate, rel,
1873 makeAlias("old", NIL),
1875 newrte = addRangeTableEntryForRelation(pstate, rel,
1876 makeAlias("new", NIL),
1878 /* Must override addRangeTableEntry's default access-check flags */
1879 oldrte->requiredPerms = 0;
1880 newrte->requiredPerms = 0;
1883 * They must be in the namespace too for lookup purposes, but only add the
1884 * one(s) that are relevant for the current kind of rule. In an UPDATE
1885 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1886 * there's no need to be so picky for INSERT & DELETE. We do not add them
1889 switch (stmt->event)
1892 addRTEtoQuery(pstate, oldrte, false, true, true);
1895 addRTEtoQuery(pstate, oldrte, false, true, true);
1896 addRTEtoQuery(pstate, newrte, false, true, true);
1899 addRTEtoQuery(pstate, newrte, false, true, true);
1902 addRTEtoQuery(pstate, oldrte, false, true, true);
1905 elog(ERROR, "unrecognized event type: %d",
1910 /* take care of the where clause */
1911 *whereClause = transformWhereClause(pstate,
1912 (Node *) copyObject(stmt->whereClause),
1915 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
1917 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1918 errmsg("rule WHERE condition cannot contain references to other relations")));
1920 /* aggregates not allowed (but subselects are okay) */
1921 if (pstate->p_hasAggs)
1923 (errcode(ERRCODE_GROUPING_ERROR),
1924 errmsg("cannot use aggregate function in rule WHERE condition")));
1925 if (pstate->p_hasWindowFuncs)
1927 (errcode(ERRCODE_WINDOWING_ERROR),
1928 errmsg("cannot use window function in rule WHERE condition")));
1931 * 'instead nothing' rules with a qualification need a query rangetable so
1932 * the rewrite handler can add the negated rule qualification to the
1933 * original query. We create a query with the new command type CMD_NOTHING
1934 * here that is treated specially by the rewrite system.
1936 if (stmt->actions == NIL)
1938 Query *nothing_qry = makeNode(Query);
1940 nothing_qry->commandType = CMD_NOTHING;
1941 nothing_qry->rtable = pstate->p_rtable;
1942 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1944 *actions = list_make1(nothing_qry);
1949 List *newactions = NIL;
1952 * transform each statement, like parse_sub_analyze()
1954 foreach(l, stmt->actions)
1956 Node *action = (Node *) lfirst(l);
1957 ParseState *sub_pstate = make_parsestate(NULL);
1964 * Since outer ParseState isn't parent of inner, have to pass down
1965 * the query text by hand.
1967 sub_pstate->p_sourcetext = queryString;
1970 * Set up OLD/NEW in the rtable for this statement. The entries
1971 * are added only to relnamespace, not varnamespace, because we
1972 * don't want them to be referred to by unqualified field names
1973 * nor "*" in the rule actions. We decide later whether to put
1974 * them in the joinlist.
1976 oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
1977 makeAlias("old", NIL),
1979 newrte = addRangeTableEntryForRelation(sub_pstate, rel,
1980 makeAlias("new", NIL),
1982 oldrte->requiredPerms = 0;
1983 newrte->requiredPerms = 0;
1984 addRTEtoQuery(sub_pstate, oldrte, false, true, false);
1985 addRTEtoQuery(sub_pstate, newrte, false, true, false);
1987 /* Transform the rule action statement */
1988 top_subqry = transformStmt(sub_pstate,
1989 (Node *) copyObject(action));
1992 * We cannot support utility-statement actions (eg NOTIFY) with
1993 * nonempty rule WHERE conditions, because there's no way to make
1994 * the utility action execute conditionally.
1996 if (top_subqry->commandType == CMD_UTILITY &&
1997 *whereClause != NULL)
1999 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2000 errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
2003 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
2004 * into the SELECT, and that's what we need to look at. (Ugly
2005 * kluge ... try to fix this when we redesign querytrees.)
2007 sub_qry = getInsertSelectQuery(top_subqry, NULL);
2010 * If the sub_qry is a setop, we cannot attach any qualifications
2011 * to it, because the planner won't notice them. This could
2012 * perhaps be relaxed someday, but for now, we may as well reject
2013 * such a rule immediately.
2015 if (sub_qry->setOperations != NULL && *whereClause != NULL)
2017 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2018 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2021 * Validate action's use of OLD/NEW, qual too
2024 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
2025 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
2027 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
2028 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
2030 switch (stmt->event)
2035 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2036 errmsg("ON SELECT rule cannot use OLD")));
2039 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2040 errmsg("ON SELECT rule cannot use NEW")));
2048 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2049 errmsg("ON INSERT rule cannot use OLD")));
2054 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2055 errmsg("ON DELETE rule cannot use NEW")));
2058 elog(ERROR, "unrecognized event type: %d",
2064 * OLD/NEW are not allowed in WITH queries, because they would
2065 * amount to outer references for the WITH, which we disallow.
2066 * However, they were already in the outer rangetable when we
2067 * analyzed the query, so we have to check.
2069 * Note that in the INSERT...SELECT case, we need to examine
2070 * the CTE lists of both top_subqry and sub_qry.
2072 * Note that we aren't digging into the body of the query
2073 * looking for WITHs in nested sub-SELECTs. A WITH down there
2074 * can legitimately refer to OLD/NEW, because it'd be an
2075 * indirect-correlated outer reference.
2077 if (rangeTableEntry_used((Node *) top_subqry->cteList,
2078 PRS2_OLD_VARNO, 0) ||
2079 rangeTableEntry_used((Node *) sub_qry->cteList,
2082 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2083 errmsg("cannot refer to OLD within WITH query")));
2084 if (rangeTableEntry_used((Node *) top_subqry->cteList,
2085 PRS2_NEW_VARNO, 0) ||
2086 rangeTableEntry_used((Node *) sub_qry->cteList,
2089 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2090 errmsg("cannot refer to NEW within WITH query")));
2093 * For efficiency's sake, add OLD to the rule action's jointree
2094 * only if it was actually referenced in the statement or qual.
2096 * For INSERT, NEW is not really a relation (only a reference to
2097 * the to-be-inserted tuple) and should never be added to the
2100 * For UPDATE, we treat NEW as being another kind of reference to
2101 * OLD, because it represents references to *transformed* tuples
2102 * of the existing relation. It would be wrong to enter NEW
2103 * separately in the jointree, since that would cause a double
2104 * join of the updated relation. It's also wrong to fail to make
2105 * a jointree entry if only NEW and not OLD is mentioned.
2107 if (has_old || (has_new && stmt->event == CMD_UPDATE))
2110 * If sub_qry is a setop, manipulating its jointree will do no
2111 * good at all, because the jointree is dummy. (This should be
2112 * a can't-happen case because of prior tests.)
2114 if (sub_qry->setOperations != NULL)
2116 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2117 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2118 /* hack so we can use addRTEtoQuery() */
2119 sub_pstate->p_rtable = sub_qry->rtable;
2120 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
2121 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
2122 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
2125 newactions = lappend(newactions, top_subqry);
2127 free_parsestate(sub_pstate);
2130 *actions = newactions;
2133 free_parsestate(pstate);
2135 /* Close relation, but keep the exclusive lock */
2136 heap_close(rel, NoLock);
2141 * transformAlterTableStmt -
2142 * parse analysis for ALTER TABLE
2144 * Returns a List of utility commands to be done in sequence. One of these
2145 * will be the transformed AlterTableStmt, but there may be additional actions
2146 * to be done before and after the actual AlterTable() call.
2149 transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
2153 CreateStmtContext cxt;
2158 List *newcmds = NIL;
2159 bool skipValidation = true;
2160 AlterTableCmd *newcmd;
2164 * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
2165 * is overkill, but easy.)
2167 stmt = (AlterTableStmt *) copyObject(stmt);
2170 * Determine the appropriate lock level for this list of subcommands.
2172 lockmode = AlterTableGetLockLevel(stmt->cmds);
2175 * Acquire appropriate lock on the target relation, which will be held until
2176 * end of transaction. This ensures any decisions we make here based on
2177 * the state of the relation will still be good at execution. We must get
2178 * lock now because execution will later require it; taking a lower grade lock
2179 * now and trying to upgrade later risks deadlock. Any new commands we add
2180 * after this must not upgrade the lock level requested here.
2182 rel = relation_openrv(stmt->relation, lockmode);
2184 /* Set up pstate and CreateStmtContext */
2185 pstate = make_parsestate(NULL);
2186 pstate->p_sourcetext = queryString;
2188 cxt.pstate = pstate;
2189 cxt.stmtType = "ALTER TABLE";
2190 cxt.relation = stmt->relation;
2192 cxt.inhRelations = NIL;
2194 cxt.hasoids = false; /* need not be right */
2196 cxt.ckconstraints = NIL;
2197 cxt.fkconstraints = NIL;
2198 cxt.ixconstraints = NIL;
2199 cxt.inh_indexes = NIL;
2205 * The only subtypes that currently require parse transformation handling
2206 * are ADD COLUMN and ADD CONSTRAINT. These largely re-use code from
2209 foreach(lcmd, stmt->cmds)
2211 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2213 switch (cmd->subtype)
2216 case AT_AddColumnToView:
2218 ColumnDef *def = (ColumnDef *) cmd->def;
2220 Assert(IsA(def, ColumnDef));
2221 transformColumnDefinition(&cxt, def);
2224 * If the column has a non-null default, we can't skip
2225 * validation of foreign keys.
2227 if (def->raw_default != NULL)
2228 skipValidation = false;
2231 * All constraints are processed in other ways. Remove the
2234 def->constraints = NIL;
2236 newcmds = lappend(newcmds, cmd);
2239 case AT_AddConstraint:
2242 * The original AddConstraint cmd node doesn't go to newcmds
2244 if (IsA(cmd->def, Constraint))
2246 transformTableConstraint(&cxt, (Constraint *) cmd->def);
2247 if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
2248 skipValidation = false;
2251 elog(ERROR, "unrecognized node type: %d",
2252 (int) nodeTag(cmd->def));
2255 case AT_ProcessedConstraint:
2258 * Already-transformed ADD CONSTRAINT, so just make it look
2259 * like the standard case.
2261 cmd->subtype = AT_AddConstraint;
2262 newcmds = lappend(newcmds, cmd);
2266 newcmds = lappend(newcmds, cmd);
2272 * transformIndexConstraints wants cxt.alist to contain only index
2273 * statements, so transfer anything we already have into save_alist
2276 save_alist = cxt.alist;
2279 /* Postprocess index and FK constraints */
2280 transformIndexConstraints(&cxt);
2282 transformFKConstraints(&cxt, skipValidation, true);
2285 * Push any index-creation commands into the ALTER, so that they can be
2286 * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
2287 * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
2288 * subcommand has already been through transformIndexStmt.
2290 foreach(l, cxt.alist)
2292 IndexStmt *idxstmt = (IndexStmt *) lfirst(l);
2294 Assert(IsA(idxstmt, IndexStmt));
2295 idxstmt = transformIndexStmt(idxstmt, queryString);
2296 newcmd = makeNode(AlterTableCmd);
2297 newcmd->subtype = OidIsValid(idxstmt->indexOid) ? AT_AddIndexConstraint : AT_AddIndex;
2298 newcmd->def = (Node *) idxstmt;
2299 newcmds = lappend(newcmds, newcmd);
2303 /* Append any CHECK or FK constraints to the commands list */
2304 foreach(l, cxt.ckconstraints)
2306 newcmd = makeNode(AlterTableCmd);
2307 newcmd->subtype = AT_AddConstraint;
2308 newcmd->def = (Node *) lfirst(l);
2309 newcmds = lappend(newcmds, newcmd);
2311 foreach(l, cxt.fkconstraints)
2313 newcmd = makeNode(AlterTableCmd);
2314 newcmd->subtype = AT_AddConstraint;
2315 newcmd->def = (Node *) lfirst(l);
2316 newcmds = lappend(newcmds, newcmd);
2319 /* Close rel but keep lock */
2320 relation_close(rel, NoLock);
2325 stmt->cmds = newcmds;
2327 result = lappend(cxt.blist, stmt);
2328 result = list_concat(result, cxt.alist);
2329 result = list_concat(result, save_alist);
2336 * Preprocess a list of column constraint clauses
2337 * to attach constraint attributes to their primary constraint nodes
2338 * and detect inconsistent/misplaced constraint attributes.
2340 * NOTE: currently, attributes are only supported for FOREIGN KEY, UNIQUE,
2341 * and PRIMARY KEY constraints, but someday they ought to be supported
2342 * for other constraint types.
2345 transformConstraintAttrs(CreateStmtContext *cxt, List *constraintList)
2347 Constraint *lastprimarycon = NULL;
2348 bool saw_deferrability = false;
2349 bool saw_initially = false;
2352 #define SUPPORTS_ATTRS(node) \
2353 ((node) != NULL && \
2354 ((node)->contype == CONSTR_PRIMARY || \
2355 (node)->contype == CONSTR_UNIQUE || \
2356 (node)->contype == CONSTR_EXCLUSION || \
2357 (node)->contype == CONSTR_FOREIGN))
2359 foreach(clist, constraintList)
2361 Constraint *con = (Constraint *) lfirst(clist);
2363 if (!IsA(con, Constraint))
2364 elog(ERROR, "unrecognized node type: %d",
2365 (int) nodeTag(con));
2366 switch (con->contype)
2368 case CONSTR_ATTR_DEFERRABLE:
2369 if (!SUPPORTS_ATTRS(lastprimarycon))
2371 (errcode(ERRCODE_SYNTAX_ERROR),
2372 errmsg("misplaced DEFERRABLE clause"),
2373 parser_errposition(cxt->pstate, con->location)));
2374 if (saw_deferrability)
2376 (errcode(ERRCODE_SYNTAX_ERROR),
2377 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2378 parser_errposition(cxt->pstate, con->location)));
2379 saw_deferrability = true;
2380 lastprimarycon->deferrable = true;
2383 case CONSTR_ATTR_NOT_DEFERRABLE:
2384 if (!SUPPORTS_ATTRS(lastprimarycon))
2386 (errcode(ERRCODE_SYNTAX_ERROR),
2387 errmsg("misplaced NOT DEFERRABLE clause"),
2388 parser_errposition(cxt->pstate, con->location)));
2389 if (saw_deferrability)
2391 (errcode(ERRCODE_SYNTAX_ERROR),
2392 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2393 parser_errposition(cxt->pstate, con->location)));
2394 saw_deferrability = true;
2395 lastprimarycon->deferrable = false;
2396 if (saw_initially &&
2397 lastprimarycon->initdeferred)
2399 (errcode(ERRCODE_SYNTAX_ERROR),
2400 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2401 parser_errposition(cxt->pstate, con->location)));
2404 case CONSTR_ATTR_DEFERRED:
2405 if (!SUPPORTS_ATTRS(lastprimarycon))
2407 (errcode(ERRCODE_SYNTAX_ERROR),
2408 errmsg("misplaced INITIALLY DEFERRED clause"),
2409 parser_errposition(cxt->pstate, con->location)));
2412 (errcode(ERRCODE_SYNTAX_ERROR),
2413 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2414 parser_errposition(cxt->pstate, con->location)));
2415 saw_initially = true;
2416 lastprimarycon->initdeferred = true;
2419 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
2421 if (!saw_deferrability)
2422 lastprimarycon->deferrable = true;
2423 else if (!lastprimarycon->deferrable)
2425 (errcode(ERRCODE_SYNTAX_ERROR),
2426 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2427 parser_errposition(cxt->pstate, con->location)));
2430 case CONSTR_ATTR_IMMEDIATE:
2431 if (!SUPPORTS_ATTRS(lastprimarycon))
2433 (errcode(ERRCODE_SYNTAX_ERROR),
2434 errmsg("misplaced INITIALLY IMMEDIATE clause"),
2435 parser_errposition(cxt->pstate, con->location)));
2438 (errcode(ERRCODE_SYNTAX_ERROR),
2439 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2440 parser_errposition(cxt->pstate, con->location)));
2441 saw_initially = true;
2442 lastprimarycon->initdeferred = false;
2446 /* Otherwise it's not an attribute */
2447 lastprimarycon = con;
2448 /* reset flags for new primary node */
2449 saw_deferrability = false;
2450 saw_initially = false;
2457 * Special handling of type definition for a column
2460 transformColumnType(CreateStmtContext *cxt, ColumnDef *column)
2463 * All we really need to do here is verify that the type is valid,
2464 * including any collation spec that might be present.
2466 Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
2468 if (column->collClause)
2470 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
2473 collOid = LookupCollation(cxt->pstate,
2474 column->collClause->collname,
2475 column->collClause->location);
2476 /* Complain if COLLATE is applied to an uncollatable type */
2477 if (!OidIsValid(typtup->typcollation))
2479 (errcode(ERRCODE_DATATYPE_MISMATCH),
2480 errmsg("collations are not supported by type %s",
2481 format_type_be(HeapTupleGetOid(ctype))),
2482 parser_errposition(cxt->pstate,
2483 column->collClause->location)));
2486 ReleaseSysCache(ctype);
2491 * transformCreateSchemaStmt -
2492 * analyzes the CREATE SCHEMA statement
2494 * Split the schema element list into individual commands and place
2495 * them in the result list in an order such that there are no forward
2496 * references (e.g. GRANT to a table created later in the list). Note
2497 * that the logic we use for determining forward references is
2498 * presently quite incomplete.
2500 * SQL92 also allows constraints to make forward references, so thumb through
2501 * the table columns and move forward references to a posterior alter-table
2504 * The result is a list of parse nodes that still need to be analyzed ---
2505 * but we can't analyze the later commands until we've executed the earlier
2506 * ones, because of possible inter-object references.
2508 * Note: this breaks the rules a little bit by modifying schema-name fields
2509 * within passed-in structs. However, the transformation would be the same
2510 * if done over, so it should be all right to scribble on the input to this
2514 transformCreateSchemaStmt(CreateSchemaStmt *stmt)
2516 CreateSchemaStmtContext cxt;
2520 cxt.stmtType = "CREATE SCHEMA";
2521 cxt.schemaname = stmt->schemaname;
2522 cxt.authid = stmt->authid;
2523 cxt.sequences = NIL;
2531 * Run through each schema element in the schema element list. Separate
2532 * statements by type, and do preliminary analysis.
2534 foreach(elements, stmt->schemaElts)
2536 Node *element = lfirst(elements);
2538 switch (nodeTag(element))
2540 case T_CreateSeqStmt:
2542 CreateSeqStmt *elp = (CreateSeqStmt *) element;
2544 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
2545 cxt.sequences = lappend(cxt.sequences, element);
2551 CreateStmt *elp = (CreateStmt *) element;
2553 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2556 * XXX todo: deal with constraints
2558 cxt.tables = lappend(cxt.tables, element);
2564 ViewStmt *elp = (ViewStmt *) element;
2566 setSchemaName(cxt.schemaname, &elp->view->schemaname);
2569 * XXX todo: deal with references between views
2571 cxt.views = lappend(cxt.views, element);
2577 IndexStmt *elp = (IndexStmt *) element;
2579 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2580 cxt.indexes = lappend(cxt.indexes, element);
2584 case T_CreateTrigStmt:
2586 CreateTrigStmt *elp = (CreateTrigStmt *) element;
2588 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2589 cxt.triggers = lappend(cxt.triggers, element);
2594 cxt.grants = lappend(cxt.grants, element);
2598 elog(ERROR, "unrecognized node type: %d",
2599 (int) nodeTag(element));
2604 result = list_concat(result, cxt.sequences);
2605 result = list_concat(result, cxt.tables);
2606 result = list_concat(result, cxt.views);
2607 result = list_concat(result, cxt.indexes);
2608 result = list_concat(result, cxt.triggers);
2609 result = list_concat(result, cxt.grants);
2616 * Set or check schema name in an element of a CREATE SCHEMA command
2619 setSchemaName(char *context_schema, char **stmt_schema_name)
2621 if (*stmt_schema_name == NULL)
2622 *stmt_schema_name = context_schema;
2623 else if (strcmp(context_schema, *stmt_schema_name) != 0)
2625 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
2626 errmsg("CREATE specifies a schema (%s) "
2627 "different from the one being created (%s)",
2628 *stmt_schema_name, context_schema)));