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 * src/backend/parser/parse_utilcmd.c
24 *-------------------------------------------------------------------------
29 #include "access/genam.h"
30 #include "access/heapam.h"
31 #include "access/reloptions.h"
32 #include "catalog/dependency.h"
33 #include "catalog/heap.h"
34 #include "catalog/index.h"
35 #include "catalog/namespace.h"
36 #include "catalog/pg_constraint.h"
37 #include "catalog/pg_opclass.h"
38 #include "catalog/pg_operator.h"
39 #include "catalog/pg_type.h"
40 #include "commands/comment.h"
41 #include "commands/defrem.h"
42 #include "commands/tablecmds.h"
43 #include "commands/tablespace.h"
44 #include "miscadmin.h"
45 #include "nodes/makefuncs.h"
46 #include "nodes/nodeFuncs.h"
47 #include "parser/analyze.h"
48 #include "parser/parse_clause.h"
49 #include "parser/parse_expr.h"
50 #include "parser/parse_relation.h"
51 #include "parser/parse_target.h"
52 #include "parser/parse_type.h"
53 #include "parser/parse_utilcmd.h"
54 #include "parser/parser.h"
55 #include "rewrite/rewriteManip.h"
56 #include "storage/lock.h"
57 #include "utils/acl.h"
58 #include "utils/builtins.h"
59 #include "utils/lsyscache.h"
60 #include "utils/relcache.h"
61 #include "utils/syscache.h"
62 #include "utils/typcache.h"
65 /* State shared by transformCreateStmt and its subroutines */
68 const char *stmtType; /* "CREATE TABLE" or "ALTER TABLE" */
69 RangeVar *relation; /* relation to create */
70 Relation rel; /* opened/locked rel, if ALTER */
71 List *inhRelations; /* relations to inherit from */
72 bool isalter; /* true if altering existing table */
73 bool hasoids; /* does relation have an OID column? */
74 List *columns; /* ColumnDef items */
75 List *ckconstraints; /* CHECK constraints */
76 List *fkconstraints; /* FOREIGN KEY constraints */
77 List *ixconstraints; /* index-creating constraints */
78 List *inh_indexes; /* cloned indexes from INCLUDING INDEXES */
79 List *blist; /* "before list" of things to do before
80 * creating the table */
81 List *alist; /* "after list" of things to do after creating
83 IndexStmt *pkey; /* PRIMARY KEY index, if any */
86 /* State shared by transformCreateSchemaStmt and its subroutines */
89 const char *stmtType; /* "CREATE SCHEMA" or "ALTER SCHEMA" */
90 char *schemaname; /* name of schema */
91 char *authid; /* owner of schema */
92 List *sequences; /* CREATE SEQUENCE items */
93 List *tables; /* CREATE TABLE items */
94 List *views; /* CREATE VIEW items */
95 List *indexes; /* CREATE INDEX items */
96 List *triggers; /* CREATE TRIGGER items */
97 List *grants; /* GRANT items */
98 } CreateSchemaStmtContext;
101 static void transformColumnDefinition(ParseState *pstate,
102 CreateStmtContext *cxt,
104 static void transformTableConstraint(ParseState *pstate,
105 CreateStmtContext *cxt,
106 Constraint *constraint);
107 static void transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
108 InhRelation *inhrelation);
109 static void transformOfType(ParseState *pstate, CreateStmtContext *cxt,
110 TypeName *ofTypename);
111 static char *chooseIndexName(const RangeVar *relation, IndexStmt *index_stmt);
112 static IndexStmt *generateClonedIndexStmt(CreateStmtContext *cxt,
113 Relation parent_index, AttrNumber *attmap);
114 static List *get_opclass(Oid opclass, Oid actual_datatype);
115 static void transformIndexConstraints(ParseState *pstate,
116 CreateStmtContext *cxt);
117 static IndexStmt *transformIndexConstraint(Constraint *constraint,
118 CreateStmtContext *cxt);
119 static void transformFKConstraints(ParseState *pstate,
120 CreateStmtContext *cxt,
122 bool isAddConstraint);
123 static void transformConstraintAttrs(ParseState *pstate, List *constraintList);
124 static void transformColumnType(ParseState *pstate, ColumnDef *column);
125 static void setSchemaName(char *context_schema, char **stmt_schema_name);
129 * transformCreateStmt -
130 * parse analysis for CREATE TABLE
132 * Returns a List of utility commands to be done in sequence. One of these
133 * will be the transformed CreateStmt, but there may be additional actions
134 * to be done before and after the actual DefineRelation() call.
136 * SQL92 allows constraints to be scattered all over, so thumb through
137 * the columns and collect all constraints into one place.
138 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
139 * then expand those into multiple IndexStmt blocks.
140 * - thomas 1997-12-02
143 transformCreateStmt(CreateStmt *stmt, const char *queryString)
146 CreateStmtContext cxt;
152 * We must not scribble on the passed-in CreateStmt, so copy it. (This is
153 * overkill, but easy.)
155 stmt = (CreateStmt *) copyObject(stmt);
158 * If the target relation name isn't schema-qualified, make it so. This
159 * prevents some corner cases in which added-on rewritten commands might
160 * think they should apply to other relations that have the same name and
161 * are earlier in the search path. "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;
365 * If this is ALTER ADD COLUMN, make sure the sequence will be owned
366 * by the table's owner. The current user might be someone else
367 * (perhaps a superuser, or someone who's only a member of the owning
368 * role), but the SEQUENCE OWNED BY mechanisms will bleat unless
369 * table and sequence have exactly the same owning role.
372 seqstmt->ownerId = cxt->rel->rd_rel->relowner;
374 seqstmt->ownerId = InvalidOid;
376 cxt->blist = lappend(cxt->blist, seqstmt);
379 * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence
380 * as owned by this column, and add it to the list of things to be
381 * done after this CREATE/ALTER TABLE.
383 altseqstmt = makeNode(AlterSeqStmt);
384 altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
385 attnamelist = list_make3(makeString(snamespace),
386 makeString(cxt->relation->relname),
387 makeString(column->colname));
388 altseqstmt->options = list_make1(makeDefElem("owned_by",
389 (Node *) attnamelist));
391 cxt->alist = lappend(cxt->alist, altseqstmt);
394 * Create appropriate constraints for SERIAL. We do this in full,
395 * rather than shortcutting, so that we will detect any conflicting
396 * constraints the user wrote (like a different DEFAULT).
398 * Create an expression tree representing the function call
399 * nextval('sequencename'). We cannot reduce the raw tree to cooked
400 * form until after the sequence is created, but there's no need to do
403 qstring = quote_qualified_identifier(snamespace, sname);
404 snamenode = makeNode(A_Const);
405 snamenode->val.type = T_String;
406 snamenode->val.val.str = qstring;
407 snamenode->location = -1;
408 castnode = makeNode(TypeCast);
409 castnode->typeName = SystemTypeName("regclass");
410 castnode->arg = (Node *) snamenode;
411 castnode->location = -1;
412 funccallnode = makeNode(FuncCall);
413 funccallnode->funcname = SystemFuncName("nextval");
414 funccallnode->args = list_make1(castnode);
415 funccallnode->agg_order = NIL;
416 funccallnode->agg_star = false;
417 funccallnode->agg_distinct = false;
418 funccallnode->func_variadic = false;
419 funccallnode->over = NULL;
420 funccallnode->location = -1;
422 constraint = makeNode(Constraint);
423 constraint->contype = CONSTR_DEFAULT;
424 constraint->location = -1;
425 constraint->raw_expr = (Node *) funccallnode;
426 constraint->cooked_expr = NULL;
427 column->constraints = lappend(column->constraints, constraint);
429 constraint = makeNode(Constraint);
430 constraint->contype = CONSTR_NOTNULL;
431 constraint->location = -1;
432 column->constraints = lappend(column->constraints, constraint);
435 /* Process column constraints, if any... */
436 transformConstraintAttrs(pstate, column->constraints);
438 saw_nullable = false;
441 foreach(clist, column->constraints)
443 constraint = lfirst(clist);
444 Assert(IsA(constraint, Constraint));
446 switch (constraint->contype)
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 = FALSE;
461 if (saw_nullable && !column->is_not_null)
463 (errcode(ERRCODE_SYNTAX_ERROR),
464 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
465 column->colname, cxt->relation->relname),
466 parser_errposition(pstate,
467 constraint->location)));
468 column->is_not_null = TRUE;
475 (errcode(ERRCODE_SYNTAX_ERROR),
476 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
477 column->colname, cxt->relation->relname),
478 parser_errposition(pstate,
479 constraint->location)));
480 column->raw_default = constraint->raw_expr;
481 Assert(constraint->cooked_expr == NULL);
486 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
491 if (constraint->keys == NIL)
492 constraint->keys = list_make1(makeString(column->colname));
493 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
496 case CONSTR_EXCLUSION:
497 /* grammar does not allow EXCLUDE as a column constraint */
498 elog(ERROR, "column exclusion constraints are not supported");
504 * Fill in the current attribute's name and throw it into the
505 * list of FK constraints to be processed later.
507 constraint->fk_attrs = list_make1(makeString(column->colname));
508 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
511 case CONSTR_ATTR_DEFERRABLE:
512 case CONSTR_ATTR_NOT_DEFERRABLE:
513 case CONSTR_ATTR_DEFERRED:
514 case CONSTR_ATTR_IMMEDIATE:
515 /* transformConstraintAttrs took care of these */
519 elog(ERROR, "unrecognized constraint type: %d",
520 constraint->contype);
527 * transformTableConstraint
528 * transform a Constraint node within CREATE TABLE or ALTER TABLE
531 transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt,
532 Constraint *constraint)
534 switch (constraint->contype)
538 case CONSTR_EXCLUSION:
539 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
543 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
547 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
553 case CONSTR_ATTR_DEFERRABLE:
554 case CONSTR_ATTR_NOT_DEFERRABLE:
555 case CONSTR_ATTR_DEFERRED:
556 case CONSTR_ATTR_IMMEDIATE:
557 elog(ERROR, "invalid context for constraint type %d",
558 constraint->contype);
562 elog(ERROR, "unrecognized constraint type: %d",
563 constraint->contype);
569 * transformInhRelation
571 * Change the LIKE <subtable> portion of a CREATE TABLE statement into
572 * column definitions which recreate the user defined column portions of
576 transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
577 InhRelation *inhRelation)
579 AttrNumber parent_attno;
586 relation = parserOpenTable(pstate, inhRelation->relation, AccessShareLock);
588 if (relation->rd_rel->relkind != RELKIND_RELATION)
590 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
591 errmsg("inherited relation \"%s\" is not a table",
592 inhRelation->relation->relname)));
595 * Check for SELECT privilages
597 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
599 if (aclresult != ACLCHECK_OK)
600 aclcheck_error(aclresult, ACL_KIND_CLASS,
601 RelationGetRelationName(relation));
603 tupleDesc = RelationGetDescr(relation);
604 constr = tupleDesc->constr;
607 * Insert the copied attributes into the cxt for the new table definition.
609 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
612 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
613 char *attributeName = NameStr(attribute->attname);
617 * Ignore dropped columns in the parent.
619 if (attribute->attisdropped)
623 * Create a new column, which is marked as NOT inherited.
625 * For constraints, ONLY the NOT NULL constraint is inherited by the
626 * new column definition per SQL99.
628 def = makeNode(ColumnDef);
629 def->colname = pstrdup(attributeName);
630 def->typeName = makeTypeNameFromOid(attribute->atttypid,
631 attribute->atttypmod);
633 def->is_local = true;
634 def->is_not_null = attribute->attnotnull;
635 def->raw_default = NULL;
636 def->cooked_default = NULL;
637 def->constraints = NIL;
642 cxt->columns = lappend(cxt->columns, def);
645 * Copy default, if present and the default has been requested
647 if (attribute->atthasdef &&
648 (inhRelation->options & CREATE_TABLE_LIKE_DEFAULTS))
650 Node *this_default = NULL;
651 AttrDefault *attrdef;
654 /* Find default in constraint structure */
655 Assert(constr != NULL);
656 attrdef = constr->defval;
657 for (i = 0; i < constr->num_defval; i++)
659 if (attrdef[i].adnum == parent_attno)
661 this_default = stringToNode(attrdef[i].adbin);
665 Assert(this_default != NULL);
668 * If default expr could contain any vars, we'd need to fix 'em,
669 * but it can't; so default is ready to apply to child.
672 def->cooked_default = this_default;
675 /* Likewise, copy storage if requested */
676 if (inhRelation->options & CREATE_TABLE_LIKE_STORAGE)
677 def->storage = attribute->attstorage;
681 /* Likewise, copy comment if requested */
682 if ((inhRelation->options & CREATE_TABLE_LIKE_COMMENTS) &&
683 (comment = GetComment(attribute->attrelid,
685 attribute->attnum)) != NULL)
687 CommentStmt *stmt = makeNode(CommentStmt);
689 stmt->objtype = OBJECT_COLUMN;
690 stmt->objname = list_make3(makeString(cxt->relation->schemaname),
691 makeString(cxt->relation->relname),
692 makeString(def->colname));
694 stmt->comment = comment;
696 cxt->alist = lappend(cxt->alist, stmt);
701 * Copy CHECK constraints if requested, being careful to adjust attribute
704 if ((inhRelation->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
707 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
710 for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
712 char *ccname = tupleDesc->constr->check[ccnum].ccname;
713 char *ccbin = tupleDesc->constr->check[ccnum].ccbin;
714 Node *ccbin_node = stringToNode(ccbin);
715 Constraint *n = makeNode(Constraint);
717 change_varattnos_of_a_node(ccbin_node, attmap);
719 n->contype = CONSTR_CHECK;
721 n->conname = pstrdup(ccname);
723 n->cooked_expr = nodeToString(ccbin_node);
724 cxt->ckconstraints = lappend(cxt->ckconstraints, n);
726 /* Copy comment on constraint */
727 if ((inhRelation->options & CREATE_TABLE_LIKE_COMMENTS) &&
728 (comment = GetComment(get_constraint_oid(RelationGetRelid(relation),
730 ConstraintRelationId,
733 CommentStmt *stmt = makeNode(CommentStmt);
735 stmt->objtype = OBJECT_CONSTRAINT;
736 stmt->objname = list_make3(makeString(cxt->relation->schemaname),
737 makeString(cxt->relation->relname),
738 makeString(n->conname));
740 stmt->comment = comment;
742 cxt->alist = lappend(cxt->alist, stmt);
748 * Likewise, copy indexes if requested
750 if ((inhRelation->options & CREATE_TABLE_LIKE_INDEXES) &&
751 relation->rd_rel->relhasindex)
753 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
754 List *parent_indexes;
757 parent_indexes = RelationGetIndexList(relation);
759 foreach(l, parent_indexes)
761 Oid parent_index_oid = lfirst_oid(l);
762 Relation parent_index;
763 IndexStmt *index_stmt;
765 parent_index = index_open(parent_index_oid, AccessShareLock);
767 /* Build CREATE INDEX statement to recreate the parent_index */
768 index_stmt = generateClonedIndexStmt(cxt, parent_index, attmap);
770 /* Copy comment on index */
771 if (inhRelation->options & CREATE_TABLE_LIKE_COMMENTS)
773 comment = GetComment(parent_index_oid, RelationRelationId, 0);
780 * We have to assign the index a name now, so that we can
781 * reference it in CommentStmt.
783 if (index_stmt->idxname == NULL)
784 index_stmt->idxname = chooseIndexName(cxt->relation,
787 stmt = makeNode(CommentStmt);
788 stmt->objtype = OBJECT_INDEX;
790 list_make2(makeString(cxt->relation->schemaname),
791 makeString(index_stmt->idxname));
793 stmt->comment = comment;
795 cxt->alist = lappend(cxt->alist, stmt);
799 /* Save it in the inh_indexes list for the time being */
800 cxt->inh_indexes = lappend(cxt->inh_indexes, index_stmt);
802 index_close(parent_index, AccessShareLock);
807 * Close the parent rel, but keep our AccessShareLock on it until xact
808 * commit. That will prevent someone else from deleting or ALTERing the
809 * parent before the child is committed.
811 heap_close(relation, NoLock);
815 transformOfType(ParseState *pstate, CreateStmtContext *cxt, TypeName *ofTypename)
823 AssertArg(ofTypename);
825 tuple = typenameType(NULL, ofTypename, NULL);
826 typ = (Form_pg_type) GETSTRUCT(tuple);
827 ofTypeId = HeapTupleGetOid(tuple);
828 ofTypename->typeOid = ofTypeId; /* cached for later */
830 if (typ->typtype != TYPTYPE_COMPOSITE)
832 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
833 errmsg("type %s is not a composite type",
834 format_type_be(ofTypeId))));
836 tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
837 for (i = 0; i < tupdesc->natts; i++)
839 Form_pg_attribute attr = tupdesc->attrs[i];
840 ColumnDef *n = makeNode(ColumnDef);
842 if (attr->attisdropped)
845 n->colname = pstrdup(NameStr(attr->attname));
846 n->typeName = makeTypeNameFromOid(attr->atttypid, attr->atttypmod);
847 n->constraints = NULL;
849 n->is_from_type = true;
850 cxt->columns = lappend(cxt->columns, n);
852 DecrTupleDescRefCount(tupdesc);
854 ReleaseSysCache(tuple);
860 * Compute name for an index. This must match code in indexcmds.c.
862 * XXX this is inherently broken because the indexes aren't created
863 * immediately, so we fail to resolve conflicts when the same name is
864 * derived for multiple indexes. However, that's a reasonably uncommon
865 * situation, so we'll live with it for now.
868 chooseIndexName(const RangeVar *relation, IndexStmt *index_stmt)
873 namespaceId = RangeVarGetCreationNamespace(relation);
874 colnames = ChooseIndexColumnNames(index_stmt->indexParams);
875 return ChooseIndexName(relation->relname, namespaceId,
876 colnames, index_stmt->excludeOpNames,
877 index_stmt->primary, index_stmt->isconstraint);
881 * Generate an IndexStmt node using information from an already existing index
882 * "source_idx". Attribute numbers should be adjusted according to attmap.
885 generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
888 Oid source_relid = RelationGetRelid(source_idx);
889 Form_pg_attribute *attrs = RelationGetDescr(source_idx)->attrs;
892 Form_pg_class idxrelrec;
893 Form_pg_index idxrec;
898 ListCell *indexpr_item;
906 * Fetch pg_class tuple of source index. We can't use the copy in the
907 * relcache entry because it doesn't include optional fields.
909 ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
910 if (!HeapTupleIsValid(ht_idxrel))
911 elog(ERROR, "cache lookup failed for relation %u", source_relid);
912 idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
914 /* Fetch pg_index tuple for source index from relcache entry */
915 ht_idx = source_idx->rd_indextuple;
916 idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
917 indrelid = idxrec->indrelid;
919 /* Fetch pg_am tuple for source index from relcache entry */
920 amrec = source_idx->rd_am;
922 /* Extract indclass from the pg_index tuple */
923 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
924 Anum_pg_index_indclass, &isnull);
926 indclass = (oidvector *) DatumGetPointer(datum);
928 /* Begin building the IndexStmt */
929 index = makeNode(IndexStmt);
930 index->relation = cxt->relation;
931 index->accessMethod = pstrdup(NameStr(amrec->amname));
932 if (OidIsValid(idxrelrec->reltablespace))
933 index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
935 index->tableSpace = NULL;
936 index->unique = idxrec->indisunique;
937 index->primary = idxrec->indisprimary;
938 index->concurrent = false;
941 * We don't try to preserve the name of the source index; instead, just
942 * let DefineIndex() choose a reasonable name.
944 index->idxname = NULL;
947 * If the index is marked PRIMARY or has an exclusion condition, it's
948 * certainly from a constraint; else, if it's not marked UNIQUE, it
949 * certainly isn't. If it is or might be from a constraint, we have to
950 * fetch the pg_constraint record.
952 if (index->primary || index->unique || idxrelrec->relhasexclusion)
954 Oid constraintId = get_index_constraint(source_relid);
956 if (OidIsValid(constraintId))
959 Form_pg_constraint conrec;
961 ht_constr = SearchSysCache1(CONSTROID,
962 ObjectIdGetDatum(constraintId));
963 if (!HeapTupleIsValid(ht_constr))
964 elog(ERROR, "cache lookup failed for constraint %u",
966 conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
968 index->isconstraint = true;
969 index->deferrable = conrec->condeferrable;
970 index->initdeferred = conrec->condeferred;
972 /* If it's an exclusion constraint, we need the operator names */
973 if (idxrelrec->relhasexclusion)
979 Assert(conrec->contype == CONSTRAINT_EXCLUSION);
980 /* Extract operator OIDs from the pg_constraint tuple */
981 datum = SysCacheGetAttr(CONSTROID, ht_constr,
982 Anum_pg_constraint_conexclop,
985 elog(ERROR, "null conexclop for constraint %u",
988 deconstruct_array(DatumGetArrayTypeP(datum),
989 OIDOID, sizeof(Oid), true, 'i',
990 &elems, NULL, &nElems);
992 for (i = 0; i < nElems; i++)
994 Oid operid = DatumGetObjectId(elems[i]);
996 Form_pg_operator operform;
1001 opertup = SearchSysCache1(OPEROID,
1002 ObjectIdGetDatum(operid));
1003 if (!HeapTupleIsValid(opertup))
1004 elog(ERROR, "cache lookup failed for operator %u",
1006 operform = (Form_pg_operator) GETSTRUCT(opertup);
1007 oprname = pstrdup(NameStr(operform->oprname));
1008 /* For simplicity we always schema-qualify the op name */
1009 nspname = get_namespace_name(operform->oprnamespace);
1010 namelist = list_make2(makeString(nspname),
1011 makeString(oprname));
1012 index->excludeOpNames = lappend(index->excludeOpNames,
1014 ReleaseSysCache(opertup);
1018 ReleaseSysCache(ht_constr);
1021 index->isconstraint = false;
1024 index->isconstraint = false;
1026 /* Get the index expressions, if any */
1027 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1028 Anum_pg_index_indexprs, &isnull);
1033 exprsString = TextDatumGetCString(datum);
1034 indexprs = (List *) stringToNode(exprsString);
1039 /* Build the list of IndexElem */
1040 index->indexParams = NIL;
1042 indexpr_item = list_head(indexprs);
1043 for (keyno = 0; keyno < idxrec->indnatts; keyno++)
1046 AttrNumber attnum = idxrec->indkey.values[keyno];
1047 int16 opt = source_idx->rd_indoption[keyno];
1049 iparam = makeNode(IndexElem);
1051 if (AttributeNumberIsValid(attnum))
1053 /* Simple index column */
1056 attname = get_relid_attribute_name(indrelid, attnum);
1057 keycoltype = get_atttype(indrelid, attnum);
1059 iparam->name = attname;
1060 iparam->expr = NULL;
1064 /* Expressional index */
1067 if (indexpr_item == NULL)
1068 elog(ERROR, "too few entries in indexprs list");
1069 indexkey = (Node *) lfirst(indexpr_item);
1070 indexpr_item = lnext(indexpr_item);
1072 /* OK to modify indexkey since we are working on a private copy */
1073 change_varattnos_of_a_node(indexkey, attmap);
1075 iparam->name = NULL;
1076 iparam->expr = indexkey;
1078 keycoltype = exprType(indexkey);
1081 /* Copy the original index column name */
1082 iparam->indexcolname = pstrdup(NameStr(attrs[keyno]->attname));
1084 /* Add the operator class name, if non-default */
1085 iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1087 iparam->ordering = SORTBY_DEFAULT;
1088 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1090 /* Adjust options if necessary */
1091 if (amrec->amcanorder)
1094 * If it supports sort ordering, copy DESC and NULLS opts. Don't
1095 * set non-default settings unnecessarily, though, so as to
1096 * improve the chance of recognizing equivalence to constraint
1099 if (opt & INDOPTION_DESC)
1101 iparam->ordering = SORTBY_DESC;
1102 if ((opt & INDOPTION_NULLS_FIRST) == 0)
1103 iparam->nulls_ordering = SORTBY_NULLS_LAST;
1107 if (opt & INDOPTION_NULLS_FIRST)
1108 iparam->nulls_ordering = SORTBY_NULLS_FIRST;
1112 index->indexParams = lappend(index->indexParams, iparam);
1115 /* Copy reloptions if any */
1116 datum = SysCacheGetAttr(RELOID, ht_idxrel,
1117 Anum_pg_class_reloptions, &isnull);
1119 index->options = untransformRelOptions(datum);
1121 /* If it's a partial index, decompile and append the predicate */
1122 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1123 Anum_pg_index_indpred, &isnull);
1128 /* Convert text string to node tree */
1129 pred_str = TextDatumGetCString(datum);
1130 index->whereClause = (Node *) stringToNode(pred_str);
1131 /* Adjust attribute numbers */
1132 change_varattnos_of_a_node(index->whereClause, attmap);
1136 ReleaseSysCache(ht_idxrel);
1142 * get_opclass - fetch name of an index operator class
1144 * If the opclass is the default for the given actual_datatype, then
1145 * the return value is NIL.
1148 get_opclass(Oid opclass, Oid actual_datatype)
1151 Form_pg_opclass opc_rec;
1154 ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1155 if (!HeapTupleIsValid(ht_opc))
1156 elog(ERROR, "cache lookup failed for opclass %u", opclass);
1157 opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
1159 if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
1161 /* For simplicity, we always schema-qualify the name */
1162 char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
1163 char *opc_name = pstrdup(NameStr(opc_rec->opcname));
1165 result = list_make2(makeString(nsp_name), makeString(opc_name));
1168 ReleaseSysCache(ht_opc);
1174 * transformIndexConstraints
1175 * Handle UNIQUE, PRIMARY KEY, EXCLUDE constraints, which create indexes.
1176 * We also merge in any index definitions arising from
1177 * LIKE ... INCLUDING INDEXES.
1180 transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
1183 List *indexlist = NIL;
1187 * Run through the constraints that need to generate an index. For PRIMARY
1188 * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
1189 * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
1192 foreach(lc, cxt->ixconstraints)
1194 Constraint *constraint = (Constraint *) lfirst(lc);
1196 Assert(IsA(constraint, Constraint));
1197 Assert(constraint->contype == CONSTR_PRIMARY ||
1198 constraint->contype == CONSTR_UNIQUE ||
1199 constraint->contype == CONSTR_EXCLUSION);
1201 index = transformIndexConstraint(constraint, cxt);
1203 indexlist = lappend(indexlist, index);
1206 /* Add in any indexes defined by LIKE ... INCLUDING INDEXES */
1207 foreach(lc, cxt->inh_indexes)
1209 index = (IndexStmt *) lfirst(lc);
1213 if (cxt->pkey != NULL)
1215 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1216 errmsg("multiple primary keys for table \"%s\" are not allowed",
1217 cxt->relation->relname)));
1221 indexlist = lappend(indexlist, index);
1225 * Scan the index list and remove any redundant index specifications. This
1226 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1227 * strict reading of SQL92 would suggest raising an error instead, but
1228 * that strikes me as too anal-retentive. - tgl 2001-02-14
1230 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1231 * pre-existing indexes, too.
1233 Assert(cxt->alist == NIL);
1234 if (cxt->pkey != NULL)
1236 /* Make sure we keep the PKEY index in preference to others... */
1237 cxt->alist = list_make1(cxt->pkey);
1240 foreach(lc, indexlist)
1247 /* if it's pkey, it's already in cxt->alist */
1248 if (index == cxt->pkey)
1251 foreach(k, cxt->alist)
1253 IndexStmt *priorindex = lfirst(k);
1255 if (equal(index->indexParams, priorindex->indexParams) &&
1256 equal(index->whereClause, priorindex->whereClause) &&
1257 equal(index->excludeOpNames, priorindex->excludeOpNames) &&
1258 strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
1259 index->deferrable == priorindex->deferrable &&
1260 index->initdeferred == priorindex->initdeferred)
1262 priorindex->unique |= index->unique;
1265 * If the prior index is as yet unnamed, and this one is
1266 * named, then transfer the name to the prior index. This
1267 * ensures that if we have named and unnamed constraints,
1268 * we'll use (at least one of) the names for the index.
1270 if (priorindex->idxname == NULL)
1271 priorindex->idxname = index->idxname;
1278 cxt->alist = lappend(cxt->alist, index);
1283 * transformIndexConstraint
1284 * Transform one UNIQUE, PRIMARY KEY, or EXCLUDE constraint for
1285 * transformIndexConstraints.
1288 transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
1293 index = makeNode(IndexStmt);
1295 index->unique = (constraint->contype != CONSTR_EXCLUSION);
1296 index->primary = (constraint->contype == CONSTR_PRIMARY);
1299 if (cxt->pkey != NULL)
1301 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1302 errmsg("multiple primary keys for table \"%s\" are not allowed",
1303 cxt->relation->relname)));
1307 * In ALTER TABLE case, a primary index might already exist, but
1308 * DefineIndex will check for it.
1311 index->isconstraint = true;
1312 index->deferrable = constraint->deferrable;
1313 index->initdeferred = constraint->initdeferred;
1315 if (constraint->conname != NULL)
1316 index->idxname = pstrdup(constraint->conname);
1318 index->idxname = NULL; /* DefineIndex will choose name */
1320 index->relation = cxt->relation;
1321 index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
1322 index->options = constraint->options;
1323 index->tableSpace = constraint->indexspace;
1324 index->whereClause = constraint->where_clause;
1325 index->indexParams = NIL;
1326 index->excludeOpNames = NIL;
1327 index->concurrent = false;
1330 * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
1331 * IndexElems and operator names. We have to break that apart into
1334 if (constraint->contype == CONSTR_EXCLUSION)
1336 foreach(lc, constraint->exclusions)
1338 List *pair = (List *) lfirst(lc);
1342 Assert(list_length(pair) == 2);
1343 elem = (IndexElem *) linitial(pair);
1344 Assert(IsA(elem, IndexElem));
1345 opname = (List *) lsecond(pair);
1346 Assert(IsA(opname, List));
1348 index->indexParams = lappend(index->indexParams, elem);
1349 index->excludeOpNames = lappend(index->excludeOpNames, opname);
1356 * For UNIQUE and PRIMARY KEY, we just have a list of column names.
1358 * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
1359 * also make sure they are NOT NULL, if possible. (Although we could leave
1360 * it to DefineIndex to mark the columns NOT NULL, it's more efficient to
1361 * get it right the first time.)
1363 foreach(lc, constraint->keys)
1365 char *key = strVal(lfirst(lc));
1367 ColumnDef *column = NULL;
1371 foreach(columns, cxt->columns)
1373 column = (ColumnDef *) lfirst(columns);
1374 Assert(IsA(column, ColumnDef));
1375 if (strcmp(column->colname, key) == 0)
1383 /* found column in the new table; force it to be NOT NULL */
1384 if (constraint->contype == CONSTR_PRIMARY)
1385 column->is_not_null = TRUE;
1387 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1390 * column will be a system column in the new table, so accept it.
1391 * System columns can't ever be null, so no need to worry about
1392 * PRIMARY/NOT NULL constraint.
1396 else if (cxt->inhRelations)
1398 /* try inherited tables */
1401 foreach(inher, cxt->inhRelations)
1403 RangeVar *inh = (RangeVar *) lfirst(inher);
1407 Assert(IsA(inh, RangeVar));
1408 rel = heap_openrv(inh, AccessShareLock);
1409 if (rel->rd_rel->relkind != RELKIND_RELATION)
1411 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1412 errmsg("inherited relation \"%s\" is not a table",
1414 for (count = 0; count < rel->rd_att->natts; count++)
1416 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1417 char *inhname = NameStr(inhattr->attname);
1419 if (inhattr->attisdropped)
1421 if (strcmp(key, inhname) == 0)
1426 * We currently have no easy way to force an inherited
1427 * column to be NOT NULL at creation, if its parent
1428 * wasn't so already. We leave it to DefineIndex to
1429 * fix things up in this case.
1434 heap_close(rel, NoLock);
1441 * In the ALTER TABLE case, don't complain about index keys not
1442 * created in the command; they may well exist already. DefineIndex
1443 * will complain about them if not, and will also take care of marking
1446 if (!found && !cxt->isalter)
1448 (errcode(ERRCODE_UNDEFINED_COLUMN),
1449 errmsg("column \"%s\" named in key does not exist",
1452 /* Check for PRIMARY KEY(foo, foo) */
1453 foreach(columns, index->indexParams)
1455 iparam = (IndexElem *) lfirst(columns);
1456 if (iparam->name && strcmp(key, iparam->name) == 0)
1460 (errcode(ERRCODE_DUPLICATE_COLUMN),
1461 errmsg("column \"%s\" appears twice in primary key constraint",
1465 (errcode(ERRCODE_DUPLICATE_COLUMN),
1466 errmsg("column \"%s\" appears twice in unique constraint",
1471 /* OK, add it to the index definition */
1472 iparam = makeNode(IndexElem);
1473 iparam->name = pstrdup(key);
1474 iparam->expr = NULL;
1475 iparam->indexcolname = NULL;
1476 iparam->opclass = NIL;
1477 iparam->ordering = SORTBY_DEFAULT;
1478 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1479 index->indexParams = lappend(index->indexParams, iparam);
1486 * transformFKConstraints
1487 * handle FOREIGN KEY constraints
1490 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1491 bool skipValidation, bool isAddConstraint)
1495 if (cxt->fkconstraints == NIL)
1499 * If CREATE TABLE or adding a column with NULL default, we can safely
1500 * skip validation of the constraint.
1504 foreach(fkclist, cxt->fkconstraints)
1506 Constraint *constraint = (Constraint *) lfirst(fkclist);
1508 constraint->skip_validation = true;
1513 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1514 * CONSTRAINT command to execute after the basic command is complete. (If
1515 * called from ADD CONSTRAINT, that routine will add the FK constraints to
1516 * its own subcommand list.)
1518 * Note: the ADD CONSTRAINT command must also execute after any index
1519 * creation commands. Thus, this should run after
1520 * transformIndexConstraints, so that the CREATE INDEX commands are
1521 * already in cxt->alist.
1523 if (!isAddConstraint)
1525 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1527 alterstmt->relation = cxt->relation;
1528 alterstmt->cmds = NIL;
1529 alterstmt->relkind = OBJECT_TABLE;
1531 foreach(fkclist, cxt->fkconstraints)
1533 Constraint *constraint = (Constraint *) lfirst(fkclist);
1534 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1536 altercmd->subtype = AT_ProcessedConstraint;
1537 altercmd->name = NULL;
1538 altercmd->def = (Node *) constraint;
1539 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1542 cxt->alist = lappend(cxt->alist, alterstmt);
1547 * transformIndexStmt - parse analysis for CREATE INDEX and ALTER TABLE
1549 * Note: this is a no-op for an index not using either index expressions or
1550 * a predicate expression. There are several code paths that create indexes
1551 * without bothering to call this, because they know they don't have any
1552 * such expressions to deal with.
1555 transformIndexStmt(IndexStmt *stmt, const char *queryString)
1563 * We must not scribble on the passed-in IndexStmt, so copy it. (This is
1564 * overkill, but easy.)
1566 stmt = (IndexStmt *) copyObject(stmt);
1569 * Open the parent table with appropriate locking. We must do this
1570 * because addRangeTableEntry() would acquire only AccessShareLock,
1571 * leaving DefineIndex() needing to do a lock upgrade with consequent risk
1572 * of deadlock. Make sure this stays in sync with the type of lock
1573 * DefineIndex() wants. If we are being called by ALTER TABLE, we will
1574 * already hold a higher lock.
1576 rel = heap_openrv(stmt->relation,
1577 (stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock));
1580 pstate = make_parsestate(NULL);
1581 pstate->p_sourcetext = queryString;
1584 * Put the parent table into the rtable so that the expressions can refer
1585 * to its fields without qualification.
1587 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1589 /* no to join list, yes to namespaces */
1590 addRTEtoQuery(pstate, rte, false, true, true);
1592 /* take care of the where clause */
1593 if (stmt->whereClause)
1594 stmt->whereClause = transformWhereClause(pstate,
1598 /* take care of any index expressions */
1599 foreach(l, stmt->indexParams)
1601 IndexElem *ielem = (IndexElem *) lfirst(l);
1605 /* Extract preliminary index col name before transforming expr */
1606 if (ielem->indexcolname == NULL)
1607 ielem->indexcolname = FigureIndexColname(ielem->expr);
1609 /* Now do parse transformation of the expression */
1610 ielem->expr = transformExpr(pstate, ielem->expr);
1613 * We check only that the result type is legitimate; this is for
1614 * consistency with what transformWhereClause() checks for the
1615 * predicate. DefineIndex() will make more checks.
1617 if (expression_returns_set(ielem->expr))
1619 (errcode(ERRCODE_DATATYPE_MISMATCH),
1620 errmsg("index expression cannot return a set")));
1625 * Check that only the base rel is mentioned.
1627 if (list_length(pstate->p_rtable) != 1)
1629 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1630 errmsg("index expressions and predicates can refer only to the table being indexed")));
1632 free_parsestate(pstate);
1634 /* Close relation, but keep the lock */
1635 heap_close(rel, NoLock);
1642 * transformRuleStmt -
1643 * transform a CREATE RULE Statement. The action is a list of parse
1644 * trees which is transformed into a list of query trees, and we also
1645 * transform the WHERE clause if any.
1647 * actions and whereClause are output parameters that receive the
1648 * transformed results.
1650 * Note that we must not scribble on the passed-in RuleStmt, so we do
1651 * copyObject() on the actions and WHERE clause.
1654 transformRuleStmt(RuleStmt *stmt, const char *queryString,
1655 List **actions, Node **whereClause)
1659 RangeTblEntry *oldrte;
1660 RangeTblEntry *newrte;
1663 * To avoid deadlock, make sure the first thing we do is grab
1664 * AccessExclusiveLock on the target relation. This will be needed by
1665 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1668 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1671 pstate = make_parsestate(NULL);
1672 pstate->p_sourcetext = queryString;
1675 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1676 * Set up their RTEs in the main pstate for use in parsing the rule
1679 oldrte = addRangeTableEntryForRelation(pstate, rel,
1680 makeAlias("old", NIL),
1682 newrte = addRangeTableEntryForRelation(pstate, rel,
1683 makeAlias("new", NIL),
1685 /* Must override addRangeTableEntry's default access-check flags */
1686 oldrte->requiredPerms = 0;
1687 newrte->requiredPerms = 0;
1690 * They must be in the namespace too for lookup purposes, but only add the
1691 * one(s) that are relevant for the current kind of rule. In an UPDATE
1692 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1693 * there's no need to be so picky for INSERT & DELETE. We do not add them
1696 switch (stmt->event)
1699 addRTEtoQuery(pstate, oldrte, false, true, true);
1702 addRTEtoQuery(pstate, oldrte, false, true, true);
1703 addRTEtoQuery(pstate, newrte, false, true, true);
1706 addRTEtoQuery(pstate, newrte, false, true, true);
1709 addRTEtoQuery(pstate, oldrte, false, true, true);
1712 elog(ERROR, "unrecognized event type: %d",
1717 /* take care of the where clause */
1718 *whereClause = transformWhereClause(pstate,
1719 (Node *) copyObject(stmt->whereClause),
1722 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
1724 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1725 errmsg("rule WHERE condition cannot contain references to other relations")));
1727 /* aggregates not allowed (but subselects are okay) */
1728 if (pstate->p_hasAggs)
1730 (errcode(ERRCODE_GROUPING_ERROR),
1731 errmsg("cannot use aggregate function in rule WHERE condition")));
1732 if (pstate->p_hasWindowFuncs)
1734 (errcode(ERRCODE_WINDOWING_ERROR),
1735 errmsg("cannot use window function in rule WHERE condition")));
1738 * 'instead nothing' rules with a qualification need a query rangetable so
1739 * the rewrite handler can add the negated rule qualification to the
1740 * original query. We create a query with the new command type CMD_NOTHING
1741 * here that is treated specially by the rewrite system.
1743 if (stmt->actions == NIL)
1745 Query *nothing_qry = makeNode(Query);
1747 nothing_qry->commandType = CMD_NOTHING;
1748 nothing_qry->rtable = pstate->p_rtable;
1749 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1751 *actions = list_make1(nothing_qry);
1756 List *newactions = NIL;
1759 * transform each statement, like parse_sub_analyze()
1761 foreach(l, stmt->actions)
1763 Node *action = (Node *) lfirst(l);
1764 ParseState *sub_pstate = make_parsestate(NULL);
1771 * Since outer ParseState isn't parent of inner, have to pass down
1772 * the query text by hand.
1774 sub_pstate->p_sourcetext = queryString;
1777 * Set up OLD/NEW in the rtable for this statement. The entries
1778 * are added only to relnamespace, not varnamespace, because we
1779 * don't want them to be referred to by unqualified field names
1780 * nor "*" in the rule actions. We decide later whether to put
1781 * them in the joinlist.
1783 oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
1784 makeAlias("old", NIL),
1786 newrte = addRangeTableEntryForRelation(sub_pstate, rel,
1787 makeAlias("new", NIL),
1789 oldrte->requiredPerms = 0;
1790 newrte->requiredPerms = 0;
1791 addRTEtoQuery(sub_pstate, oldrte, false, true, false);
1792 addRTEtoQuery(sub_pstate, newrte, false, true, false);
1794 /* Transform the rule action statement */
1795 top_subqry = transformStmt(sub_pstate,
1796 (Node *) copyObject(action));
1799 * We cannot support utility-statement actions (eg NOTIFY) with
1800 * nonempty rule WHERE conditions, because there's no way to make
1801 * the utility action execute conditionally.
1803 if (top_subqry->commandType == CMD_UTILITY &&
1804 *whereClause != NULL)
1806 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1807 errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
1810 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
1811 * into the SELECT, and that's what we need to look at. (Ugly
1812 * kluge ... try to fix this when we redesign querytrees.)
1814 sub_qry = getInsertSelectQuery(top_subqry, NULL);
1817 * If the sub_qry is a setop, we cannot attach any qualifications
1818 * to it, because the planner won't notice them. This could
1819 * perhaps be relaxed someday, but for now, we may as well reject
1820 * such a rule immediately.
1822 if (sub_qry->setOperations != NULL && *whereClause != NULL)
1824 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1825 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1828 * Validate action's use of OLD/NEW, qual too
1831 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1832 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
1834 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1835 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
1837 switch (stmt->event)
1842 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1843 errmsg("ON SELECT rule cannot use OLD")));
1846 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1847 errmsg("ON SELECT rule cannot use NEW")));
1855 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1856 errmsg("ON INSERT rule cannot use OLD")));
1861 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1862 errmsg("ON DELETE rule cannot use NEW")));
1865 elog(ERROR, "unrecognized event type: %d",
1871 * For efficiency's sake, add OLD to the rule action's jointree
1872 * only if it was actually referenced in the statement or qual.
1874 * For INSERT, NEW is not really a relation (only a reference to
1875 * the to-be-inserted tuple) and should never be added to the
1878 * For UPDATE, we treat NEW as being another kind of reference to
1879 * OLD, because it represents references to *transformed* tuples
1880 * of the existing relation. It would be wrong to enter NEW
1881 * separately in the jointree, since that would cause a double
1882 * join of the updated relation. It's also wrong to fail to make
1883 * a jointree entry if only NEW and not OLD is mentioned.
1885 if (has_old || (has_new && stmt->event == CMD_UPDATE))
1888 * If sub_qry is a setop, manipulating its jointree will do no
1889 * good at all, because the jointree is dummy. (This should be
1890 * a can't-happen case because of prior tests.)
1892 if (sub_qry->setOperations != NULL)
1894 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1895 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1896 /* hack so we can use addRTEtoQuery() */
1897 sub_pstate->p_rtable = sub_qry->rtable;
1898 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
1899 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
1900 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
1903 newactions = lappend(newactions, top_subqry);
1905 free_parsestate(sub_pstate);
1908 *actions = newactions;
1911 free_parsestate(pstate);
1913 /* Close relation, but keep the exclusive lock */
1914 heap_close(rel, NoLock);
1919 * transformAlterTableStmt -
1920 * parse analysis for ALTER TABLE
1922 * Returns a List of utility commands to be done in sequence. One of these
1923 * will be the transformed AlterTableStmt, but there may be additional actions
1924 * to be done before and after the actual AlterTable() call.
1927 transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
1931 CreateStmtContext cxt;
1936 List *newcmds = NIL;
1937 bool skipValidation = true;
1938 AlterTableCmd *newcmd;
1942 * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
1943 * is overkill, but easy.)
1945 stmt = (AlterTableStmt *) copyObject(stmt);
1948 * Assign the appropriate lock level for this list of subcommands.
1950 lockmode = AlterTableGetLockLevel(stmt->cmds);
1953 * Acquire appropriate lock on the target relation, which will be held until
1954 * end of transaction. This ensures any decisions we make here based on
1955 * the state of the relation will still be good at execution. We must get
1956 * lock now because execution will later require it; taking a lower grade lock
1957 * now and trying to upgrade later risks deadlock. Any new commands we add
1958 * after this must not upgrade the lock level requested here.
1960 rel = relation_openrv(stmt->relation, lockmode);
1963 pstate = make_parsestate(NULL);
1964 pstate->p_sourcetext = queryString;
1966 cxt.stmtType = "ALTER TABLE";
1967 cxt.relation = stmt->relation;
1969 cxt.inhRelations = NIL;
1971 cxt.hasoids = false; /* need not be right */
1973 cxt.ckconstraints = NIL;
1974 cxt.fkconstraints = NIL;
1975 cxt.ixconstraints = NIL;
1976 cxt.inh_indexes = NIL;
1982 * The only subtypes that currently require parse transformation handling
1983 * are ADD COLUMN and ADD CONSTRAINT. These largely re-use code from
1986 foreach(lcmd, stmt->cmds)
1988 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
1990 switch (cmd->subtype)
1993 case AT_AddColumnToView:
1995 ColumnDef *def = (ColumnDef *) cmd->def;
1997 Assert(IsA(def, ColumnDef));
1998 transformColumnDefinition(pstate, &cxt, def);
2001 * If the column has a non-null default, we can't skip
2002 * validation of foreign keys.
2004 if (def->raw_default != NULL)
2005 skipValidation = false;
2008 * All constraints are processed in other ways. Remove the
2011 def->constraints = NIL;
2013 newcmds = lappend(newcmds, cmd);
2016 case AT_AddConstraint:
2019 * The original AddConstraint cmd node doesn't go to newcmds
2021 if (IsA(cmd->def, Constraint))
2023 transformTableConstraint(pstate, &cxt,
2024 (Constraint *) cmd->def);
2025 if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
2026 skipValidation = false;
2029 elog(ERROR, "unrecognized node type: %d",
2030 (int) nodeTag(cmd->def));
2033 case AT_ProcessedConstraint:
2036 * Already-transformed ADD CONSTRAINT, so just make it look
2037 * like the standard case.
2039 cmd->subtype = AT_AddConstraint;
2040 newcmds = lappend(newcmds, cmd);
2044 newcmds = lappend(newcmds, cmd);
2050 * transformIndexConstraints wants cxt.alist to contain only index
2051 * statements, so transfer anything we already have into save_alist
2054 save_alist = cxt.alist;
2057 /* Postprocess index and FK constraints */
2058 transformIndexConstraints(pstate, &cxt);
2060 transformFKConstraints(pstate, &cxt, skipValidation, true);
2063 * Push any index-creation commands into the ALTER, so that they can be
2064 * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
2065 * the IndexStmt attached to an AT_AddIndex subcommand has already been
2066 * through transformIndexStmt.
2068 foreach(l, cxt.alist)
2070 Node *idxstmt = (Node *) lfirst(l);
2072 Assert(IsA(idxstmt, IndexStmt));
2073 newcmd = makeNode(AlterTableCmd);
2074 newcmd->subtype = AT_AddIndex;
2075 newcmd->def = (Node *) transformIndexStmt((IndexStmt *) idxstmt,
2077 newcmds = lappend(newcmds, newcmd);
2081 /* Append any CHECK or FK constraints to the commands list */
2082 foreach(l, cxt.ckconstraints)
2084 newcmd = makeNode(AlterTableCmd);
2085 newcmd->subtype = AT_AddConstraint;
2086 newcmd->def = (Node *) lfirst(l);
2087 newcmds = lappend(newcmds, newcmd);
2089 foreach(l, cxt.fkconstraints)
2091 newcmd = makeNode(AlterTableCmd);
2092 newcmd->subtype = AT_AddConstraint;
2093 newcmd->def = (Node *) lfirst(l);
2094 newcmds = lappend(newcmds, newcmd);
2097 /* Close rel but keep lock */
2098 relation_close(rel, NoLock);
2103 stmt->cmds = newcmds;
2105 result = lappend(cxt.blist, stmt);
2106 result = list_concat(result, cxt.alist);
2107 result = list_concat(result, save_alist);
2114 * Preprocess a list of column constraint clauses
2115 * to attach constraint attributes to their primary constraint nodes
2116 * and detect inconsistent/misplaced constraint attributes.
2118 * NOTE: currently, attributes are only supported for FOREIGN KEY, UNIQUE,
2119 * and PRIMARY KEY constraints, but someday they ought to be supported
2120 * for other constraint types.
2123 transformConstraintAttrs(ParseState *pstate, List *constraintList)
2125 Constraint *lastprimarycon = NULL;
2126 bool saw_deferrability = false;
2127 bool saw_initially = false;
2130 #define SUPPORTS_ATTRS(node) \
2131 ((node) != NULL && \
2132 ((node)->contype == CONSTR_PRIMARY || \
2133 (node)->contype == CONSTR_UNIQUE || \
2134 (node)->contype == CONSTR_EXCLUSION || \
2135 (node)->contype == CONSTR_FOREIGN))
2137 foreach(clist, constraintList)
2139 Constraint *con = (Constraint *) lfirst(clist);
2141 if (!IsA(con, Constraint))
2142 elog(ERROR, "unrecognized node type: %d",
2143 (int) nodeTag(con));
2144 switch (con->contype)
2146 case CONSTR_ATTR_DEFERRABLE:
2147 if (!SUPPORTS_ATTRS(lastprimarycon))
2149 (errcode(ERRCODE_SYNTAX_ERROR),
2150 errmsg("misplaced 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 = true;
2161 case CONSTR_ATTR_NOT_DEFERRABLE:
2162 if (!SUPPORTS_ATTRS(lastprimarycon))
2164 (errcode(ERRCODE_SYNTAX_ERROR),
2165 errmsg("misplaced NOT DEFERRABLE clause"),
2166 parser_errposition(pstate, con->location)));
2167 if (saw_deferrability)
2169 (errcode(ERRCODE_SYNTAX_ERROR),
2170 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2171 parser_errposition(pstate, con->location)));
2172 saw_deferrability = true;
2173 lastprimarycon->deferrable = false;
2174 if (saw_initially &&
2175 lastprimarycon->initdeferred)
2177 (errcode(ERRCODE_SYNTAX_ERROR),
2178 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2179 parser_errposition(pstate, con->location)));
2182 case CONSTR_ATTR_DEFERRED:
2183 if (!SUPPORTS_ATTRS(lastprimarycon))
2185 (errcode(ERRCODE_SYNTAX_ERROR),
2186 errmsg("misplaced INITIALLY DEFERRED clause"),
2187 parser_errposition(pstate, con->location)));
2190 (errcode(ERRCODE_SYNTAX_ERROR),
2191 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2192 parser_errposition(pstate, con->location)));
2193 saw_initially = true;
2194 lastprimarycon->initdeferred = true;
2197 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
2199 if (!saw_deferrability)
2200 lastprimarycon->deferrable = true;
2201 else if (!lastprimarycon->deferrable)
2203 (errcode(ERRCODE_SYNTAX_ERROR),
2204 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2205 parser_errposition(pstate, con->location)));
2208 case CONSTR_ATTR_IMMEDIATE:
2209 if (!SUPPORTS_ATTRS(lastprimarycon))
2211 (errcode(ERRCODE_SYNTAX_ERROR),
2212 errmsg("misplaced INITIALLY IMMEDIATE clause"),
2213 parser_errposition(pstate, con->location)));
2216 (errcode(ERRCODE_SYNTAX_ERROR),
2217 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2218 parser_errposition(pstate, con->location)));
2219 saw_initially = true;
2220 lastprimarycon->initdeferred = false;
2224 /* Otherwise it's not an attribute */
2225 lastprimarycon = con;
2226 /* reset flags for new primary node */
2227 saw_deferrability = false;
2228 saw_initially = false;
2235 * Special handling of type definition for a column
2238 transformColumnType(ParseState *pstate, ColumnDef *column)
2241 * All we really need to do here is verify that the type is valid.
2243 Type ctype = typenameType(pstate, column->typeName, NULL);
2245 ReleaseSysCache(ctype);
2250 * transformCreateSchemaStmt -
2251 * analyzes the CREATE SCHEMA statement
2253 * Split the schema element list into individual commands and place
2254 * them in the result list in an order such that there are no forward
2255 * references (e.g. GRANT to a table created later in the list). Note
2256 * that the logic we use for determining forward references is
2257 * presently quite incomplete.
2259 * SQL92 also allows constraints to make forward references, so thumb through
2260 * the table columns and move forward references to a posterior alter-table
2263 * The result is a list of parse nodes that still need to be analyzed ---
2264 * but we can't analyze the later commands until we've executed the earlier
2265 * ones, because of possible inter-object references.
2267 * Note: this breaks the rules a little bit by modifying schema-name fields
2268 * within passed-in structs. However, the transformation would be the same
2269 * if done over, so it should be all right to scribble on the input to this
2273 transformCreateSchemaStmt(CreateSchemaStmt *stmt)
2275 CreateSchemaStmtContext cxt;
2279 cxt.stmtType = "CREATE SCHEMA";
2280 cxt.schemaname = stmt->schemaname;
2281 cxt.authid = stmt->authid;
2282 cxt.sequences = NIL;
2290 * Run through each schema element in the schema element list. Separate
2291 * statements by type, and do preliminary analysis.
2293 foreach(elements, stmt->schemaElts)
2295 Node *element = lfirst(elements);
2297 switch (nodeTag(element))
2299 case T_CreateSeqStmt:
2301 CreateSeqStmt *elp = (CreateSeqStmt *) element;
2303 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
2304 cxt.sequences = lappend(cxt.sequences, element);
2310 CreateStmt *elp = (CreateStmt *) element;
2312 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2315 * XXX todo: deal with constraints
2317 cxt.tables = lappend(cxt.tables, element);
2323 ViewStmt *elp = (ViewStmt *) element;
2325 setSchemaName(cxt.schemaname, &elp->view->schemaname);
2328 * XXX todo: deal with references between views
2330 cxt.views = lappend(cxt.views, element);
2336 IndexStmt *elp = (IndexStmt *) element;
2338 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2339 cxt.indexes = lappend(cxt.indexes, element);
2343 case T_CreateTrigStmt:
2345 CreateTrigStmt *elp = (CreateTrigStmt *) element;
2347 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2348 cxt.triggers = lappend(cxt.triggers, element);
2353 cxt.grants = lappend(cxt.grants, element);
2357 elog(ERROR, "unrecognized node type: %d",
2358 (int) nodeTag(element));
2363 result = list_concat(result, cxt.sequences);
2364 result = list_concat(result, cxt.tables);
2365 result = list_concat(result, cxt.views);
2366 result = list_concat(result, cxt.indexes);
2367 result = list_concat(result, cxt.triggers);
2368 result = list_concat(result, cxt.grants);
2375 * Set or check schema name in an element of a CREATE SCHEMA command
2378 setSchemaName(char *context_schema, char **stmt_schema_name)
2380 if (*stmt_schema_name == NULL)
2381 *stmt_schema_name = context_schema;
2382 else if (strcmp(context_schema, *stmt_schema_name) != 0)
2384 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
2385 errmsg("CREATE specifies a schema (%s) "
2386 "different from the one being created (%s)",
2387 *stmt_schema_name, context_schema)));