1 /*-------------------------------------------------------------------------
4 * Commands for creating and altering table structures and settings
6 * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/commands/tablecmds.c,v 1.230 2007/07/17 05:02:00 neilc Exp $
13 *-------------------------------------------------------------------------
17 #include "access/genam.h"
18 #include "access/heapam.h"
19 #include "access/reloptions.h"
20 #include "access/xact.h"
21 #include "catalog/catalog.h"
22 #include "catalog/dependency.h"
23 #include "catalog/heap.h"
24 #include "catalog/index.h"
25 #include "catalog/indexing.h"
26 #include "catalog/namespace.h"
27 #include "catalog/pg_constraint.h"
28 #include "catalog/pg_depend.h"
29 #include "catalog/pg_inherits.h"
30 #include "catalog/pg_namespace.h"
31 #include "catalog/pg_opclass.h"
32 #include "catalog/pg_trigger.h"
33 #include "catalog/pg_type.h"
34 #include "catalog/toasting.h"
35 #include "commands/cluster.h"
36 #include "commands/defrem.h"
37 #include "commands/tablecmds.h"
38 #include "commands/tablespace.h"
39 #include "commands/trigger.h"
40 #include "commands/typecmds.h"
41 #include "executor/executor.h"
42 #include "miscadmin.h"
43 #include "nodes/makefuncs.h"
44 #include "nodes/parsenodes.h"
45 #include "optimizer/clauses.h"
46 #include "optimizer/plancat.h"
47 #include "optimizer/prep.h"
48 #include "parser/gramparse.h"
49 #include "parser/parse_clause.h"
50 #include "parser/parse_coerce.h"
51 #include "parser/parse_expr.h"
52 #include "parser/parse_oper.h"
53 #include "parser/parse_relation.h"
54 #include "parser/parse_type.h"
55 #include "parser/parse_utilcmd.h"
56 #include "parser/parser.h"
57 #include "rewrite/rewriteDefine.h"
58 #include "rewrite/rewriteHandler.h"
59 #include "storage/smgr.h"
60 #include "utils/acl.h"
61 #include "utils/builtins.h"
62 #include "utils/fmgroids.h"
63 #include "utils/inval.h"
64 #include "utils/lsyscache.h"
65 #include "utils/memutils.h"
66 #include "utils/relcache.h"
67 #include "utils/syscache.h"
71 * ON COMMIT action list
73 typedef struct OnCommitItem
75 Oid relid; /* relid of relation */
76 OnCommitAction oncommit; /* what to do at end of xact */
79 * If this entry was created during the current transaction,
80 * creating_subid is the ID of the creating subxact; if created in a prior
81 * transaction, creating_subid is zero. If deleted during the current
82 * transaction, deleting_subid is the ID of the deleting subxact; if no
83 * deletion request is pending, deleting_subid is zero.
85 SubTransactionId creating_subid;
86 SubTransactionId deleting_subid;
89 static List *on_commits = NIL;
93 * State information for ALTER TABLE
95 * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
96 * structs, one for each table modified by the operation (the named table
97 * plus any child tables that are affected). We save lists of subcommands
98 * to apply to this table (possibly modified by parse transformation steps);
99 * these lists will be executed in Phase 2. If a Phase 3 step is needed,
100 * necessary information is stored in the constraints and newvals lists.
102 * Phase 2 is divided into multiple passes; subcommands are executed in
103 * a pass determined by subcommand type.
106 #define AT_PASS_DROP 0 /* DROP (all flavors) */
107 #define AT_PASS_ALTER_TYPE 1 /* ALTER COLUMN TYPE */
108 #define AT_PASS_OLD_INDEX 2 /* re-add existing indexes */
109 #define AT_PASS_OLD_CONSTR 3 /* re-add existing constraints */
110 #define AT_PASS_COL_ATTRS 4 /* set other column attributes */
111 /* We could support a RENAME COLUMN pass here, but not currently used */
112 #define AT_PASS_ADD_COL 5 /* ADD COLUMN */
113 #define AT_PASS_ADD_INDEX 6 /* ADD indexes */
114 #define AT_PASS_ADD_CONSTR 7 /* ADD constraints, defaults */
115 #define AT_PASS_MISC 8 /* other stuff */
116 #define AT_NUM_PASSES 9
118 typedef struct AlteredTableInfo
120 /* Information saved before any work commences: */
121 Oid relid; /* Relation to work on */
122 char relkind; /* Its relkind */
123 TupleDesc oldDesc; /* Pre-modification tuple descriptor */
124 /* Information saved by Phase 1 for Phase 2: */
125 List *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
126 /* Information saved by Phases 1/2 for Phase 3: */
127 List *constraints; /* List of NewConstraint */
128 List *newvals; /* List of NewColumnValue */
129 bool new_notnull; /* T if we added new NOT NULL constraints */
130 Oid newTableSpace; /* new tablespace; 0 means no change */
131 /* Objects to rebuild after completing ALTER TYPE operations */
132 List *changedConstraintOids; /* OIDs of constraints to rebuild */
133 List *changedConstraintDefs; /* string definitions of same */
134 List *changedIndexOids; /* OIDs of indexes to rebuild */
135 List *changedIndexDefs; /* string definitions of same */
138 /* Struct describing one new constraint to check in Phase 3 scan */
139 /* Note: new NOT NULL constraints are handled elsewhere */
140 typedef struct NewConstraint
142 char *name; /* Constraint name, or NULL if none */
143 ConstrType contype; /* CHECK or FOREIGN */
144 Oid refrelid; /* PK rel, if FOREIGN */
145 Oid conid; /* OID of pg_constraint entry, if FOREIGN */
146 Node *qual; /* Check expr or FkConstraint struct */
147 List *qualstate; /* Execution state for CHECK */
151 * Struct describing one new column value that needs to be computed during
152 * Phase 3 copy (this could be either a new column with a non-null default, or
153 * a column that we're changing the type of). Columns without such an entry
154 * are just copied from the old table during ATRewriteTable. Note that the
155 * expr is an expression over *old* table values.
157 typedef struct NewColumnValue
159 AttrNumber attnum; /* which column */
160 Expr *expr; /* expression to compute */
161 ExprState *exprstate; /* execution state */
165 static void truncate_check_rel(Relation rel);
166 static List *MergeAttributes(List *schema, List *supers, bool istemp,
167 List **supOids, List **supconstr, int *supOidCount);
168 static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
169 static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel);
170 static void add_nonduplicate_constraint(Constraint *cdef,
171 ConstrCheck *check, int *ncheck);
172 static bool change_varattnos_walker(Node *node, const AttrNumber *newattno);
173 static void StoreCatalogInheritance(Oid relationId, List *supers);
174 static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
175 int16 seqNumber, Relation inhRelation);
176 static int findAttrByName(const char *attributeName, List *schema);
177 static void setRelhassubclassInRelation(Oid relationId, bool relhassubclass);
178 static void AlterIndexNamespaces(Relation classRel, Relation rel,
179 Oid oldNspOid, Oid newNspOid);
180 static void AlterSeqNamespaces(Relation classRel, Relation rel,
181 Oid oldNspOid, Oid newNspOid,
182 const char *newNspName);
183 static int transformColumnNameList(Oid relId, List *colList,
184 int16 *attnums, Oid *atttypids);
185 static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
187 int16 *attnums, Oid *atttypids,
189 static Oid transformFkeyCheckAttrs(Relation pkrel,
190 int numattrs, int16 *attnums,
192 static void validateForeignKeyConstraint(FkConstraint *fkconstraint,
193 Relation rel, Relation pkrel, Oid constraintOid);
194 static void createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
196 static void ATController(Relation rel, List *cmds, bool recurse);
197 static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
198 bool recurse, bool recursing);
199 static void ATRewriteCatalogs(List **wqueue);
200 static void ATExecCmd(AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd);
201 static void ATRewriteTables(List **wqueue);
202 static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap);
203 static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
204 static void ATSimplePermissions(Relation rel, bool allowView);
205 static void ATSimplePermissionsRelationOrIndex(Relation rel);
206 static void ATSimpleRecursion(List **wqueue, Relation rel,
207 AlterTableCmd *cmd, bool recurse);
208 static void ATOneLevelRecursion(List **wqueue, Relation rel,
210 static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
212 static void ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
214 static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
215 static void ATExecDropNotNull(Relation rel, const char *colName);
216 static void ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
217 const char *colName);
218 static void ATExecColumnDefault(Relation rel, const char *colName,
220 static void ATPrepSetStatistics(Relation rel, const char *colName,
222 static void ATExecSetStatistics(Relation rel, const char *colName,
224 static void ATExecSetStorage(Relation rel, const char *colName,
226 static void ATExecDropColumn(Relation rel, const char *colName,
227 DropBehavior behavior,
228 bool recurse, bool recursing);
229 static void ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
230 IndexStmt *stmt, bool is_rebuild);
231 static void ATExecAddConstraint(AlteredTableInfo *tab, Relation rel,
232 Node *newConstraint);
233 static void ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
234 FkConstraint *fkconstraint);
235 static void ATPrepDropConstraint(List **wqueue, Relation rel,
236 bool recurse, AlterTableCmd *cmd);
237 static void ATExecDropConstraint(Relation rel, const char *constrName,
238 DropBehavior behavior, bool quiet);
239 static void ATPrepAlterColumnType(List **wqueue,
240 AlteredTableInfo *tab, Relation rel,
241 bool recurse, bool recursing,
243 static void ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
244 const char *colName, TypeName *typename);
245 static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab);
246 static void ATPostAlterTypeParse(char *cmd, List **wqueue);
247 static void change_owner_recurse_to_sequences(Oid relationOid,
249 static void ATExecClusterOn(Relation rel, const char *indexName);
250 static void ATExecDropCluster(Relation rel);
251 static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
252 char *tablespacename);
253 static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace);
254 static void ATExecSetRelOptions(Relation rel, List *defList, bool isReset);
255 static void ATExecEnableDisableTrigger(Relation rel, char *trigname,
256 char fires_when, bool skip_system);
257 static void ATExecEnableDisableRule(Relation rel, char *rulename,
259 static void ATExecAddInherit(Relation rel, RangeVar *parent);
260 static void ATExecDropInherit(Relation rel, RangeVar *parent);
261 static void copy_relation_data(Relation rel, SMgrRelation dst);
264 /* ----------------------------------------------------------------
266 * Creates a new relation.
268 * If successful, returns the OID of the new relation.
269 * ----------------------------------------------------------------
272 DefineRelation(CreateStmt *stmt, char relkind)
274 char relname[NAMEDATALEN];
276 List *schema = stmt->tableElts;
280 TupleDesc descriptor;
282 List *old_constraints;
291 * Truncate relname to appropriate length (probably a waste of time, as
292 * parser should have done this already).
294 StrNCpy(relname, stmt->relation->relname, NAMEDATALEN);
297 * Check consistency of arguments
299 if (stmt->oncommit != ONCOMMIT_NOOP && !stmt->relation->istemp)
301 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
302 errmsg("ON COMMIT can only be used on temporary tables")));
305 * Look up the namespace in which we are supposed to create the relation.
306 * Check we have permission to create there. Skip check if bootstrapping,
307 * since permissions machinery may not be working yet.
309 namespaceId = RangeVarGetCreationNamespace(stmt->relation);
311 if (!IsBootstrapProcessingMode())
315 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
317 if (aclresult != ACLCHECK_OK)
318 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
319 get_namespace_name(namespaceId));
323 * Select tablespace to use. If not specified, use default tablespace
324 * (which may in turn default to database's default).
326 if (stmt->tablespacename)
328 tablespaceId = get_tablespace_oid(stmt->tablespacename);
329 if (!OidIsValid(tablespaceId))
331 (errcode(ERRCODE_UNDEFINED_OBJECT),
332 errmsg("tablespace \"%s\" does not exist",
333 stmt->tablespacename)));
337 tablespaceId = GetDefaultTablespace(stmt->relation->istemp);
338 /* note InvalidOid is OK in this case */
341 /* Check permissions except when using database's default */
342 if (OidIsValid(tablespaceId))
346 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
348 if (aclresult != ACLCHECK_OK)
349 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
350 get_tablespace_name(tablespaceId));
354 * Parse and validate reloptions, if any.
356 reloptions = transformRelOptions((Datum) 0, stmt->options, true, false);
358 (void) heap_reloptions(relkind, reloptions, true);
361 * Look up inheritance ancestors and generate relation schema, including
362 * inherited attributes.
364 schema = MergeAttributes(schema, stmt->inhRelations,
365 stmt->relation->istemp,
366 &inheritOids, &old_constraints, &parentOidCount);
369 * Create a relation descriptor from the relation schema and create the
370 * relation. Note that in this stage only inherited (pre-cooked) defaults
371 * and constraints will be included into the new relation.
372 * (BuildDescForRelation takes care of the inherited defaults, but we have
373 * to copy inherited constraints here.)
375 descriptor = BuildDescForRelation(schema);
377 localHasOids = interpretOidsOption(stmt->options);
378 descriptor->tdhasoid = (localHasOids || parentOidCount > 0);
380 if (old_constraints || stmt->constraints)
385 /* make array that's certainly big enough */
386 check = (ConstrCheck *)
387 palloc((list_length(old_constraints) +
388 list_length(stmt->constraints)) * sizeof(ConstrCheck));
389 /* deal with constraints from MergeAttributes */
390 foreach(listptr, old_constraints)
392 Constraint *cdef = (Constraint *) lfirst(listptr);
394 if (cdef->contype == CONSTR_CHECK)
395 add_nonduplicate_constraint(cdef, check, &ncheck);
398 * parse_utilcmd.c might have passed some precooked constraints too,
399 * due to LIKE tab INCLUDING CONSTRAINTS
401 foreach(listptr, stmt->constraints)
403 Constraint *cdef = (Constraint *) lfirst(listptr);
405 if (cdef->contype == CONSTR_CHECK && cdef->cooked_expr != NULL)
406 add_nonduplicate_constraint(cdef, check, &ncheck);
408 /* if we found any, insert 'em into the descriptor */
411 if (descriptor->constr == NULL)
413 descriptor->constr = (TupleConstr *) palloc(sizeof(TupleConstr));
414 descriptor->constr->defval = NULL;
415 descriptor->constr->num_defval = 0;
416 descriptor->constr->has_not_null = false;
418 descriptor->constr->num_check = ncheck;
419 descriptor->constr->check = check;
423 relationId = heap_create_with_catalog(relname,
435 allowSystemTableMods);
437 StoreCatalogInheritance(relationId, inheritOids);
440 * We must bump the command counter to make the newly-created relation
441 * tuple visible for opening.
443 CommandCounterIncrement();
446 * Open the new relation and acquire exclusive lock on it. This isn't
447 * really necessary for locking out other backends (since they can't see
448 * the new rel anyway until we commit), but it keeps the lock manager from
449 * complaining about deadlock risks.
451 rel = relation_open(relationId, AccessExclusiveLock);
454 * Now add any newly specified column default values and CHECK constraints
455 * to the new relation. These are passed to us in the form of raw
456 * parsetrees; we need to transform them to executable expression trees
457 * before they can be added. The most convenient way to do that is to
458 * apply the parser's transformExpr routine, but transformExpr doesn't
459 * work unless we have a pre-existing relation. So, the transformation has
460 * to be postponed to this final step of CREATE TABLE.
462 * First, scan schema to find new column defaults.
467 foreach(listptr, schema)
469 ColumnDef *colDef = lfirst(listptr);
473 if (colDef->raw_default != NULL)
475 RawColumnDefault *rawEnt;
477 Assert(colDef->cooked_default == NULL);
479 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
480 rawEnt->attnum = attnum;
481 rawEnt->raw_default = colDef->raw_default;
482 rawDefaults = lappend(rawDefaults, rawEnt);
487 * Parse and add the defaults/constraints, if any.
489 if (rawDefaults || stmt->constraints)
490 AddRelationRawConstraints(rel, rawDefaults, stmt->constraints);
493 * Clean up. We keep lock on new relation (although it shouldn't be
494 * visible to anyone else anyway, until commit).
496 relation_close(rel, NoLock);
503 * Deletes a relation.
506 RemoveRelation(const RangeVar *relation, DropBehavior behavior)
509 ObjectAddress object;
511 relOid = RangeVarGetRelid(relation, false);
513 object.classId = RelationRelationId;
514 object.objectId = relOid;
515 object.objectSubId = 0;
517 performDeletion(&object, behavior);
522 * Executes a TRUNCATE command.
524 * This is a multi-relation truncate. We first open and grab exclusive
525 * lock on all relations involved, checking permissions and otherwise
526 * verifying that the relation is OK for truncation. In CASCADE mode,
527 * relations having FK references to the targeted relations are automatically
528 * added to the group; in RESTRICT mode, we check that all FK references are
529 * internal to the group that's being truncated. Finally all the relations
530 * are truncated and reindexed.
533 ExecuteTruncate(TruncateStmt *stmt)
540 * Open, exclusive-lock, and check all the explicitly-specified relations
542 foreach(cell, stmt->relations)
544 RangeVar *rv = lfirst(cell);
547 rel = heap_openrv(rv, AccessExclusiveLock);
548 truncate_check_rel(rel);
549 rels = lappend(rels, rel);
550 relids = lappend_oid(relids, RelationGetRelid(rel));
554 * In CASCADE mode, suck in all referencing relations as well. This
555 * requires multiple iterations to find indirectly-dependent relations. At
556 * each phase, we need to exclusive-lock new rels before looking for their
557 * dependencies, else we might miss something. Also, we check each rel as
558 * soon as we open it, to avoid a faux pas such as holding lock for a long
559 * time on a rel we have no permissions for.
561 if (stmt->behavior == DROP_CASCADE)
567 newrelids = heap_truncate_find_FKs(relids);
568 if (newrelids == NIL)
569 break; /* nothing else to add */
571 foreach(cell, newrelids)
573 Oid relid = lfirst_oid(cell);
576 rel = heap_open(relid, AccessExclusiveLock);
578 (errmsg("truncate cascades to table \"%s\"",
579 RelationGetRelationName(rel))));
580 truncate_check_rel(rel);
581 rels = lappend(rels, rel);
582 relids = lappend_oid(relids, relid);
588 * Check foreign key references. In CASCADE mode, this should be
589 * unnecessary since we just pulled in all the references; but as a
590 * cross-check, do it anyway if in an Assert-enabled build.
592 #ifdef USE_ASSERT_CHECKING
593 heap_truncate_check_FKs(rels, false);
595 if (stmt->behavior == DROP_RESTRICT)
596 heap_truncate_check_FKs(rels, false);
600 * Also check for pending AFTER trigger events on the target relations. We
601 * can't just leave those be, since they will try to fetch tuples that the
604 AfterTriggerCheckTruncate(relids);
607 * OK, truncate each table.
611 Relation rel = (Relation) lfirst(cell);
616 * Create a new empty storage file for the relation, and assign it as
617 * the relfilenode value. The old storage file is scheduled for
618 * deletion at commit.
620 setNewRelfilenode(rel, RecentXmin);
622 heap_relid = RelationGetRelid(rel);
623 toast_relid = rel->rd_rel->reltoastrelid;
625 heap_close(rel, NoLock);
628 * The same for the toast table, if any.
630 if (OidIsValid(toast_relid))
632 rel = relation_open(toast_relid, AccessExclusiveLock);
633 setNewRelfilenode(rel, RecentXmin);
634 heap_close(rel, NoLock);
638 * Reconstruct the indexes to match, and we're done.
640 reindex_relation(heap_relid, true);
645 * Check that a given rel is safe to truncate. Subroutine for ExecuteTruncate
648 truncate_check_rel(Relation rel)
650 /* Only allow truncate on regular tables */
651 if (rel->rd_rel->relkind != RELKIND_RELATION)
653 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
654 errmsg("\"%s\" is not a table",
655 RelationGetRelationName(rel))));
657 /* Permissions checks */
658 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
659 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
660 RelationGetRelationName(rel));
662 if (!allowSystemTableMods && IsSystemRelation(rel))
664 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
665 errmsg("permission denied: \"%s\" is a system catalog",
666 RelationGetRelationName(rel))));
669 * We can never allow truncation of shared or nailed-in-cache relations,
670 * because we can't support changing their relfilenode values.
672 if (rel->rd_rel->relisshared || rel->rd_isnailed)
674 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
675 errmsg("cannot truncate system relation \"%s\"",
676 RelationGetRelationName(rel))));
679 * Don't allow truncate on temp tables of other backends ... their local
680 * buffer manager is not going to cope.
682 if (isOtherTempNamespace(RelationGetNamespace(rel)))
684 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
685 errmsg("cannot truncate temporary tables of other sessions")));
690 * Returns new schema given initial schema and superclasses.
693 * 'schema' is the column/attribute definition for the table. (It's a list
694 * of ColumnDef's.) It is destructively changed.
695 * 'supers' is a list of names (as RangeVar nodes) of parent relations.
696 * 'istemp' is TRUE if we are creating a temp relation.
699 * 'supOids' receives a list of the OIDs of the parent relations.
700 * 'supconstr' receives a list of constraints belonging to the parents,
701 * updated as necessary to be valid for the child.
702 * 'supOidCount' is set to the number of parents that have OID columns.
705 * Completed schema list.
708 * The order in which the attributes are inherited is very important.
709 * Intuitively, the inherited attributes should come first. If a table
710 * inherits from multiple parents, the order of those attributes are
711 * according to the order of the parents specified in CREATE TABLE.
715 * create table person (name text, age int4, location point);
716 * create table emp (salary int4, manager text) inherits(person);
717 * create table student (gpa float8) inherits (person);
718 * create table stud_emp (percent int4) inherits (emp, student);
720 * The order of the attributes of stud_emp is:
722 * person {1:name, 2:age, 3:location}
724 * {6:gpa} student emp {4:salary, 5:manager}
726 * stud_emp {7:percent}
728 * If the same attribute name appears multiple times, then it appears
729 * in the result table in the proper location for its first appearance.
731 * Constraints (including NOT NULL constraints) for the child table
732 * are the union of all relevant constraints, from both the child schema
735 * The default value for a child column is defined as:
736 * (1) If the child schema specifies a default, that value is used.
737 * (2) If neither the child nor any parent specifies a default, then
738 * the column will not have a default.
739 * (3) If conflicting defaults are inherited from different parents
740 * (and not overridden by the child), an error is raised.
741 * (4) Otherwise the inherited default is used.
742 * Rule (3) is new in Postgres 7.1; in earlier releases you got a
743 * rather arbitrary choice of which parent default to use.
747 MergeAttributes(List *schema, List *supers, bool istemp,
748 List **supOids, List **supconstr, int *supOidCount)
751 List *inhSchema = NIL;
752 List *parentOids = NIL;
753 List *constraints = NIL;
754 int parentsWithOids = 0;
755 bool have_bogus_defaults = false;
756 char *bogus_marker = "Bogus!"; /* marks conflicting defaults */
760 * Check for and reject tables with too many columns. We perform this
761 * check relatively early for two reasons: (a) we don't run the risk of
762 * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
763 * okay if we're processing <= 1600 columns, but could take minutes to
764 * execute if the user attempts to create a table with hundreds of
765 * thousands of columns.
767 * Note that we also need to check that any we do not exceed this figure
768 * after including columns from inherited relations.
770 if (list_length(schema) > MaxHeapAttributeNumber)
772 (errcode(ERRCODE_TOO_MANY_COLUMNS),
773 errmsg("tables can have at most %d columns",
774 MaxHeapAttributeNumber)));
777 * Check for duplicate names in the explicit list of attributes.
779 * Although we might consider merging such entries in the same way that we
780 * handle name conflicts for inherited attributes, it seems to make more
781 * sense to assume such conflicts are errors.
783 foreach(entry, schema)
785 ColumnDef *coldef = lfirst(entry);
788 for_each_cell(rest, lnext(entry))
790 ColumnDef *restdef = lfirst(rest);
792 if (strcmp(coldef->colname, restdef->colname) == 0)
794 (errcode(ERRCODE_DUPLICATE_COLUMN),
795 errmsg("column \"%s\" specified more than once",
801 * Scan the parents left-to-right, and merge their attributes to form a
802 * list of inherited attributes (inhSchema). Also check to see if we need
803 * to inherit an OID column.
806 foreach(entry, supers)
808 RangeVar *parent = (RangeVar *) lfirst(entry);
812 AttrNumber *newattno;
813 AttrNumber parent_attno;
815 relation = heap_openrv(parent, AccessShareLock);
817 if (relation->rd_rel->relkind != RELKIND_RELATION)
819 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
820 errmsg("inherited relation \"%s\" is not a table",
822 /* Permanent rels cannot inherit from temporary ones */
823 if (!istemp && isTempNamespace(RelationGetNamespace(relation)))
825 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
826 errmsg("cannot inherit from temporary relation \"%s\"",
830 * We should have an UNDER permission flag for this, but for now,
831 * demand that creator of a child table own the parent.
833 if (!pg_class_ownercheck(RelationGetRelid(relation), GetUserId()))
834 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
835 RelationGetRelationName(relation));
838 * Reject duplications in the list of parents.
840 if (list_member_oid(parentOids, RelationGetRelid(relation)))
842 (errcode(ERRCODE_DUPLICATE_TABLE),
843 errmsg("relation \"%s\" would be inherited from more than once",
846 parentOids = lappend_oid(parentOids, RelationGetRelid(relation));
848 if (relation->rd_rel->relhasoids)
851 tupleDesc = RelationGetDescr(relation);
852 constr = tupleDesc->constr;
855 * newattno[] will contain the child-table attribute numbers for the
856 * attributes of this parent table. (They are not the same for
857 * parents after the first one, nor if we have dropped columns.)
859 newattno = (AttrNumber *)
860 palloc(tupleDesc->natts * sizeof(AttrNumber));
862 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
865 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
866 char *attributeName = NameStr(attribute->attname);
871 * Ignore dropped columns in the parent.
873 if (attribute->attisdropped)
876 * change_varattnos_of_a_node asserts that this is greater
877 * than zero, so if anything tries to use it, we should find
880 newattno[parent_attno - 1] = 0;
885 * Does it conflict with some previously inherited column?
887 exist_attno = findAttrByName(attributeName, inhSchema);
894 * Yes, try to merge the two column definitions. They must
895 * have the same type and typmod.
898 (errmsg("merging multiple inherited definitions of column \"%s\"",
900 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
901 defTypeId = typenameTypeId(NULL, def->typename);
902 deftypmod = typenameTypeMod(NULL, def->typename, defTypeId);
903 if (defTypeId != attribute->atttypid ||
904 deftypmod != attribute->atttypmod)
906 (errcode(ERRCODE_DATATYPE_MISMATCH),
907 errmsg("inherited column \"%s\" has a type conflict",
909 errdetail("%s versus %s",
910 TypeNameToString(def->typename),
911 format_type_be(attribute->atttypid))));
913 /* Merge of NOT NULL constraints = OR 'em together */
914 def->is_not_null |= attribute->attnotnull;
915 /* Default and other constraints are handled below */
916 newattno[parent_attno - 1] = exist_attno;
921 * No, create a new inherited column
923 def = makeNode(ColumnDef);
924 def->colname = pstrdup(attributeName);
925 def->typename = makeTypeNameFromOid(attribute->atttypid,
926 attribute->atttypmod);
928 def->is_local = false;
929 def->is_not_null = attribute->attnotnull;
930 def->raw_default = NULL;
931 def->cooked_default = NULL;
932 def->constraints = NIL;
933 inhSchema = lappend(inhSchema, def);
934 newattno[parent_attno - 1] = ++child_attno;
938 * Copy default if any
940 if (attribute->atthasdef)
942 char *this_default = NULL;
943 AttrDefault *attrdef;
946 /* Find default in constraint structure */
947 Assert(constr != NULL);
948 attrdef = constr->defval;
949 for (i = 0; i < constr->num_defval; i++)
951 if (attrdef[i].adnum == parent_attno)
953 this_default = attrdef[i].adbin;
957 Assert(this_default != NULL);
960 * If default expr could contain any vars, we'd need to fix
961 * 'em, but it can't; so default is ready to apply to child.
963 * If we already had a default from some prior parent, check
964 * to see if they are the same. If so, no problem; if not,
965 * mark the column as having a bogus default. Below, we will
966 * complain if the bogus default isn't overridden by the child
969 Assert(def->raw_default == NULL);
970 if (def->cooked_default == NULL)
971 def->cooked_default = pstrdup(this_default);
972 else if (strcmp(def->cooked_default, this_default) != 0)
974 def->cooked_default = bogus_marker;
975 have_bogus_defaults = true;
981 * Now copy the constraints of this parent, adjusting attnos using the
982 * completed newattno[] map
984 if (constr && constr->num_check > 0)
986 ConstrCheck *check = constr->check;
989 for (i = 0; i < constr->num_check; i++)
991 Constraint *cdef = makeNode(Constraint);
994 cdef->contype = CONSTR_CHECK;
995 cdef->name = pstrdup(check[i].ccname);
996 cdef->raw_expr = NULL;
997 /* adjust varattnos of ccbin here */
998 expr = stringToNode(check[i].ccbin);
999 change_varattnos_of_a_node(expr, newattno);
1000 cdef->cooked_expr = nodeToString(expr);
1001 constraints = lappend(constraints, cdef);
1008 * Close the parent rel, but keep our AccessShareLock on it until xact
1009 * commit. That will prevent someone else from deleting or ALTERing
1010 * the parent before the child is committed.
1012 heap_close(relation, NoLock);
1016 * If we had no inherited attributes, the result schema is just the
1017 * explicitly declared columns. Otherwise, we need to merge the declared
1018 * columns into the inherited schema list.
1020 if (inhSchema != NIL)
1022 foreach(entry, schema)
1024 ColumnDef *newdef = lfirst(entry);
1025 char *attributeName = newdef->colname;
1029 * Does it conflict with some previously inherited column?
1031 exist_attno = findAttrByName(attributeName, inhSchema);
1032 if (exist_attno > 0)
1035 Oid defTypeId, newTypeId;
1036 int32 deftypmod, newtypmod;
1039 * Yes, try to merge the two column definitions. They must
1040 * have the same type and typmod.
1043 (errmsg("merging column \"%s\" with inherited definition",
1045 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1046 defTypeId = typenameTypeId(NULL, def->typename);
1047 deftypmod = typenameTypeMod(NULL, def->typename, defTypeId);
1048 newTypeId = typenameTypeId(NULL, newdef->typename);
1049 newtypmod = typenameTypeMod(NULL, newdef->typename, newTypeId);
1050 if (defTypeId != newTypeId || deftypmod != newtypmod)
1052 (errcode(ERRCODE_DATATYPE_MISMATCH),
1053 errmsg("column \"%s\" has a type conflict",
1055 errdetail("%s versus %s",
1056 TypeNameToString(def->typename),
1057 TypeNameToString(newdef->typename))));
1058 /* Mark the column as locally defined */
1059 def->is_local = true;
1060 /* Merge of NOT NULL constraints = OR 'em together */
1061 def->is_not_null |= newdef->is_not_null;
1062 /* If new def has a default, override previous default */
1063 if (newdef->raw_default != NULL)
1065 def->raw_default = newdef->raw_default;
1066 def->cooked_default = newdef->cooked_default;
1072 * No, attach new column to result schema
1074 inhSchema = lappend(inhSchema, newdef);
1081 * Check that we haven't exceeded the legal # of columns after merging
1082 * in inherited columns.
1084 if (list_length(schema) > MaxHeapAttributeNumber)
1086 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1087 errmsg("tables can have at most %d columns",
1088 MaxHeapAttributeNumber)));
1092 * If we found any conflicting parent default values, check to make sure
1093 * they were overridden by the child.
1095 if (have_bogus_defaults)
1097 foreach(entry, schema)
1099 ColumnDef *def = lfirst(entry);
1101 if (def->cooked_default == bogus_marker)
1103 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
1104 errmsg("column \"%s\" inherits conflicting default values",
1106 errhint("To resolve the conflict, specify a default explicitly.")));
1110 *supOids = parentOids;
1111 *supconstr = constraints;
1112 *supOidCount = parentsWithOids;
1118 * In multiple-inheritance situations, it's possible to inherit
1119 * the same grandparent constraint through multiple parents.
1120 * Hence, we want to discard inherited constraints that match as to
1121 * both name and expression. Otherwise, gripe if there are conflicting
1122 * names. Nonconflicting constraints are added to the array check[]
1123 * of length *ncheck ... caller must ensure there is room!
1126 add_nonduplicate_constraint(Constraint *cdef, ConstrCheck *check, int *ncheck)
1130 /* Should only see precooked constraints here */
1131 Assert(cdef->contype == CONSTR_CHECK);
1132 Assert(cdef->name != NULL);
1133 Assert(cdef->raw_expr == NULL && cdef->cooked_expr != NULL);
1135 for (i = 0; i < *ncheck; i++)
1137 if (strcmp(check[i].ccname, cdef->name) != 0)
1139 if (strcmp(check[i].ccbin, cdef->cooked_expr) == 0)
1140 return; /* duplicate constraint, so ignore it */
1142 (errcode(ERRCODE_DUPLICATE_OBJECT),
1143 errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
1146 /* No match on name, so add it to array */
1147 check[*ncheck].ccname = cdef->name;
1148 check[*ncheck].ccbin = pstrdup(cdef->cooked_expr);
1154 * Replace varattno values in an expression tree according to the given
1155 * map array, that is, varattno N is replaced by newattno[N-1]. It is
1156 * caller's responsibility to ensure that the array is long enough to
1157 * define values for all user varattnos present in the tree. System column
1158 * attnos remain unchanged.
1160 * Note that the passed node tree is modified in-place!
1163 change_varattnos_of_a_node(Node *node, const AttrNumber *newattno)
1165 /* no setup needed, so away we go */
1166 (void) change_varattnos_walker(node, newattno);
1170 change_varattnos_walker(Node *node, const AttrNumber *newattno)
1176 Var *var = (Var *) node;
1178 if (var->varlevelsup == 0 && var->varno == 1 &&
1182 * ??? the following may be a problem when the node is multiply
1183 * referenced though stringToNode() doesn't create such a node
1186 Assert(newattno[var->varattno - 1] > 0);
1187 var->varattno = newattno[var->varattno - 1];
1191 return expression_tree_walker(node, change_varattnos_walker,
1196 * Generate a map for change_varattnos_of_a_node from old and new TupleDesc's,
1197 * matching according to column name.
1200 varattnos_map(TupleDesc old, TupleDesc new)
1206 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * old->natts);
1207 for (i = 1; i <= old->natts; i++)
1209 if (old->attrs[i - 1]->attisdropped)
1210 continue; /* leave the entry as zero */
1212 for (j = 1; j <= new->natts; j++)
1214 if (strcmp(NameStr(old->attrs[i - 1]->attname),
1215 NameStr(new->attrs[j - 1]->attname)) == 0)
1226 * Generate a map for change_varattnos_of_a_node from a TupleDesc and a list
1230 varattnos_map_schema(TupleDesc old, List *schema)
1235 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * old->natts);
1236 for (i = 1; i <= old->natts; i++)
1238 if (old->attrs[i - 1]->attisdropped)
1239 continue; /* leave the entry as zero */
1241 attmap[i - 1] = findAttrByName(NameStr(old->attrs[i - 1]->attname),
1249 * StoreCatalogInheritance
1250 * Updates the system catalogs with proper inheritance information.
1252 * supers is a list of the OIDs of the new relation's direct ancestors.
1255 StoreCatalogInheritance(Oid relationId, List *supers)
1264 AssertArg(OidIsValid(relationId));
1270 * Store INHERITS information in pg_inherits using direct ancestors only.
1271 * Also enter dependencies on the direct ancestors, and make sure they are
1272 * marked with relhassubclass = true.
1274 * (Once upon a time, both direct and indirect ancestors were found here
1275 * and then entered into pg_ipl. Since that catalog doesn't exist
1276 * anymore, there's no need to look for indirect ancestors.)
1278 relation = heap_open(InheritsRelationId, RowExclusiveLock);
1281 foreach(entry, supers)
1283 Oid parentOid = lfirst_oid(entry);
1285 StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation);
1289 heap_close(relation, RowExclusiveLock);
1293 * Make catalog entries showing relationId as being an inheritance child
1294 * of parentOid. inhRelation is the already-opened pg_inherits catalog.
1297 StoreCatalogInheritance1(Oid relationId, Oid parentOid,
1298 int16 seqNumber, Relation inhRelation)
1300 TupleDesc desc = RelationGetDescr(inhRelation);
1301 Datum datum[Natts_pg_inherits];
1302 char nullarr[Natts_pg_inherits];
1303 ObjectAddress childobject,
1308 * Make the pg_inherits entry
1310 datum[0] = ObjectIdGetDatum(relationId); /* inhrelid */
1311 datum[1] = ObjectIdGetDatum(parentOid); /* inhparent */
1312 datum[2] = Int16GetDatum(seqNumber); /* inhseqno */
1318 tuple = heap_formtuple(desc, datum, nullarr);
1320 simple_heap_insert(inhRelation, tuple);
1322 CatalogUpdateIndexes(inhRelation, tuple);
1324 heap_freetuple(tuple);
1327 * Store a dependency too
1329 parentobject.classId = RelationRelationId;
1330 parentobject.objectId = parentOid;
1331 parentobject.objectSubId = 0;
1332 childobject.classId = RelationRelationId;
1333 childobject.objectId = relationId;
1334 childobject.objectSubId = 0;
1336 recordDependencyOn(&childobject, &parentobject, DEPENDENCY_NORMAL);
1339 * Mark the parent as having subclasses.
1341 setRelhassubclassInRelation(parentOid, true);
1345 * Look for an existing schema entry with the given name.
1347 * Returns the index (starting with 1) if attribute already exists in schema,
1351 findAttrByName(const char *attributeName, List *schema)
1358 ColumnDef *def = lfirst(s);
1360 if (strcmp(attributeName, def->colname) == 0)
1369 * Update a relation's pg_class.relhassubclass entry to the given value
1372 setRelhassubclassInRelation(Oid relationId, bool relhassubclass)
1374 Relation relationRelation;
1376 Form_pg_class classtuple;
1379 * Fetch a modifiable copy of the tuple, modify it, update pg_class.
1381 * If the tuple already has the right relhassubclass setting, we don't
1382 * need to update it, but we still need to issue an SI inval message.
1384 relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
1385 tuple = SearchSysCacheCopy(RELOID,
1386 ObjectIdGetDatum(relationId),
1388 if (!HeapTupleIsValid(tuple))
1389 elog(ERROR, "cache lookup failed for relation %u", relationId);
1390 classtuple = (Form_pg_class) GETSTRUCT(tuple);
1392 if (classtuple->relhassubclass != relhassubclass)
1394 classtuple->relhassubclass = relhassubclass;
1395 simple_heap_update(relationRelation, &tuple->t_self, tuple);
1397 /* keep the catalog indexes up to date */
1398 CatalogUpdateIndexes(relationRelation, tuple);
1402 /* no need to change tuple, but force relcache rebuild anyway */
1403 CacheInvalidateRelcacheByTuple(tuple);
1406 heap_freetuple(tuple);
1407 heap_close(relationRelation, RowExclusiveLock);
1412 * renameatt - changes the name of a attribute in a relation
1414 * Attname attribute is changed in attribute catalog.
1415 * No record of the previous attname is kept (correct?).
1417 * get proper relrelation from relation catalog (if not arg)
1418 * scan attribute catalog
1419 * for name conflict (within rel)
1420 * for original attribute (if not arg)
1421 * modify attname in attribute tuple
1422 * insert modified attribute in attribute catalog
1423 * delete original attribute from attribute catalog
1426 renameatt(Oid myrelid,
1427 const char *oldattname,
1428 const char *newattname,
1432 Relation targetrelation;
1433 Relation attrelation;
1435 Form_pg_attribute attform;
1438 ListCell *indexoidscan;
1441 * Grab an exclusive lock on the target table, which we will NOT release
1442 * until end of transaction.
1444 targetrelation = relation_open(myrelid, AccessExclusiveLock);
1447 * permissions checking. this would normally be done in utility.c, but
1448 * this particular routine is recursive.
1450 * normally, only the owner of a class can change its schema.
1452 if (!pg_class_ownercheck(myrelid, GetUserId()))
1453 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1454 RelationGetRelationName(targetrelation));
1455 if (!allowSystemTableMods && IsSystemRelation(targetrelation))
1457 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1458 errmsg("permission denied: \"%s\" is a system catalog",
1459 RelationGetRelationName(targetrelation))));
1462 * if the 'recurse' flag is set then we are supposed to rename this
1463 * attribute in all classes that inherit from 'relname' (as well as in
1466 * any permissions or problems with duplicate attributes will cause the
1467 * whole transaction to abort, which is what we want -- all or nothing.
1474 /* this routine is actually in the planner */
1475 children = find_all_inheritors(myrelid);
1478 * find_all_inheritors does the recursive search of the inheritance
1479 * hierarchy, so all we have to do is process all of the relids in the
1480 * list that it returns.
1482 foreach(child, children)
1484 Oid childrelid = lfirst_oid(child);
1486 if (childrelid == myrelid)
1488 /* note we need not recurse again */
1489 renameatt(childrelid, oldattname, newattname, false, true);
1495 * If we are told not to recurse, there had better not be any child
1496 * tables; else the rename would put them out of step.
1499 find_inheritance_children(myrelid) != NIL)
1501 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1502 errmsg("inherited column \"%s\" must be renamed in child tables too",
1506 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
1508 atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
1509 if (!HeapTupleIsValid(atttup))
1511 (errcode(ERRCODE_UNDEFINED_COLUMN),
1512 errmsg("column \"%s\" does not exist",
1514 attform = (Form_pg_attribute) GETSTRUCT(atttup);
1516 attnum = attform->attnum;
1519 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1520 errmsg("cannot rename system column \"%s\"",
1524 * if the attribute is inherited, forbid the renaming, unless we are
1525 * already inside a recursive rename.
1527 if (attform->attinhcount > 0 && !recursing)
1529 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1530 errmsg("cannot rename inherited column \"%s\"",
1533 /* should not already exist */
1534 /* this test is deliberately not attisdropped-aware */
1535 if (SearchSysCacheExists(ATTNAME,
1536 ObjectIdGetDatum(myrelid),
1537 PointerGetDatum(newattname),
1540 (errcode(ERRCODE_DUPLICATE_COLUMN),
1541 errmsg("column \"%s\" of relation \"%s\" already exists",
1542 newattname, RelationGetRelationName(targetrelation))));
1544 namestrcpy(&(attform->attname), newattname);
1546 simple_heap_update(attrelation, &atttup->t_self, atttup);
1548 /* keep system catalog indexes current */
1549 CatalogUpdateIndexes(attrelation, atttup);
1551 heap_freetuple(atttup);
1554 * Update column names of indexes that refer to the column being renamed.
1556 indexoidlist = RelationGetIndexList(targetrelation);
1558 foreach(indexoidscan, indexoidlist)
1560 Oid indexoid = lfirst_oid(indexoidscan);
1562 Form_pg_index indexform;
1566 * Scan through index columns to see if there's any simple index
1567 * entries for this attribute. We ignore expressional entries.
1569 indextup = SearchSysCache(INDEXRELID,
1570 ObjectIdGetDatum(indexoid),
1572 if (!HeapTupleIsValid(indextup))
1573 elog(ERROR, "cache lookup failed for index %u", indexoid);
1574 indexform = (Form_pg_index) GETSTRUCT(indextup);
1576 for (i = 0; i < indexform->indnatts; i++)
1578 if (attnum != indexform->indkey.values[i])
1582 * Found one, rename it.
1584 atttup = SearchSysCacheCopy(ATTNUM,
1585 ObjectIdGetDatum(indexoid),
1586 Int16GetDatum(i + 1),
1588 if (!HeapTupleIsValid(atttup))
1589 continue; /* should we raise an error? */
1592 * Update the (copied) attribute tuple.
1594 namestrcpy(&(((Form_pg_attribute) GETSTRUCT(atttup))->attname),
1597 simple_heap_update(attrelation, &atttup->t_self, atttup);
1599 /* keep system catalog indexes current */
1600 CatalogUpdateIndexes(attrelation, atttup);
1602 heap_freetuple(atttup);
1605 ReleaseSysCache(indextup);
1608 list_free(indexoidlist);
1610 heap_close(attrelation, RowExclusiveLock);
1612 relation_close(targetrelation, NoLock); /* close rel but keep lock */
1616 * renamerel - change the name of a relation
1618 * XXX - When renaming sequences, we don't bother to modify the
1619 * sequence name that is stored within the sequence itself
1620 * (this would cause problems with MVCC). In the future,
1621 * the sequence name should probably be removed from the
1622 * sequence, AFAIK there's no need for it to be there.
1625 renamerel(Oid myrelid, const char *newrelname, ObjectType reltype)
1627 Relation targetrelation;
1628 Relation relrelation; /* for RELATION relation */
1630 Form_pg_class relform;
1634 bool relhastriggers;
1637 * Grab an exclusive lock on the target table, index, sequence or
1638 * view, which we will NOT release until end of transaction.
1640 targetrelation = relation_open(myrelid, AccessExclusiveLock);
1642 oldrelname = pstrdup(RelationGetRelationName(targetrelation));
1643 namespaceId = RelationGetNamespace(targetrelation);
1645 if (!allowSystemTableMods && IsSystemRelation(targetrelation))
1647 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1648 errmsg("permission denied: \"%s\" is a system catalog",
1649 RelationGetRelationName(targetrelation))));
1652 * For compatibility with prior releases, we don't complain if
1653 * ALTER TABLE or ALTER INDEX is used to rename a sequence or
1656 relkind = targetrelation->rd_rel->relkind;
1657 if (reltype == OBJECT_SEQUENCE && relkind != 'S')
1659 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1660 errmsg("\"%s\" is not a sequence",
1661 RelationGetRelationName(targetrelation))));
1663 if (reltype == OBJECT_VIEW && relkind != 'v')
1665 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1666 errmsg("\"%s\" is not a view",
1667 RelationGetRelationName(targetrelation))));
1669 relhastriggers = (targetrelation->rd_rel->reltriggers > 0);
1672 * Find relation's pg_class tuple, and make sure newrelname isn't in use.
1674 relrelation = heap_open(RelationRelationId, RowExclusiveLock);
1676 reltup = SearchSysCacheCopy(RELOID,
1677 ObjectIdGetDatum(myrelid),
1679 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
1680 elog(ERROR, "cache lookup failed for relation %u", myrelid);
1681 relform = (Form_pg_class) GETSTRUCT(reltup);
1683 if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
1685 (errcode(ERRCODE_DUPLICATE_TABLE),
1686 errmsg("relation \"%s\" already exists",
1690 * Update pg_class tuple with new relname. (Scribbling on reltup is OK
1691 * because it's a copy...)
1693 namestrcpy(&(relform->relname), newrelname);
1695 simple_heap_update(relrelation, &reltup->t_self, reltup);
1697 /* keep the system catalog indexes current */
1698 CatalogUpdateIndexes(relrelation, reltup);
1700 heap_freetuple(reltup);
1701 heap_close(relrelation, RowExclusiveLock);
1704 * Also rename the associated type, if any.
1706 if (OidIsValid(targetrelation->rd_rel->reltype))
1707 TypeRename(targetrelation->rd_rel->reltype, newrelname, namespaceId);
1710 * Close rel, but keep exclusive lock!
1712 relation_close(targetrelation, NoLock);
1717 * Execute ALTER TABLE, which can be a list of subcommands
1719 * ALTER TABLE is performed in three phases:
1720 * 1. Examine subcommands and perform pre-transformation checking.
1721 * 2. Update system catalogs.
1722 * 3. Scan table(s) to check new constraints, and optionally recopy
1723 * the data into new table(s).
1724 * Phase 3 is not performed unless one or more of the subcommands requires
1725 * it. The intention of this design is to allow multiple independent
1726 * updates of the table schema to be performed with only one pass over the
1729 * ATPrepCmd performs phase 1. A "work queue" entry is created for
1730 * each table to be affected (there may be multiple affected tables if the
1731 * commands traverse a table inheritance hierarchy). Also we do preliminary
1732 * validation of the subcommands, including parse transformation of those
1733 * expressions that need to be evaluated with respect to the old table
1736 * ATRewriteCatalogs performs phase 2 for each affected table (note that
1737 * phases 2 and 3 do no explicit recursion, since phase 1 already did it).
1738 * Certain subcommands need to be performed before others to avoid
1739 * unnecessary conflicts; for example, DROP COLUMN should come before
1740 * ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
1741 * lists, one for each logical "pass" of phase 2.
1743 * ATRewriteTables performs phase 3 for those tables that need it.
1745 * Thanks to the magic of MVCC, an error anywhere along the way rolls back
1746 * the whole operation; we don't have to do anything special to clean up.
1749 AlterTable(AlterTableStmt *stmt)
1751 Relation rel = relation_openrv(stmt->relation, AccessExclusiveLock);
1752 int expected_refcnt;
1755 * Disallow ALTER TABLE when the current backend has any open reference
1756 * to it besides the one we just got (such as an open cursor or active
1757 * plan); our AccessExclusiveLock doesn't protect us against stomping on
1758 * our own foot, only other people's feet!
1760 * Note: the only case known to cause serious trouble is ALTER COLUMN TYPE,
1761 * and some changes are obviously pretty benign, so this could possibly
1762 * be relaxed to only error out for certain types of alterations. But
1763 * the use-case for allowing any of these things is not obvious, so we
1764 * won't work hard at it for now.
1766 expected_refcnt = rel->rd_isnailed ? 2 : 1;
1767 if (rel->rd_refcnt != expected_refcnt)
1769 (errcode(ERRCODE_OBJECT_IN_USE),
1770 errmsg("relation \"%s\" is being used by active queries in this session",
1771 RelationGetRelationName(rel))));
1773 ATController(rel, stmt->cmds, interpretInhOption(stmt->relation->inhOpt));
1777 * AlterTableInternal
1779 * ALTER TABLE with target specified by OID
1781 * We do not reject if the relation is already open, because it's quite
1782 * likely that one or more layers of caller have it open. That means it
1783 * is unsafe to use this entry point for alterations that could break
1784 * existing query plans.
1787 AlterTableInternal(Oid relid, List *cmds, bool recurse)
1789 Relation rel = relation_open(relid, AccessExclusiveLock);
1791 ATController(rel, cmds, recurse);
1795 ATController(Relation rel, List *cmds, bool recurse)
1800 /* Phase 1: preliminary examination of commands, create work queue */
1803 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
1805 ATPrepCmd(&wqueue, rel, cmd, recurse, false);
1808 /* Close the relation, but keep lock until commit */
1809 relation_close(rel, NoLock);
1811 /* Phase 2: update system catalogs */
1812 ATRewriteCatalogs(&wqueue);
1814 /* Phase 3: scan/rewrite tables as needed */
1815 ATRewriteTables(&wqueue);
1821 * Traffic cop for ALTER TABLE Phase 1 operations, including simple
1822 * recursion and permission checks.
1824 * Caller must have acquired AccessExclusiveLock on relation already.
1825 * This lock should be held until commit.
1828 ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
1829 bool recurse, bool recursing)
1831 AlteredTableInfo *tab;
1834 /* Find or create work queue entry for this table */
1835 tab = ATGetQueueEntry(wqueue, rel);
1838 * Copy the original subcommand for each table. This avoids conflicts
1839 * when different child tables need to make different parse
1840 * transformations (for example, the same column may have different column
1841 * numbers in different children).
1843 cmd = copyObject(cmd);
1846 * Do permissions checking, recursion to child tables if needed, and any
1847 * additional phase-1 processing needed.
1849 switch (cmd->subtype)
1851 case AT_AddColumn: /* ADD COLUMN */
1852 ATSimplePermissions(rel, false);
1853 /* Performs own recursion */
1854 ATPrepAddColumn(wqueue, rel, recurse, cmd);
1855 pass = AT_PASS_ADD_COL;
1857 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
1860 * We allow defaults on views so that INSERT into a view can have
1861 * default-ish behavior. This works because the rewriter
1862 * substitutes default values into INSERTs before it expands
1865 ATSimplePermissions(rel, true);
1866 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1867 /* No command-specific prep needed */
1868 pass = cmd->def ? AT_PASS_ADD_CONSTR : AT_PASS_DROP;
1870 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
1871 ATSimplePermissions(rel, false);
1872 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1873 /* No command-specific prep needed */
1874 pass = AT_PASS_DROP;
1876 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
1877 ATSimplePermissions(rel, false);
1878 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1879 /* No command-specific prep needed */
1880 pass = AT_PASS_ADD_CONSTR;
1882 case AT_SetStatistics: /* ALTER COLUMN STATISTICS */
1883 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1884 /* Performs own permission checks */
1885 ATPrepSetStatistics(rel, cmd->name, cmd->def);
1886 pass = AT_PASS_COL_ATTRS;
1888 case AT_SetStorage: /* ALTER COLUMN STORAGE */
1889 ATSimplePermissions(rel, false);
1890 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1891 /* No command-specific prep needed */
1892 pass = AT_PASS_COL_ATTRS;
1894 case AT_DropColumn: /* DROP COLUMN */
1895 ATSimplePermissions(rel, false);
1896 /* Recursion occurs during execution phase */
1897 /* No command-specific prep needed except saving recurse flag */
1899 cmd->subtype = AT_DropColumnRecurse;
1900 pass = AT_PASS_DROP;
1902 case AT_AddIndex: /* ADD INDEX */
1903 ATSimplePermissions(rel, false);
1904 /* This command never recurses */
1905 /* No command-specific prep needed */
1906 pass = AT_PASS_ADD_INDEX;
1908 case AT_AddConstraint: /* ADD CONSTRAINT */
1909 ATSimplePermissions(rel, false);
1912 * Currently we recurse only for CHECK constraints, never for
1913 * foreign-key constraints. UNIQUE/PKEY constraints won't be seen
1916 if (IsA(cmd->def, Constraint))
1917 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1918 /* No command-specific prep needed */
1919 pass = AT_PASS_ADD_CONSTR;
1921 case AT_DropConstraint: /* DROP CONSTRAINT */
1922 ATSimplePermissions(rel, false);
1923 /* Performs own recursion */
1924 ATPrepDropConstraint(wqueue, rel, recurse, cmd);
1925 pass = AT_PASS_DROP;
1927 case AT_DropConstraintQuietly: /* DROP CONSTRAINT for child */
1928 ATSimplePermissions(rel, false);
1929 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1930 /* No command-specific prep needed */
1931 pass = AT_PASS_DROP;
1933 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
1934 ATSimplePermissions(rel, false);
1935 /* Performs own recursion */
1936 ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd);
1937 pass = AT_PASS_ALTER_TYPE;
1939 case AT_ChangeOwner: /* ALTER OWNER */
1940 /* This command never recurses */
1941 /* No command-specific prep needed */
1942 pass = AT_PASS_MISC;
1944 case AT_ClusterOn: /* CLUSTER ON */
1945 case AT_DropCluster: /* SET WITHOUT CLUSTER */
1946 ATSimplePermissions(rel, false);
1947 /* These commands never recurse */
1948 /* No command-specific prep needed */
1949 pass = AT_PASS_MISC;
1951 case AT_DropOids: /* SET WITHOUT OIDS */
1952 ATSimplePermissions(rel, false);
1953 /* Performs own recursion */
1954 if (rel->rd_rel->relhasoids)
1956 AlterTableCmd *dropCmd = makeNode(AlterTableCmd);
1958 dropCmd->subtype = AT_DropColumn;
1959 dropCmd->name = pstrdup("oid");
1960 dropCmd->behavior = cmd->behavior;
1961 ATPrepCmd(wqueue, rel, dropCmd, recurse, false);
1963 pass = AT_PASS_DROP;
1965 case AT_SetTableSpace: /* SET TABLESPACE */
1966 ATSimplePermissionsRelationOrIndex(rel);
1967 /* This command never recurses */
1968 ATPrepSetTableSpace(tab, rel, cmd->name);
1969 pass = AT_PASS_MISC; /* doesn't actually matter */
1971 case AT_SetRelOptions: /* SET (...) */
1972 case AT_ResetRelOptions: /* RESET (...) */
1973 ATSimplePermissionsRelationOrIndex(rel);
1974 /* This command never recurses */
1975 /* No command-specific prep needed */
1976 pass = AT_PASS_MISC;
1978 case AT_EnableTrig: /* ENABLE TRIGGER variants */
1979 case AT_EnableAlwaysTrig:
1980 case AT_EnableReplicaTrig:
1981 case AT_EnableTrigAll:
1982 case AT_EnableTrigUser:
1983 case AT_DisableTrig: /* DISABLE TRIGGER variants */
1984 case AT_DisableTrigAll:
1985 case AT_DisableTrigUser:
1986 case AT_EnableRule: /* ENABLE/DISABLE RULE variants */
1987 case AT_EnableAlwaysRule:
1988 case AT_EnableReplicaRule:
1989 case AT_DisableRule:
1990 case AT_AddInherit: /* INHERIT / NO INHERIT */
1991 case AT_DropInherit:
1992 ATSimplePermissions(rel, false);
1993 /* These commands never recurse */
1994 /* No command-specific prep needed */
1995 pass = AT_PASS_MISC;
1998 elog(ERROR, "unrecognized alter table type: %d",
1999 (int) cmd->subtype);
2000 pass = 0; /* keep compiler quiet */
2004 /* Add the subcommand to the appropriate list for phase 2 */
2005 tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
2011 * Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
2012 * dispatched in a "safe" execution order (designed to avoid unnecessary
2016 ATRewriteCatalogs(List **wqueue)
2022 * We process all the tables "in parallel", one pass at a time. This is
2023 * needed because we may have to propagate work from one table to another
2024 * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
2025 * re-adding of the foreign key constraint to the other table). Work can
2026 * only be propagated into later passes, however.
2028 for (pass = 0; pass < AT_NUM_PASSES; pass++)
2030 /* Go through each table that needs to be processed */
2031 foreach(ltab, *wqueue)
2033 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2034 List *subcmds = tab->subcmds[pass];
2042 * Exclusive lock was obtained by phase 1, needn't get it again
2044 rel = relation_open(tab->relid, NoLock);
2046 foreach(lcmd, subcmds)
2047 ATExecCmd(tab, rel, (AlterTableCmd *) lfirst(lcmd));
2050 * After the ALTER TYPE pass, do cleanup work (this is not done in
2051 * ATExecAlterColumnType since it should be done only once if
2052 * multiple columns of a table are altered).
2054 if (pass == AT_PASS_ALTER_TYPE)
2055 ATPostAlterTypeCleanup(wqueue, tab);
2057 relation_close(rel, NoLock);
2062 * Check to see if a toast table must be added, if we executed any
2063 * subcommands that might have added a column or changed column storage.
2065 foreach(ltab, *wqueue)
2067 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2069 if (tab->relkind == RELKIND_RELATION &&
2070 (tab->subcmds[AT_PASS_ADD_COL] ||
2071 tab->subcmds[AT_PASS_ALTER_TYPE] ||
2072 tab->subcmds[AT_PASS_COL_ATTRS]))
2073 AlterTableCreateToastTable(tab->relid);
2078 * ATExecCmd: dispatch a subcommand to appropriate execution routine
2081 ATExecCmd(AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd)
2083 switch (cmd->subtype)
2085 case AT_AddColumn: /* ADD COLUMN */
2086 ATExecAddColumn(tab, rel, (ColumnDef *) cmd->def);
2088 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
2089 ATExecColumnDefault(rel, cmd->name, cmd->def);
2091 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
2092 ATExecDropNotNull(rel, cmd->name);
2094 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
2095 ATExecSetNotNull(tab, rel, cmd->name);
2097 case AT_SetStatistics: /* ALTER COLUMN STATISTICS */
2098 ATExecSetStatistics(rel, cmd->name, cmd->def);
2100 case AT_SetStorage: /* ALTER COLUMN STORAGE */
2101 ATExecSetStorage(rel, cmd->name, cmd->def);
2103 case AT_DropColumn: /* DROP COLUMN */
2104 ATExecDropColumn(rel, cmd->name, cmd->behavior, false, false);
2106 case AT_DropColumnRecurse: /* DROP COLUMN with recursion */
2107 ATExecDropColumn(rel, cmd->name, cmd->behavior, true, false);
2109 case AT_AddIndex: /* ADD INDEX */
2110 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false);
2112 case AT_ReAddIndex: /* ADD INDEX */
2113 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true);
2115 case AT_AddConstraint: /* ADD CONSTRAINT */
2116 ATExecAddConstraint(tab, rel, cmd->def);
2118 case AT_DropConstraint: /* DROP CONSTRAINT */
2119 ATExecDropConstraint(rel, cmd->name, cmd->behavior, false);
2121 case AT_DropConstraintQuietly: /* DROP CONSTRAINT for child */
2122 ATExecDropConstraint(rel, cmd->name, cmd->behavior, true);
2124 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
2125 ATExecAlterColumnType(tab, rel, cmd->name, (TypeName *) cmd->def);
2127 case AT_ChangeOwner: /* ALTER OWNER */
2128 ATExecChangeOwner(RelationGetRelid(rel),
2129 get_roleid_checked(cmd->name),
2132 case AT_ClusterOn: /* CLUSTER ON */
2133 ATExecClusterOn(rel, cmd->name);
2135 case AT_DropCluster: /* SET WITHOUT CLUSTER */
2136 ATExecDropCluster(rel);
2138 case AT_DropOids: /* SET WITHOUT OIDS */
2141 * Nothing to do here; we'll have generated a DropColumn
2142 * subcommand to do the real work
2145 case AT_SetTableSpace: /* SET TABLESPACE */
2148 * Nothing to do here; Phase 3 does the work
2151 case AT_SetRelOptions: /* SET (...) */
2152 ATExecSetRelOptions(rel, (List *) cmd->def, false);
2154 case AT_ResetRelOptions: /* RESET (...) */
2155 ATExecSetRelOptions(rel, (List *) cmd->def, true);
2158 case AT_EnableTrig: /* ENABLE TRIGGER name */
2159 ATExecEnableDisableTrigger(rel, cmd->name,
2160 TRIGGER_FIRES_ON_ORIGIN, false);
2162 case AT_EnableAlwaysTrig: /* ENABLE ALWAYS TRIGGER name */
2163 ATExecEnableDisableTrigger(rel, cmd->name,
2164 TRIGGER_FIRES_ALWAYS, false);
2166 case AT_EnableReplicaTrig: /* ENABLE REPLICA TRIGGER name */
2167 ATExecEnableDisableTrigger(rel, cmd->name,
2168 TRIGGER_FIRES_ON_REPLICA, false);
2170 case AT_DisableTrig: /* DISABLE TRIGGER name */
2171 ATExecEnableDisableTrigger(rel, cmd->name,
2172 TRIGGER_DISABLED, false);
2174 case AT_EnableTrigAll: /* ENABLE TRIGGER ALL */
2175 ATExecEnableDisableTrigger(rel, NULL,
2176 TRIGGER_FIRES_ON_ORIGIN, false);
2178 case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
2179 ATExecEnableDisableTrigger(rel, NULL,
2180 TRIGGER_DISABLED, false);
2182 case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
2183 ATExecEnableDisableTrigger(rel, NULL,
2184 TRIGGER_FIRES_ON_ORIGIN, true);
2186 case AT_DisableTrigUser: /* DISABLE TRIGGER USER */
2187 ATExecEnableDisableTrigger(rel, NULL,
2188 TRIGGER_DISABLED, true);
2191 case AT_EnableRule: /* ENABLE RULE name */
2192 ATExecEnableDisableRule(rel, cmd->name,
2193 RULE_FIRES_ON_ORIGIN);
2195 case AT_EnableAlwaysRule: /* ENABLE ALWAYS RULE name */
2196 ATExecEnableDisableRule(rel, cmd->name,
2199 case AT_EnableReplicaRule: /* ENABLE REPLICA RULE name */
2200 ATExecEnableDisableRule(rel, cmd->name,
2201 RULE_FIRES_ON_REPLICA);
2203 case AT_DisableRule: /* DISABLE RULE name */
2204 ATExecEnableDisableRule(rel, cmd->name,
2209 ATExecAddInherit(rel, (RangeVar *) cmd->def);
2211 case AT_DropInherit:
2212 ATExecDropInherit(rel, (RangeVar *) cmd->def);
2215 elog(ERROR, "unrecognized alter table type: %d",
2216 (int) cmd->subtype);
2221 * Bump the command counter to ensure the next subcommand in the sequence
2222 * can see the changes so far
2224 CommandCounterIncrement();
2228 * ATRewriteTables: ALTER TABLE phase 3
2231 ATRewriteTables(List **wqueue)
2235 /* Go through each table that needs to be checked or rewritten */
2236 foreach(ltab, *wqueue)
2238 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2241 * We only need to rewrite the table if at least one column needs to
2244 if (tab->newvals != NIL)
2246 /* Build a temporary relation and copy data */
2248 char NewHeapName[NAMEDATALEN];
2251 ObjectAddress object;
2253 OldHeap = heap_open(tab->relid, NoLock);
2256 * We can never allow rewriting of shared or nailed-in-cache
2257 * relations, because we can't support changing their relfilenode
2260 if (OldHeap->rd_rel->relisshared || OldHeap->rd_isnailed)
2262 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2263 errmsg("cannot rewrite system relation \"%s\"",
2264 RelationGetRelationName(OldHeap))));
2267 * Don't allow rewrite on temp tables of other backends ... their
2268 * local buffer manager is not going to cope.
2270 if (isOtherTempNamespace(RelationGetNamespace(OldHeap)))
2272 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2273 errmsg("cannot rewrite temporary tables of other sessions")));
2276 * Select destination tablespace (same as original unless user
2277 * requested a change)
2279 if (tab->newTableSpace)
2280 NewTableSpace = tab->newTableSpace;
2282 NewTableSpace = OldHeap->rd_rel->reltablespace;
2284 heap_close(OldHeap, NoLock);
2287 * Create the new heap, using a temporary name in the same
2288 * namespace as the existing table. NOTE: there is some risk of
2289 * collision with user relnames. Working around this seems more
2290 * trouble than it's worth; in particular, we can't create the new
2291 * heap in a different namespace from the old, or we will have
2292 * problems with the TEMP status of temp tables.
2294 snprintf(NewHeapName, sizeof(NewHeapName),
2295 "pg_temp_%u", tab->relid);
2297 OIDNewHeap = make_new_heap(tab->relid, NewHeapName, NewTableSpace);
2300 * Copy the heap data into the new table with the desired
2301 * modifications, and test the current data within the table
2302 * against new constraints generated by ALTER TABLE commands.
2304 ATRewriteTable(tab, OIDNewHeap);
2307 * Swap the physical files of the old and new heaps. Since we are
2308 * generating a new heap, we can use RecentXmin for the table's new
2309 * relfrozenxid because we rewrote all the tuples on
2310 * ATRewriteTable, so no older Xid remains on the table.
2312 swap_relation_files(tab->relid, OIDNewHeap, RecentXmin);
2314 CommandCounterIncrement();
2316 /* Destroy new heap with old filenode */
2317 object.classId = RelationRelationId;
2318 object.objectId = OIDNewHeap;
2319 object.objectSubId = 0;
2322 * The new relation is local to our transaction and we know
2323 * nothing depends on it, so DROP_RESTRICT should be OK.
2325 performDeletion(&object, DROP_RESTRICT);
2326 /* performDeletion does CommandCounterIncrement at end */
2329 * Rebuild each index on the relation (but not the toast table,
2330 * which is all-new anyway). We do not need
2331 * CommandCounterIncrement() because reindex_relation does it.
2333 reindex_relation(tab->relid, false);
2338 * Test the current data within the table against new constraints
2339 * generated by ALTER TABLE commands, but don't rebuild data.
2341 if (tab->constraints != NIL || tab->new_notnull)
2342 ATRewriteTable(tab, InvalidOid);
2345 * If we had SET TABLESPACE but no reason to reconstruct tuples,
2346 * just do a block-by-block copy.
2348 if (tab->newTableSpace)
2349 ATExecSetTableSpace(tab->relid, tab->newTableSpace);
2354 * Foreign key constraints are checked in a final pass, since (a) it's
2355 * generally best to examine each one separately, and (b) it's at least
2356 * theoretically possible that we have changed both relations of the
2357 * foreign key, and we'd better have finished both rewrites before we try
2358 * to read the tables.
2360 foreach(ltab, *wqueue)
2362 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2363 Relation rel = NULL;
2366 foreach(lcon, tab->constraints)
2368 NewConstraint *con = lfirst(lcon);
2370 if (con->contype == CONSTR_FOREIGN)
2372 FkConstraint *fkconstraint = (FkConstraint *) con->qual;
2377 /* Long since locked, no need for another */
2378 rel = heap_open(tab->relid, NoLock);
2381 refrel = heap_open(con->refrelid, RowShareLock);
2383 validateForeignKeyConstraint(fkconstraint, rel, refrel,
2386 heap_close(refrel, NoLock);
2391 heap_close(rel, NoLock);
2396 * ATRewriteTable: scan or rewrite one table
2398 * OIDNewHeap is InvalidOid if we don't need to rewrite
2401 ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap)
2405 TupleDesc oldTupDesc;
2406 TupleDesc newTupDesc;
2407 bool needscan = false;
2408 List *notnull_attrs;
2414 * Open the relation(s). We have surely already locked the existing
2417 oldrel = heap_open(tab->relid, NoLock);
2418 oldTupDesc = tab->oldDesc;
2419 newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
2421 if (OidIsValid(OIDNewHeap))
2422 newrel = heap_open(OIDNewHeap, AccessExclusiveLock);
2427 * If we need to rewrite the table, the operation has to be propagated to
2428 * tables that use this table's rowtype as a column type.
2430 * (Eventually this will probably become true for scans as well, but at
2431 * the moment a composite type does not enforce any constraints, so it's
2432 * not necessary/appropriate to enforce them just during ALTER.)
2435 find_composite_type_dependencies(oldrel->rd_rel->reltype,
2436 RelationGetRelationName(oldrel),
2440 * Generate the constraint and default execution states
2443 estate = CreateExecutorState();
2445 /* Build the needed expression execution states */
2446 foreach(l, tab->constraints)
2448 NewConstraint *con = lfirst(l);
2450 switch (con->contype)
2454 con->qualstate = (List *)
2455 ExecPrepareExpr((Expr *) con->qual, estate);
2457 case CONSTR_FOREIGN:
2458 /* Nothing to do here */
2461 elog(ERROR, "unrecognized constraint type: %d",
2462 (int) con->contype);
2466 foreach(l, tab->newvals)
2468 NewColumnValue *ex = lfirst(l);
2472 ex->exprstate = ExecPrepareExpr((Expr *) ex->expr, estate);
2475 notnull_attrs = NIL;
2476 if (newrel || tab->new_notnull)
2479 * If we are rebuilding the tuples OR if we added any new NOT NULL
2480 * constraints, check all not-null constraints. This is a bit of
2481 * overkill but it minimizes risk of bugs, and heap_attisnull is a
2482 * pretty cheap test anyway.
2484 for (i = 0; i < newTupDesc->natts; i++)
2486 if (newTupDesc->attrs[i]->attnotnull &&
2487 !newTupDesc->attrs[i]->attisdropped)
2488 notnull_attrs = lappend_int(notnull_attrs, i);
2496 ExprContext *econtext;
2499 TupleTableSlot *oldslot;
2500 TupleTableSlot *newslot;
2503 MemoryContext oldCxt;
2504 List *dropped_attrs = NIL;
2507 econtext = GetPerTupleExprContext(estate);
2510 * Make tuple slots for old and new tuples. Note that even when the
2511 * tuples are the same, the tupDescs might not be (consider ADD COLUMN
2512 * without a default).
2514 oldslot = MakeSingleTupleTableSlot(oldTupDesc);
2515 newslot = MakeSingleTupleTableSlot(newTupDesc);
2517 /* Preallocate values/isnull arrays */
2518 i = Max(newTupDesc->natts, oldTupDesc->natts);
2519 values = (Datum *) palloc(i * sizeof(Datum));
2520 isnull = (bool *) palloc(i * sizeof(bool));
2521 memset(values, 0, i * sizeof(Datum));
2522 memset(isnull, true, i * sizeof(bool));
2525 * Any attributes that are dropped according to the new tuple
2526 * descriptor can be set to NULL. We precompute the list of dropped
2527 * attributes to avoid needing to do so in the per-tuple loop.
2529 for (i = 0; i < newTupDesc->natts; i++)
2531 if (newTupDesc->attrs[i]->attisdropped)
2532 dropped_attrs = lappend_int(dropped_attrs, i);
2536 * Scan through the rows, generating a new row if needed and then
2537 * checking all the constraints.
2539 scan = heap_beginscan(oldrel, SnapshotNow, 0, NULL);
2542 * Switch to per-tuple memory context and reset it for each tuple
2543 * produced, so we don't leak memory.
2545 oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
2547 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2551 Oid tupOid = InvalidOid;
2553 /* Extract data from old tuple */
2554 heap_deform_tuple(tuple, oldTupDesc, values, isnull);
2555 if (oldTupDesc->tdhasoid)
2556 tupOid = HeapTupleGetOid(tuple);
2558 /* Set dropped attributes to null in new tuple */
2559 foreach(lc, dropped_attrs)
2560 isnull[lfirst_int(lc)] = true;
2563 * Process supplied expressions to replace selected columns.
2564 * Expression inputs come from the old tuple.
2566 ExecStoreTuple(tuple, oldslot, InvalidBuffer, false);
2567 econtext->ecxt_scantuple = oldslot;
2569 foreach(l, tab->newvals)
2571 NewColumnValue *ex = lfirst(l);
2573 values[ex->attnum - 1] = ExecEvalExpr(ex->exprstate,
2575 &isnull[ex->attnum - 1],
2580 * Form the new tuple. Note that we don't explicitly pfree it,
2581 * since the per-tuple memory context will be reset shortly.
2583 tuple = heap_form_tuple(newTupDesc, values, isnull);
2585 /* Preserve OID, if any */
2586 if (newTupDesc->tdhasoid)
2587 HeapTupleSetOid(tuple, tupOid);
2590 /* Now check any constraints on the possibly-changed tuple */
2591 ExecStoreTuple(tuple, newslot, InvalidBuffer, false);
2592 econtext->ecxt_scantuple = newslot;
2594 foreach(l, notnull_attrs)
2596 int attn = lfirst_int(l);
2598 if (heap_attisnull(tuple, attn + 1))
2600 (errcode(ERRCODE_NOT_NULL_VIOLATION),
2601 errmsg("column \"%s\" contains null values",
2602 NameStr(newTupDesc->attrs[attn]->attname))));
2605 foreach(l, tab->constraints)
2607 NewConstraint *con = lfirst(l);
2609 switch (con->contype)
2612 if (!ExecQual(con->qualstate, econtext, true))
2614 (errcode(ERRCODE_CHECK_VIOLATION),
2615 errmsg("check constraint \"%s\" is violated by some row",
2618 case CONSTR_FOREIGN:
2619 /* Nothing to do here */
2622 elog(ERROR, "unrecognized constraint type: %d",
2623 (int) con->contype);
2627 /* Write the tuple out to the new relation */
2629 simple_heap_insert(newrel, tuple);
2631 ResetExprContext(econtext);
2633 CHECK_FOR_INTERRUPTS();
2636 MemoryContextSwitchTo(oldCxt);
2639 ExecDropSingleTupleTableSlot(oldslot);
2640 ExecDropSingleTupleTableSlot(newslot);
2643 FreeExecutorState(estate);
2645 heap_close(oldrel, NoLock);
2647 heap_close(newrel, NoLock);
2651 * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
2653 static AlteredTableInfo *
2654 ATGetQueueEntry(List **wqueue, Relation rel)
2656 Oid relid = RelationGetRelid(rel);
2657 AlteredTableInfo *tab;
2660 foreach(ltab, *wqueue)
2662 tab = (AlteredTableInfo *) lfirst(ltab);
2663 if (tab->relid == relid)
2668 * Not there, so add it. Note that we make a copy of the relation's
2669 * existing descriptor before anything interesting can happen to it.
2671 tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
2673 tab->relkind = rel->rd_rel->relkind;
2674 tab->oldDesc = CreateTupleDescCopy(RelationGetDescr(rel));
2676 *wqueue = lappend(*wqueue, tab);
2682 * ATSimplePermissions
2684 * - Ensure that it is a relation (or possibly a view)
2685 * - Ensure this user is the owner
2686 * - Ensure that it is not a system table
2689 ATSimplePermissions(Relation rel, bool allowView)
2691 if (rel->rd_rel->relkind != RELKIND_RELATION)
2695 if (rel->rd_rel->relkind != RELKIND_VIEW)
2697 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2698 errmsg("\"%s\" is not a table or view",
2699 RelationGetRelationName(rel))));
2703 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2704 errmsg("\"%s\" is not a table",
2705 RelationGetRelationName(rel))));
2708 /* Permissions checks */
2709 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
2710 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
2711 RelationGetRelationName(rel));
2713 if (!allowSystemTableMods && IsSystemRelation(rel))
2715 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2716 errmsg("permission denied: \"%s\" is a system catalog",
2717 RelationGetRelationName(rel))));
2721 * ATSimplePermissionsRelationOrIndex
2723 * - Ensure that it is a relation or an index
2724 * - Ensure this user is the owner
2725 * - Ensure that it is not a system table
2728 ATSimplePermissionsRelationOrIndex(Relation rel)
2730 if (rel->rd_rel->relkind != RELKIND_RELATION &&
2731 rel->rd_rel->relkind != RELKIND_INDEX)
2733 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2734 errmsg("\"%s\" is not a table or index",
2735 RelationGetRelationName(rel))));
2737 /* Permissions checks */
2738 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
2739 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
2740 RelationGetRelationName(rel));
2742 if (!allowSystemTableMods && IsSystemRelation(rel))
2744 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2745 errmsg("permission denied: \"%s\" is a system catalog",
2746 RelationGetRelationName(rel))));
2752 * Simple table recursion sufficient for most ALTER TABLE operations.
2753 * All direct and indirect children are processed in an unspecified order.
2754 * Note that if a child inherits from the original table via multiple
2755 * inheritance paths, it will be visited just once.
2758 ATSimpleRecursion(List **wqueue, Relation rel,
2759 AlterTableCmd *cmd, bool recurse)
2762 * Propagate to children if desired. Non-table relations never have
2763 * children, so no need to search in that case.
2765 if (recurse && rel->rd_rel->relkind == RELKIND_RELATION)
2767 Oid relid = RelationGetRelid(rel);
2771 /* this routine is actually in the planner */
2772 children = find_all_inheritors(relid);
2775 * find_all_inheritors does the recursive search of the inheritance
2776 * hierarchy, so all we have to do is process all of the relids in the
2777 * list that it returns.
2779 foreach(child, children)
2781 Oid childrelid = lfirst_oid(child);
2784 if (childrelid == relid)
2786 childrel = relation_open(childrelid, AccessExclusiveLock);
2787 /* check for child relation in use in this session */
2788 if (childrel->rd_refcnt != 1)
2790 (errcode(ERRCODE_OBJECT_IN_USE),
2791 errmsg("relation \"%s\" is being used by active queries in this session",
2792 RelationGetRelationName(childrel))));
2793 ATPrepCmd(wqueue, childrel, cmd, false, true);
2794 relation_close(childrel, NoLock);
2800 * ATOneLevelRecursion
2802 * Here, we visit only direct inheritance children. It is expected that
2803 * the command's prep routine will recurse again to find indirect children.
2804 * When using this technique, a multiply-inheriting child will be visited
2808 ATOneLevelRecursion(List **wqueue, Relation rel,
2811 Oid relid = RelationGetRelid(rel);
2815 /* this routine is actually in the planner */
2816 children = find_inheritance_children(relid);
2818 foreach(child, children)
2820 Oid childrelid = lfirst_oid(child);
2823 childrel = relation_open(childrelid, AccessExclusiveLock);
2824 /* check for child relation in use in this session */
2825 if (childrel->rd_refcnt != 1)
2827 (errcode(ERRCODE_OBJECT_IN_USE),
2828 errmsg("relation \"%s\" is being used by active queries in this session",
2829 RelationGetRelationName(childrel))));
2830 ATPrepCmd(wqueue, childrel, cmd, true, true);
2831 relation_close(childrel, NoLock);
2837 * find_composite_type_dependencies
2839 * Check to see if a composite type is being used as a column in some
2840 * other table (possibly nested several levels deep in composite types!).
2841 * Eventually, we'd like to propagate the check or rewrite operation
2842 * into other such tables, but for now, just error out if we find any.
2844 * Caller should provide either a table name or a type name (not both) to
2845 * report in the error message, if any.
2847 * We assume that functions and views depending on the type are not reasons
2848 * to reject the ALTER. (How safe is this really?)
2851 find_composite_type_dependencies(Oid typeOid,
2852 const char *origTblName,
2853 const char *origTypeName)
2857 SysScanDesc depScan;
2862 * We scan pg_depend to find those things that depend on the rowtype. (We
2863 * assume we can ignore refobjsubid for a rowtype.)
2865 depRel = heap_open(DependRelationId, AccessShareLock);
2867 ScanKeyInit(&key[0],
2868 Anum_pg_depend_refclassid,
2869 BTEqualStrategyNumber, F_OIDEQ,
2870 ObjectIdGetDatum(TypeRelationId));
2871 ScanKeyInit(&key[1],
2872 Anum_pg_depend_refobjid,
2873 BTEqualStrategyNumber, F_OIDEQ,
2874 ObjectIdGetDatum(typeOid));
2876 depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
2877 SnapshotNow, 2, key);
2879 while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
2881 Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
2883 Form_pg_attribute att;
2885 /* Ignore dependees that aren't user columns of relations */
2886 /* (we assume system columns are never of rowtypes) */
2887 if (pg_depend->classid != RelationRelationId ||
2888 pg_depend->objsubid <= 0)
2891 rel = relation_open(pg_depend->objid, AccessShareLock);
2892 att = rel->rd_att->attrs[pg_depend->objsubid - 1];
2894 if (rel->rd_rel->relkind == RELKIND_RELATION)
2898 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2899 errmsg("cannot alter table \"%s\" because column \"%s\".\"%s\" uses its rowtype",
2901 RelationGetRelationName(rel),
2902 NameStr(att->attname))));
2905 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2906 errmsg("cannot alter type \"%s\" because column \"%s\".\"%s\" uses it",
2908 RelationGetRelationName(rel),
2909 NameStr(att->attname))));
2911 else if (OidIsValid(rel->rd_rel->reltype))
2914 * A view or composite type itself isn't a problem, but we must
2915 * recursively check for indirect dependencies via its rowtype.
2917 find_composite_type_dependencies(rel->rd_rel->reltype,
2918 origTblName, origTypeName);
2921 relation_close(rel, AccessShareLock);
2924 systable_endscan(depScan);
2926 relation_close(depRel, AccessShareLock);
2929 * If there's an array type for the rowtype, must check for uses of it,
2932 arrayOid = get_array_type(typeOid);
2933 if (OidIsValid(arrayOid))
2934 find_composite_type_dependencies(arrayOid, origTblName, origTypeName);
2939 * ALTER TABLE ADD COLUMN
2941 * Adds an additional attribute to a relation making the assumption that
2942 * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
2943 * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
2947 ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
2951 * Recurse to add the column to child classes, if requested.
2953 * We must recurse one level at a time, so that multiply-inheriting
2954 * children are visited the right number of times and end up with the
2955 * right attinhcount.
2959 AlterTableCmd *childCmd = copyObject(cmd);
2960 ColumnDef *colDefChild = (ColumnDef *) childCmd->def;
2962 /* Child should see column as singly inherited */
2963 colDefChild->inhcount = 1;
2964 colDefChild->is_local = false;
2966 ATOneLevelRecursion(wqueue, rel, childCmd);
2971 * If we are told not to recurse, there had better not be any child
2972 * tables; else the addition would put them out of step.
2974 if (find_inheritance_children(RelationGetRelid(rel)) != NIL)
2976 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2977 errmsg("column must be added to child tables too")));
2982 ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
2985 Oid myrelid = RelationGetRelid(rel);
2989 HeapTuple attributeTuple;
2990 Form_pg_attribute attribute;
2991 FormData_pg_attribute attributeD;
2995 HeapTuple typeTuple;
3001 attrdesc = heap_open(AttributeRelationId, RowExclusiveLock);
3004 * Are we adding the column to a recursion child? If so, check whether to
3005 * merge with an existing definition for the column.
3007 if (colDef->inhcount > 0)
3011 /* Does child already have a column by this name? */
3012 tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
3013 if (HeapTupleIsValid(tuple))
3015 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
3019 /* Okay if child matches by type */
3020 ctypeId = typenameTypeId(NULL, colDef->typename);
3021 ctypmod = typenameTypeMod(NULL, colDef->typename, ctypeId);
3022 if (ctypeId != childatt->atttypid ||
3023 ctypmod != childatt->atttypmod)
3025 (errcode(ERRCODE_DATATYPE_MISMATCH),
3026 errmsg("child table \"%s\" has different type for column \"%s\"",
3027 RelationGetRelationName(rel), colDef->colname)));
3029 /* Bump the existing child att's inhcount */
3030 childatt->attinhcount++;
3031 simple_heap_update(attrdesc, &tuple->t_self, tuple);
3032 CatalogUpdateIndexes(attrdesc, tuple);
3034 heap_freetuple(tuple);
3036 /* Inform the user about the merge */
3038 (errmsg("merging definition of column \"%s\" for child \"%s\"",
3039 colDef->colname, RelationGetRelationName(rel))));
3041 heap_close(attrdesc, RowExclusiveLock);
3046 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
3048 reltup = SearchSysCacheCopy(RELOID,
3049 ObjectIdGetDatum(myrelid),
3051 if (!HeapTupleIsValid(reltup))
3052 elog(ERROR, "cache lookup failed for relation %u", myrelid);
3055 * this test is deliberately not attisdropped-aware, since if one tries to
3056 * add a column matching a dropped column name, it's gonna fail anyway.
3058 if (SearchSysCacheExists(ATTNAME,
3059 ObjectIdGetDatum(myrelid),
3060 PointerGetDatum(colDef->colname),
3063 (errcode(ERRCODE_DUPLICATE_COLUMN),
3064 errmsg("column \"%s\" of relation \"%s\" already exists",
3065 colDef->colname, RelationGetRelationName(rel))));
3067 minattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts;
3068 maxatts = minattnum + 1;
3069 if (maxatts > MaxHeapAttributeNumber)
3071 (errcode(ERRCODE_TOO_MANY_COLUMNS),
3072 errmsg("tables can have at most %d columns",
3073 MaxHeapAttributeNumber)));
3076 typeTuple = typenameType(NULL, colDef->typename);
3077 tform = (Form_pg_type) GETSTRUCT(typeTuple);
3078 typeOid = HeapTupleGetOid(typeTuple);
3079 typmod = typenameTypeMod(NULL, colDef->typename, typeOid);
3081 /* make sure datatype is legal for a column */
3082 CheckAttributeType(colDef->colname, typeOid);
3084 attributeTuple = heap_addheader(Natts_pg_attribute,
3086 ATTRIBUTE_TUPLE_SIZE,
3087 (void *) &attributeD);
3089 attribute = (Form_pg_attribute) GETSTRUCT(attributeTuple);
3091 attribute->attrelid = myrelid;
3092 namestrcpy(&(attribute->attname), colDef->colname);
3093 attribute->atttypid = typeOid;
3094 attribute->attstattarget = -1;
3095 attribute->attlen = tform->typlen;
3096 attribute->attcacheoff = -1;
3097 attribute->atttypmod = typmod;
3098 attribute->attnum = i;
3099 attribute->attbyval = tform->typbyval;
3100 attribute->attndims = list_length(colDef->typename->arrayBounds);
3101 attribute->attstorage = tform->typstorage;
3102 attribute->attalign = tform->typalign;
3103 attribute->attnotnull = colDef->is_not_null;
3104 attribute->atthasdef = false;
3105 attribute->attisdropped = false;
3106 attribute->attislocal = colDef->is_local;
3107 attribute->attinhcount = colDef->inhcount;
3109 ReleaseSysCache(typeTuple);
3111 simple_heap_insert(attrdesc, attributeTuple);
3113 /* Update indexes on pg_attribute */
3114 CatalogUpdateIndexes(attrdesc, attributeTuple);
3116 heap_close(attrdesc, RowExclusiveLock);
3119 * Update number of attributes in pg_class tuple
3121 ((Form_pg_class) GETSTRUCT(reltup))->relnatts = maxatts;
3123 simple_heap_update(pgclass, &reltup->t_self, reltup);
3125 /* keep catalog indexes current */
3126 CatalogUpdateIndexes(pgclass, reltup);
3128 heap_freetuple(reltup);
3130 heap_close(pgclass, RowExclusiveLock);
3132 /* Make the attribute's catalog entry visible */
3133 CommandCounterIncrement();
3136 * Store the DEFAULT, if any, in the catalogs
3138 if (colDef->raw_default)
3140 RawColumnDefault *rawEnt;
3142 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3143 rawEnt->attnum = attribute->attnum;
3144 rawEnt->raw_default = copyObject(colDef->raw_default);
3147 * This function is intended for CREATE TABLE, so it processes a
3148 * _list_ of defaults, but we just do one.
3150 AddRelationRawConstraints(rel, list_make1(rawEnt), NIL);
3152 /* Make the additional catalog changes visible */
3153 CommandCounterIncrement();
3157 * Tell Phase 3 to fill in the default expression, if there is one.
3159 * If there is no default, Phase 3 doesn't have to do anything, because
3160 * that effectively means that the default is NULL. The heap tuple access
3161 * routines always check for attnum > # of attributes in tuple, and return
3162 * NULL if so, so without any modification of the tuple data we will get
3163 * the effect of NULL values in the new column.
3165 * An exception occurs when the new column is of a domain type: the domain
3166 * might have a NOT NULL constraint, or a check constraint that indirectly
3167 * rejects nulls. If there are any domain constraints then we construct
3168 * an explicit NULL default value that will be passed through
3169 * CoerceToDomain processing. (This is a tad inefficient, since it causes
3170 * rewriting the table which we really don't have to do, but the present
3171 * design of domain processing doesn't offer any simple way of checking
3172 * the constraints more directly.)
3174 * Note: we use build_column_default, and not just the cooked default
3175 * returned by AddRelationRawConstraints, so that the right thing happens
3176 * when a datatype's default applies.
3178 defval = (Expr *) build_column_default(rel, attribute->attnum);
3180 if (!defval && GetDomainConstraints(typeOid) != NIL)
3182 Oid basetype = getBaseType(typeOid);
3184 defval = (Expr *) makeNullConst(basetype);
3185 defval = (Expr *) coerce_to_target_type(NULL,
3190 COERCION_ASSIGNMENT,
3191 COERCE_IMPLICIT_CAST);
3192 if (defval == NULL) /* should not happen */
3193 elog(ERROR, "failed to coerce base type to domain");
3198 NewColumnValue *newval;
3200 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
3201 newval->attnum = attribute->attnum;
3202 newval->expr = defval;
3204 tab->newvals = lappend(tab->newvals, newval);
3208 * Add needed dependency entries for the new column.
3210 add_column_datatype_dependency(myrelid, i, attribute->atttypid);
3214 * Install a column's dependency on its datatype.
3217 add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
3219 ObjectAddress myself,
3222 myself.classId = RelationRelationId;
3223 myself.objectId = relid;
3224 myself.objectSubId = attnum;
3225 referenced.classId = TypeRelationId;
3226 referenced.objectId = typid;
3227 referenced.objectSubId = 0;
3228 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
3232 * ALTER TABLE ALTER COLUMN DROP NOT NULL
3235 ATExecDropNotNull(Relation rel, const char *colName)
3241 ListCell *indexoidscan;
3244 * lookup the attribute
3246 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3248 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3250 if (!HeapTupleIsValid(tuple))
3252 (errcode(ERRCODE_UNDEFINED_COLUMN),
3253 errmsg("column \"%s\" of relation \"%s\" does not exist",
3254 colName, RelationGetRelationName(rel))));
3256 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3258 /* Prevent them from altering a system attribute */
3261 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3262 errmsg("cannot alter system column \"%s\"",
3266 * Check that the attribute is not in a primary key
3269 /* Loop over all indexes on the relation */
3270 indexoidlist = RelationGetIndexList(rel);
3272 foreach(indexoidscan, indexoidlist)
3274 Oid indexoid = lfirst_oid(indexoidscan);
3275 HeapTuple indexTuple;
3276 Form_pg_index indexStruct;
3279 indexTuple = SearchSysCache(INDEXRELID,
3280 ObjectIdGetDatum(indexoid),
3282 if (!HeapTupleIsValid(indexTuple))
3283 elog(ERROR, "cache lookup failed for index %u", indexoid);
3284 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
3286 /* If the index is not a primary key, skip the check */
3287 if (indexStruct->indisprimary)
3290 * Loop over each attribute in the primary key and see if it
3291 * matches the to-be-altered attribute
3293 for (i = 0; i < indexStruct->indnatts; i++)
3295 if (indexStruct->indkey.values[i] == attnum)
3297 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3298 errmsg("column \"%s\" is in a primary key",
3303 ReleaseSysCache(indexTuple);
3306 list_free(indexoidlist);
3309 * Okay, actually perform the catalog change ... if needed
3311 if (((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3313 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = FALSE;
3315 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3317 /* keep the system catalog indexes current */
3318 CatalogUpdateIndexes(attr_rel, tuple);
3321 heap_close(attr_rel, RowExclusiveLock);
3325 * ALTER TABLE ALTER COLUMN SET NOT NULL
3328 ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
3329 const char *colName)
3336 * lookup the attribute
3338 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3340 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3342 if (!HeapTupleIsValid(tuple))
3344 (errcode(ERRCODE_UNDEFINED_COLUMN),
3345 errmsg("column \"%s\" of relation \"%s\" does not exist",
3346 colName, RelationGetRelationName(rel))));
3348 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3350 /* Prevent them from altering a system attribute */
3353 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3354 errmsg("cannot alter system column \"%s\"",
3358 * Okay, actually perform the catalog change ... if needed
3360 if (!((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3362 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = TRUE;
3364 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3366 /* keep the system catalog indexes current */
3367 CatalogUpdateIndexes(attr_rel, tuple);
3369 /* Tell Phase 3 it needs to test the constraint */
3370 tab->new_notnull = true;
3373 heap_close(attr_rel, RowExclusiveLock);
3377 * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
3380 ATExecColumnDefault(Relation rel, const char *colName,
3386 * get the number of the attribute
3388 attnum = get_attnum(RelationGetRelid(rel), colName);
3389 if (attnum == InvalidAttrNumber)
3391 (errcode(ERRCODE_UNDEFINED_COLUMN),
3392 errmsg("column \"%s\" of relation \"%s\" does not exist",
3393 colName, RelationGetRelationName(rel))));
3395 /* Prevent them from altering a system attribute */
3398 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3399 errmsg("cannot alter system column \"%s\"",
3403 * Remove any old default for the column. We use RESTRICT here for
3404 * safety, but at present we do not expect anything to depend on the
3407 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false);
3412 RawColumnDefault *rawEnt;
3414 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3415 rawEnt->attnum = attnum;
3416 rawEnt->raw_default = newDefault;
3419 * This function is intended for CREATE TABLE, so it processes a
3420 * _list_ of defaults, but we just do one.
3422 AddRelationRawConstraints(rel, list_make1(rawEnt), NIL);
3427 * ALTER TABLE ALTER COLUMN SET STATISTICS
3430 ATPrepSetStatistics(Relation rel, const char *colName, Node *flagValue)
3433 * We do our own permission checking because (a) we want to allow SET
3434 * STATISTICS on indexes (for expressional index columns), and (b) we want
3435 * to allow SET STATISTICS on system catalogs without requiring
3436 * allowSystemTableMods to be turned on.
3438 if (rel->rd_rel->relkind != RELKIND_RELATION &&
3439 rel->rd_rel->relkind != RELKIND_INDEX)
3441 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3442 errmsg("\"%s\" is not a table or index",
3443 RelationGetRelationName(rel))));
3445 /* Permissions checks */
3446 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3447 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3448 RelationGetRelationName(rel));
3452 ATExecSetStatistics(Relation rel, const char *colName, Node *newValue)
3455 Relation attrelation;
3457 Form_pg_attribute attrtuple;
3459 Assert(IsA(newValue, Integer));
3460 newtarget = intVal(newValue);
3463 * Limit target to a sane range
3468 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3469 errmsg("statistics target %d is too low",
3472 else if (newtarget > 1000)
3476 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3477 errmsg("lowering statistics target to %d",
3481 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
3483 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3485 if (!HeapTupleIsValid(tuple))
3487 (errcode(ERRCODE_UNDEFINED_COLUMN),
3488 errmsg("column \"%s\" of relation \"%s\" does not exist",
3489 colName, RelationGetRelationName(rel))));
3490 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
3492 if (attrtuple->attnum <= 0)
3494 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3495 errmsg("cannot alter system column \"%s\"",
3498 attrtuple->attstattarget = newtarget;
3500 simple_heap_update(attrelation, &tuple->t_self, tuple);
3502 /* keep system catalog indexes current */
3503 CatalogUpdateIndexes(attrelation, tuple);
3505 heap_freetuple(tuple);
3507 heap_close(attrelation, RowExclusiveLock);
3511 * ALTER TABLE ALTER COLUMN SET STORAGE
3514 ATExecSetStorage(Relation rel, const char *colName, Node *newValue)
3518 Relation attrelation;
3520 Form_pg_attribute attrtuple;
3522 Assert(IsA(newValue, String));
3523 storagemode = strVal(newValue);
3525 if (pg_strcasecmp(storagemode, "plain") == 0)
3527 else if (pg_strcasecmp(storagemode, "external") == 0)
3529 else if (pg_strcasecmp(storagemode, "extended") == 0)
3531 else if (pg_strcasecmp(storagemode, "main") == 0)
3536 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3537 errmsg("invalid storage type \"%s\"",
3539 newstorage = 0; /* keep compiler quiet */
3542 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
3544 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3546 if (!HeapTupleIsValid(tuple))
3548 (errcode(ERRCODE_UNDEFINED_COLUMN),
3549 errmsg("column \"%s\" of relation \"%s\" does not exist",
3550 colName, RelationGetRelationName(rel))));
3551 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
3553 if (attrtuple->attnum <= 0)
3555 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3556 errmsg("cannot alter system column \"%s\"",
3560 * safety check: do not allow toasted storage modes unless column datatype
3563 if (newstorage == 'p' || TypeIsToastable(attrtuple->atttypid))
3564 attrtuple->attstorage = newstorage;
3567 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3568 errmsg("column data type %s can only have storage PLAIN",
3569 format_type_be(attrtuple->atttypid))));
3571 simple_heap_update(attrelation, &tuple->t_self, tuple);
3573 /* keep system catalog indexes current */
3574 CatalogUpdateIndexes(attrelation, tuple);
3576 heap_freetuple(tuple);
3578 heap_close(attrelation, RowExclusiveLock);
3583 * ALTER TABLE DROP COLUMN
3585 * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
3586 * because we have to decide at runtime whether to recurse or not depending
3587 * on whether attinhcount goes to zero or not. (We can't check this in a
3588 * static pre-pass because it won't handle multiple inheritance situations
3589 * correctly.) Since DROP COLUMN doesn't need to create any work queue
3590 * entries for Phase 3, it's okay to recurse internally in this routine
3591 * without considering the work queue.
3594 ATExecDropColumn(Relation rel, const char *colName,
3595 DropBehavior behavior,
3596 bool recurse, bool recursing)
3599 Form_pg_attribute targetatt;
3602 ObjectAddress object;
3604 /* At top level, permission check was done in ATPrepCmd, else do it */
3606 ATSimplePermissions(rel, false);
3609 * get the number of the attribute
3611 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
3612 if (!HeapTupleIsValid(tuple))
3614 (errcode(ERRCODE_UNDEFINED_COLUMN),
3615 errmsg("column \"%s\" of relation \"%s\" does not exist",
3616 colName, RelationGetRelationName(rel))));
3617 targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
3619 attnum = targetatt->attnum;
3621 /* Can't drop a system attribute, except OID */
3622 if (attnum <= 0 && attnum != ObjectIdAttributeNumber)
3624 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3625 errmsg("cannot drop system column \"%s\"",
3628 /* Don't drop inherited columns */
3629 if (targetatt->attinhcount > 0 && !recursing)
3631 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3632 errmsg("cannot drop inherited column \"%s\"",
3635 ReleaseSysCache(tuple);
3638 * Propagate to children as appropriate. Unlike most other ALTER
3639 * routines, we have to do this one level of recursion at a time; we can't
3640 * use find_all_inheritors to do it in one pass.
3642 children = find_inheritance_children(RelationGetRelid(rel));
3649 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3650 foreach(child, children)
3652 Oid childrelid = lfirst_oid(child);
3654 Form_pg_attribute childatt;
3656 childrel = heap_open(childrelid, AccessExclusiveLock);
3657 /* check for child relation in use in this session */
3658 if (childrel->rd_refcnt != 1)
3660 (errcode(ERRCODE_OBJECT_IN_USE),
3661 errmsg("relation \"%s\" is being used by active queries in this session",
3662 RelationGetRelationName(childrel))));
3664 tuple = SearchSysCacheCopyAttName(childrelid, colName);
3665 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
3666 elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
3667 colName, childrelid);
3668 childatt = (Form_pg_attribute) GETSTRUCT(tuple);
3670 if (childatt->attinhcount <= 0) /* shouldn't happen */
3671 elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
3672 childrelid, colName);
3677 * If the child column has other definition sources, just
3678 * decrement its inheritance count; if not, recurse to delete
3681 if (childatt->attinhcount == 1 && !childatt->attislocal)
3683 /* Time to delete this child column, too */
3684 ATExecDropColumn(childrel, colName, behavior, true, true);
3688 /* Child column must survive my deletion */
3689 childatt->attinhcount--;
3691 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3693 /* keep the system catalog indexes current */
3694 CatalogUpdateIndexes(attr_rel, tuple);
3696 /* Make update visible */
3697 CommandCounterIncrement();
3703 * If we were told to drop ONLY in this table (no recursion),
3704 * we need to mark the inheritors' attribute as locally
3705 * defined rather than inherited.
3707 childatt->attinhcount--;
3708 childatt->attislocal = true;
3710 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3712 /* keep the system catalog indexes current */
3713 CatalogUpdateIndexes(attr_rel, tuple);
3715 /* Make update visible */
3716 CommandCounterIncrement();
3719 heap_freetuple(tuple);
3721 heap_close(childrel, NoLock);
3723 heap_close(attr_rel, RowExclusiveLock);
3727 * Perform the actual column deletion
3729 object.classId = RelationRelationId;
3730 object.objectId = RelationGetRelid(rel);
3731 object.objectSubId = attnum;
3733 performDeletion(&object, behavior);
3736 * If we dropped the OID column, must adjust pg_class.relhasoids
3738 if (attnum == ObjectIdAttributeNumber)
3741 Form_pg_class tuple_class;
3743 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
3745 tuple = SearchSysCacheCopy(RELOID,
3746 ObjectIdGetDatum(RelationGetRelid(rel)),
3748 if (!HeapTupleIsValid(tuple))
3749 elog(ERROR, "cache lookup failed for relation %u",
3750 RelationGetRelid(rel));
3751 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
3753 tuple_class->relhasoids = false;
3754 simple_heap_update(class_rel, &tuple->t_self, tuple);
3756 /* Keep the catalog indexes up to date */
3757 CatalogUpdateIndexes(class_rel, tuple);
3759 heap_close(class_rel, RowExclusiveLock);
3764 * ALTER TABLE ADD INDEX
3766 * There is no such command in the grammar, but parse_utilcmd.c converts
3767 * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands. This lets
3768 * us schedule creation of the index at the appropriate time during ALTER.
3771 ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
3772 IndexStmt *stmt, bool is_rebuild)
3778 Assert(IsA(stmt, IndexStmt));
3780 /* suppress schema rights check when rebuilding existing index */
3781 check_rights = !is_rebuild;
3782 /* skip index build if phase 3 will have to rewrite table anyway */
3783 skip_build = (tab->newvals != NIL);
3784 /* suppress notices when rebuilding existing index */
3787 /* The IndexStmt has already been through transformIndexStmt */
3789 DefineIndex(stmt->relation, /* relation */
3790 stmt->idxname, /* index name */
3791 InvalidOid, /* no predefined OID */
3792 stmt->accessMethod, /* am name */
3794 stmt->indexParams, /* parameters */
3795 (Expr *) stmt->whereClause,
3801 true, /* is_alter_table */
3809 * ALTER TABLE ADD CONSTRAINT
3812 ATExecAddConstraint(AlteredTableInfo *tab, Relation rel, Node *newConstraint)
3814 switch (nodeTag(newConstraint))
3818 Constraint *constr = (Constraint *) newConstraint;
3821 * Currently, we only expect to see CONSTR_CHECK nodes
3822 * arriving here (see the preprocessing done in
3823 * parse_utilcmd.c). Use a switch anyway to make it easier
3824 * to add more code later.
3826 switch (constr->contype)
3834 * Call AddRelationRawConstraints to do the work.
3835 * It returns a list of cooked constraints.
3837 newcons = AddRelationRawConstraints(rel, NIL,
3838 list_make1(constr));
3839 /* Add each constraint to Phase 3's queue */
3840 foreach(lcon, newcons)
3842 CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
3843 NewConstraint *newcon;
3845 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
3846 newcon->name = ccon->name;
3847 newcon->contype = ccon->contype;
3848 /* ExecQual wants implicit-AND format */
3849 newcon->qual = (Node *)
3850 make_ands_implicit((Expr *) ccon->expr);
3852 tab->constraints = lappend(tab->constraints,
3858 elog(ERROR, "unrecognized constraint type: %d",
3859 (int) constr->contype);
3863 case T_FkConstraint:
3865 FkConstraint *fkconstraint = (FkConstraint *) newConstraint;
3868 * Assign or validate constraint name
3870 if (fkconstraint->constr_name)
3872 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
3873 RelationGetRelid(rel),
3874 RelationGetNamespace(rel),
3875 fkconstraint->constr_name))
3877 (errcode(ERRCODE_DUPLICATE_OBJECT),
3878 errmsg("constraint \"%s\" for relation \"%s\" already exists",
3879 fkconstraint->constr_name,
3880 RelationGetRelationName(rel))));
3883 fkconstraint->constr_name =
3884 ChooseConstraintName(RelationGetRelationName(rel),
3885 strVal(linitial(fkconstraint->fk_attrs)),
3887 RelationGetNamespace(rel),
3890 ATAddForeignKeyConstraint(tab, rel, fkconstraint);
3895 elog(ERROR, "unrecognized node type: %d",
3896 (int) nodeTag(newConstraint));
3901 * Add a foreign-key constraint to a single table
3903 * Subroutine for ATExecAddConstraint. Must already hold exclusive
3904 * lock on the rel, and have done appropriate validity/permissions checks
3908 ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
3909 FkConstraint *fkconstraint)
3912 AclResult aclresult;
3913 int16 pkattnum[INDEX_MAX_KEYS];
3914 int16 fkattnum[INDEX_MAX_KEYS];
3915 Oid pktypoid[INDEX_MAX_KEYS];
3916 Oid fktypoid[INDEX_MAX_KEYS];
3917 Oid opclasses[INDEX_MAX_KEYS];
3918 Oid pfeqoperators[INDEX_MAX_KEYS];
3919 Oid ppeqoperators[INDEX_MAX_KEYS];
3920 Oid ffeqoperators[INDEX_MAX_KEYS];
3928 * Grab an exclusive lock on the pk table, so that someone doesn't delete
3929 * rows out from under us. (Although a lesser lock would do for that
3930 * purpose, we'll need exclusive lock anyway to add triggers to the pk
3931 * table; trying to start with a lesser lock will just create a risk of
3934 pkrel = heap_openrv(fkconstraint->pktable, AccessExclusiveLock);
3937 * Validity and permissions checks
3939 * Note: REFERENCES permissions checks are redundant with CREATE TRIGGER,
3940 * but we may as well error out sooner instead of later.
3942 if (pkrel->rd_rel->relkind != RELKIND_RELATION)
3944 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3945 errmsg("referenced relation \"%s\" is not a table",
3946 RelationGetRelationName(pkrel))));
3948 aclresult = pg_class_aclcheck(RelationGetRelid(pkrel), GetUserId(),
3950 if (aclresult != ACLCHECK_OK)
3951 aclcheck_error(aclresult, ACL_KIND_CLASS,
3952 RelationGetRelationName(pkrel));
3954 if (!allowSystemTableMods && IsSystemRelation(pkrel))
3956 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3957 errmsg("permission denied: \"%s\" is a system catalog",
3958 RelationGetRelationName(pkrel))));
3960 aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
3962 if (aclresult != ACLCHECK_OK)
3963 aclcheck_error(aclresult, ACL_KIND_CLASS,
3964 RelationGetRelationName(rel));
3967 * Disallow reference from permanent table to temp table or vice versa.
3968 * (The ban on perm->temp is for fairly obvious reasons. The ban on
3969 * temp->perm is because other backends might need to run the RI triggers
3970 * on the perm table, but they can't reliably see tuples the owning
3971 * backend has created in the temp table, because non-shared buffers are
3972 * used for temp tables.)
3974 if (isTempNamespace(RelationGetNamespace(pkrel)))
3976 if (!isTempNamespace(RelationGetNamespace(rel)))
3978 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3979 errmsg("cannot reference temporary table from permanent table constraint")));
3983 if (isTempNamespace(RelationGetNamespace(rel)))
3985 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3986 errmsg("cannot reference permanent table from temporary table constraint")));
3990 * Look up the referencing attributes to make sure they exist, and record
3991 * their attnums and type OIDs.
3993 MemSet(pkattnum, 0, sizeof(pkattnum));
3994 MemSet(fkattnum, 0, sizeof(fkattnum));
3995 MemSet(pktypoid, 0, sizeof(pktypoid));
3996 MemSet(fktypoid, 0, sizeof(fktypoid));
3997 MemSet(opclasses, 0, sizeof(opclasses));
3998 MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
3999 MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
4000 MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
4002 numfks = transformColumnNameList(RelationGetRelid(rel),
4003 fkconstraint->fk_attrs,
4004 fkattnum, fktypoid);
4007 * If the attribute list for the referenced table was omitted, lookup the
4008 * definition of the primary key and use it. Otherwise, validate the
4009 * supplied attribute list. In either case, discover the index OID and
4010 * index opclasses, and the attnums and type OIDs of the attributes.
4012 if (fkconstraint->pk_attrs == NIL)
4014 numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
4015 &fkconstraint->pk_attrs,
4021 numpks = transformColumnNameList(RelationGetRelid(pkrel),
4022 fkconstraint->pk_attrs,
4023 pkattnum, pktypoid);
4024 /* Look for an index matching the column list */
4025 indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
4030 * Look up the equality operators to use in the constraint.
4032 * Note that we have to be careful about the difference between the actual
4033 * PK column type and the opclass' declared input type, which might be
4034 * only binary-compatible with it. The declared opcintype is the right
4035 * thing to probe pg_amop with.
4037 if (numfks != numpks)
4039 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4040 errmsg("number of referencing and referenced columns for foreign key disagree")));
4042 for (i = 0; i < numpks; i++)
4044 Oid pktype = pktypoid[i];
4045 Oid fktype = fktypoid[i];
4048 Form_pg_opclass cla_tup;
4057 /* We need several fields out of the pg_opclass entry */
4058 cla_ht = SearchSysCache(CLAOID,
4059 ObjectIdGetDatum(opclasses[i]),
4061 if (!HeapTupleIsValid(cla_ht))
4062 elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
4063 cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
4064 amid = cla_tup->opcmethod;
4065 opfamily = cla_tup->opcfamily;
4066 opcintype = cla_tup->opcintype;
4067 ReleaseSysCache(cla_ht);
4070 * Check it's a btree; currently this can never fail since no other
4071 * index AMs support unique indexes. If we ever did have other
4072 * types of unique indexes, we'd need a way to determine which
4073 * operator strategy number is equality. (Is it reasonable to
4074 * insist that every such index AM use btree's number for equality?)
4076 if (amid != BTREE_AM_OID)
4077 elog(ERROR, "only b-tree indexes are supported for foreign keys");
4078 eqstrategy = BTEqualStrategyNumber;
4081 * There had better be a primary equality operator for the index.
4082 * We'll use it for PK = PK comparisons.
4084 ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
4087 if (!OidIsValid(ppeqop))
4088 elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
4089 eqstrategy, opcintype, opcintype, opfamily);
4092 * Are there equality operators that take exactly the FK type?
4093 * Assume we should look through any domain here.
4095 fktyped = getBaseType(fktype);
4097 pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
4099 if (OidIsValid(pfeqop))
4100 ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
4103 ffeqop = InvalidOid; /* keep compiler quiet */
4105 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4108 * Otherwise, look for an implicit cast from the FK type to
4109 * the opcintype, and if found, use the primary equality operator.
4110 * This is a bit tricky because opcintype might be a generic type
4111 * such as ANYARRAY, and so what we have to test is whether the
4112 * two actual column types can be concurrently cast to that type.
4113 * (Otherwise, we'd fail to reject combinations such as int[] and
4116 Oid input_typeids[2];
4117 Oid target_typeids[2];
4119 input_typeids[0] = pktype;
4120 input_typeids[1] = fktype;
4121 target_typeids[0] = opcintype;
4122 target_typeids[1] = opcintype;
4123 if (can_coerce_type(2, input_typeids, target_typeids,
4125 pfeqop = ffeqop = ppeqop;
4128 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4130 (errcode(ERRCODE_DATATYPE_MISMATCH),
4131 errmsg("foreign key constraint \"%s\" "
4132 "cannot be implemented",
4133 fkconstraint->constr_name),
4134 errdetail("Key columns \"%s\" and \"%s\" "
4135 "are of incompatible types: %s and %s.",
4136 strVal(list_nth(fkconstraint->fk_attrs, i)),
4137 strVal(list_nth(fkconstraint->pk_attrs, i)),
4138 format_type_be(fktype),
4139 format_type_be(pktype))));
4141 pfeqoperators[i] = pfeqop;
4142 ppeqoperators[i] = ppeqop;
4143 ffeqoperators[i] = ffeqop;
4147 * Record the FK constraint in pg_constraint.
4149 constrOid = CreateConstraintEntry(fkconstraint->constr_name,
4150 RelationGetNamespace(rel),
4152 fkconstraint->deferrable,
4153 fkconstraint->initdeferred,
4154 RelationGetRelid(rel),
4157 InvalidOid, /* not a domain
4159 RelationGetRelid(pkrel),
4165 fkconstraint->fk_upd_action,
4166 fkconstraint->fk_del_action,
4167 fkconstraint->fk_matchtype,
4169 NULL, /* no check constraint */
4174 * Create the triggers that will enforce the constraint.
4176 createForeignKeyTriggers(rel, fkconstraint, constrOid);
4179 * Tell Phase 3 to check that the constraint is satisfied by existing rows
4180 * (we can skip this during table creation).
4182 if (!fkconstraint->skip_validation)
4184 NewConstraint *newcon;
4186 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
4187 newcon->name = fkconstraint->constr_name;
4188 newcon->contype = CONSTR_FOREIGN;
4189 newcon->refrelid = RelationGetRelid(pkrel);
4190 newcon->conid = constrOid;
4191 newcon->qual = (Node *) fkconstraint;
4193 tab->constraints = lappend(tab->constraints, newcon);
4197 * Close pk table, but keep lock until we've committed.
4199 heap_close(pkrel, NoLock);
4204 * transformColumnNameList - transform list of column names
4206 * Lookup each name and return its attnum and type OID
4209 transformColumnNameList(Oid relId, List *colList,
4210 int16 *attnums, Oid *atttypids)
4218 char *attname = strVal(lfirst(l));
4221 atttuple = SearchSysCacheAttName(relId, attname);
4222 if (!HeapTupleIsValid(atttuple))
4224 (errcode(ERRCODE_UNDEFINED_COLUMN),
4225 errmsg("column \"%s\" referenced in foreign key constraint does not exist",
4227 if (attnum >= INDEX_MAX_KEYS)
4229 (errcode(ERRCODE_TOO_MANY_COLUMNS),
4230 errmsg("cannot have more than %d keys in a foreign key",
4232 attnums[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->attnum;
4233 atttypids[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->atttypid;
4234 ReleaseSysCache(atttuple);
4242 * transformFkeyGetPrimaryKey -
4244 * Look up the names, attnums, and types of the primary key attributes
4245 * for the pkrel. Also return the index OID and index opclasses of the
4246 * index supporting the primary key.
4248 * All parameters except pkrel are output parameters. Also, the function
4249 * return value is the number of attributes in the primary key.
4251 * Used when the column list in the REFERENCES specification is omitted.
4254 transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
4256 int16 *attnums, Oid *atttypids,
4260 ListCell *indexoidscan;
4261 HeapTuple indexTuple = NULL;
4262 Form_pg_index indexStruct = NULL;
4263 Datum indclassDatum;
4265 oidvector *indclass;
4269 * Get the list of index OIDs for the table from the relcache, and look up
4270 * each one in the pg_index syscache until we find one marked primary key
4271 * (hopefully there isn't more than one such).
4273 *indexOid = InvalidOid;
4275 indexoidlist = RelationGetIndexList(pkrel);
4277 foreach(indexoidscan, indexoidlist)
4279 Oid indexoid = lfirst_oid(indexoidscan);
4281 indexTuple = SearchSysCache(INDEXRELID,
4282 ObjectIdGetDatum(indexoid),
4284 if (!HeapTupleIsValid(indexTuple))
4285 elog(ERROR, "cache lookup failed for index %u", indexoid);
4286 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4287 if (indexStruct->indisprimary)
4289 *indexOid = indexoid;
4292 ReleaseSysCache(indexTuple);
4295 list_free(indexoidlist);
4298 * Check that we found it
4300 if (!OidIsValid(*indexOid))
4302 (errcode(ERRCODE_UNDEFINED_OBJECT),
4303 errmsg("there is no primary key for referenced table \"%s\"",
4304 RelationGetRelationName(pkrel))));
4306 /* Must get indclass the hard way */
4307 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4308 Anum_pg_index_indclass, &isnull);
4310 indclass = (oidvector *) DatumGetPointer(indclassDatum);
4313 * Now build the list of PK attributes from the indkey definition (we
4314 * assume a primary key cannot have expressional elements)
4317 for (i = 0; i < indexStruct->indnatts; i++)
4319 int pkattno = indexStruct->indkey.values[i];
4321 attnums[i] = pkattno;
4322 atttypids[i] = attnumTypeId(pkrel, pkattno);
4323 opclasses[i] = indclass->values[i];
4324 *attnamelist = lappend(*attnamelist,
4325 makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
4328 ReleaseSysCache(indexTuple);
4334 * transformFkeyCheckAttrs -
4336 * Make sure that the attributes of a referenced table belong to a unique
4337 * (or primary key) constraint. Return the OID of the index supporting
4338 * the constraint, as well as the opclasses associated with the index
4342 transformFkeyCheckAttrs(Relation pkrel,
4343 int numattrs, int16 *attnums,
4344 Oid *opclasses) /* output parameter */
4346 Oid indexoid = InvalidOid;
4349 ListCell *indexoidscan;
4352 * Get the list of index OIDs for the table from the relcache, and look up
4353 * each one in the pg_index syscache, and match unique indexes to the list
4354 * of attnums we are given.
4356 indexoidlist = RelationGetIndexList(pkrel);
4358 foreach(indexoidscan, indexoidlist)
4360 HeapTuple indexTuple;
4361 Form_pg_index indexStruct;
4365 indexoid = lfirst_oid(indexoidscan);
4366 indexTuple = SearchSysCache(INDEXRELID,
4367 ObjectIdGetDatum(indexoid),
4369 if (!HeapTupleIsValid(indexTuple))
4370 elog(ERROR, "cache lookup failed for index %u", indexoid);
4371 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4374 * Must have the right number of columns; must be unique and not a
4375 * partial index; forget it if there are any expressions, too
4377 if (indexStruct->indnatts == numattrs &&
4378 indexStruct->indisunique &&
4379 heap_attisnull(indexTuple, Anum_pg_index_indpred) &&
4380 heap_attisnull(indexTuple, Anum_pg_index_indexprs))
4382 /* Must get indclass the hard way */
4383 Datum indclassDatum;
4385 oidvector *indclass;
4387 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4388 Anum_pg_index_indclass, &isnull);
4390 indclass = (oidvector *) DatumGetPointer(indclassDatum);
4393 * The given attnum list may match the index columns in any order.
4394 * Check that each list is a subset of the other.
4396 for (i = 0; i < numattrs; i++)
4399 for (j = 0; j < numattrs; j++)
4401 if (attnums[i] == indexStruct->indkey.values[j])
4412 for (i = 0; i < numattrs; i++)
4415 for (j = 0; j < numattrs; j++)
4417 if (attnums[j] == indexStruct->indkey.values[i])
4419 opclasses[j] = indclass->values[i];
4429 ReleaseSysCache(indexTuple);
4436 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4437 errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
4438 RelationGetRelationName(pkrel))));
4440 list_free(indexoidlist);
4446 * Scan the existing rows in a table to verify they meet a proposed FK
4449 * Caller must have opened and locked both relations.
4452 validateForeignKeyConstraint(FkConstraint *fkconstraint,
4462 * Build a trigger call structure; we'll need it either way.
4464 MemSet(&trig, 0, sizeof(trig));
4465 trig.tgoid = InvalidOid;
4466 trig.tgname = fkconstraint->constr_name;
4467 trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
4468 trig.tgisconstraint = TRUE;
4469 trig.tgconstrrelid = RelationGetRelid(pkrel);
4470 trig.tgconstraint = constraintOid;
4471 trig.tgdeferrable = FALSE;
4472 trig.tginitdeferred = FALSE;
4473 /* we needn't fill in tgargs */
4476 * See if we can do it with a single LEFT JOIN query. A FALSE result
4477 * indicates we must proceed with the fire-the-trigger method.
4479 if (RI_Initial_Check(&trig, rel, pkrel))
4483 * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
4484 * if that tuple had just been inserted. If any of those fail, it should
4485 * ereport(ERROR) and that's that.
4487 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
4489 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
4491 FunctionCallInfoData fcinfo;
4492 TriggerData trigdata;
4495 * Make a call to the trigger function
4497 * No parameters are passed, but we do set a context
4499 MemSet(&fcinfo, 0, sizeof(fcinfo));
4502 * We assume RI_FKey_check_ins won't look at flinfo...
4504 trigdata.type = T_TriggerData;
4505 trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
4506 trigdata.tg_relation = rel;
4507 trigdata.tg_trigtuple = tuple;
4508 trigdata.tg_newtuple = NULL;
4509 trigdata.tg_trigger = &trig;
4510 trigdata.tg_trigtuplebuf = scan->rs_cbuf;
4511 trigdata.tg_newtuplebuf = InvalidBuffer;
4513 fcinfo.context = (Node *) &trigdata;
4515 RI_FKey_check_ins(&fcinfo);
4522 CreateFKCheckTrigger(RangeVar *myRel, FkConstraint *fkconstraint,
4523 Oid constraintOid, bool on_insert)
4525 CreateTrigStmt *fk_trigger;
4527 fk_trigger = makeNode(CreateTrigStmt);
4528 fk_trigger->trigname = fkconstraint->constr_name;
4529 fk_trigger->relation = myRel;
4530 fk_trigger->before = false;
4531 fk_trigger->row = true;
4533 /* Either ON INSERT or ON UPDATE */
4536 fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
4537 fk_trigger->actions[0] = 'i';
4541 fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
4542 fk_trigger->actions[0] = 'u';
4544 fk_trigger->actions[1] = '\0';
4546 fk_trigger->isconstraint = true;
4547 fk_trigger->deferrable = fkconstraint->deferrable;
4548 fk_trigger->initdeferred = fkconstraint->initdeferred;
4549 fk_trigger->constrrel = fkconstraint->pktable;
4550 fk_trigger->args = NIL;
4552 (void) CreateTrigger(fk_trigger, constraintOid);
4554 /* Make changes-so-far visible */
4555 CommandCounterIncrement();
4559 * Create the triggers that implement an FK constraint.
4562 createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
4566 CreateTrigStmt *fk_trigger;
4569 * Reconstruct a RangeVar for my relation (not passed in, unfortunately).
4571 myRel = makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
4572 pstrdup(RelationGetRelationName(rel)));
4574 /* Make changes-so-far visible */
4575 CommandCounterIncrement();
4578 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the CHECK
4579 * action for both INSERTs and UPDATEs on the referencing table.
4581 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, true);
4582 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, false);
4585 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
4586 * DELETE action on the referenced table.
4588 fk_trigger = makeNode(CreateTrigStmt);
4589 fk_trigger->trigname = fkconstraint->constr_name;
4590 fk_trigger->relation = fkconstraint->pktable;
4591 fk_trigger->before = false;
4592 fk_trigger->row = true;
4593 fk_trigger->actions[0] = 'd';
4594 fk_trigger->actions[1] = '\0';
4596 fk_trigger->isconstraint = true;
4597 fk_trigger->constrrel = myRel;
4598 switch (fkconstraint->fk_del_action)
4600 case FKCONSTR_ACTION_NOACTION:
4601 fk_trigger->deferrable = fkconstraint->deferrable;
4602 fk_trigger->initdeferred = fkconstraint->initdeferred;
4603 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
4605 case FKCONSTR_ACTION_RESTRICT:
4606 fk_trigger->deferrable = false;
4607 fk_trigger->initdeferred = false;
4608 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
4610 case FKCONSTR_ACTION_CASCADE:
4611 fk_trigger->deferrable = false;
4612 fk_trigger->initdeferred = false;
4613 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
4615 case FKCONSTR_ACTION_SETNULL:
4616 fk_trigger->deferrable = false;
4617 fk_trigger->initdeferred = false;
4618 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
4620 case FKCONSTR_ACTION_SETDEFAULT:
4621 fk_trigger->deferrable = false;
4622 fk_trigger->initdeferred = false;
4623 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
4626 elog(ERROR, "unrecognized FK action type: %d",
4627 (int) fkconstraint->fk_del_action);
4630 fk_trigger->args = NIL;
4632 (void) CreateTrigger(fk_trigger, constraintOid);
4634 /* Make changes-so-far visible */
4635 CommandCounterIncrement();
4638 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
4639 * UPDATE action on the referenced table.
4641 fk_trigger = makeNode(CreateTrigStmt);
4642 fk_trigger->trigname = fkconstraint->constr_name;
4643 fk_trigger->relation = fkconstraint->pktable;
4644 fk_trigger->before = false;
4645 fk_trigger->row = true;
4646 fk_trigger->actions[0] = 'u';
4647 fk_trigger->actions[1] = '\0';
4648 fk_trigger->isconstraint = true;
4649 fk_trigger->constrrel = myRel;
4650 switch (fkconstraint->fk_upd_action)
4652 case FKCONSTR_ACTION_NOACTION:
4653 fk_trigger->deferrable = fkconstraint->deferrable;
4654 fk_trigger->initdeferred = fkconstraint->initdeferred;
4655 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
4657 case FKCONSTR_ACTION_RESTRICT:
4658 fk_trigger->deferrable = false;
4659 fk_trigger->initdeferred = false;
4660 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
4662 case FKCONSTR_ACTION_CASCADE:
4663 fk_trigger->deferrable = false;
4664 fk_trigger->initdeferred = false;
4665 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
4667 case FKCONSTR_ACTION_SETNULL:
4668 fk_trigger->deferrable = false;
4669 fk_trigger->initdeferred = false;
4670 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
4672 case FKCONSTR_ACTION_SETDEFAULT:
4673 fk_trigger->deferrable = false;
4674 fk_trigger->initdeferred = false;
4675 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
4678 elog(ERROR, "unrecognized FK action type: %d",
4679 (int) fkconstraint->fk_upd_action);
4682 fk_trigger->args = NIL;
4684 (void) CreateTrigger(fk_trigger, constraintOid);
4688 * ALTER TABLE DROP CONSTRAINT
4691 ATPrepDropConstraint(List **wqueue, Relation rel,
4692 bool recurse, AlterTableCmd *cmd)
4695 * We don't want errors or noise from child tables, so we have to pass
4696 * down a modified command.
4700 AlterTableCmd *childCmd = copyObject(cmd);
4702 childCmd->subtype = AT_DropConstraintQuietly;
4703 ATSimpleRecursion(wqueue, rel, childCmd, recurse);
4708 ATExecDropConstraint(Relation rel, const char *constrName,
4709 DropBehavior behavior, bool quiet)
4713 deleted = RemoveRelConstraints(rel, constrName, behavior);
4717 /* If zero constraints deleted, complain */
4720 (errcode(ERRCODE_UNDEFINED_OBJECT),
4721 errmsg("constraint \"%s\" does not exist",
4723 /* Otherwise if more than one constraint deleted, notify */
4724 else if (deleted > 1)
4726 (errmsg("multiple constraints named \"%s\" were dropped",
4735 ATPrepAlterColumnType(List **wqueue,
4736 AlteredTableInfo *tab, Relation rel,
4737 bool recurse, bool recursing,
4740 char *colName = cmd->name;
4741 TypeName *typename = (TypeName *) cmd->def;
4743 Form_pg_attribute attTup;
4748 NewColumnValue *newval;
4749 ParseState *pstate = make_parsestate(NULL);
4751 /* lookup the attribute so we can check inheritance status */
4752 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
4753 if (!HeapTupleIsValid(tuple))
4755 (errcode(ERRCODE_UNDEFINED_COLUMN),
4756 errmsg("column \"%s\" of relation \"%s\" does not exist",
4757 colName, RelationGetRelationName(rel))));
4758 attTup = (Form_pg_attribute) GETSTRUCT(tuple);
4759 attnum = attTup->attnum;
4761 /* Can't alter a system attribute */
4764 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4765 errmsg("cannot alter system column \"%s\"",
4768 /* Don't alter inherited columns */
4769 if (attTup->attinhcount > 0 && !recursing)
4771 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4772 errmsg("cannot alter inherited column \"%s\"",
4775 /* Look up the target type */
4776 targettype = typenameTypeId(NULL, typename);
4777 targettypmod = typenameTypeMod(NULL, typename, targettype);
4779 /* make sure datatype is legal for a column */
4780 CheckAttributeType(colName, targettype);
4783 * Set up an expression to transform the old data value to the new type.
4784 * If a USING option was given, transform and use that expression, else
4785 * just take the old value and try to coerce it. We do this first so that
4786 * type incompatibility can be detected before we waste effort, and
4787 * because we need the expression to be parsed against the original table
4794 /* Expression must be able to access vars of old table */
4795 rte = addRangeTableEntryForRelation(pstate,
4800 addRTEtoQuery(pstate, rte, false, true, true);
4802 transform = transformExpr(pstate, cmd->transform);
4804 /* It can't return a set */
4805 if (expression_returns_set(transform))
4807 (errcode(ERRCODE_DATATYPE_MISMATCH),
4808 errmsg("transform expression must not return a set")));
4810 /* No subplans or aggregates, either... */
4811 if (pstate->p_hasSubLinks)
4813 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4814 errmsg("cannot use subquery in transform expression")));
4815 if (pstate->p_hasAggs)
4817 (errcode(ERRCODE_GROUPING_ERROR),
4818 errmsg("cannot use aggregate function in transform expression")));
4822 transform = (Node *) makeVar(1, attnum,
4823 attTup->atttypid, attTup->atttypmod,
4827 transform = coerce_to_target_type(pstate,
4828 transform, exprType(transform),
4829 targettype, targettypmod,
4830 COERCION_ASSIGNMENT,
4831 COERCE_IMPLICIT_CAST);
4832 if (transform == NULL)
4834 (errcode(ERRCODE_DATATYPE_MISMATCH),
4835 errmsg("column \"%s\" cannot be cast to type \"%s\"",
4836 colName, TypeNameToString(typename))));
4839 * Add a work queue item to make ATRewriteTable update the column
4842 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
4843 newval->attnum = attnum;
4844 newval->expr = (Expr *) transform;
4846 tab->newvals = lappend(tab->newvals, newval);
4848 ReleaseSysCache(tuple);
4851 * The recursion case is handled by ATSimpleRecursion. However, if we are
4852 * told not to recurse, there had better not be any child tables; else the
4853 * alter would put them out of step.
4856 ATSimpleRecursion(wqueue, rel, cmd, recurse);
4857 else if (!recursing &&
4858 find_inheritance_children(RelationGetRelid(rel)) != NIL)
4860 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4861 errmsg("type of inherited column \"%s\" must be changed in child tables too",
4866 ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
4867 const char *colName, TypeName *typename)
4870 Form_pg_attribute attTup;
4872 HeapTuple typeTuple;
4877 Relation attrelation;
4883 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
4885 /* Look up the target column */
4886 heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4887 if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
4889 (errcode(ERRCODE_UNDEFINED_COLUMN),
4890 errmsg("column \"%s\" of relation \"%s\" does not exist",
4891 colName, RelationGetRelationName(rel))));
4892 attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
4893 attnum = attTup->attnum;
4895 /* Check for multiple ALTER TYPE on same column --- can't cope */
4896 if (attTup->atttypid != tab->oldDesc->attrs[attnum - 1]->atttypid ||
4897 attTup->atttypmod != tab->oldDesc->attrs[attnum - 1]->atttypmod)
4899 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4900 errmsg("cannot alter type of column \"%s\" twice",
4903 /* Look up the target type (should not fail, since prep found it) */
4904 typeTuple = typenameType(NULL, typename);
4905 tform = (Form_pg_type) GETSTRUCT(typeTuple);
4906 targettype = HeapTupleGetOid(typeTuple);
4907 targettypmod = typenameTypeMod(NULL, typename, targettype);
4910 * If there is a default expression for the column, get it and ensure we
4911 * can coerce it to the new datatype. (We must do this before changing
4912 * the column type, because build_column_default itself will try to
4913 * coerce, and will not issue the error message we want if it fails.)
4915 * We remove any implicit coercion steps at the top level of the old
4916 * default expression; this has been agreed to satisfy the principle of
4917 * least surprise. (The conversion to the new column type should act like
4918 * it started from what the user sees as the stored expression, and the
4919 * implicit coercions aren't going to be shown.)
4921 if (attTup->atthasdef)
4923 defaultexpr = build_column_default(rel, attnum);
4924 Assert(defaultexpr);
4925 defaultexpr = strip_implicit_coercions(defaultexpr);
4926 defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
4927 defaultexpr, exprType(defaultexpr),
4928 targettype, targettypmod,
4929 COERCION_ASSIGNMENT,
4930 COERCE_IMPLICIT_CAST);
4931 if (defaultexpr == NULL)
4933 (errcode(ERRCODE_DATATYPE_MISMATCH),
4934 errmsg("default for column \"%s\" cannot be cast to type \"%s\"",
4935 colName, TypeNameToString(typename))));
4941 * Find everything that depends on the column (constraints, indexes, etc),
4942 * and record enough information to let us recreate the objects.
4944 * The actual recreation does not happen here, but only after we have
4945 * performed all the individual ALTER TYPE operations. We have to save
4946 * the info before executing ALTER TYPE, though, else the deparser will
4949 * There could be multiple entries for the same object, so we must check
4950 * to ensure we process each one only once. Note: we assume that an index
4951 * that implements a constraint will not show a direct dependency on the
4954 depRel = heap_open(DependRelationId, RowExclusiveLock);
4956 ScanKeyInit(&key[0],
4957 Anum_pg_depend_refclassid,
4958 BTEqualStrategyNumber, F_OIDEQ,
4959 ObjectIdGetDatum(RelationRelationId));
4960 ScanKeyInit(&key[1],
4961 Anum_pg_depend_refobjid,
4962 BTEqualStrategyNumber, F_OIDEQ,
4963 ObjectIdGetDatum(RelationGetRelid(rel)));
4964 ScanKeyInit(&key[2],
4965 Anum_pg_depend_refobjsubid,
4966 BTEqualStrategyNumber, F_INT4EQ,
4967 Int32GetDatum((int32) attnum));
4969 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
4970 SnapshotNow, 3, key);
4972 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
4974 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
4975 ObjectAddress foundObject;
4977 /* We don't expect any PIN dependencies on columns */
4978 if (foundDep->deptype == DEPENDENCY_PIN)
4979 elog(ERROR, "cannot alter type of a pinned column");
4981 foundObject.classId = foundDep->classid;
4982 foundObject.objectId = foundDep->objid;
4983 foundObject.objectSubId = foundDep->objsubid;
4985 switch (getObjectClass(&foundObject))
4989 char relKind = get_rel_relkind(foundObject.objectId);
4991 if (relKind == RELKIND_INDEX)
4993 Assert(foundObject.objectSubId == 0);
4994 if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
4996 tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
4997 foundObject.objectId);
4998 tab->changedIndexDefs = lappend(tab->changedIndexDefs,
4999 pg_get_indexdef_string(foundObject.objectId));
5002 else if (relKind == RELKIND_SEQUENCE)
5005 * This must be a SERIAL column's sequence. We need
5006 * not do anything to it.
5008 Assert(foundObject.objectSubId == 0);
5012 /* Not expecting any other direct dependencies... */
5013 elog(ERROR, "unexpected object depending on column: %s",
5014 getObjectDescription(&foundObject));
5019 case OCLASS_CONSTRAINT:
5020 Assert(foundObject.objectSubId == 0);
5021 if (!list_member_oid(tab->changedConstraintOids,
5022 foundObject.objectId))
5024 char *defstring = pg_get_constraintdef_string(foundObject.objectId);
5027 * Put NORMAL dependencies at the front of the list and
5028 * AUTO dependencies at the back. This makes sure that
5029 * foreign-key constraints depending on this column will
5030 * be dropped before unique or primary-key constraints of
5031 * the column; which we must have because the FK
5032 * constraints depend on the indexes belonging to the
5033 * unique constraints.
5035 if (foundDep->deptype == DEPENDENCY_NORMAL)
5037 tab->changedConstraintOids =
5038 lcons_oid(foundObject.objectId,
5039 tab->changedConstraintOids);
5040 tab->changedConstraintDefs =
5042 tab->changedConstraintDefs);
5046 tab->changedConstraintOids =
5047 lappend_oid(tab->changedConstraintOids,
5048 foundObject.objectId);
5049 tab->changedConstraintDefs =
5050 lappend(tab->changedConstraintDefs,
5056 case OCLASS_REWRITE:
5057 /* XXX someday see if we can cope with revising views */
5059 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5060 errmsg("cannot alter type of a column used by a view or rule"),
5061 errdetail("%s depends on column \"%s\"",
5062 getObjectDescription(&foundObject),
5066 case OCLASS_DEFAULT:
5069 * Ignore the column's default expression, since we will fix
5072 Assert(defaultexpr);
5078 case OCLASS_CONVERSION:
5079 case OCLASS_LANGUAGE:
5080 case OCLASS_OPERATOR:
5081 case OCLASS_OPCLASS:
5082 case OCLASS_TRIGGER:
5086 * We don't expect any of these sorts of objects to depend on
5089 elog(ERROR, "unexpected object depending on column: %s",
5090 getObjectDescription(&foundObject));
5094 elog(ERROR, "unrecognized object class: %u",
5095 foundObject.classId);
5099 systable_endscan(scan);
5102 * Now scan for dependencies of this column on other things. The only
5103 * thing we should find is the dependency on the column datatype, which we
5106 ScanKeyInit(&key[0],
5107 Anum_pg_depend_classid,
5108 BTEqualStrategyNumber, F_OIDEQ,
5109 ObjectIdGetDatum(RelationRelationId));
5110 ScanKeyInit(&key[1],
5111 Anum_pg_depend_objid,
5112 BTEqualStrategyNumber, F_OIDEQ,
5113 ObjectIdGetDatum(RelationGetRelid(rel)));
5114 ScanKeyInit(&key[2],
5115 Anum_pg_depend_objsubid,
5116 BTEqualStrategyNumber, F_INT4EQ,
5117 Int32GetDatum((int32) attnum));
5119 scan = systable_beginscan(depRel, DependDependerIndexId, true,
5120 SnapshotNow, 3, key);
5122 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5124 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5126 if (foundDep->deptype != DEPENDENCY_NORMAL)
5127 elog(ERROR, "found unexpected dependency type '%c'",
5129 if (foundDep->refclassid != TypeRelationId ||
5130 foundDep->refobjid != attTup->atttypid)
5131 elog(ERROR, "found unexpected dependency for column");
5133 simple_heap_delete(depRel, &depTup->t_self);
5136 systable_endscan(scan);
5138 heap_close(depRel, RowExclusiveLock);
5141 * Here we go --- change the recorded column type. (Note heapTup is a
5142 * copy of the syscache entry, so okay to scribble on.)
5144 attTup->atttypid = targettype;
5145 attTup->atttypmod = targettypmod;
5146 attTup->attndims = list_length(typename->arrayBounds);
5147 attTup->attlen = tform->typlen;
5148 attTup->attbyval = tform->typbyval;
5149 attTup->attalign = tform->typalign;
5150 attTup->attstorage = tform->typstorage;
5152 ReleaseSysCache(typeTuple);
5154 simple_heap_update(attrelation, &heapTup->t_self, heapTup);
5156 /* keep system catalog indexes current */
5157 CatalogUpdateIndexes(attrelation, heapTup);
5159 heap_close(attrelation, RowExclusiveLock);
5161 /* Install dependency on new datatype */
5162 add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
5165 * Drop any pg_statistic entry for the column, since it's now wrong type
5167 RemoveStatistics(RelationGetRelid(rel), attnum);
5170 * Update the default, if present, by brute force --- remove and re-add
5171 * the default. Probably unsafe to take shortcuts, since the new version
5172 * may well have additional dependencies. (It's okay to do this now,
5173 * rather than after other ALTER TYPE commands, since the default won't
5174 * depend on other column types.)
5178 /* Must make new row visible since it will be updated again */
5179 CommandCounterIncrement();
5182 * We use RESTRICT here for safety, but at present we do not expect
5183 * anything to depend on the default.
5185 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true);
5187 StoreAttrDefault(rel, attnum, nodeToString(defaultexpr));
5191 heap_freetuple(heapTup);
5195 * Cleanup after we've finished all the ALTER TYPE operations for a
5196 * particular relation. We have to drop and recreate all the indexes
5197 * and constraints that depend on the altered columns.
5200 ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab)
5206 * Re-parse the index and constraint definitions, and attach them to the
5207 * appropriate work queue entries. We do this before dropping because in
5208 * the case of a FOREIGN KEY constraint, we might not yet have exclusive
5209 * lock on the table the constraint is attached to, and we need to get
5210 * that before dropping. It's safe because the parser won't actually look
5211 * at the catalogs to detect the existing entry.
5213 foreach(l, tab->changedIndexDefs)
5214 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
5215 foreach(l, tab->changedConstraintDefs)
5216 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
5219 * Now we can drop the existing constraints and indexes --- constraints
5220 * first, since some of them might depend on the indexes. In fact, we
5221 * have to delete FOREIGN KEY constraints before UNIQUE constraints, but
5222 * we already ordered the constraint list to ensure that would happen. It
5223 * should be okay to use DROP_RESTRICT here, since nothing else should be
5224 * depending on these objects.
5226 foreach(l, tab->changedConstraintOids)
5228 obj.classId = ConstraintRelationId;
5229 obj.objectId = lfirst_oid(l);
5230 obj.objectSubId = 0;
5231 performDeletion(&obj, DROP_RESTRICT);
5234 foreach(l, tab->changedIndexOids)
5236 obj.classId = RelationRelationId;
5237 obj.objectId = lfirst_oid(l);
5238 obj.objectSubId = 0;
5239 performDeletion(&obj, DROP_RESTRICT);
5243 * The objects will get recreated during subsequent passes over the work
5249 ATPostAlterTypeParse(char *cmd, List **wqueue)
5251 List *raw_parsetree_list;
5252 List *querytree_list;
5253 ListCell *list_item;
5256 * We expect that we will get only ALTER TABLE and CREATE INDEX statements.
5257 * Hence, there is no need to pass them through parse_analyze() or the
5258 * rewriter, but instead we need to pass them through parse_utilcmd.c
5259 * to make them ready for execution.
5261 raw_parsetree_list = raw_parser(cmd);
5262 querytree_list = NIL;
5263 foreach(list_item, raw_parsetree_list)
5265 Node *stmt = (Node *) lfirst(list_item);
5267 if (IsA(stmt, IndexStmt))
5268 querytree_list = lappend(querytree_list,
5269 transformIndexStmt((IndexStmt *) stmt,
5271 else if (IsA(stmt, AlterTableStmt))
5272 querytree_list = list_concat(querytree_list,
5273 transformAlterTableStmt((AlterTableStmt *) stmt,
5276 querytree_list = lappend(querytree_list, stmt);
5280 * Attach each generated command to the proper place in the work queue.
5281 * Note this could result in creation of entirely new work-queue entries.
5283 foreach(list_item, querytree_list)
5285 Node *stm = (Node *) lfirst(list_item);
5287 AlteredTableInfo *tab;
5289 switch (nodeTag(stm))
5293 IndexStmt *stmt = (IndexStmt *) stm;
5294 AlterTableCmd *newcmd;
5296 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
5297 tab = ATGetQueueEntry(wqueue, rel);
5298 newcmd = makeNode(AlterTableCmd);
5299 newcmd->subtype = AT_ReAddIndex;
5300 newcmd->def = (Node *) stmt;
5301 tab->subcmds[AT_PASS_OLD_INDEX] =
5302 lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
5303 relation_close(rel, NoLock);
5306 case T_AlterTableStmt:
5308 AlterTableStmt *stmt = (AlterTableStmt *) stm;
5311 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
5312 tab = ATGetQueueEntry(wqueue, rel);
5313 foreach(lcmd, stmt->cmds)
5315 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
5317 switch (cmd->subtype)
5320 cmd->subtype = AT_ReAddIndex;
5321 tab->subcmds[AT_PASS_OLD_INDEX] =
5322 lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
5324 case AT_AddConstraint:
5325 tab->subcmds[AT_PASS_OLD_CONSTR] =
5326 lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
5329 elog(ERROR, "unexpected statement type: %d",
5330 (int) cmd->subtype);
5333 relation_close(rel, NoLock);
5337 elog(ERROR, "unexpected statement type: %d",
5338 (int) nodeTag(stm));
5347 * recursing is true if we are recursing from a table to its indexes,
5348 * sequences, or toast table. We don't allow the ownership of those things to
5349 * be changed separately from the parent table. Also, we can skip permission
5350 * checks (this is necessary not just an optimization, else we'd fail to
5351 * handle toast tables properly).
5353 * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
5354 * free-standing composite type.
5357 ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing)
5359 Relation target_rel;
5362 Form_pg_class tuple_class;
5365 * Get exclusive lock till end of transaction on the target table. Use
5366 * relation_open so that we can work on indexes and sequences.
5368 target_rel = relation_open(relationOid, AccessExclusiveLock);
5370 /* Get its pg_class tuple, too */
5371 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
5373 tuple = SearchSysCache(RELOID,
5374 ObjectIdGetDatum(relationOid),
5376 if (!HeapTupleIsValid(tuple))
5377 elog(ERROR, "cache lookup failed for relation %u", relationOid);
5378 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
5380 /* Can we change the ownership of this tuple? */
5381 switch (tuple_class->relkind)
5383 case RELKIND_RELATION:
5385 /* ok to change owner */
5391 * Because ALTER INDEX OWNER used to be allowed, and in fact
5392 * is generated by old versions of pg_dump, we give a warning
5393 * and do nothing rather than erroring out. Also, to avoid
5394 * unnecessary chatter while restoring those old dumps, say
5395 * nothing at all if the command would be a no-op anyway.
5397 if (tuple_class->relowner != newOwnerId)
5399 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5400 errmsg("cannot change owner of index \"%s\"",
5401 NameStr(tuple_class->relname)),
5402 errhint("Change the ownership of the index's table, instead.")));
5403 /* quick hack to exit via the no-op path */
5404 newOwnerId = tuple_class->relowner;
5407 case RELKIND_SEQUENCE:
5409 tuple_class->relowner != newOwnerId)
5411 /* if it's an owned sequence, disallow changing it by itself */
5415 if (sequenceIsOwned(relationOid, &tableId, &colId))
5417 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5418 errmsg("cannot change owner of sequence \"%s\"",
5419 NameStr(tuple_class->relname)),
5420 errdetail("Sequence \"%s\" is linked to table \"%s\".",
5421 NameStr(tuple_class->relname),
5422 get_rel_name(tableId))));
5425 case RELKIND_TOASTVALUE:
5426 case RELKIND_COMPOSITE_TYPE:
5432 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5433 errmsg("\"%s\" is not a table, view, or sequence",
5434 NameStr(tuple_class->relname))));
5438 * If the new owner is the same as the existing owner, consider the
5439 * command to have succeeded. This is for dump restoration purposes.
5441 if (tuple_class->relowner != newOwnerId)
5443 Datum repl_val[Natts_pg_class];
5444 char repl_null[Natts_pg_class];
5445 char repl_repl[Natts_pg_class];
5451 /* skip permission checks when recursing to index or toast table */
5454 /* Superusers can always do it */
5457 Oid namespaceOid = tuple_class->relnamespace;
5458 AclResult aclresult;
5460 /* Otherwise, must be owner of the existing object */
5461 if (!pg_class_ownercheck(relationOid, GetUserId()))
5462 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
5463 RelationGetRelationName(target_rel));
5465 /* Must be able to become new owner */
5466 check_is_member_of_role(GetUserId(), newOwnerId);
5468 /* New owner must have CREATE privilege on namespace */
5469 aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
5471 if (aclresult != ACLCHECK_OK)
5472 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
5473 get_namespace_name(namespaceOid));
5477 memset(repl_null, ' ', sizeof(repl_null));
5478 memset(repl_repl, ' ', sizeof(repl_repl));
5480 repl_repl[Anum_pg_class_relowner - 1] = 'r';
5481 repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
5484 * Determine the modified ACL for the new owner. This is only
5485 * necessary when the ACL is non-null.
5487 aclDatum = SysCacheGetAttr(RELOID, tuple,
5488 Anum_pg_class_relacl,
5492 newAcl = aclnewowner(DatumGetAclP(aclDatum),
5493 tuple_class->relowner, newOwnerId);
5494 repl_repl[Anum_pg_class_relacl - 1] = 'r';
5495 repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
5498 newtuple = heap_modifytuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
5500 simple_heap_update(class_rel, &newtuple->t_self, newtuple);
5501 CatalogUpdateIndexes(class_rel, newtuple);
5503 heap_freetuple(newtuple);
5506 * Update owner dependency reference, if any. A composite type has
5507 * none, because it's tracked for the pg_type entry instead of here;
5508 * indexes and TOAST tables don't have their own entries either.
5510 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
5511 tuple_class->relkind != RELKIND_INDEX &&
5512 tuple_class->relkind != RELKIND_TOASTVALUE)
5513 changeDependencyOnOwner(RelationRelationId, relationOid,
5517 * Also change the ownership of the table's rowtype, if it has one
5519 if (tuple_class->relkind != RELKIND_INDEX)
5520 AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId,
5521 tuple_class->relkind == RELKIND_COMPOSITE_TYPE);
5524 * If we are operating on a table, also change the ownership of any
5525 * indexes and sequences that belong to the table, as well as the
5526 * table's toast table (if it has one)
5528 if (tuple_class->relkind == RELKIND_RELATION ||
5529 tuple_class->relkind == RELKIND_TOASTVALUE)
5531 List *index_oid_list;
5534 /* Find all the indexes belonging to this relation */
5535 index_oid_list = RelationGetIndexList(target_rel);
5537 /* For each index, recursively change its ownership */
5538 foreach(i, index_oid_list)
5539 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true);
5541 list_free(index_oid_list);
5544 if (tuple_class->relkind == RELKIND_RELATION)
5546 /* If it has a toast table, recurse to change its ownership */
5547 if (tuple_class->reltoastrelid != InvalidOid)
5548 ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
5551 /* If it has dependent sequences, recurse to change them too */
5552 change_owner_recurse_to_sequences(relationOid, newOwnerId);
5556 ReleaseSysCache(tuple);
5557 heap_close(class_rel, RowExclusiveLock);
5558 relation_close(target_rel, NoLock);
5562 * change_owner_recurse_to_sequences
5564 * Helper function for ATExecChangeOwner. Examines pg_depend searching
5565 * for sequences that are dependent on serial columns, and changes their
5569 change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId)
5577 * SERIAL sequences are those having an auto dependency on one of the
5578 * table's columns (we don't care *which* column, exactly).
5580 depRel = heap_open(DependRelationId, AccessShareLock);
5582 ScanKeyInit(&key[0],
5583 Anum_pg_depend_refclassid,
5584 BTEqualStrategyNumber, F_OIDEQ,
5585 ObjectIdGetDatum(RelationRelationId));
5586 ScanKeyInit(&key[1],
5587 Anum_pg_depend_refobjid,
5588 BTEqualStrategyNumber, F_OIDEQ,
5589 ObjectIdGetDatum(relationOid));
5590 /* we leave refobjsubid unspecified */
5592 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
5593 SnapshotNow, 2, key);
5595 while (HeapTupleIsValid(tup = systable_getnext(scan)))
5597 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
5600 /* skip dependencies other than auto dependencies on columns */
5601 if (depForm->refobjsubid == 0 ||
5602 depForm->classid != RelationRelationId ||
5603 depForm->objsubid != 0 ||
5604 depForm->deptype != DEPENDENCY_AUTO)
5607 /* Use relation_open just in case it's an index */
5608 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
5610 /* skip non-sequence relations */
5611 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
5613 /* No need to keep the lock */
5614 relation_close(seqRel, AccessExclusiveLock);
5618 /* We don't need to close the sequence while we alter it. */
5619 ATExecChangeOwner(depForm->objid, newOwnerId, true);
5621 /* Now we can close it. Keep the lock till end of transaction. */
5622 relation_close(seqRel, NoLock);
5625 systable_endscan(scan);
5627 relation_close(depRel, AccessShareLock);
5631 * ALTER TABLE CLUSTER ON
5633 * The only thing we have to do is to change the indisclustered bits.
5636 ATExecClusterOn(Relation rel, const char *indexName)
5640 indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
5642 if (!OidIsValid(indexOid))
5644 (errcode(ERRCODE_UNDEFINED_OBJECT),
5645 errmsg("index \"%s\" for table \"%s\" does not exist",
5646 indexName, RelationGetRelationName(rel))));
5648 /* Check index is valid to cluster on */
5649 check_index_is_clusterable(rel, indexOid, false);
5651 /* And do the work */
5652 mark_index_clustered(rel, indexOid);
5656 * ALTER TABLE SET WITHOUT CLUSTER
5658 * We have to find any indexes on the table that have indisclustered bit
5659 * set and turn it off.
5662 ATExecDropCluster(Relation rel)
5664 mark_index_clustered(rel, InvalidOid);
5668 * ALTER TABLE SET TABLESPACE
5671 ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, char *tablespacename)
5674 AclResult aclresult;
5676 /* Check that the tablespace exists */
5677 tablespaceId = get_tablespace_oid(tablespacename);
5678 if (!OidIsValid(tablespaceId))
5680 (errcode(ERRCODE_UNDEFINED_OBJECT),
5681 errmsg("tablespace \"%s\" does not exist", tablespacename)));
5683 /* Check its permissions */
5684 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(), ACL_CREATE);
5685 if (aclresult != ACLCHECK_OK)
5686 aclcheck_error(aclresult, ACL_KIND_TABLESPACE, tablespacename);
5688 /* Save info for Phase 3 to do the real work */
5689 if (OidIsValid(tab->newTableSpace))
5691 (errcode(ERRCODE_SYNTAX_ERROR),
5692 errmsg("cannot have multiple SET TABLESPACE subcommands")));
5693 tab->newTableSpace = tablespaceId;
5697 * ALTER TABLE/INDEX SET (...) or RESET (...)
5700 ATExecSetRelOptions(Relation rel, List *defList, bool isReset)
5709 Datum repl_val[Natts_pg_class];
5710 char repl_null[Natts_pg_class];
5711 char repl_repl[Natts_pg_class];
5714 return; /* nothing to do */
5716 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
5718 /* Get the old reloptions */
5719 relid = RelationGetRelid(rel);
5720 tuple = SearchSysCache(RELOID,
5721 ObjectIdGetDatum(relid),
5723 if (!HeapTupleIsValid(tuple))
5724 elog(ERROR, "cache lookup failed for relation %u", relid);
5726 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions, &isnull);
5728 /* Generate new proposed reloptions (text array) */
5729 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
5730 defList, false, isReset);
5733 switch (rel->rd_rel->relkind)
5735 case RELKIND_RELATION:
5736 case RELKIND_TOASTVALUE:
5737 (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
5740 (void) index_reloptions(rel->rd_am->amoptions, newOptions, true);
5744 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5745 errmsg("\"%s\" is not a table, index, or TOAST table",
5746 RelationGetRelationName(rel))));
5751 * All we need do here is update the pg_class row; the new options will be
5752 * propagated into relcaches during post-commit cache inval.
5754 memset(repl_val, 0, sizeof(repl_val));
5755 memset(repl_null, ' ', sizeof(repl_null));
5756 memset(repl_repl, ' ', sizeof(repl_repl));
5758 if (newOptions != (Datum) 0)
5759 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
5761 repl_null[Anum_pg_class_reloptions - 1] = 'n';
5763 repl_repl[Anum_pg_class_reloptions - 1] = 'r';
5765 newtuple = heap_modifytuple(tuple, RelationGetDescr(pgclass),
5766 repl_val, repl_null, repl_repl);
5768 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
5770 CatalogUpdateIndexes(pgclass, newtuple);
5772 heap_freetuple(newtuple);
5774 ReleaseSysCache(tuple);
5776 heap_close(pgclass, RowExclusiveLock);
5780 * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
5781 * rewriting to be done, so we just want to copy the data as fast as possible.
5784 ATExecSetTableSpace(Oid tableOid, Oid newTableSpace)
5790 RelFileNode newrnode;
5791 SMgrRelation dstrel;
5794 Form_pg_class rd_rel;
5797 * Need lock here in case we are recursing to toast table or index
5799 rel = relation_open(tableOid, AccessExclusiveLock);
5802 * We can never allow moving of shared or nailed-in-cache relations,
5803 * because we can't support changing their reltablespace values.
5805 if (rel->rd_rel->relisshared || rel->rd_isnailed)
5807 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5808 errmsg("cannot move system relation \"%s\"",
5809 RelationGetRelationName(rel))));
5812 * Don't allow moving temp tables of other backends ... their local buffer
5813 * manager is not going to cope.
5815 if (isOtherTempNamespace(RelationGetNamespace(rel)))
5817 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5818 errmsg("cannot move temporary tables of other sessions")));
5821 * No work if no change in tablespace.
5823 oldTableSpace = rel->rd_rel->reltablespace;
5824 if (newTableSpace == oldTableSpace ||
5825 (newTableSpace == MyDatabaseTableSpace && oldTableSpace == 0))
5827 relation_close(rel, NoLock);
5831 reltoastrelid = rel->rd_rel->reltoastrelid;
5832 reltoastidxid = rel->rd_rel->reltoastidxid;
5834 /* Get a modifiable copy of the relation's pg_class row */
5835 pg_class = heap_open(RelationRelationId, RowExclusiveLock);
5837 tuple = SearchSysCacheCopy(RELOID,
5838 ObjectIdGetDatum(tableOid),
5840 if (!HeapTupleIsValid(tuple))
5841 elog(ERROR, "cache lookup failed for relation %u", tableOid);
5842 rd_rel = (Form_pg_class) GETSTRUCT(tuple);
5844 /* create another storage file. Is it a little ugly ? */
5845 /* NOTE: any conflict in relfilenode value will be caught here */
5846 newrnode = rel->rd_node;
5847 newrnode.spcNode = newTableSpace;
5849 dstrel = smgropen(newrnode);
5850 smgrcreate(dstrel, rel->rd_istemp, false);
5852 /* copy relation data to the new physical file */
5853 copy_relation_data(rel, dstrel);
5855 /* schedule unlinking old physical file */
5856 RelationOpenSmgr(rel);
5857 smgrscheduleunlink(rel->rd_smgr, rel->rd_istemp);
5860 * Now drop smgr references. The source was already dropped by
5861 * smgrscheduleunlink.
5865 /* update the pg_class row */
5866 rd_rel->reltablespace = (newTableSpace == MyDatabaseTableSpace) ? InvalidOid : newTableSpace;
5867 simple_heap_update(pg_class, &tuple->t_self, tuple);
5868 CatalogUpdateIndexes(pg_class, tuple);
5870 heap_freetuple(tuple);
5872 heap_close(pg_class, RowExclusiveLock);
5874 relation_close(rel, NoLock);
5876 /* Make sure the reltablespace change is visible */
5877 CommandCounterIncrement();
5879 /* Move associated toast relation and/or index, too */
5880 if (OidIsValid(reltoastrelid))
5881 ATExecSetTableSpace(reltoastrelid, newTableSpace);
5882 if (OidIsValid(reltoastidxid))
5883 ATExecSetTableSpace(reltoastidxid, newTableSpace);
5887 * Copy data, block by block
5890 copy_relation_data(Relation rel, SMgrRelation dst)
5894 BlockNumber nblocks;
5897 Page page = (Page) buf;
5900 * Since we copy the file directly without looking at the shared buffers,
5901 * we'd better first flush out any pages of the source relation that are
5902 * in shared buffers. We assume no new changes will be made while we are
5903 * holding exclusive lock on the rel.
5905 FlushRelationBuffers(rel);
5908 * We need to log the copied data in WAL iff WAL archiving is enabled AND
5909 * it's not a temp rel.
5911 use_wal = XLogArchivingActive() && !rel->rd_istemp;
5913 nblocks = RelationGetNumberOfBlocks(rel);
5914 /* RelationGetNumberOfBlocks will certainly have opened rd_smgr */
5917 for (blkno = 0; blkno < nblocks; blkno++)
5919 smgrread(src, blkno, buf);
5923 log_newpage(&dst->smgr_rnode, blkno, page);
5926 * Now write the page. We say isTemp = true even if it's not a temp
5927 * rel, because there's no need for smgr to schedule an fsync for this
5928 * write; we'll do it ourselves below.
5930 smgrextend(dst, blkno, buf, true);
5934 * If the rel isn't temp, we must fsync it down to disk before it's safe
5935 * to commit the transaction. (For a temp rel we don't care since the rel
5936 * will be uninteresting after a crash anyway.)
5938 * It's obvious that we must do this when not WAL-logging the copy. It's
5939 * less obvious that we have to do it even if we did WAL-log the copied
5940 * pages. The reason is that since we're copying outside shared buffers, a
5941 * CHECKPOINT occurring during the copy has no way to flush the previously
5942 * written data to disk (indeed it won't know the new rel even exists). A
5943 * crash later on would replay WAL from the checkpoint, therefore it
5944 * wouldn't replay our earlier WAL entries. If we do not fsync those pages
5945 * here, they might still not be on disk when the crash occurs.
5947 if (!rel->rd_istemp)
5952 * ALTER TABLE ENABLE/DISABLE TRIGGER
5954 * We just pass this off to trigger.c.
5957 ATExecEnableDisableTrigger(Relation rel, char *trigname,
5958 char fires_when, bool skip_system)
5960 EnableDisableTrigger(rel, trigname, fires_when, skip_system);
5964 * ALTER TABLE ENABLE/DISABLE RULE
5966 * We just pass this off to rewriteDefine.c.
5969 ATExecEnableDisableRule(Relation rel, char *trigname,
5972 EnableDisableRule(rel, trigname, fires_when);
5976 * ALTER TABLE INHERIT
5978 * Add a parent to the child's parents. This verifies that all the columns and
5979 * check constraints of the parent appear in the child and that they have the
5980 * same data types and expressions.
5983 ATExecAddInherit(Relation child_rel, RangeVar *parent)
5985 Relation parent_rel,
5989 HeapTuple inheritsTuple;
5994 * AccessShareLock on the parent is what's obtained during normal CREATE
5995 * TABLE ... INHERITS ..., so should be enough here.
5997 parent_rel = heap_openrv(parent, AccessShareLock);
6000 * Must be owner of both parent and child -- child was checked by
6001 * ATSimplePermissions call in ATPrepCmd
6003 ATSimplePermissions(parent_rel, false);
6005 /* Permanent rels cannot inherit from temporary ones */
6006 if (!isTempNamespace(RelationGetNamespace(child_rel)) &&
6007 isTempNamespace(RelationGetNamespace(parent_rel)))
6009 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6010 errmsg("cannot inherit from temporary relation \"%s\"",
6011 RelationGetRelationName(parent_rel))));
6014 * Check for duplicates in the list of parents, and determine the highest
6015 * inhseqno already present; we'll use the next one for the new parent.
6016 * (Note: get RowExclusiveLock because we will write pg_inherits below.)
6018 * Note: we do not reject the case where the child already inherits from
6019 * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
6021 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
6023 Anum_pg_inherits_inhrelid,
6024 BTEqualStrategyNumber, F_OIDEQ,
6025 ObjectIdGetDatum(RelationGetRelid(child_rel)));
6026 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
6027 true, SnapshotNow, 1, &key);
6029 /* inhseqno sequences start at 1 */
6031 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
6033 Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
6035 if (inh->inhparent == RelationGetRelid(parent_rel))
6037 (errcode(ERRCODE_DUPLICATE_TABLE),
6038 errmsg("relation \"%s\" would be inherited from more than once",
6039 RelationGetRelationName(parent_rel))));
6040 if (inh->inhseqno > inhseqno)
6041 inhseqno = inh->inhseqno;
6043 systable_endscan(scan);
6046 * Prevent circularity by seeing if proposed parent inherits from child.
6047 * (In particular, this disallows making a rel inherit from itself.)
6049 * This is not completely bulletproof because of race conditions: in
6050 * multi-level inheritance trees, someone else could concurrently
6051 * be making another inheritance link that closes the loop but does
6052 * not join either of the rels we have locked. Preventing that seems
6053 * to require exclusive locks on the entire inheritance tree, which is
6054 * a cure worse than the disease. find_all_inheritors() will cope with
6055 * circularity anyway, so don't sweat it too much.
6057 children = find_all_inheritors(RelationGetRelid(child_rel));
6059 if (list_member_oid(children, RelationGetRelid(parent_rel)))
6061 (errcode(ERRCODE_DUPLICATE_TABLE),
6062 errmsg("circular inheritance not allowed"),
6063 errdetail("\"%s\" is already a child of \"%s\".",
6065 RelationGetRelationName(child_rel))));
6067 /* If parent has OIDs then child must have OIDs */
6068 if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
6070 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6071 errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
6072 RelationGetRelationName(child_rel),
6073 RelationGetRelationName(parent_rel))));
6075 /* Match up the columns and bump attinhcount and attislocal */
6076 MergeAttributesIntoExisting(child_rel, parent_rel);
6078 /* Match up the constraints and make sure they're present in child */
6079 MergeConstraintsIntoExisting(child_rel, parent_rel);
6082 * OK, it looks valid. Make the catalog entries that show inheritance.
6084 StoreCatalogInheritance1(RelationGetRelid(child_rel),
6085 RelationGetRelid(parent_rel),
6089 /* Now we're done with pg_inherits */
6090 heap_close(catalogRelation, RowExclusiveLock);
6092 /* keep our lock on the parent relation until commit */
6093 heap_close(parent_rel, NoLock);
6097 * Obtain the source-text form of the constraint expression for a check
6098 * constraint, given its pg_constraint tuple
6101 decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
6103 Form_pg_constraint con;
6108 con = (Form_pg_constraint) GETSTRUCT(contup);
6109 attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
6111 elog(ERROR, "null conbin for constraint %u", HeapTupleGetOid(contup));
6113 expr = DirectFunctionCall2(pg_get_expr, attr,
6114 ObjectIdGetDatum(con->conrelid));
6115 return DatumGetCString(DirectFunctionCall1(textout, expr));
6119 * Check columns in child table match up with columns in parent, and increment
6120 * their attinhcount.
6122 * Called by ATExecAddInherit
6124 * Currently all parent columns must be found in child. Missing columns are an
6125 * error. One day we might consider creating new columns like CREATE TABLE
6126 * does. However, that is widely unpopular --- in the common use case of
6127 * partitioned tables it's a foot-gun.
6129 * The data type must match exactly. If the parent column is NOT NULL then
6130 * the child must be as well. Defaults are not compared, however.
6133 MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel)
6136 AttrNumber parent_attno;
6138 TupleDesc tupleDesc;
6139 TupleConstr *constr;
6142 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
6144 tupleDesc = RelationGetDescr(parent_rel);
6145 parent_natts = tupleDesc->natts;
6146 constr = tupleDesc->constr;
6148 for (parent_attno = 1; parent_attno <= parent_natts; parent_attno++)
6150 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
6151 char *attributeName = NameStr(attribute->attname);
6153 /* Ignore dropped columns in the parent. */
6154 if (attribute->attisdropped)
6157 /* Find same column in child (matching on column name). */
6158 tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel),
6160 if (HeapTupleIsValid(tuple))
6162 /* Check they are same type and typmod */
6163 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
6165 if (attribute->atttypid != childatt->atttypid ||
6166 attribute->atttypmod != childatt->atttypmod)
6168 (errcode(ERRCODE_DATATYPE_MISMATCH),
6169 errmsg("child table \"%s\" has different type for column \"%s\"",
6170 RelationGetRelationName(child_rel),
6173 if (attribute->attnotnull && !childatt->attnotnull)
6175 (errcode(ERRCODE_DATATYPE_MISMATCH),
6176 errmsg("column \"%s\" in child table must be marked NOT NULL",
6180 * OK, bump the child column's inheritance count. (If we fail
6181 * later on, this change will just roll back.)
6183 childatt->attinhcount++;
6184 simple_heap_update(attrrel, &tuple->t_self, tuple);
6185 CatalogUpdateIndexes(attrrel, tuple);
6186 heap_freetuple(tuple);
6191 (errcode(ERRCODE_DATATYPE_MISMATCH),
6192 errmsg("child table is missing column \"%s\"",
6197 heap_close(attrrel, RowExclusiveLock);
6201 * Check constraints in child table match up with constraints in parent
6203 * Called by ATExecAddInherit
6205 * Currently all constraints in parent must be present in the child. One day we
6206 * may consider adding new constraints like CREATE TABLE does. We may also want
6207 * to allow an optional flag on parent table constraints indicating they are
6208 * intended to ONLY apply to the master table, not to the children. That would
6209 * make it possible to ensure no records are mistakenly inserted into the
6210 * master in partitioned tables rather than the appropriate child.
6212 * XXX This is O(N^2) which may be an issue with tables with hundreds of
6213 * constraints. As long as tables have more like 10 constraints it shouldn't be
6214 * a problem though. Even 100 constraints ought not be the end of the world.
6217 MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
6219 Relation catalogRelation;
6220 TupleDesc tupleDesc;
6223 HeapTuple constraintTuple;
6227 /* First gather up the child's constraint definitions */
6228 catalogRelation = heap_open(ConstraintRelationId, AccessShareLock);
6229 tupleDesc = RelationGetDescr(catalogRelation);
6232 Anum_pg_constraint_conrelid,
6233 BTEqualStrategyNumber, F_OIDEQ,
6234 ObjectIdGetDatum(RelationGetRelid(child_rel)));
6235 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
6236 true, SnapshotNow, 1, &key);
6239 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
6241 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
6243 if (con->contype != CONSTRAINT_CHECK)
6246 constraints = lappend(constraints, heap_copytuple(constraintTuple));
6249 systable_endscan(scan);
6251 /* Then scan through the parent's constraints looking for matches */
6253 Anum_pg_constraint_conrelid,
6254 BTEqualStrategyNumber, F_OIDEQ,
6255 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
6256 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId, true,
6257 SnapshotNow, 1, &key);
6259 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
6261 Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
6263 Form_pg_constraint child_con = NULL;
6264 HeapTuple child_contuple = NULL;
6266 if (parent_con->contype != CONSTRAINT_CHECK)
6269 foreach(elem, constraints)
6271 child_contuple = (HeapTuple) lfirst(elem);
6272 child_con = (Form_pg_constraint) GETSTRUCT(child_contuple);
6273 if (strcmp(NameStr(parent_con->conname),
6274 NameStr(child_con->conname)) == 0)
6283 (errcode(ERRCODE_DATATYPE_MISMATCH),
6284 errmsg("child table is missing constraint \"%s\"",
6285 NameStr(parent_con->conname))));
6287 if (parent_con->condeferrable != child_con->condeferrable ||
6288 parent_con->condeferred != child_con->condeferred ||
6289 strcmp(decompile_conbin(constraintTuple, tupleDesc),
6290 decompile_conbin(child_contuple, tupleDesc)) != 0)
6292 (errcode(ERRCODE_DATATYPE_MISMATCH),
6293 errmsg("constraint definition for check constraint \"%s\" does not match",
6294 NameStr(parent_con->conname))));
6297 * TODO: add conislocal,coninhcount to constraints. This is where we
6298 * would have to bump them just like attributes
6302 systable_endscan(scan);
6303 heap_close(catalogRelation, AccessShareLock);
6307 * ALTER TABLE NO INHERIT
6309 * Drop a parent from the child's parents. This just adjusts the attinhcount
6310 * and attislocal of the columns and removes the pg_inherit and pg_depend
6313 * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
6314 * up attislocal stays true, which means if a child is ever removed from a
6315 * parent then its columns will never be automatically dropped which may
6316 * surprise. But at least we'll never surprise by dropping columns someone
6317 * isn't expecting to be dropped which would actually mean data loss.
6320 ATExecDropInherit(Relation rel, RangeVar *parent)
6322 Relation parent_rel;
6323 Relation catalogRelation;
6326 HeapTuple inheritsTuple,
6332 * AccessShareLock on the parent is probably enough, seeing that DROP TABLE
6333 * doesn't lock parent tables at all. We need some lock since we'll be
6334 * inspecting the parent's schema.
6336 parent_rel = heap_openrv(parent, AccessShareLock);
6339 * We don't bother to check ownership of the parent table --- ownership
6340 * of the child is presumed enough rights.
6344 * Find and destroy the pg_inherits entry linking the two, or error out
6347 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
6348 ScanKeyInit(&key[0],
6349 Anum_pg_inherits_inhrelid,
6350 BTEqualStrategyNumber, F_OIDEQ,
6351 ObjectIdGetDatum(RelationGetRelid(rel)));
6352 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
6353 true, SnapshotNow, 1, key);
6355 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
6359 inhparent = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
6360 if (inhparent == RelationGetRelid(parent_rel))
6362 simple_heap_delete(catalogRelation, &inheritsTuple->t_self);
6368 systable_endscan(scan);
6369 heap_close(catalogRelation, RowExclusiveLock);
6373 (errcode(ERRCODE_UNDEFINED_TABLE),
6374 errmsg("relation \"%s\" is not a parent of relation \"%s\"",
6375 RelationGetRelationName(parent_rel),
6376 RelationGetRelationName(rel))));
6379 * Search through child columns looking for ones matching parent rel
6381 catalogRelation = heap_open(AttributeRelationId, RowExclusiveLock);
6382 ScanKeyInit(&key[0],
6383 Anum_pg_attribute_attrelid,
6384 BTEqualStrategyNumber, F_OIDEQ,
6385 ObjectIdGetDatum(RelationGetRelid(rel)));
6386 scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
6387 true, SnapshotNow, 1, key);
6388 while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
6390 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
6392 /* Ignore if dropped or not inherited */
6393 if (att->attisdropped)
6395 if (att->attinhcount <= 0)
6398 if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
6399 NameStr(att->attname)))
6401 /* Decrement inhcount and possibly set islocal to true */
6402 HeapTuple copyTuple = heap_copytuple(attributeTuple);
6403 Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
6405 copy_att->attinhcount--;
6406 if (copy_att->attinhcount == 0)
6407 copy_att->attislocal = true;
6409 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
6410 CatalogUpdateIndexes(catalogRelation, copyTuple);
6411 heap_freetuple(copyTuple);
6414 systable_endscan(scan);
6415 heap_close(catalogRelation, RowExclusiveLock);
6418 * Drop the dependency
6420 * There's no convenient way to do this, so go trawling through pg_depend
6422 catalogRelation = heap_open(DependRelationId, RowExclusiveLock);
6424 ScanKeyInit(&key[0],
6425 Anum_pg_depend_classid,
6426 BTEqualStrategyNumber, F_OIDEQ,
6427 ObjectIdGetDatum(RelationRelationId));
6428 ScanKeyInit(&key[1],
6429 Anum_pg_depend_objid,
6430 BTEqualStrategyNumber, F_OIDEQ,
6431 ObjectIdGetDatum(RelationGetRelid(rel)));
6432 ScanKeyInit(&key[2],
6433 Anum_pg_depend_objsubid,
6434 BTEqualStrategyNumber, F_INT4EQ,
6437 scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
6438 SnapshotNow, 3, key);
6440 while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
6442 Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
6444 if (dep->refclassid == RelationRelationId &&
6445 dep->refobjid == RelationGetRelid(parent_rel) &&
6446 dep->refobjsubid == 0 &&
6447 dep->deptype == DEPENDENCY_NORMAL)
6448 simple_heap_delete(catalogRelation, &depTuple->t_self);
6451 systable_endscan(scan);
6452 heap_close(catalogRelation, RowExclusiveLock);
6454 /* keep our lock on the parent relation until commit */
6455 heap_close(parent_rel, NoLock);
6460 * Execute ALTER TABLE SET SCHEMA
6462 * Note: caller must have checked ownership of the relation already
6465 AlterTableNamespace(RangeVar *relation, const char *newschema)
6473 rel = heap_openrv(relation, AccessExclusiveLock);
6475 relid = RelationGetRelid(rel);
6476 oldNspOid = RelationGetNamespace(rel);
6478 /* heap_openrv allows TOAST, but we don't want to */
6479 if (rel->rd_rel->relkind == RELKIND_TOASTVALUE)
6481 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6482 errmsg("\"%s\" is a TOAST relation",
6483 RelationGetRelationName(rel))));
6485 /* if it's an owned sequence, disallow moving it by itself */
6486 if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
6491 if (sequenceIsOwned(relid, &tableId, &colId))
6493 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6494 errmsg("cannot move an owned sequence into another schema"),
6495 errdetail("Sequence \"%s\" is linked to table \"%s\".",
6496 RelationGetRelationName(rel),
6497 get_rel_name(tableId))));
6500 /* get schema OID and check its permissions */
6501 nspOid = LookupCreationNamespace(newschema);
6503 if (oldNspOid == nspOid)
6505 (errcode(ERRCODE_DUPLICATE_TABLE),
6506 errmsg("relation \"%s\" is already in schema \"%s\"",
6507 RelationGetRelationName(rel),
6510 /* disallow renaming into or out of temp schemas */
6511 if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
6513 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6514 errmsg("cannot move objects into or out of temporary schemas")));
6516 /* same for TOAST schema */
6517 if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
6519 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6520 errmsg("cannot move objects into or out of TOAST schema")));
6522 /* OK, modify the pg_class row and pg_depend entry */
6523 classRel = heap_open(RelationRelationId, RowExclusiveLock);
6525 AlterRelationNamespaceInternal(classRel, relid, oldNspOid, nspOid, true);
6527 /* Fix the table's rowtype too */
6528 AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid, false, false);
6530 /* Fix other dependent stuff */
6531 if (rel->rd_rel->relkind == RELKIND_RELATION)
6533 AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid);
6534 AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid, newschema);
6535 AlterConstraintNamespaces(relid, oldNspOid, nspOid, false);
6538 heap_close(classRel, RowExclusiveLock);
6540 /* close rel, but keep lock until commit */
6541 relation_close(rel, NoLock);
6545 * The guts of relocating a relation to another namespace: fix the pg_class
6546 * entry, and the pg_depend entry if any. Caller must already have
6547 * opened and write-locked pg_class.
6550 AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
6551 Oid oldNspOid, Oid newNspOid,
6552 bool hasDependEntry)
6555 Form_pg_class classForm;
6557 classTup = SearchSysCacheCopy(RELOID,
6558 ObjectIdGetDatum(relOid),
6560 if (!HeapTupleIsValid(classTup))
6561 elog(ERROR, "cache lookup failed for relation %u", relOid);
6562 classForm = (Form_pg_class) GETSTRUCT(classTup);
6564 Assert(classForm->relnamespace == oldNspOid);
6566 /* check for duplicate name (more friendly than unique-index failure) */
6567 if (get_relname_relid(NameStr(classForm->relname),
6568 newNspOid) != InvalidOid)
6570 (errcode(ERRCODE_DUPLICATE_TABLE),
6571 errmsg("relation \"%s\" already exists in schema \"%s\"",
6572 NameStr(classForm->relname),
6573 get_namespace_name(newNspOid))));
6575 /* classTup is a copy, so OK to scribble on */
6576 classForm->relnamespace = newNspOid;
6578 simple_heap_update(classRel, &classTup->t_self, classTup);
6579 CatalogUpdateIndexes(classRel, classTup);
6581 /* Update dependency on schema if caller said so */
6582 if (hasDependEntry &&
6583 changeDependencyFor(RelationRelationId, relOid,
6584 NamespaceRelationId, oldNspOid, newNspOid) != 1)
6585 elog(ERROR, "failed to change schema dependency for relation \"%s\"",
6586 NameStr(classForm->relname));
6588 heap_freetuple(classTup);
6592 * Move all indexes for the specified relation to another namespace.
6594 * Note: we assume adequate permission checking was done by the caller,
6595 * and that the caller has a suitable lock on the owning relation.
6598 AlterIndexNamespaces(Relation classRel, Relation rel,
6599 Oid oldNspOid, Oid newNspOid)
6604 indexList = RelationGetIndexList(rel);
6606 foreach(l, indexList)
6608 Oid indexOid = lfirst_oid(l);
6611 * Note: currently, the index will not have its own dependency on the
6612 * namespace, so we don't need to do changeDependencyFor(). There's no
6613 * rowtype in pg_type, either.
6615 AlterRelationNamespaceInternal(classRel, indexOid,
6616 oldNspOid, newNspOid,
6620 list_free(indexList);
6624 * Move all SERIAL-column sequences of the specified relation to another
6627 * Note: we assume adequate permission checking was done by the caller,
6628 * and that the caller has a suitable lock on the owning relation.
6631 AlterSeqNamespaces(Relation classRel, Relation rel,
6632 Oid oldNspOid, Oid newNspOid, const char *newNspName)
6640 * SERIAL sequences are those having an auto dependency on one of the
6641 * table's columns (we don't care *which* column, exactly).
6643 depRel = heap_open(DependRelationId, AccessShareLock);
6645 ScanKeyInit(&key[0],
6646 Anum_pg_depend_refclassid,
6647 BTEqualStrategyNumber, F_OIDEQ,
6648 ObjectIdGetDatum(RelationRelationId));
6649 ScanKeyInit(&key[1],
6650 Anum_pg_depend_refobjid,
6651 BTEqualStrategyNumber, F_OIDEQ,
6652 ObjectIdGetDatum(RelationGetRelid(rel)));
6653 /* we leave refobjsubid unspecified */
6655 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
6656 SnapshotNow, 2, key);
6658 while (HeapTupleIsValid(tup = systable_getnext(scan)))
6660 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
6663 /* skip dependencies other than auto dependencies on columns */
6664 if (depForm->refobjsubid == 0 ||
6665 depForm->classid != RelationRelationId ||
6666 depForm->objsubid != 0 ||
6667 depForm->deptype != DEPENDENCY_AUTO)
6670 /* Use relation_open just in case it's an index */
6671 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
6673 /* skip non-sequence relations */
6674 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
6676 /* No need to keep the lock */
6677 relation_close(seqRel, AccessExclusiveLock);
6681 /* Fix the pg_class and pg_depend entries */
6682 AlterRelationNamespaceInternal(classRel, depForm->objid,
6683 oldNspOid, newNspOid,
6687 * Sequences have entries in pg_type. We need to be careful to move
6688 * them to the new namespace, too.
6690 AlterTypeNamespaceInternal(RelationGetForm(seqRel)->reltype,
6691 newNspOid, false, false);
6693 /* Now we can close it. Keep the lock till end of transaction. */
6694 relation_close(seqRel, NoLock);
6697 systable_endscan(scan);
6699 relation_close(depRel, AccessShareLock);
6704 * This code supports
6705 * CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
6707 * Because we only support this for TEMP tables, it's sufficient to remember
6708 * the state in a backend-local data structure.
6712 * Register a newly-created relation's ON COMMIT action.
6715 register_on_commit_action(Oid relid, OnCommitAction action)
6718 MemoryContext oldcxt;
6721 * We needn't bother registering the relation unless there is an ON COMMIT
6722 * action we need to take.
6724 if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
6727 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
6729 oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
6731 oc->oncommit = action;
6732 oc->creating_subid = GetCurrentSubTransactionId();
6733 oc->deleting_subid = InvalidSubTransactionId;
6735 on_commits = lcons(oc, on_commits);
6737 MemoryContextSwitchTo(oldcxt);
6741 * Unregister any ON COMMIT action when a relation is deleted.
6743 * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
6746 remove_on_commit_action(Oid relid)
6750 foreach(l, on_commits)
6752 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
6754 if (oc->relid == relid)
6756 oc->deleting_subid = GetCurrentSubTransactionId();
6763 * Perform ON COMMIT actions.
6765 * This is invoked just before actually committing, since it's possible
6766 * to encounter errors.
6769 PreCommit_on_commit_actions(void)
6772 List *oids_to_truncate = NIL;
6774 foreach(l, on_commits)
6776 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
6778 /* Ignore entry if already dropped in this xact */
6779 if (oc->deleting_subid != InvalidSubTransactionId)
6782 switch (oc->oncommit)
6785 case ONCOMMIT_PRESERVE_ROWS:
6786 /* Do nothing (there shouldn't be such entries, actually) */
6788 case ONCOMMIT_DELETE_ROWS:
6789 oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
6793 ObjectAddress object;
6795 object.classId = RelationRelationId;
6796 object.objectId = oc->relid;
6797 object.objectSubId = 0;
6798 performDeletion(&object, DROP_CASCADE);
6801 * Note that table deletion will call
6802 * remove_on_commit_action, so the entry should get marked
6805 Assert(oc->deleting_subid != InvalidSubTransactionId);
6810 if (oids_to_truncate != NIL)
6812 heap_truncate(oids_to_truncate);
6813 CommandCounterIncrement(); /* XXX needed? */
6818 * Post-commit or post-abort cleanup for ON COMMIT management.
6820 * All we do here is remove no-longer-needed OnCommitItem entries.
6822 * During commit, remove entries that were deleted during this transaction;
6823 * during abort, remove those created during this transaction.
6826 AtEOXact_on_commit_actions(bool isCommit)
6829 ListCell *prev_item;
6832 cur_item = list_head(on_commits);
6834 while (cur_item != NULL)
6836 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
6838 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
6839 oc->creating_subid != InvalidSubTransactionId)
6841 /* cur_item must be removed */
6842 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
6845 cur_item = lnext(prev_item);
6847 cur_item = list_head(on_commits);
6851 /* cur_item must be preserved */
6852 oc->creating_subid = InvalidSubTransactionId;
6853 oc->deleting_subid = InvalidSubTransactionId;
6854 prev_item = cur_item;
6855 cur_item = lnext(prev_item);
6861 * Post-subcommit or post-subabort cleanup for ON COMMIT management.
6863 * During subabort, we can immediately remove entries created during this
6864 * subtransaction. During subcommit, just relabel entries marked during
6865 * this subtransaction as being the parent's responsibility.
6868 AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
6869 SubTransactionId parentSubid)
6872 ListCell *prev_item;
6875 cur_item = list_head(on_commits);
6877 while (cur_item != NULL)
6879 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
6881 if (!isCommit && oc->creating_subid == mySubid)
6883 /* cur_item must be removed */
6884 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
6887 cur_item = lnext(prev_item);
6889 cur_item = list_head(on_commits);
6893 /* cur_item must be preserved */
6894 if (oc->creating_subid == mySubid)
6895 oc->creating_subid = parentSubid;
6896 if (oc->deleting_subid == mySubid)
6897 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
6898 prev_item = cur_item;
6899 cur_item = lnext(prev_item);