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-2009, PostgreSQL Global Development Group
20 * Portions Copyright (c) 1994, Regents of the University of California
22 * $PostgreSQL: pgsql/src/backend/parser/parse_utilcmd.c,v 2.34 2009/12/22 23:54:17 tgl Exp $
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_type.h"
52 #include "parser/parse_utilcmd.h"
53 #include "parser/parser.h"
54 #include "rewrite/rewriteManip.h"
55 #include "utils/acl.h"
56 #include "utils/builtins.h"
57 #include "utils/lsyscache.h"
58 #include "utils/relcache.h"
59 #include "utils/syscache.h"
62 /* State shared by transformCreateStmt and its subroutines */
65 const char *stmtType; /* "CREATE TABLE" or "ALTER TABLE" */
66 RangeVar *relation; /* relation to create */
67 Relation rel; /* opened/locked rel, if ALTER */
68 List *inhRelations; /* relations to inherit from */
69 bool isalter; /* true if altering existing table */
70 bool hasoids; /* does relation have an OID column? */
71 List *columns; /* ColumnDef items */
72 List *ckconstraints; /* CHECK constraints */
73 List *fkconstraints; /* FOREIGN KEY constraints */
74 List *ixconstraints; /* index-creating constraints */
75 List *inh_indexes; /* cloned indexes from INCLUDING INDEXES */
76 List *blist; /* "before list" of things to do before
77 * creating the table */
78 List *alist; /* "after list" of things to do after creating
80 IndexStmt *pkey; /* PRIMARY KEY index, if any */
83 /* State shared by transformCreateSchemaStmt and its subroutines */
86 const char *stmtType; /* "CREATE SCHEMA" or "ALTER SCHEMA" */
87 char *schemaname; /* name of schema */
88 char *authid; /* owner of schema */
89 List *sequences; /* CREATE SEQUENCE items */
90 List *tables; /* CREATE TABLE items */
91 List *views; /* CREATE VIEW items */
92 List *indexes; /* CREATE INDEX items */
93 List *triggers; /* CREATE TRIGGER items */
94 List *grants; /* GRANT items */
95 } CreateSchemaStmtContext;
98 static void transformColumnDefinition(ParseState *pstate,
99 CreateStmtContext *cxt,
101 static void transformTableConstraint(ParseState *pstate,
102 CreateStmtContext *cxt,
103 Constraint *constraint);
104 static void transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
105 InhRelation *inhrelation);
106 static char *chooseIndexName(const RangeVar *relation, IndexStmt *index_stmt);
107 static IndexStmt *generateClonedIndexStmt(CreateStmtContext *cxt,
108 Relation parent_index, AttrNumber *attmap);
109 static List *get_opclass(Oid opclass, Oid actual_datatype);
110 static void transformIndexConstraints(ParseState *pstate,
111 CreateStmtContext *cxt);
112 static IndexStmt *transformIndexConstraint(Constraint *constraint,
113 CreateStmtContext *cxt);
114 static void transformFKConstraints(ParseState *pstate,
115 CreateStmtContext *cxt,
117 bool isAddConstraint);
118 static void transformConstraintAttrs(ParseState *pstate, List *constraintList);
119 static void transformColumnType(ParseState *pstate, ColumnDef *column);
120 static void setSchemaName(char *context_schema, char **stmt_schema_name);
124 * transformCreateStmt -
125 * parse analysis for CREATE TABLE
127 * Returns a List of utility commands to be done in sequence. One of these
128 * will be the transformed CreateStmt, but there may be additional actions
129 * to be done before and after the actual DefineRelation() call.
131 * SQL92 allows constraints to be scattered all over, so thumb through
132 * the columns and collect all constraints into one place.
133 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
134 * then expand those into multiple IndexStmt blocks.
135 * - thomas 1997-12-02
138 transformCreateStmt(CreateStmt *stmt, const char *queryString)
141 CreateStmtContext cxt;
147 * We must not scribble on the passed-in CreateStmt, so copy it. (This is
148 * overkill, but easy.)
150 stmt = (CreateStmt *) copyObject(stmt);
153 * If the target relation name isn't schema-qualified, make it so. This
154 * prevents some corner cases in which added-on rewritten commands might
155 * think they should apply to other relations that have the same name and
156 * are earlier in the search path. "istemp" is equivalent to a
157 * specification of pg_temp, so no need for anything extra in that case.
159 if (stmt->relation->schemaname == NULL && !stmt->relation->istemp)
161 Oid namespaceid = RangeVarGetCreationNamespace(stmt->relation);
163 stmt->relation->schemaname = get_namespace_name(namespaceid);
167 pstate = make_parsestate(NULL);
168 pstate->p_sourcetext = queryString;
170 cxt.stmtType = "CREATE TABLE";
171 cxt.relation = stmt->relation;
173 cxt.inhRelations = stmt->inhRelations;
176 cxt.ckconstraints = NIL;
177 cxt.fkconstraints = NIL;
178 cxt.ixconstraints = NIL;
179 cxt.inh_indexes = NIL;
183 cxt.hasoids = interpretOidsOption(stmt->options);
186 * Run through each primary element in the table creation clause. Separate
187 * column defs from constraints, and do preliminary analysis.
189 foreach(elements, stmt->tableElts)
191 Node *element = lfirst(elements);
193 switch (nodeTag(element))
196 transformColumnDefinition(pstate, &cxt,
197 (ColumnDef *) element);
201 transformTableConstraint(pstate, &cxt,
202 (Constraint *) element);
206 transformInhRelation(pstate, &cxt,
207 (InhRelation *) element);
211 elog(ERROR, "unrecognized node type: %d",
212 (int) nodeTag(element));
218 * transformIndexConstraints wants cxt.alist to contain only index
219 * statements, so transfer anything we already have into save_alist.
221 save_alist = cxt.alist;
224 Assert(stmt->constraints == NIL);
227 * Postprocess constraints that give rise to index definitions.
229 transformIndexConstraints(pstate, &cxt);
232 * Postprocess foreign-key constraints.
234 transformFKConstraints(pstate, &cxt, true, false);
239 stmt->tableElts = cxt.columns;
240 stmt->constraints = cxt.ckconstraints;
242 result = lappend(cxt.blist, stmt);
243 result = list_concat(result, cxt.alist);
244 result = list_concat(result, save_alist);
250 * transformColumnDefinition -
251 * transform a single ColumnDef within CREATE TABLE
252 * Also used in ALTER TABLE ADD COLUMN
255 transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
261 Constraint *constraint;
264 cxt->columns = lappend(cxt->columns, column);
266 /* Check for SERIAL pseudo-types */
268 if (list_length(column->typeName->names) == 1 &&
269 !column->typeName->pct_type)
271 char *typname = strVal(linitial(column->typeName->names));
273 if (strcmp(typname, "serial") == 0 ||
274 strcmp(typname, "serial4") == 0)
277 column->typeName->names = NIL;
278 column->typeName->typeOid = INT4OID;
280 else if (strcmp(typname, "bigserial") == 0 ||
281 strcmp(typname, "serial8") == 0)
284 column->typeName->names = NIL;
285 column->typeName->typeOid = INT8OID;
289 * We have to reject "serial[]" explicitly, because once we've set
290 * typeid, LookupTypeName won't notice arrayBounds. We don't need any
291 * special coding for serial(typmod) though.
293 if (is_serial && column->typeName->arrayBounds != NIL)
295 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
296 errmsg("array of serial is not implemented"),
297 parser_errposition(pstate, column->typeName->location)));
300 /* Do necessary work on the column type declaration */
301 transformColumnType(pstate, column);
303 /* Special actions for SERIAL pseudo-types */
312 FuncCall *funccallnode;
313 CreateSeqStmt *seqstmt;
314 AlterSeqStmt *altseqstmt;
318 * Determine namespace and name to use for the sequence.
320 * Although we use ChooseRelationName, it's not guaranteed that the
321 * selected sequence name won't conflict; given sufficiently long
322 * field names, two different serial columns in the same table could
323 * be assigned the same sequence name, and we'd not notice since we
324 * aren't creating the sequence quite yet. In practice this seems
325 * quite unlikely to be a problem, especially since few people would
326 * need two serial columns in one table.
329 snamespaceid = RelationGetNamespace(cxt->rel);
331 snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
332 snamespace = get_namespace_name(snamespaceid);
333 sname = ChooseRelationName(cxt->relation->relname,
339 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
340 cxt->stmtType, sname,
341 cxt->relation->relname, column->colname)));
344 * Build a CREATE SEQUENCE command to create the sequence object, and
345 * add it to the list of things to be done before this CREATE/ALTER
348 seqstmt = makeNode(CreateSeqStmt);
349 seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
350 seqstmt->options = NIL;
352 cxt->blist = lappend(cxt->blist, seqstmt);
355 * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence
356 * as owned by this column, and add it to the list of things to be
357 * done after this CREATE/ALTER TABLE.
359 altseqstmt = makeNode(AlterSeqStmt);
360 altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
361 attnamelist = list_make3(makeString(snamespace),
362 makeString(cxt->relation->relname),
363 makeString(column->colname));
364 altseqstmt->options = list_make1(makeDefElem("owned_by",
365 (Node *) attnamelist));
367 cxt->alist = lappend(cxt->alist, altseqstmt);
370 * Create appropriate constraints for SERIAL. We do this in full,
371 * rather than shortcutting, so that we will detect any conflicting
372 * constraints the user wrote (like a different DEFAULT).
374 * Create an expression tree representing the function call
375 * nextval('sequencename'). We cannot reduce the raw tree to cooked
376 * form until after the sequence is created, but there's no need to do
379 qstring = quote_qualified_identifier(snamespace, sname);
380 snamenode = makeNode(A_Const);
381 snamenode->val.type = T_String;
382 snamenode->val.val.str = qstring;
383 snamenode->location = -1;
384 castnode = makeNode(TypeCast);
385 castnode->typeName = SystemTypeName("regclass");
386 castnode->arg = (Node *) snamenode;
387 castnode->location = -1;
388 funccallnode = makeNode(FuncCall);
389 funccallnode->funcname = SystemFuncName("nextval");
390 funccallnode->args = list_make1(castnode);
391 funccallnode->agg_order = NIL;
392 funccallnode->agg_star = false;
393 funccallnode->agg_distinct = false;
394 funccallnode->func_variadic = false;
395 funccallnode->over = NULL;
396 funccallnode->location = -1;
398 constraint = makeNode(Constraint);
399 constraint->contype = CONSTR_DEFAULT;
400 constraint->location = -1;
401 constraint->raw_expr = (Node *) funccallnode;
402 constraint->cooked_expr = NULL;
403 column->constraints = lappend(column->constraints, constraint);
405 constraint = makeNode(Constraint);
406 constraint->contype = CONSTR_NOTNULL;
407 constraint->location = -1;
408 column->constraints = lappend(column->constraints, constraint);
411 /* Process column constraints, if any... */
412 transformConstraintAttrs(pstate, column->constraints);
414 saw_nullable = false;
417 foreach(clist, column->constraints)
419 constraint = lfirst(clist);
420 Assert(IsA(constraint, Constraint));
422 switch (constraint->contype)
425 if (saw_nullable && column->is_not_null)
427 (errcode(ERRCODE_SYNTAX_ERROR),
428 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
429 column->colname, cxt->relation->relname),
430 parser_errposition(pstate,
431 constraint->location)));
432 column->is_not_null = FALSE;
437 if (saw_nullable && !column->is_not_null)
439 (errcode(ERRCODE_SYNTAX_ERROR),
440 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
441 column->colname, cxt->relation->relname),
442 parser_errposition(pstate,
443 constraint->location)));
444 column->is_not_null = TRUE;
451 (errcode(ERRCODE_SYNTAX_ERROR),
452 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
453 column->colname, cxt->relation->relname),
454 parser_errposition(pstate,
455 constraint->location)));
456 column->raw_default = constraint->raw_expr;
457 Assert(constraint->cooked_expr == NULL);
462 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
467 if (constraint->keys == NIL)
468 constraint->keys = list_make1(makeString(column->colname));
469 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
472 case CONSTR_EXCLUSION:
473 /* grammar does not allow EXCLUDE as a column constraint */
474 elog(ERROR, "column exclusion constraints are not supported");
479 * Fill in the current attribute's name and throw it into the
480 * list of FK constraints to be processed later.
482 constraint->fk_attrs = list_make1(makeString(column->colname));
483 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
486 case CONSTR_ATTR_DEFERRABLE:
487 case CONSTR_ATTR_NOT_DEFERRABLE:
488 case CONSTR_ATTR_DEFERRED:
489 case CONSTR_ATTR_IMMEDIATE:
490 /* transformConstraintAttrs took care of these */
494 elog(ERROR, "unrecognized constraint type: %d",
495 constraint->contype);
502 * transformTableConstraint
503 * transform a Constraint node within CREATE TABLE or ALTER TABLE
506 transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt,
507 Constraint *constraint)
509 switch (constraint->contype)
513 case CONSTR_EXCLUSION:
514 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
518 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
522 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
528 case CONSTR_ATTR_DEFERRABLE:
529 case CONSTR_ATTR_NOT_DEFERRABLE:
530 case CONSTR_ATTR_DEFERRED:
531 case CONSTR_ATTR_IMMEDIATE:
532 elog(ERROR, "invalid context for constraint type %d",
533 constraint->contype);
537 elog(ERROR, "unrecognized constraint type: %d",
538 constraint->contype);
544 * transformInhRelation
546 * Change the LIKE <subtable> portion of a CREATE TABLE statement into
547 * column definitions which recreate the user defined column portions of
551 transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
552 InhRelation *inhRelation)
554 AttrNumber parent_attno;
561 relation = parserOpenTable(pstate, inhRelation->relation, AccessShareLock);
563 if (relation->rd_rel->relkind != RELKIND_RELATION)
565 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
566 errmsg("inherited relation \"%s\" is not a table",
567 inhRelation->relation->relname)));
570 * Check for SELECT privilages
572 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
574 if (aclresult != ACLCHECK_OK)
575 aclcheck_error(aclresult, ACL_KIND_CLASS,
576 RelationGetRelationName(relation));
578 tupleDesc = RelationGetDescr(relation);
579 constr = tupleDesc->constr;
582 * Insert the copied attributes into the cxt for the new table definition.
584 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
587 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
588 char *attributeName = NameStr(attribute->attname);
592 * Ignore dropped columns in the parent.
594 if (attribute->attisdropped)
598 * Create a new column, which is marked as NOT inherited.
600 * For constraints, ONLY the NOT NULL constraint is inherited by the
601 * new column definition per SQL99.
603 def = makeNode(ColumnDef);
604 def->colname = pstrdup(attributeName);
605 def->typeName = makeTypeNameFromOid(attribute->atttypid,
606 attribute->atttypmod);
608 def->is_local = true;
609 def->is_not_null = attribute->attnotnull;
610 def->raw_default = NULL;
611 def->cooked_default = NULL;
612 def->constraints = NIL;
617 cxt->columns = lappend(cxt->columns, def);
620 * Copy default, if present and the default has been requested
622 if (attribute->atthasdef &&
623 (inhRelation->options & CREATE_TABLE_LIKE_DEFAULTS))
625 Node *this_default = NULL;
626 AttrDefault *attrdef;
629 /* Find default in constraint structure */
630 Assert(constr != NULL);
631 attrdef = constr->defval;
632 for (i = 0; i < constr->num_defval; i++)
634 if (attrdef[i].adnum == parent_attno)
636 this_default = stringToNode(attrdef[i].adbin);
640 Assert(this_default != NULL);
643 * If default expr could contain any vars, we'd need to fix 'em,
644 * but it can't; so default is ready to apply to child.
647 def->cooked_default = this_default;
650 /* Likewise, copy storage if requested */
651 if (inhRelation->options & CREATE_TABLE_LIKE_STORAGE)
652 def->storage = attribute->attstorage;
656 /* Likewise, copy comment if requested */
657 if ((inhRelation->options & CREATE_TABLE_LIKE_COMMENTS) &&
658 (comment = GetComment(attribute->attrelid,
660 attribute->attnum)) != NULL)
662 CommentStmt *stmt = makeNode(CommentStmt);
664 stmt->objtype = OBJECT_COLUMN;
665 stmt->objname = list_make3(makeString(cxt->relation->schemaname),
666 makeString(cxt->relation->relname),
667 makeString(def->colname));
669 stmt->comment = comment;
671 cxt->alist = lappend(cxt->alist, stmt);
676 * Copy CHECK constraints if requested, being careful to adjust attribute
679 if ((inhRelation->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
682 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
685 for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
687 char *ccname = tupleDesc->constr->check[ccnum].ccname;
688 char *ccbin = tupleDesc->constr->check[ccnum].ccbin;
689 Node *ccbin_node = stringToNode(ccbin);
690 Constraint *n = makeNode(Constraint);
692 change_varattnos_of_a_node(ccbin_node, attmap);
694 n->contype = CONSTR_CHECK;
696 n->conname = pstrdup(ccname);
698 n->cooked_expr = nodeToString(ccbin_node);
699 cxt->ckconstraints = lappend(cxt->ckconstraints, n);
701 /* Copy comment on constraint */
702 if ((inhRelation->options & CREATE_TABLE_LIKE_COMMENTS) &&
703 (comment = GetComment(GetConstraintByName(RelationGetRelid(relation),
705 ConstraintRelationId,
708 CommentStmt *stmt = makeNode(CommentStmt);
710 stmt->objtype = OBJECT_CONSTRAINT;
711 stmt->objname = list_make3(makeString(cxt->relation->schemaname),
712 makeString(cxt->relation->relname),
713 makeString(n->conname));
715 stmt->comment = comment;
717 cxt->alist = lappend(cxt->alist, stmt);
723 * Likewise, copy indexes if requested
725 if ((inhRelation->options & CREATE_TABLE_LIKE_INDEXES) &&
726 relation->rd_rel->relhasindex)
728 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
729 List *parent_indexes;
732 parent_indexes = RelationGetIndexList(relation);
734 foreach(l, parent_indexes)
736 Oid parent_index_oid = lfirst_oid(l);
737 Relation parent_index;
738 IndexStmt *index_stmt;
740 parent_index = index_open(parent_index_oid, AccessShareLock);
742 /* Build CREATE INDEX statement to recreate the parent_index */
743 index_stmt = generateClonedIndexStmt(cxt, parent_index, attmap);
745 /* Copy comment on index */
746 if (inhRelation->options & CREATE_TABLE_LIKE_COMMENTS)
748 comment = GetComment(parent_index_oid, RelationRelationId, 0);
755 * We have to assign the index a name now, so that we
756 * can reference it in CommentStmt.
758 if (index_stmt->idxname == NULL)
759 index_stmt->idxname = chooseIndexName(cxt->relation,
762 stmt = makeNode(CommentStmt);
763 stmt->objtype = OBJECT_INDEX;
765 list_make2(makeString(cxt->relation->schemaname),
766 makeString(index_stmt->idxname));
768 stmt->comment = comment;
770 cxt->alist = lappend(cxt->alist, stmt);
774 /* Save it in the inh_indexes list for the time being */
775 cxt->inh_indexes = lappend(cxt->inh_indexes, index_stmt);
777 index_close(parent_index, AccessShareLock);
782 * Close the parent rel, but keep our AccessShareLock on it until xact
783 * commit. That will prevent someone else from deleting or ALTERing the
784 * parent before the child is committed.
786 heap_close(relation, NoLock);
792 * Set name for unnamed index. See also the same logic in DefineIndex.
795 chooseIndexName(const RangeVar *relation, IndexStmt *index_stmt)
799 namespaceId = RangeVarGetCreationNamespace(relation);
800 if (index_stmt->primary)
802 /* no need for column list with pkey */
803 return ChooseRelationName(relation->relname, NULL,
804 "pkey", namespaceId);
806 else if (index_stmt->excludeOpNames != NIL)
808 IndexElem *iparam = (IndexElem *) linitial(index_stmt->indexParams);
810 return ChooseRelationName(relation->relname, iparam->name,
811 "exclusion", namespaceId);
815 IndexElem *iparam = (IndexElem *) linitial(index_stmt->indexParams);
817 return ChooseRelationName(relation->relname, iparam->name,
823 * Generate an IndexStmt node using information from an already existing index
824 * "source_idx". Attribute numbers should be adjusted according to attmap.
827 generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
830 Oid source_relid = RelationGetRelid(source_idx);
833 Form_pg_class idxrelrec;
834 Form_pg_index idxrec;
839 ListCell *indexpr_item;
847 * Fetch pg_class tuple of source index. We can't use the copy in the
848 * relcache entry because it doesn't include optional fields.
850 ht_idxrel = SearchSysCache(RELOID,
851 ObjectIdGetDatum(source_relid),
853 if (!HeapTupleIsValid(ht_idxrel))
854 elog(ERROR, "cache lookup failed for relation %u", source_relid);
855 idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
857 /* Fetch pg_index tuple for source index from relcache entry */
858 ht_idx = source_idx->rd_indextuple;
859 idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
860 indrelid = idxrec->indrelid;
862 /* Fetch pg_am tuple for source index from relcache entry */
863 amrec = source_idx->rd_am;
865 /* Extract indclass from the pg_index tuple */
866 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
867 Anum_pg_index_indclass, &isnull);
869 indclass = (oidvector *) DatumGetPointer(datum);
871 /* Begin building the IndexStmt */
872 index = makeNode(IndexStmt);
873 index->relation = cxt->relation;
874 index->accessMethod = pstrdup(NameStr(amrec->amname));
875 if (OidIsValid(idxrelrec->reltablespace))
876 index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
878 index->tableSpace = NULL;
879 index->unique = idxrec->indisunique;
880 index->primary = idxrec->indisprimary;
881 index->concurrent = false;
884 * We don't try to preserve the name of the source index; instead, just
885 * let DefineIndex() choose a reasonable name.
887 index->idxname = NULL;
890 * If the index is marked PRIMARY or has an exclusion condition, it's
891 * certainly from a constraint; else, if it's not marked UNIQUE, it
892 * certainly isn't. If it is or might be from a constraint, we have to
893 * fetch the pg_constraint record.
895 if (index->primary || index->unique || idxrelrec->relhasexclusion)
897 Oid constraintId = get_index_constraint(source_relid);
899 if (OidIsValid(constraintId))
902 Form_pg_constraint conrec;
904 ht_constr = SearchSysCache(CONSTROID,
905 ObjectIdGetDatum(constraintId),
907 if (!HeapTupleIsValid(ht_constr))
908 elog(ERROR, "cache lookup failed for constraint %u",
910 conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
912 index->isconstraint = true;
913 index->deferrable = conrec->condeferrable;
914 index->initdeferred = conrec->condeferred;
916 /* If it's an exclusion constraint, we need the operator names */
917 if (idxrelrec->relhasexclusion)
923 Assert(conrec->contype == CONSTRAINT_EXCLUSION);
924 /* Extract operator OIDs from the pg_constraint tuple */
925 datum = SysCacheGetAttr(CONSTROID, ht_constr,
926 Anum_pg_constraint_conexclop,
929 elog(ERROR, "null conexclop for constraint %u",
932 deconstruct_array(DatumGetArrayTypeP(datum),
933 OIDOID, sizeof(Oid), true, 'i',
934 &elems, NULL, &nElems);
936 for (i = 0; i < nElems; i++)
938 Oid operid = DatumGetObjectId(elems[i]);
940 Form_pg_operator operform;
945 opertup = SearchSysCache(OPEROID,
946 ObjectIdGetDatum(operid),
948 if (!HeapTupleIsValid(opertup))
949 elog(ERROR, "cache lookup failed for operator %u",
951 operform = (Form_pg_operator) GETSTRUCT(opertup);
952 oprname = pstrdup(NameStr(operform->oprname));
953 /* For simplicity we always schema-qualify the op name */
954 nspname = get_namespace_name(operform->oprnamespace);
955 namelist = list_make2(makeString(nspname),
956 makeString(oprname));
957 index->excludeOpNames = lappend(index->excludeOpNames,
959 ReleaseSysCache(opertup);
963 ReleaseSysCache(ht_constr);
966 index->isconstraint = false;
969 index->isconstraint = false;
971 /* Get the index expressions, if any */
972 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
973 Anum_pg_index_indexprs, &isnull);
978 exprsString = TextDatumGetCString(datum);
979 indexprs = (List *) stringToNode(exprsString);
984 /* Build the list of IndexElem */
985 index->indexParams = NIL;
987 indexpr_item = list_head(indexprs);
988 for (keyno = 0; keyno < idxrec->indnatts; keyno++)
991 AttrNumber attnum = idxrec->indkey.values[keyno];
992 int16 opt = source_idx->rd_indoption[keyno];
994 iparam = makeNode(IndexElem);
996 if (AttributeNumberIsValid(attnum))
998 /* Simple index column */
1001 attname = get_relid_attribute_name(indrelid, attnum);
1002 keycoltype = get_atttype(indrelid, attnum);
1004 iparam->name = attname;
1005 iparam->expr = NULL;
1009 /* Expressional index */
1012 if (indexpr_item == NULL)
1013 elog(ERROR, "too few entries in indexprs list");
1014 indexkey = (Node *) lfirst(indexpr_item);
1015 indexpr_item = lnext(indexpr_item);
1017 /* OK to modify indexkey since we are working on a private copy */
1018 change_varattnos_of_a_node(indexkey, attmap);
1020 iparam->name = NULL;
1021 iparam->expr = indexkey;
1023 keycoltype = exprType(indexkey);
1026 /* Add the operator class name, if non-default */
1027 iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1029 iparam->ordering = SORTBY_DEFAULT;
1030 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1032 /* Adjust options if necessary */
1033 if (amrec->amcanorder)
1036 * If it supports sort ordering, copy DESC and NULLS opts. Don't
1037 * set non-default settings unnecessarily, though, so as to
1038 * improve the chance of recognizing equivalence to constraint
1041 if (opt & INDOPTION_DESC)
1043 iparam->ordering = SORTBY_DESC;
1044 if ((opt & INDOPTION_NULLS_FIRST) == 0)
1045 iparam->nulls_ordering = SORTBY_NULLS_LAST;
1049 if (opt & INDOPTION_NULLS_FIRST)
1050 iparam->nulls_ordering = SORTBY_NULLS_FIRST;
1054 index->indexParams = lappend(index->indexParams, iparam);
1057 /* Copy reloptions if any */
1058 datum = SysCacheGetAttr(RELOID, ht_idxrel,
1059 Anum_pg_class_reloptions, &isnull);
1061 index->options = untransformRelOptions(datum);
1063 /* If it's a partial index, decompile and append the predicate */
1064 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1065 Anum_pg_index_indpred, &isnull);
1070 /* Convert text string to node tree */
1071 pred_str = TextDatumGetCString(datum);
1072 index->whereClause = (Node *) stringToNode(pred_str);
1073 /* Adjust attribute numbers */
1074 change_varattnos_of_a_node(index->whereClause, attmap);
1078 ReleaseSysCache(ht_idxrel);
1084 * get_opclass - fetch name of an index operator class
1086 * If the opclass is the default for the given actual_datatype, then
1087 * the return value is NIL.
1090 get_opclass(Oid opclass, Oid actual_datatype)
1093 Form_pg_opclass opc_rec;
1096 ht_opc = SearchSysCache(CLAOID,
1097 ObjectIdGetDatum(opclass),
1099 if (!HeapTupleIsValid(ht_opc))
1100 elog(ERROR, "cache lookup failed for opclass %u", opclass);
1101 opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
1103 if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
1105 /* For simplicity, we always schema-qualify the name */
1106 char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
1107 char *opc_name = pstrdup(NameStr(opc_rec->opcname));
1109 result = list_make2(makeString(nsp_name), makeString(opc_name));
1112 ReleaseSysCache(ht_opc);
1118 * transformIndexConstraints
1119 * Handle UNIQUE, PRIMARY KEY, EXCLUDE constraints, which create indexes.
1120 * We also merge in any index definitions arising from
1121 * LIKE ... INCLUDING INDEXES.
1124 transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
1127 List *indexlist = NIL;
1131 * Run through the constraints that need to generate an index. For PRIMARY
1132 * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
1133 * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
1136 foreach(lc, cxt->ixconstraints)
1138 Constraint *constraint = (Constraint *) lfirst(lc);
1140 Assert(IsA(constraint, Constraint));
1141 Assert(constraint->contype == CONSTR_PRIMARY ||
1142 constraint->contype == CONSTR_UNIQUE ||
1143 constraint->contype == CONSTR_EXCLUSION);
1145 index = transformIndexConstraint(constraint, cxt);
1147 indexlist = lappend(indexlist, index);
1150 /* Add in any indexes defined by LIKE ... INCLUDING INDEXES */
1151 foreach(lc, cxt->inh_indexes)
1153 index = (IndexStmt *) lfirst(lc);
1157 if (cxt->pkey != NULL)
1159 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1160 errmsg("multiple primary keys for table \"%s\" are not allowed",
1161 cxt->relation->relname)));
1165 indexlist = lappend(indexlist, index);
1169 * Scan the index list and remove any redundant index specifications. This
1170 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1171 * strict reading of SQL92 would suggest raising an error instead, but
1172 * that strikes me as too anal-retentive. - tgl 2001-02-14
1174 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1175 * pre-existing indexes, too.
1177 Assert(cxt->alist == NIL);
1178 if (cxt->pkey != NULL)
1180 /* Make sure we keep the PKEY index in preference to others... */
1181 cxt->alist = list_make1(cxt->pkey);
1184 foreach(lc, indexlist)
1191 /* if it's pkey, it's already in cxt->alist */
1192 if (index == cxt->pkey)
1195 foreach(k, cxt->alist)
1197 IndexStmt *priorindex = lfirst(k);
1199 if (equal(index->indexParams, priorindex->indexParams) &&
1200 equal(index->whereClause, priorindex->whereClause) &&
1201 equal(index->excludeOpNames, priorindex->excludeOpNames) &&
1202 strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
1203 index->deferrable == priorindex->deferrable &&
1204 index->initdeferred == priorindex->initdeferred)
1206 priorindex->unique |= index->unique;
1209 * If the prior index is as yet unnamed, and this one is
1210 * named, then transfer the name to the prior index. This
1211 * ensures that if we have named and unnamed constraints,
1212 * we'll use (at least one of) the names for the index.
1214 if (priorindex->idxname == NULL)
1215 priorindex->idxname = index->idxname;
1222 cxt->alist = lappend(cxt->alist, index);
1227 * transformIndexConstraint
1228 * Transform one UNIQUE, PRIMARY KEY, or EXCLUDE constraint for
1229 * transformIndexConstraints.
1232 transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
1237 index = makeNode(IndexStmt);
1239 index->unique = (constraint->contype != CONSTR_EXCLUSION);
1240 index->primary = (constraint->contype == CONSTR_PRIMARY);
1243 if (cxt->pkey != NULL)
1245 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1246 errmsg("multiple primary keys for table \"%s\" are not allowed",
1247 cxt->relation->relname)));
1251 * In ALTER TABLE case, a primary index might already exist, but
1252 * DefineIndex will check for it.
1255 index->isconstraint = true;
1256 index->deferrable = constraint->deferrable;
1257 index->initdeferred = constraint->initdeferred;
1259 if (constraint->conname != NULL)
1260 index->idxname = pstrdup(constraint->conname);
1262 index->idxname = NULL; /* DefineIndex will choose name */
1264 index->relation = cxt->relation;
1265 index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
1266 index->options = constraint->options;
1267 index->tableSpace = constraint->indexspace;
1268 index->whereClause = constraint->where_clause;
1269 index->indexParams = NIL;
1270 index->excludeOpNames = NIL;
1271 index->concurrent = false;
1274 * If it's an EXCLUDE constraint, the grammar returns a list of pairs
1275 * of IndexElems and operator names. We have to break that apart into
1278 if (constraint->contype == CONSTR_EXCLUSION)
1280 foreach(lc, constraint->exclusions)
1282 List *pair = (List *) lfirst(lc);
1286 Assert(list_length(pair) == 2);
1287 elem = (IndexElem *) linitial(pair);
1288 Assert(IsA(elem, IndexElem));
1289 opname = (List *) lsecond(pair);
1290 Assert(IsA(opname, List));
1292 index->indexParams = lappend(index->indexParams, elem);
1293 index->excludeOpNames = lappend(index->excludeOpNames, opname);
1300 * For UNIQUE and PRIMARY KEY, we just have a list of column names.
1302 * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
1303 * also make sure they are NOT NULL, if possible. (Although we could leave
1304 * it to DefineIndex to mark the columns NOT NULL, it's more efficient to
1305 * get it right the first time.)
1307 foreach(lc, constraint->keys)
1309 char *key = strVal(lfirst(lc));
1311 ColumnDef *column = NULL;
1315 foreach(columns, cxt->columns)
1317 column = (ColumnDef *) lfirst(columns);
1318 Assert(IsA(column, ColumnDef));
1319 if (strcmp(column->colname, key) == 0)
1327 /* found column in the new table; force it to be NOT NULL */
1328 if (constraint->contype == CONSTR_PRIMARY)
1329 column->is_not_null = TRUE;
1331 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1334 * column will be a system column in the new table, so accept it.
1335 * System columns can't ever be null, so no need to worry about
1336 * PRIMARY/NOT NULL constraint.
1340 else if (cxt->inhRelations)
1342 /* try inherited tables */
1345 foreach(inher, cxt->inhRelations)
1347 RangeVar *inh = (RangeVar *) lfirst(inher);
1351 Assert(IsA(inh, RangeVar));
1352 rel = heap_openrv(inh, AccessShareLock);
1353 if (rel->rd_rel->relkind != RELKIND_RELATION)
1355 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1356 errmsg("inherited relation \"%s\" is not a table",
1358 for (count = 0; count < rel->rd_att->natts; count++)
1360 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1361 char *inhname = NameStr(inhattr->attname);
1363 if (inhattr->attisdropped)
1365 if (strcmp(key, inhname) == 0)
1370 * We currently have no easy way to force an inherited
1371 * column to be NOT NULL at creation, if its parent
1372 * wasn't so already. We leave it to DefineIndex to
1373 * fix things up in this case.
1378 heap_close(rel, NoLock);
1385 * In the ALTER TABLE case, don't complain about index keys not
1386 * created in the command; they may well exist already. DefineIndex
1387 * will complain about them if not, and will also take care of marking
1390 if (!found && !cxt->isalter)
1392 (errcode(ERRCODE_UNDEFINED_COLUMN),
1393 errmsg("column \"%s\" named in key does not exist",
1396 /* Check for PRIMARY KEY(foo, foo) */
1397 foreach(columns, index->indexParams)
1399 iparam = (IndexElem *) lfirst(columns);
1400 if (iparam->name && strcmp(key, iparam->name) == 0)
1404 (errcode(ERRCODE_DUPLICATE_COLUMN),
1405 errmsg("column \"%s\" appears twice in primary key constraint",
1409 (errcode(ERRCODE_DUPLICATE_COLUMN),
1410 errmsg("column \"%s\" appears twice in unique constraint",
1415 /* OK, add it to the index definition */
1416 iparam = makeNode(IndexElem);
1417 iparam->name = pstrdup(key);
1418 iparam->expr = NULL;
1419 iparam->opclass = NIL;
1420 iparam->ordering = SORTBY_DEFAULT;
1421 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1422 index->indexParams = lappend(index->indexParams, iparam);
1429 * transformFKConstraints
1430 * handle FOREIGN KEY constraints
1433 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1434 bool skipValidation, bool isAddConstraint)
1438 if (cxt->fkconstraints == NIL)
1442 * If CREATE TABLE or adding a column with NULL default, we can safely
1443 * skip validation of the constraint.
1447 foreach(fkclist, cxt->fkconstraints)
1449 Constraint *constraint = (Constraint *) lfirst(fkclist);
1451 constraint->skip_validation = true;
1456 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1457 * CONSTRAINT command to execute after the basic command is complete. (If
1458 * called from ADD CONSTRAINT, that routine will add the FK constraints to
1459 * its own subcommand list.)
1461 * Note: the ADD CONSTRAINT command must also execute after any index
1462 * creation commands. Thus, this should run after
1463 * transformIndexConstraints, so that the CREATE INDEX commands are
1464 * already in cxt->alist.
1466 if (!isAddConstraint)
1468 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1470 alterstmt->relation = cxt->relation;
1471 alterstmt->cmds = NIL;
1472 alterstmt->relkind = OBJECT_TABLE;
1474 foreach(fkclist, cxt->fkconstraints)
1476 Constraint *constraint = (Constraint *) lfirst(fkclist);
1477 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1479 altercmd->subtype = AT_ProcessedConstraint;
1480 altercmd->name = NULL;
1481 altercmd->def = (Node *) constraint;
1482 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1485 cxt->alist = lappend(cxt->alist, alterstmt);
1490 * transformIndexStmt - parse analysis for CREATE INDEX
1492 * Note: this is a no-op for an index not using either index expressions or
1493 * a predicate expression. There are several code paths that create indexes
1494 * without bothering to call this, because they know they don't have any
1495 * such expressions to deal with.
1498 transformIndexStmt(IndexStmt *stmt, const char *queryString)
1506 * We must not scribble on the passed-in IndexStmt, so copy it. (This is
1507 * overkill, but easy.)
1509 stmt = (IndexStmt *) copyObject(stmt);
1512 * Open the parent table with appropriate locking. We must do this
1513 * because addRangeTableEntry() would acquire only AccessShareLock,
1514 * leaving DefineIndex() needing to do a lock upgrade with consequent risk
1515 * of deadlock. Make sure this stays in sync with the type of lock
1516 * DefineIndex() wants.
1518 rel = heap_openrv(stmt->relation,
1519 (stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock));
1522 pstate = make_parsestate(NULL);
1523 pstate->p_sourcetext = queryString;
1526 * Put the parent table into the rtable so that the expressions can refer
1527 * to its fields without qualification.
1529 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1531 /* no to join list, yes to namespaces */
1532 addRTEtoQuery(pstate, rte, false, true, true);
1534 /* take care of the where clause */
1535 if (stmt->whereClause)
1536 stmt->whereClause = transformWhereClause(pstate,
1540 /* take care of any index expressions */
1541 foreach(l, stmt->indexParams)
1543 IndexElem *ielem = (IndexElem *) lfirst(l);
1547 ielem->expr = transformExpr(pstate, ielem->expr);
1550 * We check only that the result type is legitimate; this is for
1551 * consistency with what transformWhereClause() checks for the
1552 * predicate. DefineIndex() will make more checks.
1554 if (expression_returns_set(ielem->expr))
1556 (errcode(ERRCODE_DATATYPE_MISMATCH),
1557 errmsg("index expression cannot return a set")));
1562 * Check that only the base rel is mentioned.
1564 if (list_length(pstate->p_rtable) != 1)
1566 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1567 errmsg("index expressions and predicates can refer only to the table being indexed")));
1569 free_parsestate(pstate);
1571 /* Close relation, but keep the lock */
1572 heap_close(rel, NoLock);
1579 * transformRuleStmt -
1580 * transform a CREATE RULE Statement. The action is a list of parse
1581 * trees which is transformed into a list of query trees, and we also
1582 * transform the WHERE clause if any.
1584 * actions and whereClause are output parameters that receive the
1585 * transformed results.
1587 * Note that we must not scribble on the passed-in RuleStmt, so we do
1588 * copyObject() on the actions and WHERE clause.
1591 transformRuleStmt(RuleStmt *stmt, const char *queryString,
1592 List **actions, Node **whereClause)
1596 RangeTblEntry *oldrte;
1597 RangeTblEntry *newrte;
1600 * To avoid deadlock, make sure the first thing we do is grab
1601 * AccessExclusiveLock on the target relation. This will be needed by
1602 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1605 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1608 pstate = make_parsestate(NULL);
1609 pstate->p_sourcetext = queryString;
1612 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1613 * Set up their RTEs in the main pstate for use in parsing the rule
1616 oldrte = addRangeTableEntryForRelation(pstate, rel,
1617 makeAlias("old", NIL),
1619 newrte = addRangeTableEntryForRelation(pstate, rel,
1620 makeAlias("new", NIL),
1622 /* Must override addRangeTableEntry's default access-check flags */
1623 oldrte->requiredPerms = 0;
1624 newrte->requiredPerms = 0;
1627 * They must be in the namespace too for lookup purposes, but only add the
1628 * one(s) that are relevant for the current kind of rule. In an UPDATE
1629 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1630 * there's no need to be so picky for INSERT & DELETE. We do not add them
1633 switch (stmt->event)
1636 addRTEtoQuery(pstate, oldrte, false, true, true);
1639 addRTEtoQuery(pstate, oldrte, false, true, true);
1640 addRTEtoQuery(pstate, newrte, false, true, true);
1643 addRTEtoQuery(pstate, newrte, false, true, true);
1646 addRTEtoQuery(pstate, oldrte, false, true, true);
1649 elog(ERROR, "unrecognized event type: %d",
1654 /* take care of the where clause */
1655 *whereClause = transformWhereClause(pstate,
1656 (Node *) copyObject(stmt->whereClause),
1659 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
1661 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1662 errmsg("rule WHERE condition cannot contain references to other relations")));
1664 /* aggregates not allowed (but subselects are okay) */
1665 if (pstate->p_hasAggs)
1667 (errcode(ERRCODE_GROUPING_ERROR),
1668 errmsg("cannot use aggregate function in rule WHERE condition")));
1669 if (pstate->p_hasWindowFuncs)
1671 (errcode(ERRCODE_WINDOWING_ERROR),
1672 errmsg("cannot use window function in rule WHERE condition")));
1675 * 'instead nothing' rules with a qualification need a query rangetable so
1676 * the rewrite handler can add the negated rule qualification to the
1677 * original query. We create a query with the new command type CMD_NOTHING
1678 * here that is treated specially by the rewrite system.
1680 if (stmt->actions == NIL)
1682 Query *nothing_qry = makeNode(Query);
1684 nothing_qry->commandType = CMD_NOTHING;
1685 nothing_qry->rtable = pstate->p_rtable;
1686 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1688 *actions = list_make1(nothing_qry);
1693 List *newactions = NIL;
1696 * transform each statement, like parse_sub_analyze()
1698 foreach(l, stmt->actions)
1700 Node *action = (Node *) lfirst(l);
1701 ParseState *sub_pstate = make_parsestate(NULL);
1708 * Since outer ParseState isn't parent of inner, have to pass down
1709 * the query text by hand.
1711 sub_pstate->p_sourcetext = queryString;
1714 * Set up OLD/NEW in the rtable for this statement. The entries
1715 * are added only to relnamespace, not varnamespace, because we
1716 * don't want them to be referred to by unqualified field names
1717 * nor "*" in the rule actions. We decide later whether to put
1718 * them in the joinlist.
1720 oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
1721 makeAlias("old", NIL),
1723 newrte = addRangeTableEntryForRelation(sub_pstate, rel,
1724 makeAlias("new", NIL),
1726 oldrte->requiredPerms = 0;
1727 newrte->requiredPerms = 0;
1728 addRTEtoQuery(sub_pstate, oldrte, false, true, false);
1729 addRTEtoQuery(sub_pstate, newrte, false, true, false);
1731 /* Transform the rule action statement */
1732 top_subqry = transformStmt(sub_pstate,
1733 (Node *) copyObject(action));
1736 * We cannot support utility-statement actions (eg NOTIFY) with
1737 * nonempty rule WHERE conditions, because there's no way to make
1738 * the utility action execute conditionally.
1740 if (top_subqry->commandType == CMD_UTILITY &&
1741 *whereClause != NULL)
1743 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1744 errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
1747 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
1748 * into the SELECT, and that's what we need to look at. (Ugly
1749 * kluge ... try to fix this when we redesign querytrees.)
1751 sub_qry = getInsertSelectQuery(top_subqry, NULL);
1754 * If the sub_qry is a setop, we cannot attach any qualifications
1755 * to it, because the planner won't notice them. This could
1756 * perhaps be relaxed someday, but for now, we may as well reject
1757 * such a rule immediately.
1759 if (sub_qry->setOperations != NULL && *whereClause != NULL)
1761 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1762 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1765 * Validate action's use of OLD/NEW, qual too
1768 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1769 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
1771 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1772 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
1774 switch (stmt->event)
1779 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1780 errmsg("ON SELECT rule cannot use OLD")));
1783 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1784 errmsg("ON SELECT rule cannot use NEW")));
1792 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1793 errmsg("ON INSERT rule cannot use OLD")));
1798 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1799 errmsg("ON DELETE rule cannot use NEW")));
1802 elog(ERROR, "unrecognized event type: %d",
1808 * For efficiency's sake, add OLD to the rule action's jointree
1809 * only if it was actually referenced in the statement or qual.
1811 * For INSERT, NEW is not really a relation (only a reference to
1812 * the to-be-inserted tuple) and should never be added to the
1815 * For UPDATE, we treat NEW as being another kind of reference to
1816 * OLD, because it represents references to *transformed* tuples
1817 * of the existing relation. It would be wrong to enter NEW
1818 * separately in the jointree, since that would cause a double
1819 * join of the updated relation. It's also wrong to fail to make
1820 * a jointree entry if only NEW and not OLD is mentioned.
1822 if (has_old || (has_new && stmt->event == CMD_UPDATE))
1825 * If sub_qry is a setop, manipulating its jointree will do no
1826 * good at all, because the jointree is dummy. (This should be
1827 * a can't-happen case because of prior tests.)
1829 if (sub_qry->setOperations != NULL)
1831 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1832 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1833 /* hack so we can use addRTEtoQuery() */
1834 sub_pstate->p_rtable = sub_qry->rtable;
1835 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
1836 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
1837 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
1840 newactions = lappend(newactions, top_subqry);
1842 free_parsestate(sub_pstate);
1845 *actions = newactions;
1848 free_parsestate(pstate);
1850 /* Close relation, but keep the exclusive lock */
1851 heap_close(rel, NoLock);
1856 * transformAlterTableStmt -
1857 * parse analysis for ALTER TABLE
1859 * Returns a List of utility commands to be done in sequence. One of these
1860 * will be the transformed AlterTableStmt, but there may be additional actions
1861 * to be done before and after the actual AlterTable() call.
1864 transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
1868 CreateStmtContext cxt;
1873 List *newcmds = NIL;
1874 bool skipValidation = true;
1875 AlterTableCmd *newcmd;
1878 * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
1879 * is overkill, but easy.)
1881 stmt = (AlterTableStmt *) copyObject(stmt);
1884 * Acquire exclusive lock on the target relation, which will be held until
1885 * end of transaction. This ensures any decisions we make here based on
1886 * the state of the relation will still be good at execution. We must get
1887 * exclusive lock now because execution will; taking a lower grade lock
1888 * now and trying to upgrade later risks deadlock.
1890 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
1893 pstate = make_parsestate(NULL);
1894 pstate->p_sourcetext = queryString;
1896 cxt.stmtType = "ALTER TABLE";
1897 cxt.relation = stmt->relation;
1899 cxt.inhRelations = NIL;
1901 cxt.hasoids = false; /* need not be right */
1903 cxt.ckconstraints = NIL;
1904 cxt.fkconstraints = NIL;
1905 cxt.ixconstraints = NIL;
1906 cxt.inh_indexes = NIL;
1912 * The only subtypes that currently require parse transformation handling
1913 * are ADD COLUMN and ADD CONSTRAINT. These largely re-use code from
1916 foreach(lcmd, stmt->cmds)
1918 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
1920 switch (cmd->subtype)
1923 case AT_AddColumnToView:
1925 ColumnDef *def = (ColumnDef *) cmd->def;
1927 Assert(IsA(def, ColumnDef));
1928 transformColumnDefinition(pstate, &cxt, def);
1931 * If the column has a non-null default, we can't skip
1932 * validation of foreign keys.
1934 if (def->raw_default != NULL)
1935 skipValidation = false;
1938 * All constraints are processed in other ways. Remove the
1941 def->constraints = NIL;
1943 newcmds = lappend(newcmds, cmd);
1946 case AT_AddConstraint:
1949 * The original AddConstraint cmd node doesn't go to newcmds
1951 if (IsA(cmd->def, Constraint))
1953 transformTableConstraint(pstate, &cxt,
1954 (Constraint *) cmd->def);
1955 if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
1956 skipValidation = false;
1959 elog(ERROR, "unrecognized node type: %d",
1960 (int) nodeTag(cmd->def));
1963 case AT_ProcessedConstraint:
1966 * Already-transformed ADD CONSTRAINT, so just make it look
1967 * like the standard case.
1969 cmd->subtype = AT_AddConstraint;
1970 newcmds = lappend(newcmds, cmd);
1974 newcmds = lappend(newcmds, cmd);
1980 * transformIndexConstraints wants cxt.alist to contain only index
1981 * statements, so transfer anything we already have into save_alist
1984 save_alist = cxt.alist;
1987 /* Postprocess index and FK constraints */
1988 transformIndexConstraints(pstate, &cxt);
1990 transformFKConstraints(pstate, &cxt, skipValidation, true);
1993 * Push any index-creation commands into the ALTER, so that they can be
1994 * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
1995 * the IndexStmt attached to an AT_AddIndex subcommand has already been
1996 * through transformIndexStmt.
1998 foreach(l, cxt.alist)
2000 Node *idxstmt = (Node *) lfirst(l);
2002 Assert(IsA(idxstmt, IndexStmt));
2003 newcmd = makeNode(AlterTableCmd);
2004 newcmd->subtype = AT_AddIndex;
2005 newcmd->def = (Node *) transformIndexStmt((IndexStmt *) idxstmt,
2007 newcmds = lappend(newcmds, newcmd);
2011 /* Append any CHECK or FK constraints to the commands list */
2012 foreach(l, cxt.ckconstraints)
2014 newcmd = makeNode(AlterTableCmd);
2015 newcmd->subtype = AT_AddConstraint;
2016 newcmd->def = (Node *) lfirst(l);
2017 newcmds = lappend(newcmds, newcmd);
2019 foreach(l, cxt.fkconstraints)
2021 newcmd = makeNode(AlterTableCmd);
2022 newcmd->subtype = AT_AddConstraint;
2023 newcmd->def = (Node *) lfirst(l);
2024 newcmds = lappend(newcmds, newcmd);
2027 /* Close rel but keep lock */
2028 relation_close(rel, NoLock);
2033 stmt->cmds = newcmds;
2035 result = lappend(cxt.blist, stmt);
2036 result = list_concat(result, cxt.alist);
2037 result = list_concat(result, save_alist);
2044 * Preprocess a list of column constraint clauses
2045 * to attach constraint attributes to their primary constraint nodes
2046 * and detect inconsistent/misplaced constraint attributes.
2048 * NOTE: currently, attributes are only supported for FOREIGN KEY, UNIQUE,
2049 * and PRIMARY KEY constraints, but someday they ought to be supported
2050 * for other constraint types.
2053 transformConstraintAttrs(ParseState *pstate, List *constraintList)
2055 Constraint *lastprimarycon = NULL;
2056 bool saw_deferrability = false;
2057 bool saw_initially = false;
2060 #define SUPPORTS_ATTRS(node) \
2061 ((node) != NULL && \
2062 ((node)->contype == CONSTR_PRIMARY || \
2063 (node)->contype == CONSTR_UNIQUE || \
2064 (node)->contype == CONSTR_EXCLUSION || \
2065 (node)->contype == CONSTR_FOREIGN))
2067 foreach(clist, constraintList)
2069 Constraint *con = (Constraint *) lfirst(clist);
2071 if (!IsA(con, Constraint))
2072 elog(ERROR, "unrecognized node type: %d",
2073 (int) nodeTag(con));
2074 switch (con->contype)
2076 case CONSTR_ATTR_DEFERRABLE:
2077 if (!SUPPORTS_ATTRS(lastprimarycon))
2079 (errcode(ERRCODE_SYNTAX_ERROR),
2080 errmsg("misplaced DEFERRABLE clause"),
2081 parser_errposition(pstate, con->location)));
2082 if (saw_deferrability)
2084 (errcode(ERRCODE_SYNTAX_ERROR),
2085 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2086 parser_errposition(pstate, con->location)));
2087 saw_deferrability = true;
2088 lastprimarycon->deferrable = true;
2091 case CONSTR_ATTR_NOT_DEFERRABLE:
2092 if (!SUPPORTS_ATTRS(lastprimarycon))
2094 (errcode(ERRCODE_SYNTAX_ERROR),
2095 errmsg("misplaced NOT DEFERRABLE clause"),
2096 parser_errposition(pstate, con->location)));
2097 if (saw_deferrability)
2099 (errcode(ERRCODE_SYNTAX_ERROR),
2100 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2101 parser_errposition(pstate, con->location)));
2102 saw_deferrability = true;
2103 lastprimarycon->deferrable = false;
2104 if (saw_initially &&
2105 lastprimarycon->initdeferred)
2107 (errcode(ERRCODE_SYNTAX_ERROR),
2108 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2109 parser_errposition(pstate, con->location)));
2112 case CONSTR_ATTR_DEFERRED:
2113 if (!SUPPORTS_ATTRS(lastprimarycon))
2115 (errcode(ERRCODE_SYNTAX_ERROR),
2116 errmsg("misplaced INITIALLY DEFERRED clause"),
2117 parser_errposition(pstate, con->location)));
2120 (errcode(ERRCODE_SYNTAX_ERROR),
2121 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2122 parser_errposition(pstate, con->location)));
2123 saw_initially = true;
2124 lastprimarycon->initdeferred = true;
2127 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
2129 if (!saw_deferrability)
2130 lastprimarycon->deferrable = true;
2131 else if (!lastprimarycon->deferrable)
2133 (errcode(ERRCODE_SYNTAX_ERROR),
2134 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2135 parser_errposition(pstate, con->location)));
2138 case CONSTR_ATTR_IMMEDIATE:
2139 if (!SUPPORTS_ATTRS(lastprimarycon))
2141 (errcode(ERRCODE_SYNTAX_ERROR),
2142 errmsg("misplaced INITIALLY IMMEDIATE clause"),
2143 parser_errposition(pstate, con->location)));
2146 (errcode(ERRCODE_SYNTAX_ERROR),
2147 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2148 parser_errposition(pstate, con->location)));
2149 saw_initially = true;
2150 lastprimarycon->initdeferred = false;
2154 /* Otherwise it's not an attribute */
2155 lastprimarycon = con;
2156 /* reset flags for new primary node */
2157 saw_deferrability = false;
2158 saw_initially = false;
2165 * Special handling of type definition for a column
2168 transformColumnType(ParseState *pstate, ColumnDef *column)
2171 * All we really need to do here is verify that the type is valid.
2173 Type ctype = typenameType(pstate, column->typeName, NULL);
2175 ReleaseSysCache(ctype);
2180 * transformCreateSchemaStmt -
2181 * analyzes the CREATE SCHEMA statement
2183 * Split the schema element list into individual commands and place
2184 * them in the result list in an order such that there are no forward
2185 * references (e.g. GRANT to a table created later in the list). Note
2186 * that the logic we use for determining forward references is
2187 * presently quite incomplete.
2189 * SQL92 also allows constraints to make forward references, so thumb through
2190 * the table columns and move forward references to a posterior alter-table
2193 * The result is a list of parse nodes that still need to be analyzed ---
2194 * but we can't analyze the later commands until we've executed the earlier
2195 * ones, because of possible inter-object references.
2197 * Note: this breaks the rules a little bit by modifying schema-name fields
2198 * within passed-in structs. However, the transformation would be the same
2199 * if done over, so it should be all right to scribble on the input to this
2203 transformCreateSchemaStmt(CreateSchemaStmt *stmt)
2205 CreateSchemaStmtContext cxt;
2209 cxt.stmtType = "CREATE SCHEMA";
2210 cxt.schemaname = stmt->schemaname;
2211 cxt.authid = stmt->authid;
2212 cxt.sequences = NIL;
2220 * Run through each schema element in the schema element list. Separate
2221 * statements by type, and do preliminary analysis.
2223 foreach(elements, stmt->schemaElts)
2225 Node *element = lfirst(elements);
2227 switch (nodeTag(element))
2229 case T_CreateSeqStmt:
2231 CreateSeqStmt *elp = (CreateSeqStmt *) element;
2233 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
2234 cxt.sequences = lappend(cxt.sequences, element);
2240 CreateStmt *elp = (CreateStmt *) element;
2242 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2245 * XXX todo: deal with constraints
2247 cxt.tables = lappend(cxt.tables, element);
2253 ViewStmt *elp = (ViewStmt *) element;
2255 setSchemaName(cxt.schemaname, &elp->view->schemaname);
2258 * XXX todo: deal with references between views
2260 cxt.views = lappend(cxt.views, element);
2266 IndexStmt *elp = (IndexStmt *) element;
2268 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2269 cxt.indexes = lappend(cxt.indexes, element);
2273 case T_CreateTrigStmt:
2275 CreateTrigStmt *elp = (CreateTrigStmt *) element;
2277 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2278 cxt.triggers = lappend(cxt.triggers, element);
2283 cxt.grants = lappend(cxt.grants, element);
2287 elog(ERROR, "unrecognized node type: %d",
2288 (int) nodeTag(element));
2293 result = list_concat(result, cxt.sequences);
2294 result = list_concat(result, cxt.tables);
2295 result = list_concat(result, cxt.views);
2296 result = list_concat(result, cxt.indexes);
2297 result = list_concat(result, cxt.triggers);
2298 result = list_concat(result, cxt.grants);
2305 * Set or check schema name in an element of a CREATE SCHEMA command
2308 setSchemaName(char *context_schema, char **stmt_schema_name)
2310 if (*stmt_schema_name == NULL)
2311 *stmt_schema_name = context_schema;
2312 else if (strcmp(context_schema, *stmt_schema_name) != 0)
2314 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
2315 errmsg("CREATE specifies a schema (%s) "
2316 "different from the one being created (%s)",
2317 *stmt_schema_name, context_schema)));