1 /*-------------------------------------------------------------------------
4 * Perform parse analysis work for various utility commands
6 * Formerly we did this work during parse_analyze() in analyze.c. However
7 * that is fairly unsafe in the presence of querytree caching, since any
8 * database state that we depend on in making the transformations might be
9 * obsolete by the time the utility command is executed; and utility commands
10 * have no infrastructure for holding locks or rechecking plan validity.
11 * Hence these functions are now called at the start of execution of their
12 * respective utility commands.
14 * NOTE: in general we must avoid scribbling on the passed-in raw parse
15 * tree, since it might be in a plan cache. The simplest solution is
16 * a quick copyObject() call before manipulating the query tree.
19 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
20 * Portions Copyright (c) 1994, Regents of the University of California
22 * src/backend/parser/parse_utilcmd.c
24 *-------------------------------------------------------------------------
29 #include "access/genam.h"
30 #include "access/heapam.h"
31 #include "access/reloptions.h"
32 #include "catalog/dependency.h"
33 #include "catalog/heap.h"
34 #include "catalog/index.h"
35 #include "catalog/namespace.h"
36 #include "catalog/pg_constraint.h"
37 #include "catalog/pg_opclass.h"
38 #include "catalog/pg_operator.h"
39 #include "catalog/pg_type.h"
40 #include "commands/comment.h"
41 #include "commands/defrem.h"
42 #include "commands/tablecmds.h"
43 #include "commands/tablespace.h"
44 #include "miscadmin.h"
45 #include "nodes/makefuncs.h"
46 #include "nodes/nodeFuncs.h"
47 #include "parser/analyze.h"
48 #include "parser/parse_clause.h"
49 #include "parser/parse_expr.h"
50 #include "parser/parse_relation.h"
51 #include "parser/parse_target.h"
52 #include "parser/parse_type.h"
53 #include "parser/parse_utilcmd.h"
54 #include "parser/parser.h"
55 #include "rewrite/rewriteManip.h"
56 #include "storage/lock.h"
57 #include "utils/acl.h"
58 #include "utils/builtins.h"
59 #include "utils/lsyscache.h"
60 #include "utils/relcache.h"
61 #include "utils/syscache.h"
62 #include "utils/typcache.h"
65 /* State shared by transformCreateStmt and its subroutines */
68 const char *stmtType; /* "CREATE TABLE" or "ALTER TABLE" */
69 RangeVar *relation; /* relation to create */
70 Relation rel; /* opened/locked rel, if ALTER */
71 List *inhRelations; /* relations to inherit from */
72 bool isalter; /* true if altering existing table */
73 bool hasoids; /* does relation have an OID column? */
74 List *columns; /* ColumnDef items */
75 List *ckconstraints; /* CHECK constraints */
76 List *fkconstraints; /* FOREIGN KEY constraints */
77 List *ixconstraints; /* index-creating constraints */
78 List *inh_indexes; /* cloned indexes from INCLUDING INDEXES */
79 List *blist; /* "before list" of things to do before
80 * creating the table */
81 List *alist; /* "after list" of things to do after creating
83 IndexStmt *pkey; /* PRIMARY KEY index, if any */
86 /* State shared by transformCreateSchemaStmt and its subroutines */
89 const char *stmtType; /* "CREATE SCHEMA" or "ALTER SCHEMA" */
90 char *schemaname; /* name of schema */
91 char *authid; /* owner of schema */
92 List *sequences; /* CREATE SEQUENCE items */
93 List *tables; /* CREATE TABLE items */
94 List *views; /* CREATE VIEW items */
95 List *indexes; /* CREATE INDEX items */
96 List *triggers; /* CREATE TRIGGER items */
97 List *grants; /* GRANT items */
98 } CreateSchemaStmtContext;
101 static void transformColumnDefinition(ParseState *pstate,
102 CreateStmtContext *cxt,
104 static void transformTableConstraint(ParseState *pstate,
105 CreateStmtContext *cxt,
106 Constraint *constraint);
107 static void transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
108 InhRelation *inhrelation);
109 static void transformOfType(ParseState *pstate, 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(ParseState *pstate,
116 CreateStmtContext *cxt);
117 static IndexStmt *transformIndexConstraint(Constraint *constraint,
118 CreateStmtContext *cxt);
119 static void transformFKConstraints(ParseState *pstate,
120 CreateStmtContext *cxt,
122 bool isAddConstraint);
123 static void transformConstraintAttrs(ParseState *pstate, List *constraintList);
124 static void transformColumnType(ParseState *pstate, ColumnDef *column);
125 static void setSchemaName(char *context_schema, char **stmt_schema_name);
129 * transformCreateStmt -
130 * parse analysis for CREATE TABLE
132 * Returns a List of utility commands to be done in sequence. One of these
133 * will be the transformed CreateStmt, but there may be additional actions
134 * to be done before and after the actual DefineRelation() call.
136 * SQL92 allows constraints to be scattered all over, so thumb through
137 * the columns and collect all constraints into one place.
138 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
139 * then expand those into multiple IndexStmt blocks.
140 * - thomas 1997-12-02
143 transformCreateStmt(CreateStmt *stmt, const char *queryString)
146 CreateStmtContext cxt;
152 * We must not scribble on the passed-in CreateStmt, so copy it. (This is
153 * overkill, but easy.)
155 stmt = (CreateStmt *) copyObject(stmt);
158 * If the target relation name isn't schema-qualified, make it so. This
159 * prevents some corner cases in which added-on rewritten commands might
160 * think they should apply to other relations that have the same name and
161 * are earlier in the search path. But a local temp table is effectively
162 * specified to be in pg_temp, so no need for anything extra in that case.
164 if (stmt->relation->schemaname == NULL
165 && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
167 Oid namespaceid = RangeVarGetCreationNamespace(stmt->relation);
169 stmt->relation->schemaname = get_namespace_name(namespaceid);
173 pstate = make_parsestate(NULL);
174 pstate->p_sourcetext = queryString;
176 cxt.stmtType = "CREATE TABLE";
177 cxt.relation = stmt->relation;
179 cxt.inhRelations = stmt->inhRelations;
182 cxt.ckconstraints = NIL;
183 cxt.fkconstraints = NIL;
184 cxt.ixconstraints = NIL;
185 cxt.inh_indexes = NIL;
189 cxt.hasoids = interpretOidsOption(stmt->options);
191 Assert(!stmt->ofTypename || !stmt->inhRelations); /* grammar enforces */
193 if (stmt->ofTypename)
194 transformOfType(pstate, &cxt, stmt->ofTypename);
197 * Run through each primary element in the table creation clause. Separate
198 * column defs from constraints, and do preliminary analysis.
200 foreach(elements, stmt->tableElts)
202 Node *element = lfirst(elements);
204 switch (nodeTag(element))
207 transformColumnDefinition(pstate, &cxt,
208 (ColumnDef *) element);
212 transformTableConstraint(pstate, &cxt,
213 (Constraint *) element);
217 transformInhRelation(pstate, &cxt,
218 (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(pstate, &cxt);
243 * Postprocess foreign-key constraints.
245 transformFKConstraints(pstate, &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(ParseState *pstate, CreateStmtContext *cxt,
272 Constraint *constraint;
275 cxt->columns = lappend(cxt->columns, column);
277 /* Check for SERIAL pseudo-types */
280 && list_length(column->typeName->names) == 1
281 && !column->typeName->pct_type)
283 char *typname = strVal(linitial(column->typeName->names));
285 if (strcmp(typname, "serial") == 0 ||
286 strcmp(typname, "serial4") == 0)
289 column->typeName->names = NIL;
290 column->typeName->typeOid = INT4OID;
292 else if (strcmp(typname, "bigserial") == 0 ||
293 strcmp(typname, "serial8") == 0)
296 column->typeName->names = NIL;
297 column->typeName->typeOid = INT8OID;
301 * We have to reject "serial[]" explicitly, because once we've set
302 * typeid, LookupTypeName won't notice arrayBounds. We don't need any
303 * special coding for serial(typmod) though.
305 if (is_serial && column->typeName->arrayBounds != NIL)
307 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
308 errmsg("array of serial is not implemented"),
309 parser_errposition(pstate, column->typeName->location)));
312 /* Do necessary work on the column type declaration */
313 if (column->typeName)
314 transformColumnType(pstate, 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(pstate, 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(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(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(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(ParseState *pstate, CreateStmtContext *cxt,
533 Constraint *constraint)
535 switch (constraint->contype)
539 case CONSTR_EXCLUSION:
540 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
544 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
548 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
554 case CONSTR_ATTR_DEFERRABLE:
555 case CONSTR_ATTR_NOT_DEFERRABLE:
556 case CONSTR_ATTR_DEFERRED:
557 case CONSTR_ATTR_IMMEDIATE:
558 elog(ERROR, "invalid context for constraint type %d",
559 constraint->contype);
563 elog(ERROR, "unrecognized constraint type: %d",
564 constraint->contype);
570 * transformInhRelation
572 * Change the LIKE <subtable> portion of a CREATE TABLE statement into
573 * column definitions which recreate the user defined column portions of
577 transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
578 InhRelation *inhRelation)
580 AttrNumber parent_attno;
587 relation = parserOpenTable(pstate, inhRelation->relation, AccessShareLock);
589 if (relation->rd_rel->relkind != RELKIND_RELATION)
591 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
592 errmsg("inherited relation \"%s\" is not a table",
593 inhRelation->relation->relname)));
596 * Check for SELECT privilages
598 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
600 if (aclresult != ACLCHECK_OK)
601 aclcheck_error(aclresult, ACL_KIND_CLASS,
602 RelationGetRelationName(relation));
604 tupleDesc = RelationGetDescr(relation);
605 constr = tupleDesc->constr;
608 * Insert the copied attributes into the cxt for the new table definition.
610 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
613 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
614 char *attributeName = NameStr(attribute->attname);
618 * Ignore dropped columns in the parent.
620 if (attribute->attisdropped)
624 * Create a new column, which is marked as NOT inherited.
626 * For constraints, ONLY the NOT NULL constraint is inherited by the
627 * new column definition per SQL99.
629 def = makeNode(ColumnDef);
630 def->colname = pstrdup(attributeName);
631 def->typeName = makeTypeNameFromOid(attribute->atttypid,
632 attribute->atttypmod);
634 def->is_local = true;
635 def->is_not_null = attribute->attnotnull;
636 def->raw_default = NULL;
637 def->cooked_default = NULL;
638 def->constraints = NIL;
643 cxt->columns = lappend(cxt->columns, def);
646 * Copy default, if present and the default has been requested
648 if (attribute->atthasdef &&
649 (inhRelation->options & CREATE_TABLE_LIKE_DEFAULTS))
651 Node *this_default = NULL;
652 AttrDefault *attrdef;
655 /* Find default in constraint structure */
656 Assert(constr != NULL);
657 attrdef = constr->defval;
658 for (i = 0; i < constr->num_defval; i++)
660 if (attrdef[i].adnum == parent_attno)
662 this_default = stringToNode(attrdef[i].adbin);
666 Assert(this_default != NULL);
669 * If default expr could contain any vars, we'd need to fix 'em,
670 * but it can't; so default is ready to apply to child.
673 def->cooked_default = this_default;
676 /* Likewise, copy storage if requested */
677 if (inhRelation->options & CREATE_TABLE_LIKE_STORAGE)
678 def->storage = attribute->attstorage;
682 /* Likewise, copy comment if requested */
683 if ((inhRelation->options & CREATE_TABLE_LIKE_COMMENTS) &&
684 (comment = GetComment(attribute->attrelid,
686 attribute->attnum)) != NULL)
688 CommentStmt *stmt = makeNode(CommentStmt);
690 stmt->objtype = OBJECT_COLUMN;
691 stmt->objname = list_make3(makeString(cxt->relation->schemaname),
692 makeString(cxt->relation->relname),
693 makeString(def->colname));
695 stmt->comment = comment;
697 cxt->alist = lappend(cxt->alist, stmt);
702 * Copy CHECK constraints if requested, being careful to adjust attribute
705 if ((inhRelation->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
708 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
711 for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
713 char *ccname = tupleDesc->constr->check[ccnum].ccname;
714 char *ccbin = tupleDesc->constr->check[ccnum].ccbin;
715 Node *ccbin_node = stringToNode(ccbin);
716 Constraint *n = makeNode(Constraint);
718 change_varattnos_of_a_node(ccbin_node, attmap);
720 n->contype = CONSTR_CHECK;
722 n->conname = pstrdup(ccname);
724 n->cooked_expr = nodeToString(ccbin_node);
725 cxt->ckconstraints = lappend(cxt->ckconstraints, n);
727 /* Copy comment on constraint */
728 if ((inhRelation->options & CREATE_TABLE_LIKE_COMMENTS) &&
729 (comment = GetComment(get_constraint_oid(RelationGetRelid(relation),
731 ConstraintRelationId,
734 CommentStmt *stmt = makeNode(CommentStmt);
736 stmt->objtype = OBJECT_CONSTRAINT;
737 stmt->objname = list_make3(makeString(cxt->relation->schemaname),
738 makeString(cxt->relation->relname),
739 makeString(n->conname));
741 stmt->comment = comment;
743 cxt->alist = lappend(cxt->alist, stmt);
749 * Likewise, copy indexes if requested
751 if ((inhRelation->options & CREATE_TABLE_LIKE_INDEXES) &&
752 relation->rd_rel->relhasindex)
754 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
755 List *parent_indexes;
758 parent_indexes = RelationGetIndexList(relation);
760 foreach(l, parent_indexes)
762 Oid parent_index_oid = lfirst_oid(l);
763 Relation parent_index;
764 IndexStmt *index_stmt;
766 parent_index = index_open(parent_index_oid, AccessShareLock);
768 /* Build CREATE INDEX statement to recreate the parent_index */
769 index_stmt = generateClonedIndexStmt(cxt, parent_index, attmap);
771 /* Copy comment on index */
772 if (inhRelation->options & CREATE_TABLE_LIKE_COMMENTS)
774 comment = GetComment(parent_index_oid, RelationRelationId, 0);
781 * We have to assign the index a name now, so that we can
782 * reference it in CommentStmt.
784 if (index_stmt->idxname == NULL)
785 index_stmt->idxname = chooseIndexName(cxt->relation,
788 stmt = makeNode(CommentStmt);
789 stmt->objtype = OBJECT_INDEX;
791 list_make2(makeString(cxt->relation->schemaname),
792 makeString(index_stmt->idxname));
794 stmt->comment = comment;
796 cxt->alist = lappend(cxt->alist, stmt);
800 /* Save it in the inh_indexes list for the time being */
801 cxt->inh_indexes = lappend(cxt->inh_indexes, index_stmt);
803 index_close(parent_index, AccessShareLock);
808 * Close the parent rel, but keep our AccessShareLock on it until xact
809 * commit. That will prevent someone else from deleting or ALTERing the
810 * parent before the child is committed.
812 heap_close(relation, NoLock);
816 transformOfType(ParseState *pstate, CreateStmtContext *cxt, TypeName *ofTypename)
824 AssertArg(ofTypename);
826 tuple = typenameType(NULL, ofTypename, NULL);
827 typ = (Form_pg_type) GETSTRUCT(tuple);
828 ofTypeId = HeapTupleGetOid(tuple);
829 ofTypename->typeOid = ofTypeId; /* cached for later */
831 if (typ->typtype != TYPTYPE_COMPOSITE)
833 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
834 errmsg("type %s is not a composite type",
835 format_type_be(ofTypeId))));
837 tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
838 for (i = 0; i < tupdesc->natts; i++)
840 Form_pg_attribute attr = tupdesc->attrs[i];
841 ColumnDef *n = makeNode(ColumnDef);
843 if (attr->attisdropped)
846 n->colname = pstrdup(NameStr(attr->attname));
847 n->typeName = makeTypeNameFromOid(attr->atttypid, attr->atttypmod);
848 n->constraints = NULL;
850 n->is_from_type = true;
851 cxt->columns = lappend(cxt->columns, n);
853 DecrTupleDescRefCount(tupdesc);
855 ReleaseSysCache(tuple);
861 * Compute name for an index. This must match code in indexcmds.c.
863 * XXX this is inherently broken because the indexes aren't created
864 * immediately, so we fail to resolve conflicts when the same name is
865 * derived for multiple indexes. However, that's a reasonably uncommon
866 * situation, so we'll live with it for now.
869 chooseIndexName(const RangeVar *relation, IndexStmt *index_stmt)
874 namespaceId = RangeVarGetCreationNamespace(relation);
875 colnames = ChooseIndexColumnNames(index_stmt->indexParams);
876 return ChooseIndexName(relation->relname, namespaceId,
877 colnames, index_stmt->excludeOpNames,
878 index_stmt->primary, index_stmt->isconstraint);
882 * Generate an IndexStmt node using information from an already existing index
883 * "source_idx". Attribute numbers should be adjusted according to attmap.
886 generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
889 Oid source_relid = RelationGetRelid(source_idx);
890 Form_pg_attribute *attrs = RelationGetDescr(source_idx)->attrs;
893 Form_pg_class idxrelrec;
894 Form_pg_index idxrec;
899 ListCell *indexpr_item;
907 * Fetch pg_class tuple of source index. We can't use the copy in the
908 * relcache entry because it doesn't include optional fields.
910 ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
911 if (!HeapTupleIsValid(ht_idxrel))
912 elog(ERROR, "cache lookup failed for relation %u", source_relid);
913 idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
915 /* Fetch pg_index tuple for source index from relcache entry */
916 ht_idx = source_idx->rd_indextuple;
917 idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
918 indrelid = idxrec->indrelid;
920 /* Fetch pg_am tuple for source index from relcache entry */
921 amrec = source_idx->rd_am;
923 /* Extract indclass from the pg_index tuple */
924 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
925 Anum_pg_index_indclass, &isnull);
927 indclass = (oidvector *) DatumGetPointer(datum);
929 /* Begin building the IndexStmt */
930 index = makeNode(IndexStmt);
931 index->relation = cxt->relation;
932 index->accessMethod = pstrdup(NameStr(amrec->amname));
933 if (OidIsValid(idxrelrec->reltablespace))
934 index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
936 index->tableSpace = NULL;
937 index->unique = idxrec->indisunique;
938 index->primary = idxrec->indisprimary;
939 index->concurrent = false;
942 * We don't try to preserve the name of the source index; instead, just
943 * let DefineIndex() choose a reasonable name.
945 index->idxname = NULL;
948 * If the index is marked PRIMARY or has an exclusion condition, it's
949 * certainly from a constraint; else, if it's not marked UNIQUE, it
950 * certainly isn't. If it is or might be from a constraint, we have to
951 * fetch the pg_constraint record.
953 if (index->primary || index->unique || idxrelrec->relhasexclusion)
955 Oid constraintId = get_index_constraint(source_relid);
957 if (OidIsValid(constraintId))
960 Form_pg_constraint conrec;
962 ht_constr = SearchSysCache1(CONSTROID,
963 ObjectIdGetDatum(constraintId));
964 if (!HeapTupleIsValid(ht_constr))
965 elog(ERROR, "cache lookup failed for constraint %u",
967 conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
969 index->isconstraint = true;
970 index->deferrable = conrec->condeferrable;
971 index->initdeferred = conrec->condeferred;
973 /* If it's an exclusion constraint, we need the operator names */
974 if (idxrelrec->relhasexclusion)
980 Assert(conrec->contype == CONSTRAINT_EXCLUSION);
981 /* Extract operator OIDs from the pg_constraint tuple */
982 datum = SysCacheGetAttr(CONSTROID, ht_constr,
983 Anum_pg_constraint_conexclop,
986 elog(ERROR, "null conexclop for constraint %u",
989 deconstruct_array(DatumGetArrayTypeP(datum),
990 OIDOID, sizeof(Oid), true, 'i',
991 &elems, NULL, &nElems);
993 for (i = 0; i < nElems; i++)
995 Oid operid = DatumGetObjectId(elems[i]);
997 Form_pg_operator operform;
1002 opertup = SearchSysCache1(OPEROID,
1003 ObjectIdGetDatum(operid));
1004 if (!HeapTupleIsValid(opertup))
1005 elog(ERROR, "cache lookup failed for operator %u",
1007 operform = (Form_pg_operator) GETSTRUCT(opertup);
1008 oprname = pstrdup(NameStr(operform->oprname));
1009 /* For simplicity we always schema-qualify the op name */
1010 nspname = get_namespace_name(operform->oprnamespace);
1011 namelist = list_make2(makeString(nspname),
1012 makeString(oprname));
1013 index->excludeOpNames = lappend(index->excludeOpNames,
1015 ReleaseSysCache(opertup);
1019 ReleaseSysCache(ht_constr);
1022 index->isconstraint = false;
1025 index->isconstraint = false;
1027 /* Get the index expressions, if any */
1028 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1029 Anum_pg_index_indexprs, &isnull);
1034 exprsString = TextDatumGetCString(datum);
1035 indexprs = (List *) stringToNode(exprsString);
1040 /* Build the list of IndexElem */
1041 index->indexParams = NIL;
1043 indexpr_item = list_head(indexprs);
1044 for (keyno = 0; keyno < idxrec->indnatts; keyno++)
1047 AttrNumber attnum = idxrec->indkey.values[keyno];
1048 int16 opt = source_idx->rd_indoption[keyno];
1050 iparam = makeNode(IndexElem);
1052 if (AttributeNumberIsValid(attnum))
1054 /* Simple index column */
1057 attname = get_relid_attribute_name(indrelid, attnum);
1058 keycoltype = get_atttype(indrelid, attnum);
1060 iparam->name = attname;
1061 iparam->expr = NULL;
1065 /* Expressional index */
1068 if (indexpr_item == NULL)
1069 elog(ERROR, "too few entries in indexprs list");
1070 indexkey = (Node *) lfirst(indexpr_item);
1071 indexpr_item = lnext(indexpr_item);
1073 /* OK to modify indexkey since we are working on a private copy */
1074 change_varattnos_of_a_node(indexkey, attmap);
1076 iparam->name = NULL;
1077 iparam->expr = indexkey;
1079 keycoltype = exprType(indexkey);
1082 /* Copy the original index column name */
1083 iparam->indexcolname = pstrdup(NameStr(attrs[keyno]->attname));
1085 /* Add the operator class name, if non-default */
1086 iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1088 iparam->ordering = SORTBY_DEFAULT;
1089 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1091 /* Adjust options if necessary */
1092 if (amrec->amcanorder)
1095 * If it supports sort ordering, copy DESC and NULLS opts. Don't
1096 * set non-default settings unnecessarily, though, so as to
1097 * improve the chance of recognizing equivalence to constraint
1100 if (opt & INDOPTION_DESC)
1102 iparam->ordering = SORTBY_DESC;
1103 if ((opt & INDOPTION_NULLS_FIRST) == 0)
1104 iparam->nulls_ordering = SORTBY_NULLS_LAST;
1108 if (opt & INDOPTION_NULLS_FIRST)
1109 iparam->nulls_ordering = SORTBY_NULLS_FIRST;
1113 index->indexParams = lappend(index->indexParams, iparam);
1116 /* Copy reloptions if any */
1117 datum = SysCacheGetAttr(RELOID, ht_idxrel,
1118 Anum_pg_class_reloptions, &isnull);
1120 index->options = untransformRelOptions(datum);
1122 /* If it's a partial index, decompile and append the predicate */
1123 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1124 Anum_pg_index_indpred, &isnull);
1129 /* Convert text string to node tree */
1130 pred_str = TextDatumGetCString(datum);
1131 index->whereClause = (Node *) stringToNode(pred_str);
1132 /* Adjust attribute numbers */
1133 change_varattnos_of_a_node(index->whereClause, attmap);
1137 ReleaseSysCache(ht_idxrel);
1143 * get_opclass - fetch name of an index operator class
1145 * If the opclass is the default for the given actual_datatype, then
1146 * the return value is NIL.
1149 get_opclass(Oid opclass, Oid actual_datatype)
1152 Form_pg_opclass opc_rec;
1155 ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1156 if (!HeapTupleIsValid(ht_opc))
1157 elog(ERROR, "cache lookup failed for opclass %u", opclass);
1158 opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
1160 if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
1162 /* For simplicity, we always schema-qualify the name */
1163 char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
1164 char *opc_name = pstrdup(NameStr(opc_rec->opcname));
1166 result = list_make2(makeString(nsp_name), makeString(opc_name));
1169 ReleaseSysCache(ht_opc);
1175 * transformIndexConstraints
1176 * Handle UNIQUE, PRIMARY KEY, EXCLUDE constraints, which create indexes.
1177 * We also merge in any index definitions arising from
1178 * LIKE ... INCLUDING INDEXES.
1181 transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
1184 List *indexlist = NIL;
1188 * Run through the constraints that need to generate an index. For PRIMARY
1189 * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
1190 * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
1193 foreach(lc, cxt->ixconstraints)
1195 Constraint *constraint = (Constraint *) lfirst(lc);
1197 Assert(IsA(constraint, Constraint));
1198 Assert(constraint->contype == CONSTR_PRIMARY ||
1199 constraint->contype == CONSTR_UNIQUE ||
1200 constraint->contype == CONSTR_EXCLUSION);
1202 index = transformIndexConstraint(constraint, cxt);
1204 indexlist = lappend(indexlist, index);
1207 /* Add in any indexes defined by LIKE ... INCLUDING INDEXES */
1208 foreach(lc, cxt->inh_indexes)
1210 index = (IndexStmt *) lfirst(lc);
1214 if (cxt->pkey != NULL)
1216 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1217 errmsg("multiple primary keys for table \"%s\" are not allowed",
1218 cxt->relation->relname)));
1222 indexlist = lappend(indexlist, index);
1226 * Scan the index list and remove any redundant index specifications. This
1227 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1228 * strict reading of SQL92 would suggest raising an error instead, but
1229 * that strikes me as too anal-retentive. - tgl 2001-02-14
1231 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1232 * pre-existing indexes, too.
1234 Assert(cxt->alist == NIL);
1235 if (cxt->pkey != NULL)
1237 /* Make sure we keep the PKEY index in preference to others... */
1238 cxt->alist = list_make1(cxt->pkey);
1241 foreach(lc, indexlist)
1248 /* if it's pkey, it's already in cxt->alist */
1249 if (index == cxt->pkey)
1252 foreach(k, cxt->alist)
1254 IndexStmt *priorindex = lfirst(k);
1256 if (equal(index->indexParams, priorindex->indexParams) &&
1257 equal(index->whereClause, priorindex->whereClause) &&
1258 equal(index->excludeOpNames, priorindex->excludeOpNames) &&
1259 strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
1260 index->deferrable == priorindex->deferrable &&
1261 index->initdeferred == priorindex->initdeferred)
1263 priorindex->unique |= index->unique;
1266 * If the prior index is as yet unnamed, and this one is
1267 * named, then transfer the name to the prior index. This
1268 * ensures that if we have named and unnamed constraints,
1269 * we'll use (at least one of) the names for the index.
1271 if (priorindex->idxname == NULL)
1272 priorindex->idxname = index->idxname;
1279 cxt->alist = lappend(cxt->alist, index);
1284 * transformIndexConstraint
1285 * Transform one UNIQUE, PRIMARY KEY, or EXCLUDE constraint for
1286 * transformIndexConstraints.
1289 transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
1294 index = makeNode(IndexStmt);
1296 index->unique = (constraint->contype != CONSTR_EXCLUSION);
1297 index->primary = (constraint->contype == CONSTR_PRIMARY);
1300 if (cxt->pkey != NULL)
1302 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1303 errmsg("multiple primary keys for table \"%s\" are not allowed",
1304 cxt->relation->relname)));
1308 * In ALTER TABLE case, a primary index might already exist, but
1309 * DefineIndex will check for it.
1312 index->isconstraint = true;
1313 index->deferrable = constraint->deferrable;
1314 index->initdeferred = constraint->initdeferred;
1316 if (constraint->conname != NULL)
1317 index->idxname = pstrdup(constraint->conname);
1319 index->idxname = NULL; /* DefineIndex will choose name */
1321 index->relation = cxt->relation;
1322 index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
1323 index->options = constraint->options;
1324 index->tableSpace = constraint->indexspace;
1325 index->whereClause = constraint->where_clause;
1326 index->indexParams = NIL;
1327 index->excludeOpNames = NIL;
1328 index->concurrent = false;
1331 * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
1332 * IndexElems and operator names. We have to break that apart into
1335 if (constraint->contype == CONSTR_EXCLUSION)
1337 foreach(lc, constraint->exclusions)
1339 List *pair = (List *) lfirst(lc);
1343 Assert(list_length(pair) == 2);
1344 elem = (IndexElem *) linitial(pair);
1345 Assert(IsA(elem, IndexElem));
1346 opname = (List *) lsecond(pair);
1347 Assert(IsA(opname, List));
1349 index->indexParams = lappend(index->indexParams, elem);
1350 index->excludeOpNames = lappend(index->excludeOpNames, opname);
1357 * For UNIQUE and PRIMARY KEY, we just have a list of column names.
1359 * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
1360 * also make sure they are NOT NULL, if possible. (Although we could leave
1361 * it to DefineIndex to mark the columns NOT NULL, it's more efficient to
1362 * get it right the first time.)
1364 foreach(lc, constraint->keys)
1366 char *key = strVal(lfirst(lc));
1368 ColumnDef *column = NULL;
1372 foreach(columns, cxt->columns)
1374 column = (ColumnDef *) lfirst(columns);
1375 Assert(IsA(column, ColumnDef));
1376 if (strcmp(column->colname, key) == 0)
1384 /* found column in the new table; force it to be NOT NULL */
1385 if (constraint->contype == CONSTR_PRIMARY)
1386 column->is_not_null = TRUE;
1388 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1391 * column will be a system column in the new table, so accept it.
1392 * System columns can't ever be null, so no need to worry about
1393 * PRIMARY/NOT NULL constraint.
1397 else if (cxt->inhRelations)
1399 /* try inherited tables */
1402 foreach(inher, cxt->inhRelations)
1404 RangeVar *inh = (RangeVar *) lfirst(inher);
1408 Assert(IsA(inh, RangeVar));
1409 rel = heap_openrv(inh, AccessShareLock);
1410 if (rel->rd_rel->relkind != RELKIND_RELATION)
1412 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1413 errmsg("inherited relation \"%s\" is not a table",
1415 for (count = 0; count < rel->rd_att->natts; count++)
1417 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1418 char *inhname = NameStr(inhattr->attname);
1420 if (inhattr->attisdropped)
1422 if (strcmp(key, inhname) == 0)
1427 * We currently have no easy way to force an inherited
1428 * column to be NOT NULL at creation, if its parent
1429 * wasn't so already. We leave it to DefineIndex to
1430 * fix things up in this case.
1435 heap_close(rel, NoLock);
1442 * In the ALTER TABLE case, don't complain about index keys not
1443 * created in the command; they may well exist already. DefineIndex
1444 * will complain about them if not, and will also take care of marking
1447 if (!found && !cxt->isalter)
1449 (errcode(ERRCODE_UNDEFINED_COLUMN),
1450 errmsg("column \"%s\" named in key does not exist",
1453 /* Check for PRIMARY KEY(foo, foo) */
1454 foreach(columns, index->indexParams)
1456 iparam = (IndexElem *) lfirst(columns);
1457 if (iparam->name && strcmp(key, iparam->name) == 0)
1461 (errcode(ERRCODE_DUPLICATE_COLUMN),
1462 errmsg("column \"%s\" appears twice in primary key constraint",
1466 (errcode(ERRCODE_DUPLICATE_COLUMN),
1467 errmsg("column \"%s\" appears twice in unique constraint",
1472 /* OK, add it to the index definition */
1473 iparam = makeNode(IndexElem);
1474 iparam->name = pstrdup(key);
1475 iparam->expr = NULL;
1476 iparam->indexcolname = NULL;
1477 iparam->opclass = NIL;
1478 iparam->ordering = SORTBY_DEFAULT;
1479 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1480 index->indexParams = lappend(index->indexParams, iparam);
1487 * transformFKConstraints
1488 * handle FOREIGN KEY constraints
1491 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1492 bool skipValidation, bool isAddConstraint)
1496 if (cxt->fkconstraints == NIL)
1500 * If CREATE TABLE or adding a column with NULL default, we can safely
1501 * skip validation of the constraint.
1505 foreach(fkclist, cxt->fkconstraints)
1507 Constraint *constraint = (Constraint *) lfirst(fkclist);
1509 constraint->skip_validation = true;
1514 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1515 * CONSTRAINT command to execute after the basic command is complete. (If
1516 * called from ADD CONSTRAINT, that routine will add the FK constraints to
1517 * its own subcommand list.)
1519 * Note: the ADD CONSTRAINT command must also execute after any index
1520 * creation commands. Thus, this should run after
1521 * transformIndexConstraints, so that the CREATE INDEX commands are
1522 * already in cxt->alist.
1524 if (!isAddConstraint)
1526 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1528 alterstmt->relation = cxt->relation;
1529 alterstmt->cmds = NIL;
1530 alterstmt->relkind = OBJECT_TABLE;
1532 foreach(fkclist, cxt->fkconstraints)
1534 Constraint *constraint = (Constraint *) lfirst(fkclist);
1535 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1537 altercmd->subtype = AT_ProcessedConstraint;
1538 altercmd->name = NULL;
1539 altercmd->def = (Node *) constraint;
1540 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1543 cxt->alist = lappend(cxt->alist, alterstmt);
1548 * transformIndexStmt - parse analysis for CREATE INDEX and ALTER TABLE
1550 * Note: this is a no-op for an index not using either index expressions or
1551 * a predicate expression. There are several code paths that create indexes
1552 * without bothering to call this, because they know they don't have any
1553 * such expressions to deal with.
1556 transformIndexStmt(IndexStmt *stmt, const char *queryString)
1564 * We must not scribble on the passed-in IndexStmt, so copy it. (This is
1565 * overkill, but easy.)
1567 stmt = (IndexStmt *) copyObject(stmt);
1570 * Open the parent table with appropriate locking. We must do this
1571 * because addRangeTableEntry() would acquire only AccessShareLock,
1572 * leaving DefineIndex() needing to do a lock upgrade with consequent risk
1573 * of deadlock. Make sure this stays in sync with the type of lock
1574 * DefineIndex() wants. If we are being called by ALTER TABLE, we will
1575 * already hold a higher lock.
1577 rel = heap_openrv(stmt->relation,
1578 (stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock));
1581 pstate = make_parsestate(NULL);
1582 pstate->p_sourcetext = queryString;
1585 * Put the parent table into the rtable so that the expressions can refer
1586 * to its fields without qualification.
1588 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1590 /* no to join list, yes to namespaces */
1591 addRTEtoQuery(pstate, rte, false, true, true);
1593 /* take care of the where clause */
1594 if (stmt->whereClause)
1595 stmt->whereClause = transformWhereClause(pstate,
1599 /* take care of any index expressions */
1600 foreach(l, stmt->indexParams)
1602 IndexElem *ielem = (IndexElem *) lfirst(l);
1606 /* Extract preliminary index col name before transforming expr */
1607 if (ielem->indexcolname == NULL)
1608 ielem->indexcolname = FigureIndexColname(ielem->expr);
1610 /* Now do parse transformation of the expression */
1611 ielem->expr = transformExpr(pstate, ielem->expr);
1614 * We check only that the result type is legitimate; this is for
1615 * consistency with what transformWhereClause() checks for the
1616 * predicate. DefineIndex() will make more checks.
1618 if (expression_returns_set(ielem->expr))
1620 (errcode(ERRCODE_DATATYPE_MISMATCH),
1621 errmsg("index expression cannot return a set")));
1626 * Check that only the base rel is mentioned.
1628 if (list_length(pstate->p_rtable) != 1)
1630 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1631 errmsg("index expressions and predicates can refer only to the table being indexed")));
1633 free_parsestate(pstate);
1635 /* Close relation, but keep the lock */
1636 heap_close(rel, NoLock);
1643 * transformRuleStmt -
1644 * transform a CREATE RULE Statement. The action is a list of parse
1645 * trees which is transformed into a list of query trees, and we also
1646 * transform the WHERE clause if any.
1648 * actions and whereClause are output parameters that receive the
1649 * transformed results.
1651 * Note that we must not scribble on the passed-in RuleStmt, so we do
1652 * copyObject() on the actions and WHERE clause.
1655 transformRuleStmt(RuleStmt *stmt, const char *queryString,
1656 List **actions, Node **whereClause)
1660 RangeTblEntry *oldrte;
1661 RangeTblEntry *newrte;
1664 * To avoid deadlock, make sure the first thing we do is grab
1665 * AccessExclusiveLock on the target relation. This will be needed by
1666 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1669 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1672 pstate = make_parsestate(NULL);
1673 pstate->p_sourcetext = queryString;
1676 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1677 * Set up their RTEs in the main pstate for use in parsing the rule
1680 oldrte = addRangeTableEntryForRelation(pstate, rel,
1681 makeAlias("old", NIL),
1683 newrte = addRangeTableEntryForRelation(pstate, rel,
1684 makeAlias("new", NIL),
1686 /* Must override addRangeTableEntry's default access-check flags */
1687 oldrte->requiredPerms = 0;
1688 newrte->requiredPerms = 0;
1691 * They must be in the namespace too for lookup purposes, but only add the
1692 * one(s) that are relevant for the current kind of rule. In an UPDATE
1693 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1694 * there's no need to be so picky for INSERT & DELETE. We do not add them
1697 switch (stmt->event)
1700 addRTEtoQuery(pstate, oldrte, false, true, true);
1703 addRTEtoQuery(pstate, oldrte, false, true, true);
1704 addRTEtoQuery(pstate, newrte, false, true, true);
1707 addRTEtoQuery(pstate, newrte, false, true, true);
1710 addRTEtoQuery(pstate, oldrte, false, true, true);
1713 elog(ERROR, "unrecognized event type: %d",
1718 /* take care of the where clause */
1719 *whereClause = transformWhereClause(pstate,
1720 (Node *) copyObject(stmt->whereClause),
1723 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
1725 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1726 errmsg("rule WHERE condition cannot contain references to other relations")));
1728 /* aggregates not allowed (but subselects are okay) */
1729 if (pstate->p_hasAggs)
1731 (errcode(ERRCODE_GROUPING_ERROR),
1732 errmsg("cannot use aggregate function in rule WHERE condition")));
1733 if (pstate->p_hasWindowFuncs)
1735 (errcode(ERRCODE_WINDOWING_ERROR),
1736 errmsg("cannot use window function in rule WHERE condition")));
1739 * 'instead nothing' rules with a qualification need a query rangetable so
1740 * the rewrite handler can add the negated rule qualification to the
1741 * original query. We create a query with the new command type CMD_NOTHING
1742 * here that is treated specially by the rewrite system.
1744 if (stmt->actions == NIL)
1746 Query *nothing_qry = makeNode(Query);
1748 nothing_qry->commandType = CMD_NOTHING;
1749 nothing_qry->rtable = pstate->p_rtable;
1750 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1752 *actions = list_make1(nothing_qry);
1757 List *newactions = NIL;
1760 * transform each statement, like parse_sub_analyze()
1762 foreach(l, stmt->actions)
1764 Node *action = (Node *) lfirst(l);
1765 ParseState *sub_pstate = make_parsestate(NULL);
1772 * Since outer ParseState isn't parent of inner, have to pass down
1773 * the query text by hand.
1775 sub_pstate->p_sourcetext = queryString;
1778 * Set up OLD/NEW in the rtable for this statement. The entries
1779 * are added only to relnamespace, not varnamespace, because we
1780 * don't want them to be referred to by unqualified field names
1781 * nor "*" in the rule actions. We decide later whether to put
1782 * them in the joinlist.
1784 oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
1785 makeAlias("old", NIL),
1787 newrte = addRangeTableEntryForRelation(sub_pstate, rel,
1788 makeAlias("new", NIL),
1790 oldrte->requiredPerms = 0;
1791 newrte->requiredPerms = 0;
1792 addRTEtoQuery(sub_pstate, oldrte, false, true, false);
1793 addRTEtoQuery(sub_pstate, newrte, false, true, false);
1795 /* Transform the rule action statement */
1796 top_subqry = transformStmt(sub_pstate,
1797 (Node *) copyObject(action));
1800 * We cannot support utility-statement actions (eg NOTIFY) with
1801 * nonempty rule WHERE conditions, because there's no way to make
1802 * the utility action execute conditionally.
1804 if (top_subqry->commandType == CMD_UTILITY &&
1805 *whereClause != NULL)
1807 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1808 errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
1811 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
1812 * into the SELECT, and that's what we need to look at. (Ugly
1813 * kluge ... try to fix this when we redesign querytrees.)
1815 sub_qry = getInsertSelectQuery(top_subqry, NULL);
1818 * If the sub_qry is a setop, we cannot attach any qualifications
1819 * to it, because the planner won't notice them. This could
1820 * perhaps be relaxed someday, but for now, we may as well reject
1821 * such a rule immediately.
1823 if (sub_qry->setOperations != NULL && *whereClause != NULL)
1825 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1826 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1829 * Validate action's use of OLD/NEW, qual too
1832 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1833 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
1835 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1836 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
1838 switch (stmt->event)
1843 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1844 errmsg("ON SELECT rule cannot use OLD")));
1847 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1848 errmsg("ON SELECT rule cannot use NEW")));
1856 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1857 errmsg("ON INSERT rule cannot use OLD")));
1862 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1863 errmsg("ON DELETE rule cannot use NEW")));
1866 elog(ERROR, "unrecognized event type: %d",
1872 * OLD/NEW are not allowed in WITH queries, because they would
1873 * amount to outer references for the WITH, which we disallow.
1874 * However, they were already in the outer rangetable when we
1875 * analyzed the query, so we have to check.
1877 * Note that in the INSERT...SELECT case, we need to examine
1878 * the CTE lists of both top_subqry and sub_qry.
1880 * Note that we aren't digging into the body of the query
1881 * looking for WITHs in nested sub-SELECTs. A WITH down there
1882 * can legitimately refer to OLD/NEW, because it'd be an
1883 * indirect-correlated outer reference.
1885 if (rangeTableEntry_used((Node *) top_subqry->cteList,
1886 PRS2_OLD_VARNO, 0) ||
1887 rangeTableEntry_used((Node *) sub_qry->cteList,
1890 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1891 errmsg("cannot refer to OLD within WITH query")));
1892 if (rangeTableEntry_used((Node *) top_subqry->cteList,
1893 PRS2_NEW_VARNO, 0) ||
1894 rangeTableEntry_used((Node *) sub_qry->cteList,
1897 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1898 errmsg("cannot refer to NEW within WITH query")));
1901 * For efficiency's sake, add OLD to the rule action's jointree
1902 * only if it was actually referenced in the statement or qual.
1904 * For INSERT, NEW is not really a relation (only a reference to
1905 * the to-be-inserted tuple) and should never be added to the
1908 * For UPDATE, we treat NEW as being another kind of reference to
1909 * OLD, because it represents references to *transformed* tuples
1910 * of the existing relation. It would be wrong to enter NEW
1911 * separately in the jointree, since that would cause a double
1912 * join of the updated relation. It's also wrong to fail to make
1913 * a jointree entry if only NEW and not OLD is mentioned.
1915 if (has_old || (has_new && stmt->event == CMD_UPDATE))
1918 * If sub_qry is a setop, manipulating its jointree will do no
1919 * good at all, because the jointree is dummy. (This should be
1920 * a can't-happen case because of prior tests.)
1922 if (sub_qry->setOperations != NULL)
1924 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1925 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1926 /* hack so we can use addRTEtoQuery() */
1927 sub_pstate->p_rtable = sub_qry->rtable;
1928 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
1929 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
1930 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
1933 newactions = lappend(newactions, top_subqry);
1935 free_parsestate(sub_pstate);
1938 *actions = newactions;
1941 free_parsestate(pstate);
1943 /* Close relation, but keep the exclusive lock */
1944 heap_close(rel, NoLock);
1949 * transformAlterTableStmt -
1950 * parse analysis for ALTER TABLE
1952 * Returns a List of utility commands to be done in sequence. One of these
1953 * will be the transformed AlterTableStmt, but there may be additional actions
1954 * to be done before and after the actual AlterTable() call.
1957 transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
1961 CreateStmtContext cxt;
1966 List *newcmds = NIL;
1967 bool skipValidation = true;
1968 AlterTableCmd *newcmd;
1972 * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
1973 * is overkill, but easy.)
1975 stmt = (AlterTableStmt *) copyObject(stmt);
1978 * Assign the appropriate lock level for this list of subcommands.
1980 lockmode = AlterTableGetLockLevel(stmt->cmds);
1983 * Acquire appropriate lock on the target relation, which will be held until
1984 * end of transaction. This ensures any decisions we make here based on
1985 * the state of the relation will still be good at execution. We must get
1986 * lock now because execution will later require it; taking a lower grade lock
1987 * now and trying to upgrade later risks deadlock. Any new commands we add
1988 * after this must not upgrade the lock level requested here.
1990 rel = relation_openrv(stmt->relation, lockmode);
1993 pstate = make_parsestate(NULL);
1994 pstate->p_sourcetext = queryString;
1996 cxt.stmtType = "ALTER TABLE";
1997 cxt.relation = stmt->relation;
1999 cxt.inhRelations = NIL;
2001 cxt.hasoids = false; /* need not be right */
2003 cxt.ckconstraints = NIL;
2004 cxt.fkconstraints = NIL;
2005 cxt.ixconstraints = NIL;
2006 cxt.inh_indexes = NIL;
2012 * The only subtypes that currently require parse transformation handling
2013 * are ADD COLUMN and ADD CONSTRAINT. These largely re-use code from
2016 foreach(lcmd, stmt->cmds)
2018 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2020 switch (cmd->subtype)
2023 case AT_AddColumnToView:
2025 ColumnDef *def = (ColumnDef *) cmd->def;
2027 Assert(IsA(def, ColumnDef));
2028 transformColumnDefinition(pstate, &cxt, def);
2031 * If the column has a non-null default, we can't skip
2032 * validation of foreign keys.
2034 if (def->raw_default != NULL)
2035 skipValidation = false;
2038 * All constraints are processed in other ways. Remove the
2041 def->constraints = NIL;
2043 newcmds = lappend(newcmds, cmd);
2046 case AT_AddConstraint:
2049 * The original AddConstraint cmd node doesn't go to newcmds
2051 if (IsA(cmd->def, Constraint))
2053 transformTableConstraint(pstate, &cxt,
2054 (Constraint *) cmd->def);
2055 if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
2056 skipValidation = false;
2059 elog(ERROR, "unrecognized node type: %d",
2060 (int) nodeTag(cmd->def));
2063 case AT_ProcessedConstraint:
2066 * Already-transformed ADD CONSTRAINT, so just make it look
2067 * like the standard case.
2069 cmd->subtype = AT_AddConstraint;
2070 newcmds = lappend(newcmds, cmd);
2074 newcmds = lappend(newcmds, cmd);
2080 * transformIndexConstraints wants cxt.alist to contain only index
2081 * statements, so transfer anything we already have into save_alist
2084 save_alist = cxt.alist;
2087 /* Postprocess index and FK constraints */
2088 transformIndexConstraints(pstate, &cxt);
2090 transformFKConstraints(pstate, &cxt, skipValidation, true);
2093 * Push any index-creation commands into the ALTER, so that they can be
2094 * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
2095 * the IndexStmt attached to an AT_AddIndex subcommand has already been
2096 * through transformIndexStmt.
2098 foreach(l, cxt.alist)
2100 Node *idxstmt = (Node *) lfirst(l);
2102 Assert(IsA(idxstmt, IndexStmt));
2103 newcmd = makeNode(AlterTableCmd);
2104 newcmd->subtype = AT_AddIndex;
2105 newcmd->def = (Node *) transformIndexStmt((IndexStmt *) idxstmt,
2107 newcmds = lappend(newcmds, newcmd);
2111 /* Append any CHECK or FK constraints to the commands list */
2112 foreach(l, cxt.ckconstraints)
2114 newcmd = makeNode(AlterTableCmd);
2115 newcmd->subtype = AT_AddConstraint;
2116 newcmd->def = (Node *) lfirst(l);
2117 newcmds = lappend(newcmds, newcmd);
2119 foreach(l, cxt.fkconstraints)
2121 newcmd = makeNode(AlterTableCmd);
2122 newcmd->subtype = AT_AddConstraint;
2123 newcmd->def = (Node *) lfirst(l);
2124 newcmds = lappend(newcmds, newcmd);
2127 /* Close rel but keep lock */
2128 relation_close(rel, NoLock);
2133 stmt->cmds = newcmds;
2135 result = lappend(cxt.blist, stmt);
2136 result = list_concat(result, cxt.alist);
2137 result = list_concat(result, save_alist);
2144 * Preprocess a list of column constraint clauses
2145 * to attach constraint attributes to their primary constraint nodes
2146 * and detect inconsistent/misplaced constraint attributes.
2148 * NOTE: currently, attributes are only supported for FOREIGN KEY, UNIQUE,
2149 * and PRIMARY KEY constraints, but someday they ought to be supported
2150 * for other constraint types.
2153 transformConstraintAttrs(ParseState *pstate, List *constraintList)
2155 Constraint *lastprimarycon = NULL;
2156 bool saw_deferrability = false;
2157 bool saw_initially = false;
2160 #define SUPPORTS_ATTRS(node) \
2161 ((node) != NULL && \
2162 ((node)->contype == CONSTR_PRIMARY || \
2163 (node)->contype == CONSTR_UNIQUE || \
2164 (node)->contype == CONSTR_EXCLUSION || \
2165 (node)->contype == CONSTR_FOREIGN))
2167 foreach(clist, constraintList)
2169 Constraint *con = (Constraint *) lfirst(clist);
2171 if (!IsA(con, Constraint))
2172 elog(ERROR, "unrecognized node type: %d",
2173 (int) nodeTag(con));
2174 switch (con->contype)
2176 case CONSTR_ATTR_DEFERRABLE:
2177 if (!SUPPORTS_ATTRS(lastprimarycon))
2179 (errcode(ERRCODE_SYNTAX_ERROR),
2180 errmsg("misplaced DEFERRABLE clause"),
2181 parser_errposition(pstate, con->location)));
2182 if (saw_deferrability)
2184 (errcode(ERRCODE_SYNTAX_ERROR),
2185 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2186 parser_errposition(pstate, con->location)));
2187 saw_deferrability = true;
2188 lastprimarycon->deferrable = true;
2191 case CONSTR_ATTR_NOT_DEFERRABLE:
2192 if (!SUPPORTS_ATTRS(lastprimarycon))
2194 (errcode(ERRCODE_SYNTAX_ERROR),
2195 errmsg("misplaced NOT DEFERRABLE clause"),
2196 parser_errposition(pstate, con->location)));
2197 if (saw_deferrability)
2199 (errcode(ERRCODE_SYNTAX_ERROR),
2200 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2201 parser_errposition(pstate, con->location)));
2202 saw_deferrability = true;
2203 lastprimarycon->deferrable = false;
2204 if (saw_initially &&
2205 lastprimarycon->initdeferred)
2207 (errcode(ERRCODE_SYNTAX_ERROR),
2208 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2209 parser_errposition(pstate, con->location)));
2212 case CONSTR_ATTR_DEFERRED:
2213 if (!SUPPORTS_ATTRS(lastprimarycon))
2215 (errcode(ERRCODE_SYNTAX_ERROR),
2216 errmsg("misplaced INITIALLY DEFERRED clause"),
2217 parser_errposition(pstate, con->location)));
2220 (errcode(ERRCODE_SYNTAX_ERROR),
2221 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2222 parser_errposition(pstate, con->location)));
2223 saw_initially = true;
2224 lastprimarycon->initdeferred = true;
2227 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
2229 if (!saw_deferrability)
2230 lastprimarycon->deferrable = true;
2231 else if (!lastprimarycon->deferrable)
2233 (errcode(ERRCODE_SYNTAX_ERROR),
2234 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2235 parser_errposition(pstate, con->location)));
2238 case CONSTR_ATTR_IMMEDIATE:
2239 if (!SUPPORTS_ATTRS(lastprimarycon))
2241 (errcode(ERRCODE_SYNTAX_ERROR),
2242 errmsg("misplaced INITIALLY IMMEDIATE clause"),
2243 parser_errposition(pstate, con->location)));
2246 (errcode(ERRCODE_SYNTAX_ERROR),
2247 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2248 parser_errposition(pstate, con->location)));
2249 saw_initially = true;
2250 lastprimarycon->initdeferred = false;
2254 /* Otherwise it's not an attribute */
2255 lastprimarycon = con;
2256 /* reset flags for new primary node */
2257 saw_deferrability = false;
2258 saw_initially = false;
2265 * Special handling of type definition for a column
2268 transformColumnType(ParseState *pstate, ColumnDef *column)
2271 * All we really need to do here is verify that the type is valid.
2273 Type ctype = typenameType(pstate, column->typeName, NULL);
2275 ReleaseSysCache(ctype);
2280 * transformCreateSchemaStmt -
2281 * analyzes the CREATE SCHEMA statement
2283 * Split the schema element list into individual commands and place
2284 * them in the result list in an order such that there are no forward
2285 * references (e.g. GRANT to a table created later in the list). Note
2286 * that the logic we use for determining forward references is
2287 * presently quite incomplete.
2289 * SQL92 also allows constraints to make forward references, so thumb through
2290 * the table columns and move forward references to a posterior alter-table
2293 * The result is a list of parse nodes that still need to be analyzed ---
2294 * but we can't analyze the later commands until we've executed the earlier
2295 * ones, because of possible inter-object references.
2297 * Note: this breaks the rules a little bit by modifying schema-name fields
2298 * within passed-in structs. However, the transformation would be the same
2299 * if done over, so it should be all right to scribble on the input to this
2303 transformCreateSchemaStmt(CreateSchemaStmt *stmt)
2305 CreateSchemaStmtContext cxt;
2309 cxt.stmtType = "CREATE SCHEMA";
2310 cxt.schemaname = stmt->schemaname;
2311 cxt.authid = stmt->authid;
2312 cxt.sequences = NIL;
2320 * Run through each schema element in the schema element list. Separate
2321 * statements by type, and do preliminary analysis.
2323 foreach(elements, stmt->schemaElts)
2325 Node *element = lfirst(elements);
2327 switch (nodeTag(element))
2329 case T_CreateSeqStmt:
2331 CreateSeqStmt *elp = (CreateSeqStmt *) element;
2333 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
2334 cxt.sequences = lappend(cxt.sequences, element);
2340 CreateStmt *elp = (CreateStmt *) element;
2342 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2345 * XXX todo: deal with constraints
2347 cxt.tables = lappend(cxt.tables, element);
2353 ViewStmt *elp = (ViewStmt *) element;
2355 setSchemaName(cxt.schemaname, &elp->view->schemaname);
2358 * XXX todo: deal with references between views
2360 cxt.views = lappend(cxt.views, element);
2366 IndexStmt *elp = (IndexStmt *) element;
2368 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2369 cxt.indexes = lappend(cxt.indexes, element);
2373 case T_CreateTrigStmt:
2375 CreateTrigStmt *elp = (CreateTrigStmt *) element;
2377 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2378 cxt.triggers = lappend(cxt.triggers, element);
2383 cxt.grants = lappend(cxt.grants, element);
2387 elog(ERROR, "unrecognized node type: %d",
2388 (int) nodeTag(element));
2393 result = list_concat(result, cxt.sequences);
2394 result = list_concat(result, cxt.tables);
2395 result = list_concat(result, cxt.views);
2396 result = list_concat(result, cxt.indexes);
2397 result = list_concat(result, cxt.triggers);
2398 result = list_concat(result, cxt.grants);
2405 * Set or check schema name in an element of a CREATE SCHEMA command
2408 setSchemaName(char *context_schema, char **stmt_schema_name)
2410 if (*stmt_schema_name == NULL)
2411 *stmt_schema_name = context_schema;
2412 else if (strcmp(context_schema, *stmt_schema_name) != 0)
2414 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
2415 errmsg("CREATE specifies a schema (%s) "
2416 "different from the one being created (%s)",
2417 *stmt_schema_name, context_schema)));