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-2010, 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.41 2010/07/28 05:22:24 sriggs 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_target.h"
52 #include "parser/parse_type.h"
53 #include "parser/parse_utilcmd.h"
54 #include "parser/parser.h"
55 #include "rewrite/rewriteManip.h"
56 #include "storage/lock.h"
57 #include "utils/acl.h"
58 #include "utils/builtins.h"
59 #include "utils/lsyscache.h"
60 #include "utils/relcache.h"
61 #include "utils/syscache.h"
62 #include "utils/typcache.h"
65 /* State shared by transformCreateStmt and its subroutines */
68 const char *stmtType; /* "CREATE TABLE" or "ALTER TABLE" */
69 RangeVar *relation; /* relation to create */
70 Relation rel; /* opened/locked rel, if ALTER */
71 List *inhRelations; /* relations to inherit from */
72 bool isalter; /* true if altering existing table */
73 bool hasoids; /* does relation have an OID column? */
74 List *columns; /* ColumnDef items */
75 List *ckconstraints; /* CHECK constraints */
76 List *fkconstraints; /* FOREIGN KEY constraints */
77 List *ixconstraints; /* index-creating constraints */
78 List *inh_indexes; /* cloned indexes from INCLUDING INDEXES */
79 List *blist; /* "before list" of things to do before
80 * creating the table */
81 List *alist; /* "after list" of things to do after creating
83 IndexStmt *pkey; /* PRIMARY KEY index, if any */
86 /* State shared by transformCreateSchemaStmt and its subroutines */
89 const char *stmtType; /* "CREATE SCHEMA" or "ALTER SCHEMA" */
90 char *schemaname; /* name of schema */
91 char *authid; /* owner of schema */
92 List *sequences; /* CREATE SEQUENCE items */
93 List *tables; /* CREATE TABLE items */
94 List *views; /* CREATE VIEW items */
95 List *indexes; /* CREATE INDEX items */
96 List *triggers; /* CREATE TRIGGER items */
97 List *grants; /* GRANT items */
98 } CreateSchemaStmtContext;
101 static void transformColumnDefinition(ParseState *pstate,
102 CreateStmtContext *cxt,
104 static void transformTableConstraint(ParseState *pstate,
105 CreateStmtContext *cxt,
106 Constraint *constraint);
107 static void transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
108 InhRelation *inhrelation);
109 static void transformOfType(ParseState *pstate, CreateStmtContext *cxt,
110 TypeName *ofTypename);
111 static char *chooseIndexName(const RangeVar *relation, IndexStmt *index_stmt);
112 static IndexStmt *generateClonedIndexStmt(CreateStmtContext *cxt,
113 Relation parent_index, AttrNumber *attmap);
114 static List *get_opclass(Oid opclass, Oid actual_datatype);
115 static void transformIndexConstraints(ParseState *pstate,
116 CreateStmtContext *cxt);
117 static IndexStmt *transformIndexConstraint(Constraint *constraint,
118 CreateStmtContext *cxt);
119 static void transformFKConstraints(ParseState *pstate,
120 CreateStmtContext *cxt,
122 bool isAddConstraint);
123 static void transformConstraintAttrs(ParseState *pstate, List *constraintList);
124 static void transformColumnType(ParseState *pstate, ColumnDef *column);
125 static void setSchemaName(char *context_schema, char **stmt_schema_name);
129 * transformCreateStmt -
130 * parse analysis for CREATE TABLE
132 * Returns a List of utility commands to be done in sequence. One of these
133 * will be the transformed CreateStmt, but there may be additional actions
134 * to be done before and after the actual DefineRelation() call.
136 * SQL92 allows constraints to be scattered all over, so thumb through
137 * the columns and collect all constraints into one place.
138 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
139 * then expand those into multiple IndexStmt blocks.
140 * - thomas 1997-12-02
143 transformCreateStmt(CreateStmt *stmt, const char *queryString)
146 CreateStmtContext cxt;
152 * We must not scribble on the passed-in CreateStmt, so copy it. (This is
153 * overkill, but easy.)
155 stmt = (CreateStmt *) copyObject(stmt);
158 * If the target relation name isn't schema-qualified, make it so. This
159 * prevents some corner cases in which added-on rewritten commands might
160 * think they should apply to other relations that have the same name and
161 * are earlier in the search path. "istemp" is equivalent to a
162 * specification of pg_temp, so no need for anything extra in that case.
164 if (stmt->relation->schemaname == NULL && !stmt->relation->istemp)
166 Oid namespaceid = RangeVarGetCreationNamespace(stmt->relation);
168 stmt->relation->schemaname = get_namespace_name(namespaceid);
172 pstate = make_parsestate(NULL);
173 pstate->p_sourcetext = queryString;
175 cxt.stmtType = "CREATE TABLE";
176 cxt.relation = stmt->relation;
178 cxt.inhRelations = stmt->inhRelations;
181 cxt.ckconstraints = NIL;
182 cxt.fkconstraints = NIL;
183 cxt.ixconstraints = NIL;
184 cxt.inh_indexes = NIL;
188 cxt.hasoids = interpretOidsOption(stmt->options);
190 Assert(!stmt->ofTypename || !stmt->inhRelations); /* grammar enforces */
192 if (stmt->ofTypename)
193 transformOfType(pstate, &cxt, stmt->ofTypename);
196 * Run through each primary element in the table creation clause. Separate
197 * column defs from constraints, and do preliminary analysis.
199 foreach(elements, stmt->tableElts)
201 Node *element = lfirst(elements);
203 switch (nodeTag(element))
206 transformColumnDefinition(pstate, &cxt,
207 (ColumnDef *) element);
211 transformTableConstraint(pstate, &cxt,
212 (Constraint *) element);
216 transformInhRelation(pstate, &cxt,
217 (InhRelation *) element);
221 elog(ERROR, "unrecognized node type: %d",
222 (int) nodeTag(element));
228 * transformIndexConstraints wants cxt.alist to contain only index
229 * statements, so transfer anything we already have into save_alist.
231 save_alist = cxt.alist;
234 Assert(stmt->constraints == NIL);
237 * Postprocess constraints that give rise to index definitions.
239 transformIndexConstraints(pstate, &cxt);
242 * Postprocess foreign-key constraints.
244 transformFKConstraints(pstate, &cxt, true, false);
249 stmt->tableElts = cxt.columns;
250 stmt->constraints = cxt.ckconstraints;
252 result = lappend(cxt.blist, stmt);
253 result = list_concat(result, cxt.alist);
254 result = list_concat(result, save_alist);
260 * transformColumnDefinition -
261 * transform a single ColumnDef within CREATE TABLE
262 * Also used in ALTER TABLE ADD COLUMN
265 transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
271 Constraint *constraint;
274 cxt->columns = lappend(cxt->columns, column);
276 /* Check for SERIAL pseudo-types */
279 && list_length(column->typeName->names) == 1
280 && !column->typeName->pct_type)
282 char *typname = strVal(linitial(column->typeName->names));
284 if (strcmp(typname, "serial") == 0 ||
285 strcmp(typname, "serial4") == 0)
288 column->typeName->names = NIL;
289 column->typeName->typeOid = INT4OID;
291 else if (strcmp(typname, "bigserial") == 0 ||
292 strcmp(typname, "serial8") == 0)
295 column->typeName->names = NIL;
296 column->typeName->typeOid = INT8OID;
300 * We have to reject "serial[]" explicitly, because once we've set
301 * typeid, LookupTypeName won't notice arrayBounds. We don't need any
302 * special coding for serial(typmod) though.
304 if (is_serial && column->typeName->arrayBounds != NIL)
306 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
307 errmsg("array of serial is not implemented"),
308 parser_errposition(pstate, column->typeName->location)));
311 /* Do necessary work on the column type declaration */
312 if (column->typeName)
313 transformColumnType(pstate, column);
315 /* Special actions for SERIAL pseudo-types */
324 FuncCall *funccallnode;
325 CreateSeqStmt *seqstmt;
326 AlterSeqStmt *altseqstmt;
330 * Determine namespace and name to use for the sequence.
332 * Although we use ChooseRelationName, it's not guaranteed that the
333 * selected sequence name won't conflict; given sufficiently long
334 * field names, two different serial columns in the same table could
335 * be assigned the same sequence name, and we'd not notice since we
336 * aren't creating the sequence quite yet. In practice this seems
337 * quite unlikely to be a problem, especially since few people would
338 * need two serial columns in one table.
341 snamespaceid = RelationGetNamespace(cxt->rel);
343 snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
344 snamespace = get_namespace_name(snamespaceid);
345 sname = ChooseRelationName(cxt->relation->relname,
351 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
352 cxt->stmtType, sname,
353 cxt->relation->relname, column->colname)));
356 * Build a CREATE SEQUENCE command to create the sequence object, and
357 * add it to the list of things to be done before this CREATE/ALTER
360 seqstmt = makeNode(CreateSeqStmt);
361 seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
362 seqstmt->options = NIL;
364 cxt->blist = lappend(cxt->blist, seqstmt);
367 * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence
368 * as owned by this column, and add it to the list of things to be
369 * done after this CREATE/ALTER TABLE.
371 altseqstmt = makeNode(AlterSeqStmt);
372 altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
373 attnamelist = list_make3(makeString(snamespace),
374 makeString(cxt->relation->relname),
375 makeString(column->colname));
376 altseqstmt->options = list_make1(makeDefElem("owned_by",
377 (Node *) attnamelist));
379 cxt->alist = lappend(cxt->alist, altseqstmt);
382 * Create appropriate constraints for SERIAL. We do this in full,
383 * rather than shortcutting, so that we will detect any conflicting
384 * constraints the user wrote (like a different DEFAULT).
386 * Create an expression tree representing the function call
387 * nextval('sequencename'). We cannot reduce the raw tree to cooked
388 * form until after the sequence is created, but there's no need to do
391 qstring = quote_qualified_identifier(snamespace, sname);
392 snamenode = makeNode(A_Const);
393 snamenode->val.type = T_String;
394 snamenode->val.val.str = qstring;
395 snamenode->location = -1;
396 castnode = makeNode(TypeCast);
397 castnode->typeName = SystemTypeName("regclass");
398 castnode->arg = (Node *) snamenode;
399 castnode->location = -1;
400 funccallnode = makeNode(FuncCall);
401 funccallnode->funcname = SystemFuncName("nextval");
402 funccallnode->args = list_make1(castnode);
403 funccallnode->agg_order = NIL;
404 funccallnode->agg_star = false;
405 funccallnode->agg_distinct = false;
406 funccallnode->func_variadic = false;
407 funccallnode->over = NULL;
408 funccallnode->location = -1;
410 constraint = makeNode(Constraint);
411 constraint->contype = CONSTR_DEFAULT;
412 constraint->location = -1;
413 constraint->raw_expr = (Node *) funccallnode;
414 constraint->cooked_expr = NULL;
415 column->constraints = lappend(column->constraints, constraint);
417 constraint = makeNode(Constraint);
418 constraint->contype = CONSTR_NOTNULL;
419 constraint->location = -1;
420 column->constraints = lappend(column->constraints, constraint);
423 /* Process column constraints, if any... */
424 transformConstraintAttrs(pstate, column->constraints);
426 saw_nullable = false;
429 foreach(clist, column->constraints)
431 constraint = lfirst(clist);
432 Assert(IsA(constraint, Constraint));
434 switch (constraint->contype)
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 = FALSE;
449 if (saw_nullable && !column->is_not_null)
451 (errcode(ERRCODE_SYNTAX_ERROR),
452 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
453 column->colname, cxt->relation->relname),
454 parser_errposition(pstate,
455 constraint->location)));
456 column->is_not_null = TRUE;
463 (errcode(ERRCODE_SYNTAX_ERROR),
464 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
465 column->colname, cxt->relation->relname),
466 parser_errposition(pstate,
467 constraint->location)));
468 column->raw_default = constraint->raw_expr;
469 Assert(constraint->cooked_expr == NULL);
474 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
479 if (constraint->keys == NIL)
480 constraint->keys = list_make1(makeString(column->colname));
481 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
484 case CONSTR_EXCLUSION:
485 /* grammar does not allow EXCLUDE as a column constraint */
486 elog(ERROR, "column exclusion constraints are not supported");
492 * Fill in the current attribute's name and throw it into the
493 * list of FK constraints to be processed later.
495 constraint->fk_attrs = list_make1(makeString(column->colname));
496 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
499 case CONSTR_ATTR_DEFERRABLE:
500 case CONSTR_ATTR_NOT_DEFERRABLE:
501 case CONSTR_ATTR_DEFERRED:
502 case CONSTR_ATTR_IMMEDIATE:
503 /* transformConstraintAttrs took care of these */
507 elog(ERROR, "unrecognized constraint type: %d",
508 constraint->contype);
515 * transformTableConstraint
516 * transform a Constraint node within CREATE TABLE or ALTER TABLE
519 transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt,
520 Constraint *constraint)
522 switch (constraint->contype)
526 case CONSTR_EXCLUSION:
527 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
531 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
535 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
541 case CONSTR_ATTR_DEFERRABLE:
542 case CONSTR_ATTR_NOT_DEFERRABLE:
543 case CONSTR_ATTR_DEFERRED:
544 case CONSTR_ATTR_IMMEDIATE:
545 elog(ERROR, "invalid context for constraint type %d",
546 constraint->contype);
550 elog(ERROR, "unrecognized constraint type: %d",
551 constraint->contype);
557 * transformInhRelation
559 * Change the LIKE <subtable> portion of a CREATE TABLE statement into
560 * column definitions which recreate the user defined column portions of
564 transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
565 InhRelation *inhRelation)
567 AttrNumber parent_attno;
574 relation = parserOpenTable(pstate, inhRelation->relation, AccessShareLock);
576 if (relation->rd_rel->relkind != RELKIND_RELATION)
578 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
579 errmsg("inherited relation \"%s\" is not a table",
580 inhRelation->relation->relname)));
583 * Check for SELECT privilages
585 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
587 if (aclresult != ACLCHECK_OK)
588 aclcheck_error(aclresult, ACL_KIND_CLASS,
589 RelationGetRelationName(relation));
591 tupleDesc = RelationGetDescr(relation);
592 constr = tupleDesc->constr;
595 * Insert the copied attributes into the cxt for the new table definition.
597 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
600 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
601 char *attributeName = NameStr(attribute->attname);
605 * Ignore dropped columns in the parent.
607 if (attribute->attisdropped)
611 * Create a new column, which is marked as NOT inherited.
613 * For constraints, ONLY the NOT NULL constraint is inherited by the
614 * new column definition per SQL99.
616 def = makeNode(ColumnDef);
617 def->colname = pstrdup(attributeName);
618 def->typeName = makeTypeNameFromOid(attribute->atttypid,
619 attribute->atttypmod);
621 def->is_local = true;
622 def->is_not_null = attribute->attnotnull;
623 def->raw_default = NULL;
624 def->cooked_default = NULL;
625 def->constraints = NIL;
630 cxt->columns = lappend(cxt->columns, def);
633 * Copy default, if present and the default has been requested
635 if (attribute->atthasdef &&
636 (inhRelation->options & CREATE_TABLE_LIKE_DEFAULTS))
638 Node *this_default = NULL;
639 AttrDefault *attrdef;
642 /* Find default in constraint structure */
643 Assert(constr != NULL);
644 attrdef = constr->defval;
645 for (i = 0; i < constr->num_defval; i++)
647 if (attrdef[i].adnum == parent_attno)
649 this_default = stringToNode(attrdef[i].adbin);
653 Assert(this_default != NULL);
656 * If default expr could contain any vars, we'd need to fix 'em,
657 * but it can't; so default is ready to apply to child.
660 def->cooked_default = this_default;
663 /* Likewise, copy storage if requested */
664 if (inhRelation->options & CREATE_TABLE_LIKE_STORAGE)
665 def->storage = attribute->attstorage;
669 /* Likewise, copy comment if requested */
670 if ((inhRelation->options & CREATE_TABLE_LIKE_COMMENTS) &&
671 (comment = GetComment(attribute->attrelid,
673 attribute->attnum)) != NULL)
675 CommentStmt *stmt = makeNode(CommentStmt);
677 stmt->objtype = OBJECT_COLUMN;
678 stmt->objname = list_make3(makeString(cxt->relation->schemaname),
679 makeString(cxt->relation->relname),
680 makeString(def->colname));
682 stmt->comment = comment;
684 cxt->alist = lappend(cxt->alist, stmt);
689 * Copy CHECK constraints if requested, being careful to adjust attribute
692 if ((inhRelation->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
695 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
698 for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
700 char *ccname = tupleDesc->constr->check[ccnum].ccname;
701 char *ccbin = tupleDesc->constr->check[ccnum].ccbin;
702 Node *ccbin_node = stringToNode(ccbin);
703 Constraint *n = makeNode(Constraint);
705 change_varattnos_of_a_node(ccbin_node, attmap);
707 n->contype = CONSTR_CHECK;
709 n->conname = pstrdup(ccname);
711 n->cooked_expr = nodeToString(ccbin_node);
712 cxt->ckconstraints = lappend(cxt->ckconstraints, n);
714 /* Copy comment on constraint */
715 if ((inhRelation->options & CREATE_TABLE_LIKE_COMMENTS) &&
716 (comment = GetComment(GetConstraintByName(RelationGetRelid(relation),
718 ConstraintRelationId,
721 CommentStmt *stmt = makeNode(CommentStmt);
723 stmt->objtype = OBJECT_CONSTRAINT;
724 stmt->objname = list_make3(makeString(cxt->relation->schemaname),
725 makeString(cxt->relation->relname),
726 makeString(n->conname));
728 stmt->comment = comment;
730 cxt->alist = lappend(cxt->alist, stmt);
736 * Likewise, copy indexes if requested
738 if ((inhRelation->options & CREATE_TABLE_LIKE_INDEXES) &&
739 relation->rd_rel->relhasindex)
741 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
742 List *parent_indexes;
745 parent_indexes = RelationGetIndexList(relation);
747 foreach(l, parent_indexes)
749 Oid parent_index_oid = lfirst_oid(l);
750 Relation parent_index;
751 IndexStmt *index_stmt;
753 parent_index = index_open(parent_index_oid, AccessShareLock);
755 /* Build CREATE INDEX statement to recreate the parent_index */
756 index_stmt = generateClonedIndexStmt(cxt, parent_index, attmap);
758 /* Copy comment on index */
759 if (inhRelation->options & CREATE_TABLE_LIKE_COMMENTS)
761 comment = GetComment(parent_index_oid, RelationRelationId, 0);
768 * We have to assign the index a name now, so that we can
769 * reference it in CommentStmt.
771 if (index_stmt->idxname == NULL)
772 index_stmt->idxname = chooseIndexName(cxt->relation,
775 stmt = makeNode(CommentStmt);
776 stmt->objtype = OBJECT_INDEX;
778 list_make2(makeString(cxt->relation->schemaname),
779 makeString(index_stmt->idxname));
781 stmt->comment = comment;
783 cxt->alist = lappend(cxt->alist, stmt);
787 /* Save it in the inh_indexes list for the time being */
788 cxt->inh_indexes = lappend(cxt->inh_indexes, index_stmt);
790 index_close(parent_index, AccessShareLock);
795 * Close the parent rel, but keep our AccessShareLock on it until xact
796 * commit. That will prevent someone else from deleting or ALTERing the
797 * parent before the child is committed.
799 heap_close(relation, NoLock);
803 transformOfType(ParseState *pstate, CreateStmtContext *cxt, TypeName *ofTypename)
811 AssertArg(ofTypename);
813 tuple = typenameType(NULL, ofTypename, NULL);
814 typ = (Form_pg_type) GETSTRUCT(tuple);
815 ofTypeId = HeapTupleGetOid(tuple);
816 ofTypename->typeOid = ofTypeId; /* cached for later */
818 if (typ->typtype != TYPTYPE_COMPOSITE)
820 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
821 errmsg("type %s is not a composite type",
822 format_type_be(ofTypeId))));
824 tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
825 for (i = 0; i < tupdesc->natts; i++)
827 Form_pg_attribute attr = tupdesc->attrs[i];
828 ColumnDef *n = makeNode(ColumnDef);
830 n->colname = pstrdup(NameStr(attr->attname));
831 n->typeName = makeTypeNameFromOid(attr->atttypid, attr->atttypmod);
832 n->constraints = NULL;
834 n->is_from_type = true;
835 cxt->columns = lappend(cxt->columns, n);
837 DecrTupleDescRefCount(tupdesc);
839 ReleaseSysCache(tuple);
845 * Compute name for an index. This must match code in indexcmds.c.
847 * XXX this is inherently broken because the indexes aren't created
848 * immediately, so we fail to resolve conflicts when the same name is
849 * derived for multiple indexes. However, that's a reasonably uncommon
850 * situation, so we'll live with it for now.
853 chooseIndexName(const RangeVar *relation, IndexStmt *index_stmt)
858 namespaceId = RangeVarGetCreationNamespace(relation);
859 colnames = ChooseIndexColumnNames(index_stmt->indexParams);
860 return ChooseIndexName(relation->relname, namespaceId,
861 colnames, index_stmt->excludeOpNames,
862 index_stmt->primary, index_stmt->isconstraint);
866 * Generate an IndexStmt node using information from an already existing index
867 * "source_idx". Attribute numbers should be adjusted according to attmap.
870 generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
873 Oid source_relid = RelationGetRelid(source_idx);
874 Form_pg_attribute *attrs = RelationGetDescr(source_idx)->attrs;
877 Form_pg_class idxrelrec;
878 Form_pg_index idxrec;
883 ListCell *indexpr_item;
891 * Fetch pg_class tuple of source index. We can't use the copy in the
892 * relcache entry because it doesn't include optional fields.
894 ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
895 if (!HeapTupleIsValid(ht_idxrel))
896 elog(ERROR, "cache lookup failed for relation %u", source_relid);
897 idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
899 /* Fetch pg_index tuple for source index from relcache entry */
900 ht_idx = source_idx->rd_indextuple;
901 idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
902 indrelid = idxrec->indrelid;
904 /* Fetch pg_am tuple for source index from relcache entry */
905 amrec = source_idx->rd_am;
907 /* Extract indclass from the pg_index tuple */
908 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
909 Anum_pg_index_indclass, &isnull);
911 indclass = (oidvector *) DatumGetPointer(datum);
913 /* Begin building the IndexStmt */
914 index = makeNode(IndexStmt);
915 index->relation = cxt->relation;
916 index->accessMethod = pstrdup(NameStr(amrec->amname));
917 if (OidIsValid(idxrelrec->reltablespace))
918 index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
920 index->tableSpace = NULL;
921 index->unique = idxrec->indisunique;
922 index->primary = idxrec->indisprimary;
923 index->concurrent = false;
926 * We don't try to preserve the name of the source index; instead, just
927 * let DefineIndex() choose a reasonable name.
929 index->idxname = NULL;
932 * If the index is marked PRIMARY or has an exclusion condition, it's
933 * certainly from a constraint; else, if it's not marked UNIQUE, it
934 * certainly isn't. If it is or might be from a constraint, we have to
935 * fetch the pg_constraint record.
937 if (index->primary || index->unique || idxrelrec->relhasexclusion)
939 Oid constraintId = get_index_constraint(source_relid);
941 if (OidIsValid(constraintId))
944 Form_pg_constraint conrec;
946 ht_constr = SearchSysCache1(CONSTROID,
947 ObjectIdGetDatum(constraintId));
948 if (!HeapTupleIsValid(ht_constr))
949 elog(ERROR, "cache lookup failed for constraint %u",
951 conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
953 index->isconstraint = true;
954 index->deferrable = conrec->condeferrable;
955 index->initdeferred = conrec->condeferred;
957 /* If it's an exclusion constraint, we need the operator names */
958 if (idxrelrec->relhasexclusion)
964 Assert(conrec->contype == CONSTRAINT_EXCLUSION);
965 /* Extract operator OIDs from the pg_constraint tuple */
966 datum = SysCacheGetAttr(CONSTROID, ht_constr,
967 Anum_pg_constraint_conexclop,
970 elog(ERROR, "null conexclop for constraint %u",
973 deconstruct_array(DatumGetArrayTypeP(datum),
974 OIDOID, sizeof(Oid), true, 'i',
975 &elems, NULL, &nElems);
977 for (i = 0; i < nElems; i++)
979 Oid operid = DatumGetObjectId(elems[i]);
981 Form_pg_operator operform;
986 opertup = SearchSysCache1(OPEROID,
987 ObjectIdGetDatum(operid));
988 if (!HeapTupleIsValid(opertup))
989 elog(ERROR, "cache lookup failed for operator %u",
991 operform = (Form_pg_operator) GETSTRUCT(opertup);
992 oprname = pstrdup(NameStr(operform->oprname));
993 /* For simplicity we always schema-qualify the op name */
994 nspname = get_namespace_name(operform->oprnamespace);
995 namelist = list_make2(makeString(nspname),
996 makeString(oprname));
997 index->excludeOpNames = lappend(index->excludeOpNames,
999 ReleaseSysCache(opertup);
1003 ReleaseSysCache(ht_constr);
1006 index->isconstraint = false;
1009 index->isconstraint = false;
1011 /* Get the index expressions, if any */
1012 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1013 Anum_pg_index_indexprs, &isnull);
1018 exprsString = TextDatumGetCString(datum);
1019 indexprs = (List *) stringToNode(exprsString);
1024 /* Build the list of IndexElem */
1025 index->indexParams = NIL;
1027 indexpr_item = list_head(indexprs);
1028 for (keyno = 0; keyno < idxrec->indnatts; keyno++)
1031 AttrNumber attnum = idxrec->indkey.values[keyno];
1032 int16 opt = source_idx->rd_indoption[keyno];
1034 iparam = makeNode(IndexElem);
1036 if (AttributeNumberIsValid(attnum))
1038 /* Simple index column */
1041 attname = get_relid_attribute_name(indrelid, attnum);
1042 keycoltype = get_atttype(indrelid, attnum);
1044 iparam->name = attname;
1045 iparam->expr = NULL;
1049 /* Expressional index */
1052 if (indexpr_item == NULL)
1053 elog(ERROR, "too few entries in indexprs list");
1054 indexkey = (Node *) lfirst(indexpr_item);
1055 indexpr_item = lnext(indexpr_item);
1057 /* OK to modify indexkey since we are working on a private copy */
1058 change_varattnos_of_a_node(indexkey, attmap);
1060 iparam->name = NULL;
1061 iparam->expr = indexkey;
1063 keycoltype = exprType(indexkey);
1066 /* Copy the original index column name */
1067 iparam->indexcolname = pstrdup(NameStr(attrs[keyno]->attname));
1069 /* Add the operator class name, if non-default */
1070 iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1072 iparam->ordering = SORTBY_DEFAULT;
1073 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1075 /* Adjust options if necessary */
1076 if (amrec->amcanorder)
1079 * If it supports sort ordering, copy DESC and NULLS opts. Don't
1080 * set non-default settings unnecessarily, though, so as to
1081 * improve the chance of recognizing equivalence to constraint
1084 if (opt & INDOPTION_DESC)
1086 iparam->ordering = SORTBY_DESC;
1087 if ((opt & INDOPTION_NULLS_FIRST) == 0)
1088 iparam->nulls_ordering = SORTBY_NULLS_LAST;
1092 if (opt & INDOPTION_NULLS_FIRST)
1093 iparam->nulls_ordering = SORTBY_NULLS_FIRST;
1097 index->indexParams = lappend(index->indexParams, iparam);
1100 /* Copy reloptions if any */
1101 datum = SysCacheGetAttr(RELOID, ht_idxrel,
1102 Anum_pg_class_reloptions, &isnull);
1104 index->options = untransformRelOptions(datum);
1106 /* If it's a partial index, decompile and append the predicate */
1107 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1108 Anum_pg_index_indpred, &isnull);
1113 /* Convert text string to node tree */
1114 pred_str = TextDatumGetCString(datum);
1115 index->whereClause = (Node *) stringToNode(pred_str);
1116 /* Adjust attribute numbers */
1117 change_varattnos_of_a_node(index->whereClause, attmap);
1121 ReleaseSysCache(ht_idxrel);
1127 * get_opclass - fetch name of an index operator class
1129 * If the opclass is the default for the given actual_datatype, then
1130 * the return value is NIL.
1133 get_opclass(Oid opclass, Oid actual_datatype)
1136 Form_pg_opclass opc_rec;
1139 ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1140 if (!HeapTupleIsValid(ht_opc))
1141 elog(ERROR, "cache lookup failed for opclass %u", opclass);
1142 opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
1144 if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
1146 /* For simplicity, we always schema-qualify the name */
1147 char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
1148 char *opc_name = pstrdup(NameStr(opc_rec->opcname));
1150 result = list_make2(makeString(nsp_name), makeString(opc_name));
1153 ReleaseSysCache(ht_opc);
1159 * transformIndexConstraints
1160 * Handle UNIQUE, PRIMARY KEY, EXCLUDE constraints, which create indexes.
1161 * We also merge in any index definitions arising from
1162 * LIKE ... INCLUDING INDEXES.
1165 transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
1168 List *indexlist = NIL;
1172 * Run through the constraints that need to generate an index. For PRIMARY
1173 * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
1174 * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
1177 foreach(lc, cxt->ixconstraints)
1179 Constraint *constraint = (Constraint *) lfirst(lc);
1181 Assert(IsA(constraint, Constraint));
1182 Assert(constraint->contype == CONSTR_PRIMARY ||
1183 constraint->contype == CONSTR_UNIQUE ||
1184 constraint->contype == CONSTR_EXCLUSION);
1186 index = transformIndexConstraint(constraint, cxt);
1188 indexlist = lappend(indexlist, index);
1191 /* Add in any indexes defined by LIKE ... INCLUDING INDEXES */
1192 foreach(lc, cxt->inh_indexes)
1194 index = (IndexStmt *) lfirst(lc);
1198 if (cxt->pkey != NULL)
1200 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1201 errmsg("multiple primary keys for table \"%s\" are not allowed",
1202 cxt->relation->relname)));
1206 indexlist = lappend(indexlist, index);
1210 * Scan the index list and remove any redundant index specifications. This
1211 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1212 * strict reading of SQL92 would suggest raising an error instead, but
1213 * that strikes me as too anal-retentive. - tgl 2001-02-14
1215 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1216 * pre-existing indexes, too.
1218 Assert(cxt->alist == NIL);
1219 if (cxt->pkey != NULL)
1221 /* Make sure we keep the PKEY index in preference to others... */
1222 cxt->alist = list_make1(cxt->pkey);
1225 foreach(lc, indexlist)
1232 /* if it's pkey, it's already in cxt->alist */
1233 if (index == cxt->pkey)
1236 foreach(k, cxt->alist)
1238 IndexStmt *priorindex = lfirst(k);
1240 if (equal(index->indexParams, priorindex->indexParams) &&
1241 equal(index->whereClause, priorindex->whereClause) &&
1242 equal(index->excludeOpNames, priorindex->excludeOpNames) &&
1243 strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
1244 index->deferrable == priorindex->deferrable &&
1245 index->initdeferred == priorindex->initdeferred)
1247 priorindex->unique |= index->unique;
1250 * If the prior index is as yet unnamed, and this one is
1251 * named, then transfer the name to the prior index. This
1252 * ensures that if we have named and unnamed constraints,
1253 * we'll use (at least one of) the names for the index.
1255 if (priorindex->idxname == NULL)
1256 priorindex->idxname = index->idxname;
1263 cxt->alist = lappend(cxt->alist, index);
1268 * transformIndexConstraint
1269 * Transform one UNIQUE, PRIMARY KEY, or EXCLUDE constraint for
1270 * transformIndexConstraints.
1273 transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
1278 index = makeNode(IndexStmt);
1280 index->unique = (constraint->contype != CONSTR_EXCLUSION);
1281 index->primary = (constraint->contype == CONSTR_PRIMARY);
1284 if (cxt->pkey != NULL)
1286 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1287 errmsg("multiple primary keys for table \"%s\" are not allowed",
1288 cxt->relation->relname)));
1292 * In ALTER TABLE case, a primary index might already exist, but
1293 * DefineIndex will check for it.
1296 index->isconstraint = true;
1297 index->deferrable = constraint->deferrable;
1298 index->initdeferred = constraint->initdeferred;
1300 if (constraint->conname != NULL)
1301 index->idxname = pstrdup(constraint->conname);
1303 index->idxname = NULL; /* DefineIndex will choose name */
1305 index->relation = cxt->relation;
1306 index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
1307 index->options = constraint->options;
1308 index->tableSpace = constraint->indexspace;
1309 index->whereClause = constraint->where_clause;
1310 index->indexParams = NIL;
1311 index->excludeOpNames = NIL;
1312 index->concurrent = false;
1315 * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
1316 * IndexElems and operator names. We have to break that apart into
1319 if (constraint->contype == CONSTR_EXCLUSION)
1321 foreach(lc, constraint->exclusions)
1323 List *pair = (List *) lfirst(lc);
1327 Assert(list_length(pair) == 2);
1328 elem = (IndexElem *) linitial(pair);
1329 Assert(IsA(elem, IndexElem));
1330 opname = (List *) lsecond(pair);
1331 Assert(IsA(opname, List));
1333 index->indexParams = lappend(index->indexParams, elem);
1334 index->excludeOpNames = lappend(index->excludeOpNames, opname);
1341 * For UNIQUE and PRIMARY KEY, we just have a list of column names.
1343 * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
1344 * also make sure they are NOT NULL, if possible. (Although we could leave
1345 * it to DefineIndex to mark the columns NOT NULL, it's more efficient to
1346 * get it right the first time.)
1348 foreach(lc, constraint->keys)
1350 char *key = strVal(lfirst(lc));
1352 ColumnDef *column = NULL;
1356 foreach(columns, cxt->columns)
1358 column = (ColumnDef *) lfirst(columns);
1359 Assert(IsA(column, ColumnDef));
1360 if (strcmp(column->colname, key) == 0)
1368 /* found column in the new table; force it to be NOT NULL */
1369 if (constraint->contype == CONSTR_PRIMARY)
1370 column->is_not_null = TRUE;
1372 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1375 * column will be a system column in the new table, so accept it.
1376 * System columns can't ever be null, so no need to worry about
1377 * PRIMARY/NOT NULL constraint.
1381 else if (cxt->inhRelations)
1383 /* try inherited tables */
1386 foreach(inher, cxt->inhRelations)
1388 RangeVar *inh = (RangeVar *) lfirst(inher);
1392 Assert(IsA(inh, RangeVar));
1393 rel = heap_openrv(inh, AccessShareLock);
1394 if (rel->rd_rel->relkind != RELKIND_RELATION)
1396 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1397 errmsg("inherited relation \"%s\" is not a table",
1399 for (count = 0; count < rel->rd_att->natts; count++)
1401 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1402 char *inhname = NameStr(inhattr->attname);
1404 if (inhattr->attisdropped)
1406 if (strcmp(key, inhname) == 0)
1411 * We currently have no easy way to force an inherited
1412 * column to be NOT NULL at creation, if its parent
1413 * wasn't so already. We leave it to DefineIndex to
1414 * fix things up in this case.
1419 heap_close(rel, NoLock);
1426 * In the ALTER TABLE case, don't complain about index keys not
1427 * created in the command; they may well exist already. DefineIndex
1428 * will complain about them if not, and will also take care of marking
1431 if (!found && !cxt->isalter)
1433 (errcode(ERRCODE_UNDEFINED_COLUMN),
1434 errmsg("column \"%s\" named in key does not exist",
1437 /* Check for PRIMARY KEY(foo, foo) */
1438 foreach(columns, index->indexParams)
1440 iparam = (IndexElem *) lfirst(columns);
1441 if (iparam->name && strcmp(key, iparam->name) == 0)
1445 (errcode(ERRCODE_DUPLICATE_COLUMN),
1446 errmsg("column \"%s\" appears twice in primary key constraint",
1450 (errcode(ERRCODE_DUPLICATE_COLUMN),
1451 errmsg("column \"%s\" appears twice in unique constraint",
1456 /* OK, add it to the index definition */
1457 iparam = makeNode(IndexElem);
1458 iparam->name = pstrdup(key);
1459 iparam->expr = NULL;
1460 iparam->indexcolname = NULL;
1461 iparam->opclass = NIL;
1462 iparam->ordering = SORTBY_DEFAULT;
1463 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1464 index->indexParams = lappend(index->indexParams, iparam);
1471 * transformFKConstraints
1472 * handle FOREIGN KEY constraints
1475 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1476 bool skipValidation, bool isAddConstraint)
1480 if (cxt->fkconstraints == NIL)
1484 * If CREATE TABLE or adding a column with NULL default, we can safely
1485 * skip validation of the constraint.
1489 foreach(fkclist, cxt->fkconstraints)
1491 Constraint *constraint = (Constraint *) lfirst(fkclist);
1493 constraint->skip_validation = true;
1498 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1499 * CONSTRAINT command to execute after the basic command is complete. (If
1500 * called from ADD CONSTRAINT, that routine will add the FK constraints to
1501 * its own subcommand list.)
1503 * Note: the ADD CONSTRAINT command must also execute after any index
1504 * creation commands. Thus, this should run after
1505 * transformIndexConstraints, so that the CREATE INDEX commands are
1506 * already in cxt->alist.
1508 if (!isAddConstraint)
1510 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1512 alterstmt->relation = cxt->relation;
1513 alterstmt->cmds = NIL;
1514 alterstmt->relkind = OBJECT_TABLE;
1516 foreach(fkclist, cxt->fkconstraints)
1518 Constraint *constraint = (Constraint *) lfirst(fkclist);
1519 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1521 altercmd->subtype = AT_ProcessedConstraint;
1522 altercmd->name = NULL;
1523 altercmd->def = (Node *) constraint;
1524 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1527 cxt->alist = lappend(cxt->alist, alterstmt);
1532 * transformIndexStmt - parse analysis for CREATE INDEX and ALTER TABLE
1534 * Note: this is a no-op for an index not using either index expressions or
1535 * a predicate expression. There are several code paths that create indexes
1536 * without bothering to call this, because they know they don't have any
1537 * such expressions to deal with.
1540 transformIndexStmt(IndexStmt *stmt, const char *queryString)
1548 * We must not scribble on the passed-in IndexStmt, so copy it. (This is
1549 * overkill, but easy.)
1551 stmt = (IndexStmt *) copyObject(stmt);
1554 * Open the parent table with appropriate locking. We must do this
1555 * because addRangeTableEntry() would acquire only AccessShareLock,
1556 * leaving DefineIndex() needing to do a lock upgrade with consequent risk
1557 * of deadlock. Make sure this stays in sync with the type of lock
1558 * DefineIndex() wants. If we are being called by ALTER TABLE, we will
1559 * already hold a higher lock.
1561 rel = heap_openrv(stmt->relation,
1562 (stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock));
1565 pstate = make_parsestate(NULL);
1566 pstate->p_sourcetext = queryString;
1569 * Put the parent table into the rtable so that the expressions can refer
1570 * to its fields without qualification.
1572 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1574 /* no to join list, yes to namespaces */
1575 addRTEtoQuery(pstate, rte, false, true, true);
1577 /* take care of the where clause */
1578 if (stmt->whereClause)
1579 stmt->whereClause = transformWhereClause(pstate,
1583 /* take care of any index expressions */
1584 foreach(l, stmt->indexParams)
1586 IndexElem *ielem = (IndexElem *) lfirst(l);
1590 /* Extract preliminary index col name before transforming expr */
1591 if (ielem->indexcolname == NULL)
1592 ielem->indexcolname = FigureIndexColname(ielem->expr);
1594 /* Now do parse transformation of the expression */
1595 ielem->expr = transformExpr(pstate, ielem->expr);
1598 * We check only that the result type is legitimate; this is for
1599 * consistency with what transformWhereClause() checks for the
1600 * predicate. DefineIndex() will make more checks.
1602 if (expression_returns_set(ielem->expr))
1604 (errcode(ERRCODE_DATATYPE_MISMATCH),
1605 errmsg("index expression cannot return a set")));
1610 * Check that only the base rel is mentioned.
1612 if (list_length(pstate->p_rtable) != 1)
1614 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1615 errmsg("index expressions and predicates can refer only to the table being indexed")));
1617 free_parsestate(pstate);
1619 /* Close relation, but keep the lock */
1620 heap_close(rel, NoLock);
1627 * transformRuleStmt -
1628 * transform a CREATE RULE Statement. The action is a list of parse
1629 * trees which is transformed into a list of query trees, and we also
1630 * transform the WHERE clause if any.
1632 * actions and whereClause are output parameters that receive the
1633 * transformed results.
1635 * Note that we must not scribble on the passed-in RuleStmt, so we do
1636 * copyObject() on the actions and WHERE clause.
1639 transformRuleStmt(RuleStmt *stmt, const char *queryString,
1640 List **actions, Node **whereClause)
1644 RangeTblEntry *oldrte;
1645 RangeTblEntry *newrte;
1648 * To avoid deadlock, make sure the first thing we do is grab
1649 * AccessExclusiveLock on the target relation. This will be needed by
1650 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1653 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1656 pstate = make_parsestate(NULL);
1657 pstate->p_sourcetext = queryString;
1660 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1661 * Set up their RTEs in the main pstate for use in parsing the rule
1664 oldrte = addRangeTableEntryForRelation(pstate, rel,
1665 makeAlias("old", NIL),
1667 newrte = addRangeTableEntryForRelation(pstate, rel,
1668 makeAlias("new", NIL),
1670 /* Must override addRangeTableEntry's default access-check flags */
1671 oldrte->requiredPerms = 0;
1672 newrte->requiredPerms = 0;
1675 * They must be in the namespace too for lookup purposes, but only add the
1676 * one(s) that are relevant for the current kind of rule. In an UPDATE
1677 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1678 * there's no need to be so picky for INSERT & DELETE. We do not add them
1681 switch (stmt->event)
1684 addRTEtoQuery(pstate, oldrte, false, true, true);
1687 addRTEtoQuery(pstate, oldrte, false, true, true);
1688 addRTEtoQuery(pstate, newrte, false, true, true);
1691 addRTEtoQuery(pstate, newrte, false, true, true);
1694 addRTEtoQuery(pstate, oldrte, false, true, true);
1697 elog(ERROR, "unrecognized event type: %d",
1702 /* take care of the where clause */
1703 *whereClause = transformWhereClause(pstate,
1704 (Node *) copyObject(stmt->whereClause),
1707 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
1709 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1710 errmsg("rule WHERE condition cannot contain references to other relations")));
1712 /* aggregates not allowed (but subselects are okay) */
1713 if (pstate->p_hasAggs)
1715 (errcode(ERRCODE_GROUPING_ERROR),
1716 errmsg("cannot use aggregate function in rule WHERE condition")));
1717 if (pstate->p_hasWindowFuncs)
1719 (errcode(ERRCODE_WINDOWING_ERROR),
1720 errmsg("cannot use window function in rule WHERE condition")));
1723 * 'instead nothing' rules with a qualification need a query rangetable so
1724 * the rewrite handler can add the negated rule qualification to the
1725 * original query. We create a query with the new command type CMD_NOTHING
1726 * here that is treated specially by the rewrite system.
1728 if (stmt->actions == NIL)
1730 Query *nothing_qry = makeNode(Query);
1732 nothing_qry->commandType = CMD_NOTHING;
1733 nothing_qry->rtable = pstate->p_rtable;
1734 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1736 *actions = list_make1(nothing_qry);
1741 List *newactions = NIL;
1744 * transform each statement, like parse_sub_analyze()
1746 foreach(l, stmt->actions)
1748 Node *action = (Node *) lfirst(l);
1749 ParseState *sub_pstate = make_parsestate(NULL);
1756 * Since outer ParseState isn't parent of inner, have to pass down
1757 * the query text by hand.
1759 sub_pstate->p_sourcetext = queryString;
1762 * Set up OLD/NEW in the rtable for this statement. The entries
1763 * are added only to relnamespace, not varnamespace, because we
1764 * don't want them to be referred to by unqualified field names
1765 * nor "*" in the rule actions. We decide later whether to put
1766 * them in the joinlist.
1768 oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
1769 makeAlias("old", NIL),
1771 newrte = addRangeTableEntryForRelation(sub_pstate, rel,
1772 makeAlias("new", NIL),
1774 oldrte->requiredPerms = 0;
1775 newrte->requiredPerms = 0;
1776 addRTEtoQuery(sub_pstate, oldrte, false, true, false);
1777 addRTEtoQuery(sub_pstate, newrte, false, true, false);
1779 /* Transform the rule action statement */
1780 top_subqry = transformStmt(sub_pstate,
1781 (Node *) copyObject(action));
1784 * We cannot support utility-statement actions (eg NOTIFY) with
1785 * nonempty rule WHERE conditions, because there's no way to make
1786 * the utility action execute conditionally.
1788 if (top_subqry->commandType == CMD_UTILITY &&
1789 *whereClause != NULL)
1791 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1792 errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
1795 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
1796 * into the SELECT, and that's what we need to look at. (Ugly
1797 * kluge ... try to fix this when we redesign querytrees.)
1799 sub_qry = getInsertSelectQuery(top_subqry, NULL);
1802 * If the sub_qry is a setop, we cannot attach any qualifications
1803 * to it, because the planner won't notice them. This could
1804 * perhaps be relaxed someday, but for now, we may as well reject
1805 * such a rule immediately.
1807 if (sub_qry->setOperations != NULL && *whereClause != NULL)
1809 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1810 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1813 * Validate action's use of OLD/NEW, qual too
1816 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1817 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
1819 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1820 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
1822 switch (stmt->event)
1827 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1828 errmsg("ON SELECT rule cannot use OLD")));
1831 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1832 errmsg("ON SELECT rule cannot use NEW")));
1840 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1841 errmsg("ON INSERT rule cannot use OLD")));
1846 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1847 errmsg("ON DELETE rule cannot use NEW")));
1850 elog(ERROR, "unrecognized event type: %d",
1856 * For efficiency's sake, add OLD to the rule action's jointree
1857 * only if it was actually referenced in the statement or qual.
1859 * For INSERT, NEW is not really a relation (only a reference to
1860 * the to-be-inserted tuple) and should never be added to the
1863 * For UPDATE, we treat NEW as being another kind of reference to
1864 * OLD, because it represents references to *transformed* tuples
1865 * of the existing relation. It would be wrong to enter NEW
1866 * separately in the jointree, since that would cause a double
1867 * join of the updated relation. It's also wrong to fail to make
1868 * a jointree entry if only NEW and not OLD is mentioned.
1870 if (has_old || (has_new && stmt->event == CMD_UPDATE))
1873 * If sub_qry is a setop, manipulating its jointree will do no
1874 * good at all, because the jointree is dummy. (This should be
1875 * a can't-happen case because of prior tests.)
1877 if (sub_qry->setOperations != NULL)
1879 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1880 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1881 /* hack so we can use addRTEtoQuery() */
1882 sub_pstate->p_rtable = sub_qry->rtable;
1883 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
1884 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
1885 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
1888 newactions = lappend(newactions, top_subqry);
1890 free_parsestate(sub_pstate);
1893 *actions = newactions;
1896 free_parsestate(pstate);
1898 /* Close relation, but keep the exclusive lock */
1899 heap_close(rel, NoLock);
1904 * transformAlterTableStmt -
1905 * parse analysis for ALTER TABLE
1907 * Returns a List of utility commands to be done in sequence. One of these
1908 * will be the transformed AlterTableStmt, but there may be additional actions
1909 * to be done before and after the actual AlterTable() call.
1912 transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
1916 CreateStmtContext cxt;
1921 List *newcmds = NIL;
1922 bool skipValidation = true;
1923 AlterTableCmd *newcmd;
1927 * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
1928 * is overkill, but easy.)
1930 stmt = (AlterTableStmt *) copyObject(stmt);
1933 * Assign the appropriate lock level for this list of subcommands.
1935 lockmode = AlterTableGetLockLevel(stmt->cmds);
1938 * Acquire appropriate lock on the target relation, which will be held until
1939 * end of transaction. This ensures any decisions we make here based on
1940 * the state of the relation will still be good at execution. We must get
1941 * lock now because execution will later require it; taking a lower grade lock
1942 * now and trying to upgrade later risks deadlock. Any new commands we add
1943 * after this must not upgrade the lock level requested here.
1945 rel = relation_openrv(stmt->relation, lockmode);
1948 pstate = make_parsestate(NULL);
1949 pstate->p_sourcetext = queryString;
1951 cxt.stmtType = "ALTER TABLE";
1952 cxt.relation = stmt->relation;
1954 cxt.inhRelations = NIL;
1956 cxt.hasoids = false; /* need not be right */
1958 cxt.ckconstraints = NIL;
1959 cxt.fkconstraints = NIL;
1960 cxt.ixconstraints = NIL;
1961 cxt.inh_indexes = NIL;
1967 * The only subtypes that currently require parse transformation handling
1968 * are ADD COLUMN and ADD CONSTRAINT. These largely re-use code from
1971 foreach(lcmd, stmt->cmds)
1973 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
1975 switch (cmd->subtype)
1978 case AT_AddColumnToView:
1980 ColumnDef *def = (ColumnDef *) cmd->def;
1982 Assert(IsA(def, ColumnDef));
1983 transformColumnDefinition(pstate, &cxt, def);
1986 * If the column has a non-null default, we can't skip
1987 * validation of foreign keys.
1989 if (def->raw_default != NULL)
1990 skipValidation = false;
1993 * All constraints are processed in other ways. Remove the
1996 def->constraints = NIL;
1998 newcmds = lappend(newcmds, cmd);
2001 case AT_AddConstraint:
2004 * The original AddConstraint cmd node doesn't go to newcmds
2006 if (IsA(cmd->def, Constraint))
2008 transformTableConstraint(pstate, &cxt,
2009 (Constraint *) cmd->def);
2010 if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
2011 skipValidation = false;
2014 elog(ERROR, "unrecognized node type: %d",
2015 (int) nodeTag(cmd->def));
2018 case AT_ProcessedConstraint:
2021 * Already-transformed ADD CONSTRAINT, so just make it look
2022 * like the standard case.
2024 cmd->subtype = AT_AddConstraint;
2025 newcmds = lappend(newcmds, cmd);
2029 newcmds = lappend(newcmds, cmd);
2035 * transformIndexConstraints wants cxt.alist to contain only index
2036 * statements, so transfer anything we already have into save_alist
2039 save_alist = cxt.alist;
2042 /* Postprocess index and FK constraints */
2043 transformIndexConstraints(pstate, &cxt);
2045 transformFKConstraints(pstate, &cxt, skipValidation, true);
2048 * Push any index-creation commands into the ALTER, so that they can be
2049 * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
2050 * the IndexStmt attached to an AT_AddIndex subcommand has already been
2051 * through transformIndexStmt.
2053 foreach(l, cxt.alist)
2055 Node *idxstmt = (Node *) lfirst(l);
2057 Assert(IsA(idxstmt, IndexStmt));
2058 newcmd = makeNode(AlterTableCmd);
2059 newcmd->subtype = AT_AddIndex;
2060 newcmd->def = (Node *) transformIndexStmt((IndexStmt *) idxstmt,
2062 newcmds = lappend(newcmds, newcmd);
2066 /* Append any CHECK or FK constraints to the commands list */
2067 foreach(l, cxt.ckconstraints)
2069 newcmd = makeNode(AlterTableCmd);
2070 newcmd->subtype = AT_AddConstraint;
2071 newcmd->def = (Node *) lfirst(l);
2072 newcmds = lappend(newcmds, newcmd);
2074 foreach(l, cxt.fkconstraints)
2076 newcmd = makeNode(AlterTableCmd);
2077 newcmd->subtype = AT_AddConstraint;
2078 newcmd->def = (Node *) lfirst(l);
2079 newcmds = lappend(newcmds, newcmd);
2082 /* Close rel but keep lock */
2083 relation_close(rel, NoLock);
2088 stmt->cmds = newcmds;
2090 result = lappend(cxt.blist, stmt);
2091 result = list_concat(result, cxt.alist);
2092 result = list_concat(result, save_alist);
2099 * Preprocess a list of column constraint clauses
2100 * to attach constraint attributes to their primary constraint nodes
2101 * and detect inconsistent/misplaced constraint attributes.
2103 * NOTE: currently, attributes are only supported for FOREIGN KEY, UNIQUE,
2104 * and PRIMARY KEY constraints, but someday they ought to be supported
2105 * for other constraint types.
2108 transformConstraintAttrs(ParseState *pstate, List *constraintList)
2110 Constraint *lastprimarycon = NULL;
2111 bool saw_deferrability = false;
2112 bool saw_initially = false;
2115 #define SUPPORTS_ATTRS(node) \
2116 ((node) != NULL && \
2117 ((node)->contype == CONSTR_PRIMARY || \
2118 (node)->contype == CONSTR_UNIQUE || \
2119 (node)->contype == CONSTR_EXCLUSION || \
2120 (node)->contype == CONSTR_FOREIGN))
2122 foreach(clist, constraintList)
2124 Constraint *con = (Constraint *) lfirst(clist);
2126 if (!IsA(con, Constraint))
2127 elog(ERROR, "unrecognized node type: %d",
2128 (int) nodeTag(con));
2129 switch (con->contype)
2131 case CONSTR_ATTR_DEFERRABLE:
2132 if (!SUPPORTS_ATTRS(lastprimarycon))
2134 (errcode(ERRCODE_SYNTAX_ERROR),
2135 errmsg("misplaced DEFERRABLE clause"),
2136 parser_errposition(pstate, con->location)));
2137 if (saw_deferrability)
2139 (errcode(ERRCODE_SYNTAX_ERROR),
2140 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2141 parser_errposition(pstate, con->location)));
2142 saw_deferrability = true;
2143 lastprimarycon->deferrable = true;
2146 case CONSTR_ATTR_NOT_DEFERRABLE:
2147 if (!SUPPORTS_ATTRS(lastprimarycon))
2149 (errcode(ERRCODE_SYNTAX_ERROR),
2150 errmsg("misplaced NOT DEFERRABLE clause"),
2151 parser_errposition(pstate, con->location)));
2152 if (saw_deferrability)
2154 (errcode(ERRCODE_SYNTAX_ERROR),
2155 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2156 parser_errposition(pstate, con->location)));
2157 saw_deferrability = true;
2158 lastprimarycon->deferrable = false;
2159 if (saw_initially &&
2160 lastprimarycon->initdeferred)
2162 (errcode(ERRCODE_SYNTAX_ERROR),
2163 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2164 parser_errposition(pstate, con->location)));
2167 case CONSTR_ATTR_DEFERRED:
2168 if (!SUPPORTS_ATTRS(lastprimarycon))
2170 (errcode(ERRCODE_SYNTAX_ERROR),
2171 errmsg("misplaced INITIALLY DEFERRED clause"),
2172 parser_errposition(pstate, con->location)));
2175 (errcode(ERRCODE_SYNTAX_ERROR),
2176 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2177 parser_errposition(pstate, con->location)));
2178 saw_initially = true;
2179 lastprimarycon->initdeferred = true;
2182 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
2184 if (!saw_deferrability)
2185 lastprimarycon->deferrable = true;
2186 else if (!lastprimarycon->deferrable)
2188 (errcode(ERRCODE_SYNTAX_ERROR),
2189 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2190 parser_errposition(pstate, con->location)));
2193 case CONSTR_ATTR_IMMEDIATE:
2194 if (!SUPPORTS_ATTRS(lastprimarycon))
2196 (errcode(ERRCODE_SYNTAX_ERROR),
2197 errmsg("misplaced INITIALLY IMMEDIATE clause"),
2198 parser_errposition(pstate, con->location)));
2201 (errcode(ERRCODE_SYNTAX_ERROR),
2202 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2203 parser_errposition(pstate, con->location)));
2204 saw_initially = true;
2205 lastprimarycon->initdeferred = false;
2209 /* Otherwise it's not an attribute */
2210 lastprimarycon = con;
2211 /* reset flags for new primary node */
2212 saw_deferrability = false;
2213 saw_initially = false;
2220 * Special handling of type definition for a column
2223 transformColumnType(ParseState *pstate, ColumnDef *column)
2226 * All we really need to do here is verify that the type is valid.
2228 Type ctype = typenameType(pstate, column->typeName, NULL);
2230 ReleaseSysCache(ctype);
2235 * transformCreateSchemaStmt -
2236 * analyzes the CREATE SCHEMA statement
2238 * Split the schema element list into individual commands and place
2239 * them in the result list in an order such that there are no forward
2240 * references (e.g. GRANT to a table created later in the list). Note
2241 * that the logic we use for determining forward references is
2242 * presently quite incomplete.
2244 * SQL92 also allows constraints to make forward references, so thumb through
2245 * the table columns and move forward references to a posterior alter-table
2248 * The result is a list of parse nodes that still need to be analyzed ---
2249 * but we can't analyze the later commands until we've executed the earlier
2250 * ones, because of possible inter-object references.
2252 * Note: this breaks the rules a little bit by modifying schema-name fields
2253 * within passed-in structs. However, the transformation would be the same
2254 * if done over, so it should be all right to scribble on the input to this
2258 transformCreateSchemaStmt(CreateSchemaStmt *stmt)
2260 CreateSchemaStmtContext cxt;
2264 cxt.stmtType = "CREATE SCHEMA";
2265 cxt.schemaname = stmt->schemaname;
2266 cxt.authid = stmt->authid;
2267 cxt.sequences = NIL;
2275 * Run through each schema element in the schema element list. Separate
2276 * statements by type, and do preliminary analysis.
2278 foreach(elements, stmt->schemaElts)
2280 Node *element = lfirst(elements);
2282 switch (nodeTag(element))
2284 case T_CreateSeqStmt:
2286 CreateSeqStmt *elp = (CreateSeqStmt *) element;
2288 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
2289 cxt.sequences = lappend(cxt.sequences, element);
2295 CreateStmt *elp = (CreateStmt *) element;
2297 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2300 * XXX todo: deal with constraints
2302 cxt.tables = lappend(cxt.tables, element);
2308 ViewStmt *elp = (ViewStmt *) element;
2310 setSchemaName(cxt.schemaname, &elp->view->schemaname);
2313 * XXX todo: deal with references between views
2315 cxt.views = lappend(cxt.views, element);
2321 IndexStmt *elp = (IndexStmt *) element;
2323 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2324 cxt.indexes = lappend(cxt.indexes, element);
2328 case T_CreateTrigStmt:
2330 CreateTrigStmt *elp = (CreateTrigStmt *) element;
2332 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2333 cxt.triggers = lappend(cxt.triggers, element);
2338 cxt.grants = lappend(cxt.grants, element);
2342 elog(ERROR, "unrecognized node type: %d",
2343 (int) nodeTag(element));
2348 result = list_concat(result, cxt.sequences);
2349 result = list_concat(result, cxt.tables);
2350 result = list_concat(result, cxt.views);
2351 result = list_concat(result, cxt.indexes);
2352 result = list_concat(result, cxt.triggers);
2353 result = list_concat(result, cxt.grants);
2360 * Set or check schema name in an element of a CREATE SCHEMA command
2363 setSchemaName(char *context_schema, char **stmt_schema_name)
2365 if (*stmt_schema_name == NULL)
2366 *stmt_schema_name = context_schema;
2367 else if (strcmp(context_schema, *stmt_schema_name) != 0)
2369 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
2370 errmsg("CREATE specifies a schema (%s) "
2371 "different from the one being created (%s)",
2372 *stmt_schema_name, context_schema)));