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.27 2009/10/12 19:49:24 adunstan 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_type.h"
39 #include "commands/comment.h"
40 #include "commands/defrem.h"
41 #include "commands/tablecmds.h"
42 #include "commands/tablespace.h"
43 #include "miscadmin.h"
44 #include "nodes/makefuncs.h"
45 #include "nodes/nodeFuncs.h"
46 #include "parser/analyze.h"
47 #include "parser/parse_clause.h"
48 #include "parser/parse_expr.h"
49 #include "parser/parse_relation.h"
50 #include "parser/parse_type.h"
51 #include "parser/parse_utilcmd.h"
52 #include "parser/parser.h"
53 #include "rewrite/rewriteManip.h"
54 #include "utils/acl.h"
55 #include "utils/builtins.h"
56 #include "utils/lsyscache.h"
57 #include "utils/relcache.h"
58 #include "utils/syscache.h"
61 /* State shared by transformCreateStmt and its subroutines */
64 const char *stmtType; /* "CREATE TABLE" or "ALTER TABLE" */
65 RangeVar *relation; /* relation to create */
66 Relation rel; /* opened/locked rel, if ALTER */
67 List *inhRelations; /* relations to inherit from */
68 bool isalter; /* true if altering existing table */
69 bool hasoids; /* does relation have an OID column? */
70 List *columns; /* ColumnDef items */
71 List *ckconstraints; /* CHECK constraints */
72 List *fkconstraints; /* FOREIGN KEY constraints */
73 List *ixconstraints; /* index-creating constraints */
74 List *inh_indexes; /* cloned indexes from INCLUDING INDEXES */
75 List *blist; /* "before list" of things to do before
76 * creating the table */
77 List *alist; /* "after list" of things to do after creating
79 IndexStmt *pkey; /* PRIMARY KEY index, if any */
82 /* State shared by transformCreateSchemaStmt and its subroutines */
85 const char *stmtType; /* "CREATE SCHEMA" or "ALTER SCHEMA" */
86 char *schemaname; /* name of schema */
87 char *authid; /* owner of schema */
88 List *sequences; /* CREATE SEQUENCE items */
89 List *tables; /* CREATE TABLE items */
90 List *views; /* CREATE VIEW items */
91 List *indexes; /* CREATE INDEX items */
92 List *triggers; /* CREATE TRIGGER items */
93 List *grants; /* GRANT items */
94 } CreateSchemaStmtContext;
97 static void transformColumnDefinition(ParseState *pstate,
98 CreateStmtContext *cxt,
100 static void transformTableConstraint(ParseState *pstate,
101 CreateStmtContext *cxt,
102 Constraint *constraint);
103 static void transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
104 InhRelation *inhrelation);
105 static char *chooseIndexName(const RangeVar *relation, IndexStmt *index_stmt);
106 static IndexStmt *generateClonedIndexStmt(CreateStmtContext *cxt,
107 Relation parent_index, AttrNumber *attmap);
108 static List *get_opclass(Oid opclass, Oid actual_datatype);
109 static void transformIndexConstraints(ParseState *pstate,
110 CreateStmtContext *cxt);
111 static IndexStmt *transformIndexConstraint(Constraint *constraint,
112 CreateStmtContext *cxt);
113 static void transformFKConstraints(ParseState *pstate,
114 CreateStmtContext *cxt,
116 bool isAddConstraint);
117 static void transformConstraintAttrs(ParseState *pstate, List *constraintList);
118 static void transformColumnType(ParseState *pstate, ColumnDef *column);
119 static void setSchemaName(char *context_schema, char **stmt_schema_name);
123 * transformCreateStmt -
124 * parse analysis for CREATE TABLE
126 * Returns a List of utility commands to be done in sequence. One of these
127 * will be the transformed CreateStmt, but there may be additional actions
128 * to be done before and after the actual DefineRelation() call.
130 * SQL92 allows constraints to be scattered all over, so thumb through
131 * the columns and collect all constraints into one place.
132 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
133 * then expand those into multiple IndexStmt blocks.
134 * - thomas 1997-12-02
137 transformCreateStmt(CreateStmt *stmt, const char *queryString)
140 CreateStmtContext cxt;
146 * We must not scribble on the passed-in CreateStmt, so copy it. (This is
147 * overkill, but easy.)
149 stmt = (CreateStmt *) copyObject(stmt);
152 * If the target relation name isn't schema-qualified, make it so. This
153 * prevents some corner cases in which added-on rewritten commands might
154 * think they should apply to other relations that have the same name and
155 * are earlier in the search path. "istemp" is equivalent to a
156 * specification of pg_temp, so no need for anything extra in that case.
158 if (stmt->relation->schemaname == NULL && !stmt->relation->istemp)
160 Oid namespaceid = RangeVarGetCreationNamespace(stmt->relation);
162 stmt->relation->schemaname = get_namespace_name(namespaceid);
166 pstate = make_parsestate(NULL);
167 pstate->p_sourcetext = queryString;
169 cxt.stmtType = "CREATE TABLE";
170 cxt.relation = stmt->relation;
172 cxt.inhRelations = stmt->inhRelations;
175 cxt.ckconstraints = NIL;
176 cxt.fkconstraints = NIL;
177 cxt.ixconstraints = NIL;
178 cxt.inh_indexes = NIL;
182 cxt.hasoids = interpretOidsOption(stmt->options);
185 * Run through each primary element in the table creation clause. Separate
186 * column defs from constraints, and do preliminary analysis.
188 foreach(elements, stmt->tableElts)
190 Node *element = lfirst(elements);
192 switch (nodeTag(element))
195 transformColumnDefinition(pstate, &cxt,
196 (ColumnDef *) element);
200 transformTableConstraint(pstate, &cxt,
201 (Constraint *) element);
205 transformInhRelation(pstate, &cxt,
206 (InhRelation *) element);
210 elog(ERROR, "unrecognized node type: %d",
211 (int) nodeTag(element));
217 * transformIndexConstraints wants cxt.alist to contain only index
218 * statements, so transfer anything we already have into save_alist.
220 save_alist = cxt.alist;
223 Assert(stmt->constraints == NIL);
226 * Postprocess constraints that give rise to index definitions.
228 transformIndexConstraints(pstate, &cxt);
231 * Postprocess foreign-key constraints.
233 transformFKConstraints(pstate, &cxt, true, false);
238 stmt->tableElts = cxt.columns;
239 stmt->constraints = cxt.ckconstraints;
241 result = lappend(cxt.blist, stmt);
242 result = list_concat(result, cxt.alist);
243 result = list_concat(result, save_alist);
249 * transformColumnDefinition -
250 * transform a single ColumnDef within CREATE TABLE
251 * Also used in ALTER TABLE ADD COLUMN
254 transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
260 Constraint *constraint;
263 cxt->columns = lappend(cxt->columns, column);
265 /* Check for SERIAL pseudo-types */
267 if (list_length(column->typeName->names) == 1 &&
268 !column->typeName->pct_type)
270 char *typname = strVal(linitial(column->typeName->names));
272 if (strcmp(typname, "serial") == 0 ||
273 strcmp(typname, "serial4") == 0)
276 column->typeName->names = NIL;
277 column->typeName->typeOid = INT4OID;
279 else if (strcmp(typname, "bigserial") == 0 ||
280 strcmp(typname, "serial8") == 0)
283 column->typeName->names = NIL;
284 column->typeName->typeOid = INT8OID;
288 * We have to reject "serial[]" explicitly, because once we've set
289 * typeid, LookupTypeName won't notice arrayBounds. We don't need any
290 * special coding for serial(typmod) though.
292 if (is_serial && column->typeName->arrayBounds != NIL)
294 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
295 errmsg("array of serial is not implemented"),
296 parser_errposition(pstate, column->typeName->location)));
299 /* Do necessary work on the column type declaration */
300 transformColumnType(pstate, column);
302 /* Special actions for SERIAL pseudo-types */
311 FuncCall *funccallnode;
312 CreateSeqStmt *seqstmt;
313 AlterSeqStmt *altseqstmt;
317 * Determine namespace and name to use for the sequence.
319 * Although we use ChooseRelationName, it's not guaranteed that the
320 * selected sequence name won't conflict; given sufficiently long
321 * field names, two different serial columns in the same table could
322 * be assigned the same sequence name, and we'd not notice since we
323 * aren't creating the sequence quite yet. In practice this seems
324 * quite unlikely to be a problem, especially since few people would
325 * need two serial columns in one table.
328 snamespaceid = RelationGetNamespace(cxt->rel);
330 snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
331 snamespace = get_namespace_name(snamespaceid);
332 sname = ChooseRelationName(cxt->relation->relname,
338 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
339 cxt->stmtType, sname,
340 cxt->relation->relname, column->colname)));
343 * Build a CREATE SEQUENCE command to create the sequence object, and
344 * add it to the list of things to be done before this CREATE/ALTER
347 seqstmt = makeNode(CreateSeqStmt);
348 seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
349 seqstmt->options = NIL;
351 cxt->blist = lappend(cxt->blist, seqstmt);
354 * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence
355 * as owned by this column, and add it to the list of things to be
356 * done after this CREATE/ALTER TABLE.
358 altseqstmt = makeNode(AlterSeqStmt);
359 altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
360 attnamelist = list_make3(makeString(snamespace),
361 makeString(cxt->relation->relname),
362 makeString(column->colname));
363 altseqstmt->options = list_make1(makeDefElem("owned_by",
364 (Node *) attnamelist));
366 cxt->alist = lappend(cxt->alist, altseqstmt);
369 * Create appropriate constraints for SERIAL. We do this in full,
370 * rather than shortcutting, so that we will detect any conflicting
371 * constraints the user wrote (like a different DEFAULT).
373 * Create an expression tree representing the function call
374 * nextval('sequencename'). We cannot reduce the raw tree to cooked
375 * form until after the sequence is created, but there's no need to do
378 qstring = quote_qualified_identifier(snamespace, sname);
379 snamenode = makeNode(A_Const);
380 snamenode->val.type = T_String;
381 snamenode->val.val.str = qstring;
382 snamenode->location = -1;
383 castnode = makeNode(TypeCast);
384 castnode->typeName = SystemTypeName("regclass");
385 castnode->arg = (Node *) snamenode;
386 castnode->location = -1;
387 funccallnode = makeNode(FuncCall);
388 funccallnode->funcname = SystemFuncName("nextval");
389 funccallnode->args = list_make1(castnode);
390 funccallnode->agg_star = false;
391 funccallnode->agg_distinct = false;
392 funccallnode->func_variadic = false;
393 funccallnode->over = NULL;
394 funccallnode->location = -1;
396 constraint = makeNode(Constraint);
397 constraint->contype = CONSTR_DEFAULT;
398 constraint->location = -1;
399 constraint->raw_expr = (Node *) funccallnode;
400 constraint->cooked_expr = NULL;
401 column->constraints = lappend(column->constraints, constraint);
403 constraint = makeNode(Constraint);
404 constraint->contype = CONSTR_NOTNULL;
405 constraint->location = -1;
406 column->constraints = lappend(column->constraints, constraint);
409 /* Process column constraints, if any... */
410 transformConstraintAttrs(pstate, column->constraints);
412 saw_nullable = false;
415 foreach(clist, column->constraints)
417 constraint = lfirst(clist);
418 Assert(IsA(constraint, Constraint));
420 switch (constraint->contype)
423 if (saw_nullable && column->is_not_null)
425 (errcode(ERRCODE_SYNTAX_ERROR),
426 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
427 column->colname, cxt->relation->relname),
428 parser_errposition(pstate,
429 constraint->location)));
430 column->is_not_null = FALSE;
435 if (saw_nullable && !column->is_not_null)
437 (errcode(ERRCODE_SYNTAX_ERROR),
438 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
439 column->colname, cxt->relation->relname),
440 parser_errposition(pstate,
441 constraint->location)));
442 column->is_not_null = TRUE;
449 (errcode(ERRCODE_SYNTAX_ERROR),
450 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
451 column->colname, cxt->relation->relname),
452 parser_errposition(pstate,
453 constraint->location)));
454 column->raw_default = constraint->raw_expr;
455 Assert(constraint->cooked_expr == NULL);
461 if (constraint->keys == NIL)
462 constraint->keys = list_make1(makeString(column->colname));
463 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
467 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
472 * Fill in the current attribute's name and throw it into the
473 * list of FK constraints to be processed later.
475 constraint->fk_attrs = list_make1(makeString(column->colname));
476 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
479 case CONSTR_ATTR_DEFERRABLE:
480 case CONSTR_ATTR_NOT_DEFERRABLE:
481 case CONSTR_ATTR_DEFERRED:
482 case CONSTR_ATTR_IMMEDIATE:
483 /* transformConstraintAttrs took care of these */
487 elog(ERROR, "unrecognized constraint type: %d",
488 constraint->contype);
495 * transformTableConstraint
496 * transform a Constraint node within CREATE TABLE or ALTER TABLE
499 transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt,
500 Constraint *constraint)
502 switch (constraint->contype)
506 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
510 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
514 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
520 case CONSTR_ATTR_DEFERRABLE:
521 case CONSTR_ATTR_NOT_DEFERRABLE:
522 case CONSTR_ATTR_DEFERRED:
523 case CONSTR_ATTR_IMMEDIATE:
524 elog(ERROR, "invalid context for constraint type %d",
525 constraint->contype);
529 elog(ERROR, "unrecognized constraint type: %d",
530 constraint->contype);
536 * transformInhRelation
538 * Change the LIKE <subtable> portion of a CREATE TABLE statement into
539 * column definitions which recreate the user defined column portions of
543 transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
544 InhRelation *inhRelation)
546 AttrNumber parent_attno;
553 relation = parserOpenTable(pstate, inhRelation->relation, AccessShareLock);
555 if (relation->rd_rel->relkind != RELKIND_RELATION)
557 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
558 errmsg("inherited relation \"%s\" is not a table",
559 inhRelation->relation->relname)));
562 * Check for SELECT privilages
564 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
566 if (aclresult != ACLCHECK_OK)
567 aclcheck_error(aclresult, ACL_KIND_CLASS,
568 RelationGetRelationName(relation));
570 tupleDesc = RelationGetDescr(relation);
571 constr = tupleDesc->constr;
574 * Insert the copied attributes into the cxt for the new table definition.
576 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
579 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
580 char *attributeName = NameStr(attribute->attname);
584 * Ignore dropped columns in the parent.
586 if (attribute->attisdropped)
590 * Create a new column, which is marked as NOT inherited.
592 * For constraints, ONLY the NOT NULL constraint is inherited by the
593 * new column definition per SQL99.
595 def = makeNode(ColumnDef);
596 def->colname = pstrdup(attributeName);
597 def->typeName = makeTypeNameFromOid(attribute->atttypid,
598 attribute->atttypmod);
600 def->is_local = true;
601 def->is_not_null = attribute->attnotnull;
602 def->raw_default = NULL;
603 def->cooked_default = NULL;
604 def->constraints = NIL;
609 cxt->columns = lappend(cxt->columns, def);
612 * Copy default, if present and the default has been requested
614 if (attribute->atthasdef &&
615 (inhRelation->options & CREATE_TABLE_LIKE_DEFAULTS))
617 Node *this_default = NULL;
618 AttrDefault *attrdef;
621 /* Find default in constraint structure */
622 Assert(constr != NULL);
623 attrdef = constr->defval;
624 for (i = 0; i < constr->num_defval; i++)
626 if (attrdef[i].adnum == parent_attno)
628 this_default = stringToNode(attrdef[i].adbin);
632 Assert(this_default != NULL);
635 * If default expr could contain any vars, we'd need to fix 'em,
636 * but it can't; so default is ready to apply to child.
639 def->cooked_default = this_default;
642 /* Likewise, copy storage if requested */
643 if (inhRelation->options & CREATE_TABLE_LIKE_STORAGE)
644 def->storage = attribute->attstorage;
646 /* Likewise, copy comment if requested */
647 if ((inhRelation->options & CREATE_TABLE_LIKE_COMMENTS) &&
648 (comment = GetComment(attribute->attrelid, RelationRelationId,
649 attribute->attnum)) != NULL)
651 CommentStmt *stmt = makeNode(CommentStmt);
653 stmt->objtype = OBJECT_COLUMN;
654 stmt->objname = list_make3(makeString(cxt->relation->schemaname),
655 makeString(cxt->relation->relname),
656 makeString(def->colname));
658 stmt->comment = comment;
660 cxt->alist = lappend(cxt->alist, stmt);
665 * Copy CHECK constraints if requested, being careful to adjust attribute
668 if ((inhRelation->options & CREATE_TABLE_LIKE_CONSTRAINTS) && tupleDesc->constr)
670 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
673 for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
675 char *ccname = tupleDesc->constr->check[ccnum].ccname;
676 char *ccbin = tupleDesc->constr->check[ccnum].ccbin;
677 Node *ccbin_node = stringToNode(ccbin);
678 Constraint *n = makeNode(Constraint);
680 change_varattnos_of_a_node(ccbin_node, attmap);
682 n->contype = CONSTR_CHECK;
684 n->conname = pstrdup(ccname);
686 n->cooked_expr = nodeToString(ccbin_node);
687 cxt->ckconstraints = lappend(cxt->ckconstraints, n);
689 /* Copy comment on constraint */
690 if ((inhRelation->options & CREATE_TABLE_LIKE_COMMENTS) &&
691 (comment = GetComment(GetConstraintByName(RelationGetRelid(
692 relation), n->conname), ConstraintRelationId, 0)) != NULL)
694 CommentStmt *stmt = makeNode(CommentStmt);
696 stmt->objtype = OBJECT_CONSTRAINT;
697 stmt->objname = list_make3(makeString(cxt->relation->schemaname),
698 makeString(cxt->relation->relname),
699 makeString(n->conname));
701 stmt->comment = comment;
703 cxt->alist = lappend(cxt->alist, stmt);
709 * Likewise, copy indexes if requested
711 if ((inhRelation->options & CREATE_TABLE_LIKE_INDEXES) &&
712 relation->rd_rel->relhasindex)
714 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
715 List *parent_indexes;
718 parent_indexes = RelationGetIndexList(relation);
720 foreach(l, parent_indexes)
722 Oid parent_index_oid = lfirst_oid(l);
723 Relation parent_index;
724 IndexStmt *index_stmt;
726 parent_index = index_open(parent_index_oid, AccessShareLock);
728 /* Build CREATE INDEX statement to recreate the parent_index */
729 index_stmt = generateClonedIndexStmt(cxt, parent_index, attmap);
731 /* Copy comment on index */
732 if (inhRelation->options & CREATE_TABLE_LIKE_COMMENTS)
738 comment = GetComment(parent_index_oid, RelationRelationId, 0);
742 /* Assign name for index because CommentStmt requires name. */
743 if (index_stmt->idxname == NULL)
744 index_stmt->idxname = chooseIndexName(cxt->relation, index_stmt);
746 stmt = makeNode(CommentStmt);
747 stmt->objtype = OBJECT_INDEX;
748 stmt->objname = list_make2(makeString(cxt->relation->schemaname),
749 makeString(index_stmt->idxname));
751 stmt->comment = comment;
753 cxt->alist = lappend(cxt->alist, stmt);
756 /* Copy comment on index's columns */
758 foreach(lc, index_stmt->indexParams)
763 comment = GetComment(parent_index_oid, RelationRelationId, i);
767 /* Assign name for index because CommentStmt requires name. */
768 if (index_stmt->idxname == NULL)
769 index_stmt->idxname = chooseIndexName(cxt->relation, index_stmt);
771 attname = ((IndexElem *) lfirst(lc))->name;
773 /* expression index has a dummy column name */
776 attname = palloc(NAMEDATALEN);
777 sprintf(attname, "pg_expression_%d", i);
780 stmt = makeNode(CommentStmt);
781 stmt->objtype = OBJECT_COLUMN;
782 stmt->objname = list_make3(
783 makeString(cxt->relation->schemaname),
784 makeString(index_stmt->idxname),
785 makeString(attname));
787 stmt->comment = comment;
789 cxt->alist = lappend(cxt->alist, stmt);
793 /* Save it in the inh_indexes list for the time being */
794 cxt->inh_indexes = lappend(cxt->inh_indexes, index_stmt);
796 index_close(parent_index, AccessShareLock);
801 * Close the parent rel, but keep our AccessShareLock on it until xact
802 * commit. That will prevent someone else from deleting or ALTERing the
803 * parent before the child is committed.
805 heap_close(relation, NoLock);
811 * Set name to unnamed index. See also the same logic in DefineIndex.
814 chooseIndexName(const RangeVar *relation, IndexStmt *index_stmt)
818 namespaceId = RangeVarGetCreationNamespace(relation);
819 if (index_stmt->primary)
821 /* no need for column list with pkey */
822 return ChooseRelationName(relation->relname, NULL,
823 "pkey", namespaceId);
827 IndexElem *iparam = (IndexElem *) linitial(index_stmt->indexParams);
829 return ChooseRelationName(relation->relname, iparam->name,
835 * Generate an IndexStmt node using information from an already existing index
836 * "source_idx". Attribute numbers should be adjusted according to attmap.
839 generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
842 Oid source_relid = RelationGetRelid(source_idx);
845 Form_pg_class idxrelrec;
846 Form_pg_index idxrec;
851 ListCell *indexpr_item;
859 * Fetch pg_class tuple of source index. We can't use the copy in the
860 * relcache entry because it doesn't include optional fields.
862 ht_idxrel = SearchSysCache(RELOID,
863 ObjectIdGetDatum(source_relid),
865 if (!HeapTupleIsValid(ht_idxrel))
866 elog(ERROR, "cache lookup failed for relation %u", source_relid);
867 idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
869 /* Fetch pg_index tuple for source index from relcache entry */
870 ht_idx = source_idx->rd_indextuple;
871 idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
872 indrelid = idxrec->indrelid;
874 /* Fetch pg_am tuple for source index from relcache entry */
875 amrec = source_idx->rd_am;
877 /* Must get indclass the hard way, since it's not stored in relcache */
878 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
879 Anum_pg_index_indclass, &isnull);
881 indclass = (oidvector *) DatumGetPointer(datum);
883 /* Begin building the IndexStmt */
884 index = makeNode(IndexStmt);
885 index->relation = cxt->relation;
886 index->accessMethod = pstrdup(NameStr(amrec->amname));
887 if (OidIsValid(idxrelrec->reltablespace))
888 index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
890 index->tableSpace = NULL;
891 index->unique = idxrec->indisunique;
892 index->primary = idxrec->indisprimary;
893 index->concurrent = false;
896 * We don't try to preserve the name of the source index; instead, just
897 * let DefineIndex() choose a reasonable name.
899 index->idxname = NULL;
902 * If the index is marked PRIMARY, it's certainly from a constraint; else,
903 * if it's not marked UNIQUE, it certainly isn't. If it is or might be
904 * from a constraint, we have to fetch the constraint to check for
905 * deferrability attributes.
907 if (index->primary || index->unique)
909 Oid constraintId = get_index_constraint(source_relid);
911 if (OidIsValid(constraintId))
914 Form_pg_constraint conrec;
916 ht_constr = SearchSysCache(CONSTROID,
917 ObjectIdGetDatum(constraintId),
919 if (!HeapTupleIsValid(ht_constr))
920 elog(ERROR, "cache lookup failed for constraint %u",
922 conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
924 index->isconstraint = true;
925 index->deferrable = conrec->condeferrable;
926 index->initdeferred = conrec->condeferred;
928 ReleaseSysCache(ht_constr);
931 index->isconstraint = false;
934 index->isconstraint = false;
936 /* Get the index expressions, if any */
937 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
938 Anum_pg_index_indexprs, &isnull);
943 exprsString = TextDatumGetCString(datum);
944 indexprs = (List *) stringToNode(exprsString);
949 /* Build the list of IndexElem */
950 index->indexParams = NIL;
952 indexpr_item = list_head(indexprs);
953 for (keyno = 0; keyno < idxrec->indnatts; keyno++)
956 AttrNumber attnum = idxrec->indkey.values[keyno];
957 int16 opt = source_idx->rd_indoption[keyno];
959 iparam = makeNode(IndexElem);
961 if (AttributeNumberIsValid(attnum))
963 /* Simple index column */
966 attname = get_relid_attribute_name(indrelid, attnum);
967 keycoltype = get_atttype(indrelid, attnum);
969 iparam->name = attname;
974 /* Expressional index */
977 if (indexpr_item == NULL)
978 elog(ERROR, "too few entries in indexprs list");
979 indexkey = (Node *) lfirst(indexpr_item);
980 indexpr_item = lnext(indexpr_item);
982 /* OK to modify indexkey since we are working on a private copy */
983 change_varattnos_of_a_node(indexkey, attmap);
986 iparam->expr = indexkey;
988 keycoltype = exprType(indexkey);
991 /* Add the operator class name, if non-default */
992 iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
994 iparam->ordering = SORTBY_DEFAULT;
995 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
997 /* Adjust options if necessary */
998 if (amrec->amcanorder)
1001 * If it supports sort ordering, copy DESC and NULLS opts. Don't
1002 * set non-default settings unnecessarily, though, so as to
1003 * improve the chance of recognizing equivalence to constraint
1006 if (opt & INDOPTION_DESC)
1008 iparam->ordering = SORTBY_DESC;
1009 if ((opt & INDOPTION_NULLS_FIRST) == 0)
1010 iparam->nulls_ordering = SORTBY_NULLS_LAST;
1014 if (opt & INDOPTION_NULLS_FIRST)
1015 iparam->nulls_ordering = SORTBY_NULLS_FIRST;
1019 index->indexParams = lappend(index->indexParams, iparam);
1022 /* Copy reloptions if any */
1023 datum = SysCacheGetAttr(RELOID, ht_idxrel,
1024 Anum_pg_class_reloptions, &isnull);
1026 index->options = untransformRelOptions(datum);
1028 /* If it's a partial index, decompile and append the predicate */
1029 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1030 Anum_pg_index_indpred, &isnull);
1035 /* Convert text string to node tree */
1036 pred_str = TextDatumGetCString(datum);
1037 index->whereClause = (Node *) stringToNode(pred_str);
1038 /* Adjust attribute numbers */
1039 change_varattnos_of_a_node(index->whereClause, attmap);
1043 ReleaseSysCache(ht_idxrel);
1049 * get_opclass - fetch name of an index operator class
1051 * If the opclass is the default for the given actual_datatype, then
1052 * the return value is NIL.
1055 get_opclass(Oid opclass, Oid actual_datatype)
1058 Form_pg_opclass opc_rec;
1061 ht_opc = SearchSysCache(CLAOID,
1062 ObjectIdGetDatum(opclass),
1064 if (!HeapTupleIsValid(ht_opc))
1065 elog(ERROR, "cache lookup failed for opclass %u", opclass);
1066 opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
1068 if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
1070 /* For simplicity, we always schema-qualify the name */
1071 char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
1072 char *opc_name = pstrdup(NameStr(opc_rec->opcname));
1074 result = list_make2(makeString(nsp_name), makeString(opc_name));
1077 ReleaseSysCache(ht_opc);
1083 * transformIndexConstraints
1084 * Handle UNIQUE and PRIMARY KEY constraints, which create indexes.
1085 * We also merge in any index definitions arising from
1086 * LIKE ... INCLUDING INDEXES.
1089 transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
1092 List *indexlist = NIL;
1096 * Run through the constraints that need to generate an index. For PRIMARY
1097 * KEY, mark each column as NOT NULL and create an index. For UNIQUE,
1098 * create an index as for PRIMARY KEY, but do not insist on NOT NULL.
1100 foreach(lc, cxt->ixconstraints)
1102 Constraint *constraint = (Constraint *) lfirst(lc);
1104 Assert(IsA(constraint, Constraint));
1105 Assert(constraint->contype == CONSTR_PRIMARY ||
1106 constraint->contype == CONSTR_UNIQUE);
1108 index = transformIndexConstraint(constraint, cxt);
1110 indexlist = lappend(indexlist, index);
1113 /* Add in any indexes defined by LIKE ... INCLUDING INDEXES */
1114 foreach(lc, cxt->inh_indexes)
1116 index = (IndexStmt *) lfirst(lc);
1120 if (cxt->pkey != NULL)
1122 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1123 errmsg("multiple primary keys for table \"%s\" are not allowed",
1124 cxt->relation->relname)));
1128 indexlist = lappend(indexlist, index);
1132 * Scan the index list and remove any redundant index specifications. This
1133 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1134 * strict reading of SQL92 would suggest raising an error instead, but
1135 * that strikes me as too anal-retentive. - tgl 2001-02-14
1137 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1138 * pre-existing indexes, too.
1140 Assert(cxt->alist == NIL);
1141 if (cxt->pkey != NULL)
1143 /* Make sure we keep the PKEY index in preference to others... */
1144 cxt->alist = list_make1(cxt->pkey);
1147 foreach(lc, indexlist)
1154 /* if it's pkey, it's already in cxt->alist */
1155 if (index == cxt->pkey)
1158 foreach(k, cxt->alist)
1160 IndexStmt *priorindex = lfirst(k);
1162 if (equal(index->indexParams, priorindex->indexParams) &&
1163 equal(index->whereClause, priorindex->whereClause) &&
1164 strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
1165 index->deferrable == priorindex->deferrable &&
1166 index->initdeferred == priorindex->initdeferred)
1168 priorindex->unique |= index->unique;
1171 * If the prior index is as yet unnamed, and this one is
1172 * named, then transfer the name to the prior index. This
1173 * ensures that if we have named and unnamed constraints,
1174 * we'll use (at least one of) the names for the index.
1176 if (priorindex->idxname == NULL)
1177 priorindex->idxname = index->idxname;
1184 cxt->alist = lappend(cxt->alist, index);
1189 * transformIndexConstraint
1190 * Transform one UNIQUE or PRIMARY KEY constraint for
1191 * transformIndexConstraints.
1194 transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
1200 index = makeNode(IndexStmt);
1202 index->unique = true;
1203 index->primary = (constraint->contype == CONSTR_PRIMARY);
1206 if (cxt->pkey != NULL)
1208 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1209 errmsg("multiple primary keys for table \"%s\" are not allowed",
1210 cxt->relation->relname)));
1214 * In ALTER TABLE case, a primary index might already exist, but
1215 * DefineIndex will check for it.
1218 index->isconstraint = true;
1219 index->deferrable = constraint->deferrable;
1220 index->initdeferred = constraint->initdeferred;
1222 if (constraint->conname != NULL)
1223 index->idxname = pstrdup(constraint->conname);
1225 index->idxname = NULL; /* DefineIndex will choose name */
1227 index->relation = cxt->relation;
1228 index->accessMethod = DEFAULT_INDEX_TYPE;
1229 index->options = constraint->options;
1230 index->tableSpace = constraint->indexspace;
1231 index->indexParams = NIL;
1232 index->whereClause = NULL;
1233 index->concurrent = false;
1236 * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
1237 * also make sure they are NOT NULL, if possible. (Although we could leave
1238 * it to DefineIndex to mark the columns NOT NULL, it's more efficient to
1239 * get it right the first time.)
1241 foreach(keys, constraint->keys)
1243 char *key = strVal(lfirst(keys));
1245 ColumnDef *column = NULL;
1248 foreach(columns, cxt->columns)
1250 column = (ColumnDef *) lfirst(columns);
1251 Assert(IsA(column, ColumnDef));
1252 if (strcmp(column->colname, key) == 0)
1260 /* found column in the new table; force it to be NOT NULL */
1261 if (constraint->contype == CONSTR_PRIMARY)
1262 column->is_not_null = TRUE;
1264 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1267 * column will be a system column in the new table, so accept it.
1268 * System columns can't ever be null, so no need to worry about
1269 * PRIMARY/NOT NULL constraint.
1273 else if (cxt->inhRelations)
1275 /* try inherited tables */
1278 foreach(inher, cxt->inhRelations)
1280 RangeVar *inh = (RangeVar *) lfirst(inher);
1284 Assert(IsA(inh, RangeVar));
1285 rel = heap_openrv(inh, AccessShareLock);
1286 if (rel->rd_rel->relkind != RELKIND_RELATION)
1288 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1289 errmsg("inherited relation \"%s\" is not a table",
1291 for (count = 0; count < rel->rd_att->natts; count++)
1293 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1294 char *inhname = NameStr(inhattr->attname);
1296 if (inhattr->attisdropped)
1298 if (strcmp(key, inhname) == 0)
1303 * We currently have no easy way to force an inherited
1304 * column to be NOT NULL at creation, if its parent
1305 * wasn't so already. We leave it to DefineIndex to
1306 * fix things up in this case.
1311 heap_close(rel, NoLock);
1318 * In the ALTER TABLE case, don't complain about index keys not
1319 * created in the command; they may well exist already. DefineIndex
1320 * will complain about them if not, and will also take care of marking
1323 if (!found && !cxt->isalter)
1325 (errcode(ERRCODE_UNDEFINED_COLUMN),
1326 errmsg("column \"%s\" named in key does not exist",
1329 /* Check for PRIMARY KEY(foo, foo) */
1330 foreach(columns, index->indexParams)
1332 iparam = (IndexElem *) lfirst(columns);
1333 if (iparam->name && strcmp(key, iparam->name) == 0)
1337 (errcode(ERRCODE_DUPLICATE_COLUMN),
1338 errmsg("column \"%s\" appears twice in primary key constraint",
1342 (errcode(ERRCODE_DUPLICATE_COLUMN),
1343 errmsg("column \"%s\" appears twice in unique constraint",
1348 /* OK, add it to the index definition */
1349 iparam = makeNode(IndexElem);
1350 iparam->name = pstrdup(key);
1351 iparam->expr = NULL;
1352 iparam->opclass = NIL;
1353 iparam->ordering = SORTBY_DEFAULT;
1354 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1355 index->indexParams = lappend(index->indexParams, iparam);
1362 * transformFKConstraints
1363 * handle FOREIGN KEY constraints
1366 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1367 bool skipValidation, bool isAddConstraint)
1371 if (cxt->fkconstraints == NIL)
1375 * If CREATE TABLE or adding a column with NULL default, we can safely
1376 * skip validation of the constraint.
1380 foreach(fkclist, cxt->fkconstraints)
1382 Constraint *constraint = (Constraint *) lfirst(fkclist);
1384 constraint->skip_validation = true;
1389 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1390 * CONSTRAINT command to execute after the basic command is complete. (If
1391 * called from ADD CONSTRAINT, that routine will add the FK constraints to
1392 * its own subcommand list.)
1394 * Note: the ADD CONSTRAINT command must also execute after any index
1395 * creation commands. Thus, this should run after
1396 * transformIndexConstraints, so that the CREATE INDEX commands are
1397 * already in cxt->alist.
1399 if (!isAddConstraint)
1401 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1403 alterstmt->relation = cxt->relation;
1404 alterstmt->cmds = NIL;
1405 alterstmt->relkind = OBJECT_TABLE;
1407 foreach(fkclist, cxt->fkconstraints)
1409 Constraint *constraint = (Constraint *) lfirst(fkclist);
1410 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1412 altercmd->subtype = AT_ProcessedConstraint;
1413 altercmd->name = NULL;
1414 altercmd->def = (Node *) constraint;
1415 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1418 cxt->alist = lappend(cxt->alist, alterstmt);
1423 * transformIndexStmt - parse analysis for CREATE INDEX
1425 * Note: this is a no-op for an index not using either index expressions or
1426 * a predicate expression. There are several code paths that create indexes
1427 * without bothering to call this, because they know they don't have any
1428 * such expressions to deal with.
1431 transformIndexStmt(IndexStmt *stmt, const char *queryString)
1439 * We must not scribble on the passed-in IndexStmt, so copy it. (This is
1440 * overkill, but easy.)
1442 stmt = (IndexStmt *) copyObject(stmt);
1445 * Open the parent table with appropriate locking. We must do this
1446 * because addRangeTableEntry() would acquire only AccessShareLock,
1447 * leaving DefineIndex() needing to do a lock upgrade with consequent risk
1448 * of deadlock. Make sure this stays in sync with the type of lock
1449 * DefineIndex() wants.
1451 rel = heap_openrv(stmt->relation,
1452 (stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock));
1455 pstate = make_parsestate(NULL);
1456 pstate->p_sourcetext = queryString;
1459 * Put the parent table into the rtable so that the expressions can refer
1460 * to its fields without qualification.
1462 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1464 /* no to join list, yes to namespaces */
1465 addRTEtoQuery(pstate, rte, false, true, true);
1467 /* take care of the where clause */
1468 if (stmt->whereClause)
1469 stmt->whereClause = transformWhereClause(pstate,
1473 /* take care of any index expressions */
1474 foreach(l, stmt->indexParams)
1476 IndexElem *ielem = (IndexElem *) lfirst(l);
1480 ielem->expr = transformExpr(pstate, ielem->expr);
1483 * We check only that the result type is legitimate; this is for
1484 * consistency with what transformWhereClause() checks for the
1485 * predicate. DefineIndex() will make more checks.
1487 if (expression_returns_set(ielem->expr))
1489 (errcode(ERRCODE_DATATYPE_MISMATCH),
1490 errmsg("index expression cannot return a set")));
1495 * Check that only the base rel is mentioned.
1497 if (list_length(pstate->p_rtable) != 1)
1499 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1500 errmsg("index expressions and predicates can refer only to the table being indexed")));
1502 free_parsestate(pstate);
1504 /* Close relation, but keep the lock */
1505 heap_close(rel, NoLock);
1512 * transformRuleStmt -
1513 * transform a CREATE RULE Statement. The action is a list of parse
1514 * trees which is transformed into a list of query trees, and we also
1515 * transform the WHERE clause if any.
1517 * actions and whereClause are output parameters that receive the
1518 * transformed results.
1520 * Note that we must not scribble on the passed-in RuleStmt, so we do
1521 * copyObject() on the actions and WHERE clause.
1524 transformRuleStmt(RuleStmt *stmt, const char *queryString,
1525 List **actions, Node **whereClause)
1529 RangeTblEntry *oldrte;
1530 RangeTblEntry *newrte;
1533 * To avoid deadlock, make sure the first thing we do is grab
1534 * AccessExclusiveLock on the target relation. This will be needed by
1535 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1538 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1541 pstate = make_parsestate(NULL);
1542 pstate->p_sourcetext = queryString;
1545 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1546 * Set up their RTEs in the main pstate for use in parsing the rule
1549 oldrte = addRangeTableEntryForRelation(pstate, rel,
1550 makeAlias("*OLD*", NIL),
1552 newrte = addRangeTableEntryForRelation(pstate, rel,
1553 makeAlias("*NEW*", NIL),
1555 /* Must override addRangeTableEntry's default access-check flags */
1556 oldrte->requiredPerms = 0;
1557 newrte->requiredPerms = 0;
1560 * They must be in the namespace too for lookup purposes, but only add the
1561 * one(s) that are relevant for the current kind of rule. In an UPDATE
1562 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1563 * there's no need to be so picky for INSERT & DELETE. We do not add them
1566 switch (stmt->event)
1569 addRTEtoQuery(pstate, oldrte, false, true, true);
1572 addRTEtoQuery(pstate, oldrte, false, true, true);
1573 addRTEtoQuery(pstate, newrte, false, true, true);
1576 addRTEtoQuery(pstate, newrte, false, true, true);
1579 addRTEtoQuery(pstate, oldrte, false, true, true);
1582 elog(ERROR, "unrecognized event type: %d",
1587 /* take care of the where clause */
1588 *whereClause = transformWhereClause(pstate,
1589 (Node *) copyObject(stmt->whereClause),
1592 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
1594 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1595 errmsg("rule WHERE condition cannot contain references to other relations")));
1597 /* aggregates not allowed (but subselects are okay) */
1598 if (pstate->p_hasAggs)
1600 (errcode(ERRCODE_GROUPING_ERROR),
1601 errmsg("cannot use aggregate function in rule WHERE condition")));
1602 if (pstate->p_hasWindowFuncs)
1604 (errcode(ERRCODE_WINDOWING_ERROR),
1605 errmsg("cannot use window function in rule WHERE condition")));
1608 * 'instead nothing' rules with a qualification need a query rangetable so
1609 * the rewrite handler can add the negated rule qualification to the
1610 * original query. We create a query with the new command type CMD_NOTHING
1611 * here that is treated specially by the rewrite system.
1613 if (stmt->actions == NIL)
1615 Query *nothing_qry = makeNode(Query);
1617 nothing_qry->commandType = CMD_NOTHING;
1618 nothing_qry->rtable = pstate->p_rtable;
1619 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1621 *actions = list_make1(nothing_qry);
1626 List *newactions = NIL;
1629 * transform each statement, like parse_sub_analyze()
1631 foreach(l, stmt->actions)
1633 Node *action = (Node *) lfirst(l);
1634 ParseState *sub_pstate = make_parsestate(NULL);
1641 * Since outer ParseState isn't parent of inner, have to pass down
1642 * the query text by hand.
1644 sub_pstate->p_sourcetext = queryString;
1647 * Set up OLD/NEW in the rtable for this statement. The entries
1648 * are added only to relnamespace, not varnamespace, because we
1649 * don't want them to be referred to by unqualified field names
1650 * nor "*" in the rule actions. We decide later whether to put
1651 * them in the joinlist.
1653 oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
1654 makeAlias("*OLD*", NIL),
1656 newrte = addRangeTableEntryForRelation(sub_pstate, rel,
1657 makeAlias("*NEW*", NIL),
1659 oldrte->requiredPerms = 0;
1660 newrte->requiredPerms = 0;
1661 addRTEtoQuery(sub_pstate, oldrte, false, true, false);
1662 addRTEtoQuery(sub_pstate, newrte, false, true, false);
1664 /* Transform the rule action statement */
1665 top_subqry = transformStmt(sub_pstate,
1666 (Node *) copyObject(action));
1669 * We cannot support utility-statement actions (eg NOTIFY) with
1670 * nonempty rule WHERE conditions, because there's no way to make
1671 * the utility action execute conditionally.
1673 if (top_subqry->commandType == CMD_UTILITY &&
1674 *whereClause != NULL)
1676 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1677 errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
1680 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
1681 * into the SELECT, and that's what we need to look at. (Ugly
1682 * kluge ... try to fix this when we redesign querytrees.)
1684 sub_qry = getInsertSelectQuery(top_subqry, NULL);
1687 * If the sub_qry is a setop, we cannot attach any qualifications
1688 * to it, because the planner won't notice them. This could
1689 * perhaps be relaxed someday, but for now, we may as well reject
1690 * such a rule immediately.
1692 if (sub_qry->setOperations != NULL && *whereClause != NULL)
1694 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1695 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1698 * Validate action's use of OLD/NEW, qual too
1701 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1702 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
1704 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1705 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
1707 switch (stmt->event)
1712 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1713 errmsg("ON SELECT rule cannot use OLD")));
1716 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1717 errmsg("ON SELECT rule cannot use NEW")));
1725 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1726 errmsg("ON INSERT rule cannot use OLD")));
1731 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1732 errmsg("ON DELETE rule cannot use NEW")));
1735 elog(ERROR, "unrecognized event type: %d",
1741 * For efficiency's sake, add OLD to the rule action's jointree
1742 * only if it was actually referenced in the statement or qual.
1744 * For INSERT, NEW is not really a relation (only a reference to
1745 * the to-be-inserted tuple) and should never be added to the
1748 * For UPDATE, we treat NEW as being another kind of reference to
1749 * OLD, because it represents references to *transformed* tuples
1750 * of the existing relation. It would be wrong to enter NEW
1751 * separately in the jointree, since that would cause a double
1752 * join of the updated relation. It's also wrong to fail to make
1753 * a jointree entry if only NEW and not OLD is mentioned.
1755 if (has_old || (has_new && stmt->event == CMD_UPDATE))
1758 * If sub_qry is a setop, manipulating its jointree will do no
1759 * good at all, because the jointree is dummy. (This should be
1760 * a can't-happen case because of prior tests.)
1762 if (sub_qry->setOperations != NULL)
1764 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1765 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1766 /* hack so we can use addRTEtoQuery() */
1767 sub_pstate->p_rtable = sub_qry->rtable;
1768 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
1769 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
1770 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
1773 newactions = lappend(newactions, top_subqry);
1775 free_parsestate(sub_pstate);
1778 *actions = newactions;
1781 free_parsestate(pstate);
1783 /* Close relation, but keep the exclusive lock */
1784 heap_close(rel, NoLock);
1789 * transformAlterTableStmt -
1790 * parse analysis for ALTER TABLE
1792 * Returns a List of utility commands to be done in sequence. One of these
1793 * will be the transformed AlterTableStmt, but there may be additional actions
1794 * to be done before and after the actual AlterTable() call.
1797 transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
1801 CreateStmtContext cxt;
1806 List *newcmds = NIL;
1807 bool skipValidation = true;
1808 AlterTableCmd *newcmd;
1811 * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
1812 * is overkill, but easy.)
1814 stmt = (AlterTableStmt *) copyObject(stmt);
1817 * Acquire exclusive lock on the target relation, which will be held until
1818 * end of transaction. This ensures any decisions we make here based on
1819 * the state of the relation will still be good at execution. We must get
1820 * exclusive lock now because execution will; taking a lower grade lock
1821 * now and trying to upgrade later risks deadlock.
1823 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
1826 pstate = make_parsestate(NULL);
1827 pstate->p_sourcetext = queryString;
1829 cxt.stmtType = "ALTER TABLE";
1830 cxt.relation = stmt->relation;
1832 cxt.inhRelations = NIL;
1834 cxt.hasoids = false; /* need not be right */
1836 cxt.ckconstraints = NIL;
1837 cxt.fkconstraints = NIL;
1838 cxt.ixconstraints = NIL;
1839 cxt.inh_indexes = NIL;
1845 * The only subtypes that currently require parse transformation handling
1846 * are ADD COLUMN and ADD CONSTRAINT. These largely re-use code from
1849 foreach(lcmd, stmt->cmds)
1851 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
1853 switch (cmd->subtype)
1856 case AT_AddColumnToView:
1858 ColumnDef *def = (ColumnDef *) cmd->def;
1860 Assert(IsA(def, ColumnDef));
1861 transformColumnDefinition(pstate, &cxt, def);
1864 * If the column has a non-null default, we can't skip
1865 * validation of foreign keys.
1867 if (def->raw_default != NULL)
1868 skipValidation = false;
1871 * All constraints are processed in other ways. Remove the
1874 def->constraints = NIL;
1876 newcmds = lappend(newcmds, cmd);
1879 case AT_AddConstraint:
1882 * The original AddConstraint cmd node doesn't go to newcmds
1884 if (IsA(cmd->def, Constraint))
1886 transformTableConstraint(pstate, &cxt,
1887 (Constraint *) cmd->def);
1888 if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
1889 skipValidation = false;
1892 elog(ERROR, "unrecognized node type: %d",
1893 (int) nodeTag(cmd->def));
1896 case AT_ProcessedConstraint:
1899 * Already-transformed ADD CONSTRAINT, so just make it look
1900 * like the standard case.
1902 cmd->subtype = AT_AddConstraint;
1903 newcmds = lappend(newcmds, cmd);
1907 newcmds = lappend(newcmds, cmd);
1913 * transformIndexConstraints wants cxt.alist to contain only index
1914 * statements, so transfer anything we already have into save_alist
1917 save_alist = cxt.alist;
1920 /* Postprocess index and FK constraints */
1921 transformIndexConstraints(pstate, &cxt);
1923 transformFKConstraints(pstate, &cxt, skipValidation, true);
1926 * Push any index-creation commands into the ALTER, so that they can be
1927 * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
1928 * the IndexStmt attached to an AT_AddIndex subcommand has already been
1929 * through transformIndexStmt.
1931 foreach(l, cxt.alist)
1933 Node *idxstmt = (Node *) lfirst(l);
1935 Assert(IsA(idxstmt, IndexStmt));
1936 newcmd = makeNode(AlterTableCmd);
1937 newcmd->subtype = AT_AddIndex;
1938 newcmd->def = (Node *) transformIndexStmt((IndexStmt *) idxstmt,
1940 newcmds = lappend(newcmds, newcmd);
1944 /* Append any CHECK or FK constraints to the commands list */
1945 foreach(l, cxt.ckconstraints)
1947 newcmd = makeNode(AlterTableCmd);
1948 newcmd->subtype = AT_AddConstraint;
1949 newcmd->def = (Node *) lfirst(l);
1950 newcmds = lappend(newcmds, newcmd);
1952 foreach(l, cxt.fkconstraints)
1954 newcmd = makeNode(AlterTableCmd);
1955 newcmd->subtype = AT_AddConstraint;
1956 newcmd->def = (Node *) lfirst(l);
1957 newcmds = lappend(newcmds, newcmd);
1960 /* Close rel but keep lock */
1961 relation_close(rel, NoLock);
1966 stmt->cmds = newcmds;
1968 result = lappend(cxt.blist, stmt);
1969 result = list_concat(result, cxt.alist);
1970 result = list_concat(result, save_alist);
1977 * Preprocess a list of column constraint clauses
1978 * to attach constraint attributes to their primary constraint nodes
1979 * and detect inconsistent/misplaced constraint attributes.
1981 * NOTE: currently, attributes are only supported for FOREIGN KEY, UNIQUE,
1982 * and PRIMARY KEY constraints, but someday they ought to be supported
1983 * for other constraint types.
1986 transformConstraintAttrs(ParseState *pstate, List *constraintList)
1988 Constraint *lastprimarycon = NULL;
1989 bool saw_deferrability = false;
1990 bool saw_initially = false;
1993 #define SUPPORTS_ATTRS(node) \
1994 ((node) != NULL && \
1995 ((node)->contype == CONSTR_PRIMARY || \
1996 (node)->contype == CONSTR_UNIQUE || \
1997 (node)->contype == CONSTR_FOREIGN))
1999 foreach(clist, constraintList)
2001 Constraint *con = (Constraint *) lfirst(clist);
2003 if (!IsA(con, Constraint))
2004 elog(ERROR, "unrecognized node type: %d",
2005 (int) nodeTag(con));
2006 switch (con->contype)
2008 case CONSTR_ATTR_DEFERRABLE:
2009 if (!SUPPORTS_ATTRS(lastprimarycon))
2011 (errcode(ERRCODE_SYNTAX_ERROR),
2012 errmsg("misplaced DEFERRABLE clause"),
2013 parser_errposition(pstate, con->location)));
2014 if (saw_deferrability)
2016 (errcode(ERRCODE_SYNTAX_ERROR),
2017 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2018 parser_errposition(pstate, con->location)));
2019 saw_deferrability = true;
2020 lastprimarycon->deferrable = true;
2023 case CONSTR_ATTR_NOT_DEFERRABLE:
2024 if (!SUPPORTS_ATTRS(lastprimarycon))
2026 (errcode(ERRCODE_SYNTAX_ERROR),
2027 errmsg("misplaced NOT DEFERRABLE clause"),
2028 parser_errposition(pstate, con->location)));
2029 if (saw_deferrability)
2031 (errcode(ERRCODE_SYNTAX_ERROR),
2032 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2033 parser_errposition(pstate, con->location)));
2034 saw_deferrability = true;
2035 lastprimarycon->deferrable = false;
2036 if (saw_initially &&
2037 lastprimarycon->initdeferred)
2039 (errcode(ERRCODE_SYNTAX_ERROR),
2040 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2041 parser_errposition(pstate, con->location)));
2044 case CONSTR_ATTR_DEFERRED:
2045 if (!SUPPORTS_ATTRS(lastprimarycon))
2047 (errcode(ERRCODE_SYNTAX_ERROR),
2048 errmsg("misplaced INITIALLY DEFERRED clause"),
2049 parser_errposition(pstate, con->location)));
2052 (errcode(ERRCODE_SYNTAX_ERROR),
2053 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2054 parser_errposition(pstate, con->location)));
2055 saw_initially = true;
2056 lastprimarycon->initdeferred = true;
2059 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
2061 if (!saw_deferrability)
2062 lastprimarycon->deferrable = true;
2063 else if (!lastprimarycon->deferrable)
2065 (errcode(ERRCODE_SYNTAX_ERROR),
2066 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2067 parser_errposition(pstate, con->location)));
2070 case CONSTR_ATTR_IMMEDIATE:
2071 if (!SUPPORTS_ATTRS(lastprimarycon))
2073 (errcode(ERRCODE_SYNTAX_ERROR),
2074 errmsg("misplaced INITIALLY IMMEDIATE clause"),
2075 parser_errposition(pstate, con->location)));
2078 (errcode(ERRCODE_SYNTAX_ERROR),
2079 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2080 parser_errposition(pstate, con->location)));
2081 saw_initially = true;
2082 lastprimarycon->initdeferred = false;
2086 /* Otherwise it's not an attribute */
2087 lastprimarycon = con;
2088 /* reset flags for new primary node */
2089 saw_deferrability = false;
2090 saw_initially = false;
2097 * Special handling of type definition for a column
2100 transformColumnType(ParseState *pstate, ColumnDef *column)
2103 * All we really need to do here is verify that the type is valid.
2105 Type ctype = typenameType(pstate, column->typeName, NULL);
2107 ReleaseSysCache(ctype);
2112 * transformCreateSchemaStmt -
2113 * analyzes the CREATE SCHEMA statement
2115 * Split the schema element list into individual commands and place
2116 * them in the result list in an order such that there are no forward
2117 * references (e.g. GRANT to a table created later in the list). Note
2118 * that the logic we use for determining forward references is
2119 * presently quite incomplete.
2121 * SQL92 also allows constraints to make forward references, so thumb through
2122 * the table columns and move forward references to a posterior alter-table
2125 * The result is a list of parse nodes that still need to be analyzed ---
2126 * but we can't analyze the later commands until we've executed the earlier
2127 * ones, because of possible inter-object references.
2129 * Note: this breaks the rules a little bit by modifying schema-name fields
2130 * within passed-in structs. However, the transformation would be the same
2131 * if done over, so it should be all right to scribble on the input to this
2135 transformCreateSchemaStmt(CreateSchemaStmt *stmt)
2137 CreateSchemaStmtContext cxt;
2141 cxt.stmtType = "CREATE SCHEMA";
2142 cxt.schemaname = stmt->schemaname;
2143 cxt.authid = stmt->authid;
2144 cxt.sequences = NIL;
2152 * Run through each schema element in the schema element list. Separate
2153 * statements by type, and do preliminary analysis.
2155 foreach(elements, stmt->schemaElts)
2157 Node *element = lfirst(elements);
2159 switch (nodeTag(element))
2161 case T_CreateSeqStmt:
2163 CreateSeqStmt *elp = (CreateSeqStmt *) element;
2165 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
2166 cxt.sequences = lappend(cxt.sequences, element);
2172 CreateStmt *elp = (CreateStmt *) element;
2174 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2177 * XXX todo: deal with constraints
2179 cxt.tables = lappend(cxt.tables, element);
2185 ViewStmt *elp = (ViewStmt *) element;
2187 setSchemaName(cxt.schemaname, &elp->view->schemaname);
2190 * XXX todo: deal with references between views
2192 cxt.views = lappend(cxt.views, element);
2198 IndexStmt *elp = (IndexStmt *) element;
2200 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2201 cxt.indexes = lappend(cxt.indexes, element);
2205 case T_CreateTrigStmt:
2207 CreateTrigStmt *elp = (CreateTrigStmt *) element;
2209 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2210 cxt.triggers = lappend(cxt.triggers, element);
2215 cxt.grants = lappend(cxt.grants, element);
2219 elog(ERROR, "unrecognized node type: %d",
2220 (int) nodeTag(element));
2225 result = list_concat(result, cxt.sequences);
2226 result = list_concat(result, cxt.tables);
2227 result = list_concat(result, cxt.views);
2228 result = list_concat(result, cxt.indexes);
2229 result = list_concat(result, cxt.triggers);
2230 result = list_concat(result, cxt.grants);
2237 * Set or check schema name in an element of a CREATE SCHEMA command
2240 setSchemaName(char *context_schema, char **stmt_schema_name)
2242 if (*stmt_schema_name == NULL)
2243 *stmt_schema_name = context_schema;
2244 else if (strcmp(context_schema, *stmt_schema_name) != 0)
2246 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
2247 errmsg("CREATE specifies a schema (%s) "
2248 "different from the one being created (%s)",
2249 *stmt_schema_name, context_schema)));