1 /*-------------------------------------------------------------------------
4 * Commands for creating and altering table structures and settings
6 * Portions Copyright (c) 1996-2008, 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.244 2008/03/25 22:42:42 tgl 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_tablespace.h"
33 #include "catalog/pg_trigger.h"
34 #include "catalog/pg_type.h"
35 #include "catalog/toasting.h"
36 #include "commands/cluster.h"
37 #include "commands/defrem.h"
38 #include "commands/tablecmds.h"
39 #include "commands/tablespace.h"
40 #include "commands/trigger.h"
41 #include "commands/typecmds.h"
42 #include "executor/executor.h"
43 #include "miscadmin.h"
44 #include "nodes/makefuncs.h"
45 #include "nodes/parsenodes.h"
46 #include "optimizer/clauses.h"
47 #include "optimizer/plancat.h"
48 #include "optimizer/prep.h"
49 #include "parser/gramparse.h"
50 #include "parser/parse_clause.h"
51 #include "parser/parse_coerce.h"
52 #include "parser/parse_expr.h"
53 #include "parser/parse_oper.h"
54 #include "parser/parse_relation.h"
55 #include "parser/parse_type.h"
56 #include "parser/parse_utilcmd.h"
57 #include "parser/parser.h"
58 #include "rewrite/rewriteDefine.h"
59 #include "rewrite/rewriteHandler.h"
60 #include "storage/smgr.h"
61 #include "utils/acl.h"
62 #include "utils/builtins.h"
63 #include "utils/fmgroids.h"
64 #include "utils/inval.h"
65 #include "utils/lsyscache.h"
66 #include "utils/memutils.h"
67 #include "utils/relcache.h"
68 #include "utils/syscache.h"
72 * ON COMMIT action list
74 typedef struct OnCommitItem
76 Oid relid; /* relid of relation */
77 OnCommitAction oncommit; /* what to do at end of xact */
80 * If this entry was created during the current transaction,
81 * creating_subid is the ID of the creating subxact; if created in a prior
82 * transaction, creating_subid is zero. If deleted during the current
83 * transaction, deleting_subid is the ID of the deleting subxact; if no
84 * deletion request is pending, deleting_subid is zero.
86 SubTransactionId creating_subid;
87 SubTransactionId deleting_subid;
90 static List *on_commits = NIL;
94 * State information for ALTER TABLE
96 * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
97 * structs, one for each table modified by the operation (the named table
98 * plus any child tables that are affected). We save lists of subcommands
99 * to apply to this table (possibly modified by parse transformation steps);
100 * these lists will be executed in Phase 2. If a Phase 3 step is needed,
101 * necessary information is stored in the constraints and newvals lists.
103 * Phase 2 is divided into multiple passes; subcommands are executed in
104 * a pass determined by subcommand type.
107 #define AT_PASS_DROP 0 /* DROP (all flavors) */
108 #define AT_PASS_ALTER_TYPE 1 /* ALTER COLUMN TYPE */
109 #define AT_PASS_OLD_INDEX 2 /* re-add existing indexes */
110 #define AT_PASS_OLD_CONSTR 3 /* re-add existing constraints */
111 #define AT_PASS_COL_ATTRS 4 /* set other column attributes */
112 /* We could support a RENAME COLUMN pass here, but not currently used */
113 #define AT_PASS_ADD_COL 5 /* ADD COLUMN */
114 #define AT_PASS_ADD_INDEX 6 /* ADD indexes */
115 #define AT_PASS_ADD_CONSTR 7 /* ADD constraints, defaults */
116 #define AT_PASS_MISC 8 /* other stuff */
117 #define AT_NUM_PASSES 9
119 typedef struct AlteredTableInfo
121 /* Information saved before any work commences: */
122 Oid relid; /* Relation to work on */
123 char relkind; /* Its relkind */
124 TupleDesc oldDesc; /* Pre-modification tuple descriptor */
125 /* Information saved by Phase 1 for Phase 2: */
126 List *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
127 /* Information saved by Phases 1/2 for Phase 3: */
128 List *constraints; /* List of NewConstraint */
129 List *newvals; /* List of NewColumnValue */
130 bool new_notnull; /* T if we added new NOT NULL constraints */
131 Oid newTableSpace; /* new tablespace; 0 means no change */
132 /* Objects to rebuild after completing ALTER TYPE operations */
133 List *changedConstraintOids; /* OIDs of constraints to rebuild */
134 List *changedConstraintDefs; /* string definitions of same */
135 List *changedIndexOids; /* OIDs of indexes to rebuild */
136 List *changedIndexDefs; /* string definitions of same */
139 /* Struct describing one new constraint to check in Phase 3 scan */
140 /* Note: new NOT NULL constraints are handled elsewhere */
141 typedef struct NewConstraint
143 char *name; /* Constraint name, or NULL if none */
144 ConstrType contype; /* CHECK or FOREIGN */
145 Oid refrelid; /* PK rel, if FOREIGN */
146 Oid conid; /* OID of pg_constraint entry, if FOREIGN */
147 Node *qual; /* Check expr or FkConstraint struct */
148 List *qualstate; /* Execution state for CHECK */
152 * Struct describing one new column value that needs to be computed during
153 * Phase 3 copy (this could be either a new column with a non-null default, or
154 * a column that we're changing the type of). Columns without such an entry
155 * are just copied from the old table during ATRewriteTable. Note that the
156 * expr is an expression over *old* table values.
158 typedef struct NewColumnValue
160 AttrNumber attnum; /* which column */
161 Expr *expr; /* expression to compute */
162 ExprState *exprstate; /* execution state */
166 static void truncate_check_rel(Relation rel);
167 static List *MergeAttributes(List *schema, List *supers, bool istemp,
168 List **supOids, List **supconstr, int *supOidCount);
169 static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
170 static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel);
171 static void add_nonduplicate_constraint(Constraint *cdef,
172 ConstrCheck *check, int *ncheck);
173 static bool change_varattnos_walker(Node *node, const AttrNumber *newattno);
174 static void StoreCatalogInheritance(Oid relationId, List *supers);
175 static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
176 int16 seqNumber, Relation inhRelation);
177 static int findAttrByName(const char *attributeName, List *schema);
178 static void setRelhassubclassInRelation(Oid relationId, bool relhassubclass);
179 static void AlterIndexNamespaces(Relation classRel, Relation rel,
180 Oid oldNspOid, Oid newNspOid);
181 static void AlterSeqNamespaces(Relation classRel, Relation rel,
182 Oid oldNspOid, Oid newNspOid,
183 const char *newNspName);
184 static int transformColumnNameList(Oid relId, List *colList,
185 int16 *attnums, Oid *atttypids);
186 static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
188 int16 *attnums, Oid *atttypids,
190 static Oid transformFkeyCheckAttrs(Relation pkrel,
191 int numattrs, int16 *attnums,
193 static void validateForeignKeyConstraint(FkConstraint *fkconstraint,
194 Relation rel, Relation pkrel, Oid constraintOid);
195 static void createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
197 static void ATController(Relation rel, List *cmds, bool recurse);
198 static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
199 bool recurse, bool recursing);
200 static void ATRewriteCatalogs(List **wqueue);
201 static void ATExecCmd(AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd);
202 static void ATRewriteTables(List **wqueue);
203 static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap);
204 static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
205 static void ATSimplePermissions(Relation rel, bool allowView);
206 static void ATSimplePermissionsRelationOrIndex(Relation rel);
207 static void ATSimpleRecursion(List **wqueue, Relation rel,
208 AlterTableCmd *cmd, bool recurse);
209 static void ATOneLevelRecursion(List **wqueue, Relation rel,
211 static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
213 static void ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
215 static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
216 static void ATExecDropNotNull(Relation rel, const char *colName);
217 static void ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
218 const char *colName);
219 static void ATExecColumnDefault(Relation rel, const char *colName,
221 static void ATPrepSetStatistics(Relation rel, const char *colName,
223 static void ATExecSetStatistics(Relation rel, const char *colName,
225 static void ATExecSetStorage(Relation rel, const char *colName,
227 static void ATExecDropColumn(Relation rel, const char *colName,
228 DropBehavior behavior,
229 bool recurse, bool recursing);
230 static void ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
231 IndexStmt *stmt, bool is_rebuild);
232 static void ATExecAddConstraint(AlteredTableInfo *tab, Relation rel,
233 Node *newConstraint);
234 static void ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
235 FkConstraint *fkconstraint);
236 static void ATPrepDropConstraint(List **wqueue, Relation rel,
237 bool recurse, AlterTableCmd *cmd);
238 static void ATExecDropConstraint(Relation rel, const char *constrName,
239 DropBehavior behavior, bool quiet);
240 static void ATPrepAlterColumnType(List **wqueue,
241 AlteredTableInfo *tab, Relation rel,
242 bool recurse, bool recursing,
244 static void ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
245 const char *colName, TypeName *typename);
246 static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab);
247 static void ATPostAlterTypeParse(char *cmd, List **wqueue);
248 static void change_owner_recurse_to_sequences(Oid relationOid,
250 static void ATExecClusterOn(Relation rel, const char *indexName);
251 static void ATExecDropCluster(Relation rel);
252 static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
253 char *tablespacename);
254 static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace);
255 static void ATExecSetRelOptions(Relation rel, List *defList, bool isReset);
256 static void ATExecEnableDisableTrigger(Relation rel, char *trigname,
257 char fires_when, bool skip_system);
258 static void ATExecEnableDisableRule(Relation rel, char *rulename,
260 static void ATExecAddInherit(Relation rel, RangeVar *parent);
261 static void ATExecDropInherit(Relation rel, RangeVar *parent);
262 static void copy_relation_data(Relation rel, SMgrRelation dst);
265 /* ----------------------------------------------------------------
267 * Creates a new relation.
269 * If successful, returns the OID of the new relation.
270 * ----------------------------------------------------------------
273 DefineRelation(CreateStmt *stmt, char relkind)
275 char relname[NAMEDATALEN];
277 List *schema = stmt->tableElts;
281 TupleDesc descriptor;
283 List *old_constraints;
292 * Truncate relname to appropriate length (probably a waste of time, as
293 * parser should have done this already).
295 StrNCpy(relname, stmt->relation->relname, NAMEDATALEN);
298 * Check consistency of arguments
300 if (stmt->oncommit != ONCOMMIT_NOOP && !stmt->relation->istemp)
302 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
303 errmsg("ON COMMIT can only be used on temporary tables")));
306 * Look up the namespace in which we are supposed to create the relation.
307 * Check we have permission to create there. Skip check if bootstrapping,
308 * since permissions machinery may not be working yet.
310 namespaceId = RangeVarGetCreationNamespace(stmt->relation);
312 if (!IsBootstrapProcessingMode())
316 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
318 if (aclresult != ACLCHECK_OK)
319 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
320 get_namespace_name(namespaceId));
324 * Select tablespace to use. If not specified, use default tablespace
325 * (which may in turn default to database's default).
327 if (stmt->tablespacename)
329 tablespaceId = get_tablespace_oid(stmt->tablespacename);
330 if (!OidIsValid(tablespaceId))
332 (errcode(ERRCODE_UNDEFINED_OBJECT),
333 errmsg("tablespace \"%s\" does not exist",
334 stmt->tablespacename)));
338 tablespaceId = GetDefaultTablespace(stmt->relation->istemp);
339 /* note InvalidOid is OK in this case */
342 /* Check permissions except when using database's default */
343 if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
347 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
349 if (aclresult != ACLCHECK_OK)
350 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
351 get_tablespace_name(tablespaceId));
355 * Parse and validate reloptions, if any.
357 reloptions = transformRelOptions((Datum) 0, stmt->options, true, false);
359 (void) heap_reloptions(relkind, reloptions, true);
362 * Look up inheritance ancestors and generate relation schema, including
363 * inherited attributes.
365 schema = MergeAttributes(schema, stmt->inhRelations,
366 stmt->relation->istemp,
367 &inheritOids, &old_constraints, &parentOidCount);
370 * Create a relation descriptor from the relation schema and create the
371 * relation. Note that in this stage only inherited (pre-cooked) defaults
372 * and constraints will be included into the new relation.
373 * (BuildDescForRelation takes care of the inherited defaults, but we have
374 * to copy inherited constraints here.)
376 descriptor = BuildDescForRelation(schema);
378 localHasOids = interpretOidsOption(stmt->options);
379 descriptor->tdhasoid = (localHasOids || parentOidCount > 0);
381 if (old_constraints || stmt->constraints)
386 /* make array that's certainly big enough */
387 check = (ConstrCheck *)
388 palloc((list_length(old_constraints) +
389 list_length(stmt->constraints)) * sizeof(ConstrCheck));
390 /* deal with constraints from MergeAttributes */
391 foreach(listptr, old_constraints)
393 Constraint *cdef = (Constraint *) lfirst(listptr);
395 if (cdef->contype == CONSTR_CHECK)
396 add_nonduplicate_constraint(cdef, check, &ncheck);
400 * parse_utilcmd.c might have passed some precooked constraints too,
401 * due to LIKE tab INCLUDING CONSTRAINTS
403 foreach(listptr, stmt->constraints)
405 Constraint *cdef = (Constraint *) lfirst(listptr);
407 if (cdef->contype == CONSTR_CHECK && cdef->cooked_expr != NULL)
408 add_nonduplicate_constraint(cdef, check, &ncheck);
410 /* if we found any, insert 'em into the descriptor */
413 if (descriptor->constr == NULL)
415 descriptor->constr = (TupleConstr *) palloc(sizeof(TupleConstr));
416 descriptor->constr->defval = NULL;
417 descriptor->constr->num_defval = 0;
418 descriptor->constr->has_not_null = false;
420 descriptor->constr->num_check = ncheck;
421 descriptor->constr->check = check;
425 relationId = heap_create_with_catalog(relname,
437 allowSystemTableMods);
439 StoreCatalogInheritance(relationId, inheritOids);
442 * We must bump the command counter to make the newly-created relation
443 * tuple visible for opening.
445 CommandCounterIncrement();
448 * Open the new relation and acquire exclusive lock on it. This isn't
449 * really necessary for locking out other backends (since they can't see
450 * the new rel anyway until we commit), but it keeps the lock manager from
451 * complaining about deadlock risks.
453 rel = relation_open(relationId, AccessExclusiveLock);
456 * Now add any newly specified column default values and CHECK constraints
457 * to the new relation. These are passed to us in the form of raw
458 * parsetrees; we need to transform them to executable expression trees
459 * before they can be added. The most convenient way to do that is to
460 * apply the parser's transformExpr routine, but transformExpr doesn't
461 * work unless we have a pre-existing relation. So, the transformation has
462 * to be postponed to this final step of CREATE TABLE.
464 * First, scan schema to find new column defaults.
469 foreach(listptr, schema)
471 ColumnDef *colDef = lfirst(listptr);
475 if (colDef->raw_default != NULL)
477 RawColumnDefault *rawEnt;
479 Assert(colDef->cooked_default == NULL);
481 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
482 rawEnt->attnum = attnum;
483 rawEnt->raw_default = colDef->raw_default;
484 rawDefaults = lappend(rawDefaults, rawEnt);
489 * Parse and add the defaults/constraints, if any.
491 if (rawDefaults || stmt->constraints)
492 AddRelationRawConstraints(rel, rawDefaults, stmt->constraints);
495 * Clean up. We keep lock on new relation (although it shouldn't be
496 * visible to anyone else anyway, until commit).
498 relation_close(rel, NoLock);
505 * Deletes a relation.
508 RemoveRelation(const RangeVar *relation, DropBehavior behavior)
511 ObjectAddress object;
513 relOid = RangeVarGetRelid(relation, false);
515 object.classId = RelationRelationId;
516 object.objectId = relOid;
517 object.objectSubId = 0;
519 performDeletion(&object, behavior);
524 * Executes a TRUNCATE command.
526 * This is a multi-relation truncate. We first open and grab exclusive
527 * lock on all relations involved, checking permissions and otherwise
528 * verifying that the relation is OK for truncation. In CASCADE mode,
529 * relations having FK references to the targeted relations are automatically
530 * added to the group; in RESTRICT mode, we check that all FK references are
531 * internal to the group that's being truncated. Finally all the relations
532 * are truncated and reindexed.
535 ExecuteTruncate(TruncateStmt *stmt)
542 * Open, exclusive-lock, and check all the explicitly-specified relations
544 foreach(cell, stmt->relations)
546 RangeVar *rv = lfirst(cell);
549 rel = heap_openrv(rv, AccessExclusiveLock);
550 truncate_check_rel(rel);
551 rels = lappend(rels, rel);
552 relids = lappend_oid(relids, RelationGetRelid(rel));
556 * In CASCADE mode, suck in all referencing relations as well. This
557 * requires multiple iterations to find indirectly-dependent relations. At
558 * each phase, we need to exclusive-lock new rels before looking for their
559 * dependencies, else we might miss something. Also, we check each rel as
560 * soon as we open it, to avoid a faux pas such as holding lock for a long
561 * time on a rel we have no permissions for.
563 if (stmt->behavior == DROP_CASCADE)
569 newrelids = heap_truncate_find_FKs(relids);
570 if (newrelids == NIL)
571 break; /* nothing else to add */
573 foreach(cell, newrelids)
575 Oid relid = lfirst_oid(cell);
578 rel = heap_open(relid, AccessExclusiveLock);
580 (errmsg("truncate cascades to table \"%s\"",
581 RelationGetRelationName(rel))));
582 truncate_check_rel(rel);
583 rels = lappend(rels, rel);
584 relids = lappend_oid(relids, relid);
590 * Check foreign key references. In CASCADE mode, this should be
591 * unnecessary since we just pulled in all the references; but as a
592 * cross-check, do it anyway if in an Assert-enabled build.
594 #ifdef USE_ASSERT_CHECKING
595 heap_truncate_check_FKs(rels, false);
597 if (stmt->behavior == DROP_RESTRICT)
598 heap_truncate_check_FKs(rels, false);
602 * OK, truncate each table.
606 Relation rel = (Relation) lfirst(cell);
611 * Create a new empty storage file for the relation, and assign it as
612 * the relfilenode value. The old storage file is scheduled for
613 * deletion at commit.
615 setNewRelfilenode(rel, RecentXmin);
617 heap_relid = RelationGetRelid(rel);
618 toast_relid = rel->rd_rel->reltoastrelid;
620 heap_close(rel, NoLock);
623 * The same for the toast table, if any.
625 if (OidIsValid(toast_relid))
627 rel = relation_open(toast_relid, AccessExclusiveLock);
628 setNewRelfilenode(rel, RecentXmin);
629 heap_close(rel, NoLock);
633 * Reconstruct the indexes to match, and we're done.
635 reindex_relation(heap_relid, true);
640 * Check that a given rel is safe to truncate. Subroutine for ExecuteTruncate
643 truncate_check_rel(Relation rel)
645 /* Only allow truncate on regular tables */
646 if (rel->rd_rel->relkind != RELKIND_RELATION)
648 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
649 errmsg("\"%s\" is not a table",
650 RelationGetRelationName(rel))));
652 /* Permissions checks */
653 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
654 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
655 RelationGetRelationName(rel));
657 if (!allowSystemTableMods && IsSystemRelation(rel))
659 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
660 errmsg("permission denied: \"%s\" is a system catalog",
661 RelationGetRelationName(rel))));
664 * We can never allow truncation of shared or nailed-in-cache relations,
665 * because we can't support changing their relfilenode values.
667 if (rel->rd_rel->relisshared || rel->rd_isnailed)
669 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
670 errmsg("cannot truncate system relation \"%s\"",
671 RelationGetRelationName(rel))));
674 * Don't allow truncate on temp tables of other backends ... their local
675 * buffer manager is not going to cope.
677 if (isOtherTempNamespace(RelationGetNamespace(rel)))
679 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
680 errmsg("cannot truncate temporary tables of other sessions")));
683 * Also check for active uses of the relation in the current transaction,
684 * including open scans and pending AFTER trigger events.
686 CheckTableNotInUse(rel, "TRUNCATE");
691 * Returns new schema given initial schema and superclasses.
694 * 'schema' is the column/attribute definition for the table. (It's a list
695 * of ColumnDef's.) It is destructively changed.
696 * 'supers' is a list of names (as RangeVar nodes) of parent relations.
697 * 'istemp' is TRUE if we are creating a temp relation.
700 * 'supOids' receives a list of the OIDs of the parent relations.
701 * 'supconstr' receives a list of constraints belonging to the parents,
702 * updated as necessary to be valid for the child.
703 * 'supOidCount' is set to the number of parents that have OID columns.
706 * Completed schema list.
709 * The order in which the attributes are inherited is very important.
710 * Intuitively, the inherited attributes should come first. If a table
711 * inherits from multiple parents, the order of those attributes are
712 * according to the order of the parents specified in CREATE TABLE.
716 * create table person (name text, age int4, location point);
717 * create table emp (salary int4, manager text) inherits(person);
718 * create table student (gpa float8) inherits (person);
719 * create table stud_emp (percent int4) inherits (emp, student);
721 * The order of the attributes of stud_emp is:
723 * person {1:name, 2:age, 3:location}
725 * {6:gpa} student emp {4:salary, 5:manager}
727 * stud_emp {7:percent}
729 * If the same attribute name appears multiple times, then it appears
730 * in the result table in the proper location for its first appearance.
732 * Constraints (including NOT NULL constraints) for the child table
733 * are the union of all relevant constraints, from both the child schema
736 * The default value for a child column is defined as:
737 * (1) If the child schema specifies a default, that value is used.
738 * (2) If neither the child nor any parent specifies a default, then
739 * the column will not have a default.
740 * (3) If conflicting defaults are inherited from different parents
741 * (and not overridden by the child), an error is raised.
742 * (4) Otherwise the inherited default is used.
743 * Rule (3) is new in Postgres 7.1; in earlier releases you got a
744 * rather arbitrary choice of which parent default to use.
748 MergeAttributes(List *schema, List *supers, bool istemp,
749 List **supOids, List **supconstr, int *supOidCount)
752 List *inhSchema = NIL;
753 List *parentOids = NIL;
754 List *constraints = NIL;
755 int parentsWithOids = 0;
756 bool have_bogus_defaults = false;
757 char *bogus_marker = "Bogus!"; /* marks conflicting defaults */
761 * Check for and reject tables with too many columns. We perform this
762 * check relatively early for two reasons: (a) we don't run the risk of
763 * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
764 * okay if we're processing <= 1600 columns, but could take minutes to
765 * execute if the user attempts to create a table with hundreds of
766 * thousands of columns.
768 * Note that we also need to check that any we do not exceed this figure
769 * after including columns from inherited relations.
771 if (list_length(schema) > MaxHeapAttributeNumber)
773 (errcode(ERRCODE_TOO_MANY_COLUMNS),
774 errmsg("tables can have at most %d columns",
775 MaxHeapAttributeNumber)));
778 * Check for duplicate names in the explicit list of attributes.
780 * Although we might consider merging such entries in the same way that we
781 * handle name conflicts for inherited attributes, it seems to make more
782 * sense to assume such conflicts are errors.
784 foreach(entry, schema)
786 ColumnDef *coldef = lfirst(entry);
789 for_each_cell(rest, lnext(entry))
791 ColumnDef *restdef = lfirst(rest);
793 if (strcmp(coldef->colname, restdef->colname) == 0)
795 (errcode(ERRCODE_DUPLICATE_COLUMN),
796 errmsg("column \"%s\" specified more than once",
802 * Scan the parents left-to-right, and merge their attributes to form a
803 * list of inherited attributes (inhSchema). Also check to see if we need
804 * to inherit an OID column.
807 foreach(entry, supers)
809 RangeVar *parent = (RangeVar *) lfirst(entry);
813 AttrNumber *newattno;
814 AttrNumber parent_attno;
816 relation = heap_openrv(parent, AccessShareLock);
818 if (relation->rd_rel->relkind != RELKIND_RELATION)
820 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
821 errmsg("inherited relation \"%s\" is not a table",
823 /* Permanent rels cannot inherit from temporary ones */
824 if (!istemp && isTempNamespace(RelationGetNamespace(relation)))
826 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
827 errmsg("cannot inherit from temporary relation \"%s\"",
831 * We should have an UNDER permission flag for this, but for now,
832 * demand that creator of a child table own the parent.
834 if (!pg_class_ownercheck(RelationGetRelid(relation), GetUserId()))
835 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
836 RelationGetRelationName(relation));
839 * Reject duplications in the list of parents.
841 if (list_member_oid(parentOids, RelationGetRelid(relation)))
843 (errcode(ERRCODE_DUPLICATE_TABLE),
844 errmsg("relation \"%s\" would be inherited from more than once",
847 parentOids = lappend_oid(parentOids, RelationGetRelid(relation));
849 if (relation->rd_rel->relhasoids)
852 tupleDesc = RelationGetDescr(relation);
853 constr = tupleDesc->constr;
856 * newattno[] will contain the child-table attribute numbers for the
857 * attributes of this parent table. (They are not the same for
858 * parents after the first one, nor if we have dropped columns.)
860 newattno = (AttrNumber *)
861 palloc(tupleDesc->natts * sizeof(AttrNumber));
863 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
866 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
867 char *attributeName = NameStr(attribute->attname);
872 * Ignore dropped columns in the parent.
874 if (attribute->attisdropped)
877 * change_varattnos_of_a_node asserts that this is greater
878 * than zero, so if anything tries to use it, we should find
881 newattno[parent_attno - 1] = 0;
886 * Does it conflict with some previously inherited column?
888 exist_attno = findAttrByName(attributeName, inhSchema);
895 * Yes, try to merge the two column definitions. They must
896 * have the same type and typmod.
899 (errmsg("merging multiple inherited definitions of column \"%s\"",
901 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
902 defTypeId = typenameTypeId(NULL, def->typename, &deftypmod);
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)
1041 * Yes, try to merge the two column definitions. They must
1042 * have the same type and typmod.
1045 (errmsg("merging column \"%s\" with inherited definition",
1047 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1048 defTypeId = typenameTypeId(NULL, def->typename, &deftypmod);
1049 newTypeId = typenameTypeId(NULL, newdef->typename, &newtypmod);
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 */
1617 * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW RENAME
1619 * Caller has already done permissions checks.
1622 RenameRelation(Oid myrelid, const char *newrelname, ObjectType reltype)
1624 Relation targetrelation;
1629 * Grab an exclusive lock on the target table, index, sequence or view,
1630 * which we will NOT release until end of transaction.
1632 targetrelation = relation_open(myrelid, AccessExclusiveLock);
1634 namespaceId = RelationGetNamespace(targetrelation);
1635 relkind = targetrelation->rd_rel->relkind;
1638 * For compatibility with prior releases, we don't complain if ALTER TABLE
1639 * or ALTER INDEX is used to rename a sequence or view.
1641 if (reltype == OBJECT_SEQUENCE && relkind != RELKIND_SEQUENCE)
1643 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1644 errmsg("\"%s\" is not a sequence",
1645 RelationGetRelationName(targetrelation))));
1647 if (reltype == OBJECT_VIEW && relkind != RELKIND_VIEW)
1649 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1650 errmsg("\"%s\" is not a view",
1651 RelationGetRelationName(targetrelation))));
1654 * Don't allow ALTER TABLE on composite types.
1655 * We want people to use ALTER TYPE for that.
1657 if (relkind == RELKIND_COMPOSITE_TYPE)
1659 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1660 errmsg("\"%s\" is a composite type",
1661 RelationGetRelationName(targetrelation)),
1662 errhint("Use ALTER TYPE instead.")));
1665 RenameRelationInternal(myrelid, newrelname, namespaceId);
1668 * Close rel, but keep exclusive lock!
1670 relation_close(targetrelation, NoLock);
1674 * RenameRelationInternal - change the name of a relation
1676 * XXX - When renaming sequences, we don't bother to modify the
1677 * sequence name that is stored within the sequence itself
1678 * (this would cause problems with MVCC). In the future,
1679 * the sequence name should probably be removed from the
1680 * sequence, AFAIK there's no need for it to be there.
1683 RenameRelationInternal(Oid myrelid, const char *newrelname, Oid namespaceId)
1685 Relation targetrelation;
1686 Relation relrelation; /* for RELATION relation */
1688 Form_pg_class relform;
1691 * Grab an exclusive lock on the target table, index, sequence or
1692 * view, which we will NOT release until end of transaction.
1694 targetrelation = relation_open(myrelid, AccessExclusiveLock);
1697 * Find relation's pg_class tuple, and make sure newrelname isn't in use.
1699 relrelation = heap_open(RelationRelationId, RowExclusiveLock);
1701 reltup = SearchSysCacheCopy(RELOID,
1702 ObjectIdGetDatum(myrelid),
1704 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
1705 elog(ERROR, "cache lookup failed for relation %u", myrelid);
1706 relform = (Form_pg_class) GETSTRUCT(reltup);
1708 if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
1710 (errcode(ERRCODE_DUPLICATE_TABLE),
1711 errmsg("relation \"%s\" already exists",
1715 * Update pg_class tuple with new relname. (Scribbling on reltup is OK
1716 * because it's a copy...)
1718 namestrcpy(&(relform->relname), newrelname);
1720 simple_heap_update(relrelation, &reltup->t_self, reltup);
1722 /* keep the system catalog indexes current */
1723 CatalogUpdateIndexes(relrelation, reltup);
1725 heap_freetuple(reltup);
1726 heap_close(relrelation, RowExclusiveLock);
1729 * Also rename the associated type, if any.
1731 if (OidIsValid(targetrelation->rd_rel->reltype))
1732 RenameTypeInternal(targetrelation->rd_rel->reltype,
1733 newrelname, namespaceId);
1736 * Also rename the associated constraint, if any.
1738 if (targetrelation->rd_rel->relkind == RELKIND_INDEX)
1740 Oid constraintId = get_index_constraint(myrelid);
1742 if (OidIsValid(constraintId))
1743 RenameConstraintById(constraintId, newrelname);
1747 * Close rel, but keep exclusive lock!
1749 relation_close(targetrelation, NoLock);
1753 * Disallow ALTER TABLE (and similar commands) when the current backend has
1754 * any open reference to the target table besides the one just acquired by
1755 * the calling command; this implies there's an open cursor or active plan.
1756 * We need this check because our AccessExclusiveLock doesn't protect us
1757 * against stomping on our own foot, only other people's feet!
1759 * For ALTER TABLE, the only case known to cause serious trouble is ALTER
1760 * COLUMN TYPE, and some changes are obviously pretty benign, so this could
1761 * possibly be relaxed to only error out for certain types of alterations.
1762 * But the use-case for allowing any of these things is not obvious, so we
1763 * won't work hard at it for now.
1765 * We also reject these commands if there are any pending AFTER trigger events
1766 * for the rel. This is certainly necessary for the rewriting variants of
1767 * ALTER TABLE, because they don't preserve tuple TIDs and so the pending
1768 * events would try to fetch the wrong tuples. It might be overly cautious
1769 * in other cases, but again it seems better to err on the side of paranoia.
1771 * REINDEX calls this with "rel" referencing the index to be rebuilt; here
1772 * we are worried about active indexscans on the index. The trigger-event
1773 * check can be skipped, since we are doing no damage to the parent table.
1775 * The statement name (eg, "ALTER TABLE") is passed for use in error messages.
1778 CheckTableNotInUse(Relation rel, const char *stmt)
1780 int expected_refcnt;
1782 expected_refcnt = rel->rd_isnailed ? 2 : 1;
1783 if (rel->rd_refcnt != expected_refcnt)
1785 (errcode(ERRCODE_OBJECT_IN_USE),
1786 /* translator: first %s is a SQL command, eg ALTER TABLE */
1787 errmsg("cannot %s \"%s\" because "
1788 "it is being used by active queries in this session",
1789 stmt, RelationGetRelationName(rel))));
1791 if (rel->rd_rel->relkind != RELKIND_INDEX &&
1792 AfterTriggerPendingOnRel(RelationGetRelid(rel)))
1794 (errcode(ERRCODE_OBJECT_IN_USE),
1795 /* translator: first %s is a SQL command, eg ALTER TABLE */
1796 errmsg("cannot %s \"%s\" because "
1797 "it has pending trigger events",
1798 stmt, RelationGetRelationName(rel))));
1803 * Execute ALTER TABLE, which can be a list of subcommands
1805 * ALTER TABLE is performed in three phases:
1806 * 1. Examine subcommands and perform pre-transformation checking.
1807 * 2. Update system catalogs.
1808 * 3. Scan table(s) to check new constraints, and optionally recopy
1809 * the data into new table(s).
1810 * Phase 3 is not performed unless one or more of the subcommands requires
1811 * it. The intention of this design is to allow multiple independent
1812 * updates of the table schema to be performed with only one pass over the
1815 * ATPrepCmd performs phase 1. A "work queue" entry is created for
1816 * each table to be affected (there may be multiple affected tables if the
1817 * commands traverse a table inheritance hierarchy). Also we do preliminary
1818 * validation of the subcommands, including parse transformation of those
1819 * expressions that need to be evaluated with respect to the old table
1822 * ATRewriteCatalogs performs phase 2 for each affected table (note that
1823 * phases 2 and 3 do no explicit recursion, since phase 1 already did it).
1824 * Certain subcommands need to be performed before others to avoid
1825 * unnecessary conflicts; for example, DROP COLUMN should come before
1826 * ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
1827 * lists, one for each logical "pass" of phase 2.
1829 * ATRewriteTables performs phase 3 for those tables that need it.
1831 * Thanks to the magic of MVCC, an error anywhere along the way rolls back
1832 * the whole operation; we don't have to do anything special to clean up.
1835 AlterTable(AlterTableStmt *stmt)
1837 Relation rel = relation_openrv(stmt->relation, AccessExclusiveLock);
1839 CheckTableNotInUse(rel, "ALTER TABLE");
1841 ATController(rel, stmt->cmds, interpretInhOption(stmt->relation->inhOpt));
1845 * AlterTableInternal
1847 * ALTER TABLE with target specified by OID
1849 * We do not reject if the relation is already open, because it's quite
1850 * likely that one or more layers of caller have it open. That means it
1851 * is unsafe to use this entry point for alterations that could break
1852 * existing query plans. On the assumption it's not used for such, we
1853 * don't have to reject pending AFTER triggers, either.
1856 AlterTableInternal(Oid relid, List *cmds, bool recurse)
1858 Relation rel = relation_open(relid, AccessExclusiveLock);
1860 ATController(rel, cmds, recurse);
1864 ATController(Relation rel, List *cmds, bool recurse)
1869 /* Phase 1: preliminary examination of commands, create work queue */
1872 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
1874 ATPrepCmd(&wqueue, rel, cmd, recurse, false);
1877 /* Close the relation, but keep lock until commit */
1878 relation_close(rel, NoLock);
1880 /* Phase 2: update system catalogs */
1881 ATRewriteCatalogs(&wqueue);
1883 /* Phase 3: scan/rewrite tables as needed */
1884 ATRewriteTables(&wqueue);
1890 * Traffic cop for ALTER TABLE Phase 1 operations, including simple
1891 * recursion and permission checks.
1893 * Caller must have acquired AccessExclusiveLock on relation already.
1894 * This lock should be held until commit.
1897 ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
1898 bool recurse, bool recursing)
1900 AlteredTableInfo *tab;
1903 /* Find or create work queue entry for this table */
1904 tab = ATGetQueueEntry(wqueue, rel);
1907 * Copy the original subcommand for each table. This avoids conflicts
1908 * when different child tables need to make different parse
1909 * transformations (for example, the same column may have different column
1910 * numbers in different children).
1912 cmd = copyObject(cmd);
1915 * Do permissions checking, recursion to child tables if needed, and any
1916 * additional phase-1 processing needed.
1918 switch (cmd->subtype)
1920 case AT_AddColumn: /* ADD COLUMN */
1921 ATSimplePermissions(rel, false);
1922 /* Performs own recursion */
1923 ATPrepAddColumn(wqueue, rel, recurse, cmd);
1924 pass = AT_PASS_ADD_COL;
1926 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
1929 * We allow defaults on views so that INSERT into a view can have
1930 * default-ish behavior. This works because the rewriter
1931 * substitutes default values into INSERTs before it expands
1934 ATSimplePermissions(rel, true);
1935 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1936 /* No command-specific prep needed */
1937 pass = cmd->def ? AT_PASS_ADD_CONSTR : AT_PASS_DROP;
1939 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
1940 ATSimplePermissions(rel, false);
1941 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1942 /* No command-specific prep needed */
1943 pass = AT_PASS_DROP;
1945 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
1946 ATSimplePermissions(rel, false);
1947 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1948 /* No command-specific prep needed */
1949 pass = AT_PASS_ADD_CONSTR;
1951 case AT_SetStatistics: /* ALTER COLUMN STATISTICS */
1952 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1953 /* Performs own permission checks */
1954 ATPrepSetStatistics(rel, cmd->name, cmd->def);
1955 pass = AT_PASS_COL_ATTRS;
1957 case AT_SetStorage: /* ALTER COLUMN STORAGE */
1958 ATSimplePermissions(rel, false);
1959 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1960 /* No command-specific prep needed */
1961 pass = AT_PASS_COL_ATTRS;
1963 case AT_DropColumn: /* DROP COLUMN */
1964 ATSimplePermissions(rel, false);
1965 /* Recursion occurs during execution phase */
1966 /* No command-specific prep needed except saving recurse flag */
1968 cmd->subtype = AT_DropColumnRecurse;
1969 pass = AT_PASS_DROP;
1971 case AT_AddIndex: /* ADD INDEX */
1972 ATSimplePermissions(rel, false);
1973 /* This command never recurses */
1974 /* No command-specific prep needed */
1975 pass = AT_PASS_ADD_INDEX;
1977 case AT_AddConstraint: /* ADD CONSTRAINT */
1978 ATSimplePermissions(rel, false);
1981 * Currently we recurse only for CHECK constraints, never for
1982 * foreign-key constraints. UNIQUE/PKEY constraints won't be seen
1985 if (IsA(cmd->def, Constraint))
1986 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1987 /* No command-specific prep needed */
1988 pass = AT_PASS_ADD_CONSTR;
1990 case AT_DropConstraint: /* DROP CONSTRAINT */
1991 ATSimplePermissions(rel, false);
1992 /* Performs own recursion */
1993 ATPrepDropConstraint(wqueue, rel, recurse, cmd);
1994 pass = AT_PASS_DROP;
1996 case AT_DropConstraintQuietly: /* DROP CONSTRAINT for child */
1997 ATSimplePermissions(rel, false);
1998 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1999 /* No command-specific prep needed */
2000 pass = AT_PASS_DROP;
2002 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
2003 ATSimplePermissions(rel, false);
2004 /* Performs own recursion */
2005 ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd);
2006 pass = AT_PASS_ALTER_TYPE;
2008 case AT_ChangeOwner: /* ALTER OWNER */
2009 /* This command never recurses */
2010 /* No command-specific prep needed */
2011 pass = AT_PASS_MISC;
2013 case AT_ClusterOn: /* CLUSTER ON */
2014 case AT_DropCluster: /* SET WITHOUT CLUSTER */
2015 ATSimplePermissions(rel, false);
2016 /* These commands never recurse */
2017 /* No command-specific prep needed */
2018 pass = AT_PASS_MISC;
2020 case AT_DropOids: /* SET WITHOUT OIDS */
2021 ATSimplePermissions(rel, false);
2022 /* Performs own recursion */
2023 if (rel->rd_rel->relhasoids)
2025 AlterTableCmd *dropCmd = makeNode(AlterTableCmd);
2027 dropCmd->subtype = AT_DropColumn;
2028 dropCmd->name = pstrdup("oid");
2029 dropCmd->behavior = cmd->behavior;
2030 ATPrepCmd(wqueue, rel, dropCmd, recurse, false);
2032 pass = AT_PASS_DROP;
2034 case AT_SetTableSpace: /* SET TABLESPACE */
2035 ATSimplePermissionsRelationOrIndex(rel);
2036 /* This command never recurses */
2037 ATPrepSetTableSpace(tab, rel, cmd->name);
2038 pass = AT_PASS_MISC; /* doesn't actually matter */
2040 case AT_SetRelOptions: /* SET (...) */
2041 case AT_ResetRelOptions: /* RESET (...) */
2042 ATSimplePermissionsRelationOrIndex(rel);
2043 /* This command never recurses */
2044 /* No command-specific prep needed */
2045 pass = AT_PASS_MISC;
2047 case AT_EnableTrig: /* ENABLE TRIGGER variants */
2048 case AT_EnableAlwaysTrig:
2049 case AT_EnableReplicaTrig:
2050 case AT_EnableTrigAll:
2051 case AT_EnableTrigUser:
2052 case AT_DisableTrig: /* DISABLE TRIGGER variants */
2053 case AT_DisableTrigAll:
2054 case AT_DisableTrigUser:
2055 case AT_EnableRule: /* ENABLE/DISABLE RULE variants */
2056 case AT_EnableAlwaysRule:
2057 case AT_EnableReplicaRule:
2058 case AT_DisableRule:
2059 case AT_AddInherit: /* INHERIT / NO INHERIT */
2060 case AT_DropInherit:
2061 ATSimplePermissions(rel, false);
2062 /* These commands never recurse */
2063 /* No command-specific prep needed */
2064 pass = AT_PASS_MISC;
2067 elog(ERROR, "unrecognized alter table type: %d",
2068 (int) cmd->subtype);
2069 pass = 0; /* keep compiler quiet */
2073 /* Add the subcommand to the appropriate list for phase 2 */
2074 tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
2080 * Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
2081 * dispatched in a "safe" execution order (designed to avoid unnecessary
2085 ATRewriteCatalogs(List **wqueue)
2091 * We process all the tables "in parallel", one pass at a time. This is
2092 * needed because we may have to propagate work from one table to another
2093 * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
2094 * re-adding of the foreign key constraint to the other table). Work can
2095 * only be propagated into later passes, however.
2097 for (pass = 0; pass < AT_NUM_PASSES; pass++)
2099 /* Go through each table that needs to be processed */
2100 foreach(ltab, *wqueue)
2102 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2103 List *subcmds = tab->subcmds[pass];
2111 * Exclusive lock was obtained by phase 1, needn't get it again
2113 rel = relation_open(tab->relid, NoLock);
2115 foreach(lcmd, subcmds)
2116 ATExecCmd(tab, rel, (AlterTableCmd *) lfirst(lcmd));
2119 * After the ALTER TYPE pass, do cleanup work (this is not done in
2120 * ATExecAlterColumnType since it should be done only once if
2121 * multiple columns of a table are altered).
2123 if (pass == AT_PASS_ALTER_TYPE)
2124 ATPostAlterTypeCleanup(wqueue, tab);
2126 relation_close(rel, NoLock);
2131 * Check to see if a toast table must be added, if we executed any
2132 * subcommands that might have added a column or changed column storage.
2134 foreach(ltab, *wqueue)
2136 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2138 if (tab->relkind == RELKIND_RELATION &&
2139 (tab->subcmds[AT_PASS_ADD_COL] ||
2140 tab->subcmds[AT_PASS_ALTER_TYPE] ||
2141 tab->subcmds[AT_PASS_COL_ATTRS]))
2142 AlterTableCreateToastTable(tab->relid);
2147 * ATExecCmd: dispatch a subcommand to appropriate execution routine
2150 ATExecCmd(AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd)
2152 switch (cmd->subtype)
2154 case AT_AddColumn: /* ADD COLUMN */
2155 ATExecAddColumn(tab, rel, (ColumnDef *) cmd->def);
2157 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
2158 ATExecColumnDefault(rel, cmd->name, cmd->def);
2160 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
2161 ATExecDropNotNull(rel, cmd->name);
2163 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
2164 ATExecSetNotNull(tab, rel, cmd->name);
2166 case AT_SetStatistics: /* ALTER COLUMN STATISTICS */
2167 ATExecSetStatistics(rel, cmd->name, cmd->def);
2169 case AT_SetStorage: /* ALTER COLUMN STORAGE */
2170 ATExecSetStorage(rel, cmd->name, cmd->def);
2172 case AT_DropColumn: /* DROP COLUMN */
2173 ATExecDropColumn(rel, cmd->name, cmd->behavior, false, false);
2175 case AT_DropColumnRecurse: /* DROP COLUMN with recursion */
2176 ATExecDropColumn(rel, cmd->name, cmd->behavior, true, false);
2178 case AT_AddIndex: /* ADD INDEX */
2179 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false);
2181 case AT_ReAddIndex: /* ADD INDEX */
2182 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true);
2184 case AT_AddConstraint: /* ADD CONSTRAINT */
2185 ATExecAddConstraint(tab, rel, cmd->def);
2187 case AT_DropConstraint: /* DROP CONSTRAINT */
2188 ATExecDropConstraint(rel, cmd->name, cmd->behavior, false);
2190 case AT_DropConstraintQuietly: /* DROP CONSTRAINT for child */
2191 ATExecDropConstraint(rel, cmd->name, cmd->behavior, true);
2193 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
2194 ATExecAlterColumnType(tab, rel, cmd->name, (TypeName *) cmd->def);
2196 case AT_ChangeOwner: /* ALTER OWNER */
2197 ATExecChangeOwner(RelationGetRelid(rel),
2198 get_roleid_checked(cmd->name),
2201 case AT_ClusterOn: /* CLUSTER ON */
2202 ATExecClusterOn(rel, cmd->name);
2204 case AT_DropCluster: /* SET WITHOUT CLUSTER */
2205 ATExecDropCluster(rel);
2207 case AT_DropOids: /* SET WITHOUT OIDS */
2210 * Nothing to do here; we'll have generated a DropColumn
2211 * subcommand to do the real work
2214 case AT_SetTableSpace: /* SET TABLESPACE */
2217 * Nothing to do here; Phase 3 does the work
2220 case AT_SetRelOptions: /* SET (...) */
2221 ATExecSetRelOptions(rel, (List *) cmd->def, false);
2223 case AT_ResetRelOptions: /* RESET (...) */
2224 ATExecSetRelOptions(rel, (List *) cmd->def, true);
2227 case AT_EnableTrig: /* ENABLE TRIGGER name */
2228 ATExecEnableDisableTrigger(rel, cmd->name,
2229 TRIGGER_FIRES_ON_ORIGIN, false);
2231 case AT_EnableAlwaysTrig: /* ENABLE ALWAYS TRIGGER name */
2232 ATExecEnableDisableTrigger(rel, cmd->name,
2233 TRIGGER_FIRES_ALWAYS, false);
2235 case AT_EnableReplicaTrig: /* ENABLE REPLICA TRIGGER name */
2236 ATExecEnableDisableTrigger(rel, cmd->name,
2237 TRIGGER_FIRES_ON_REPLICA, false);
2239 case AT_DisableTrig: /* DISABLE TRIGGER name */
2240 ATExecEnableDisableTrigger(rel, cmd->name,
2241 TRIGGER_DISABLED, false);
2243 case AT_EnableTrigAll: /* ENABLE TRIGGER ALL */
2244 ATExecEnableDisableTrigger(rel, NULL,
2245 TRIGGER_FIRES_ON_ORIGIN, false);
2247 case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
2248 ATExecEnableDisableTrigger(rel, NULL,
2249 TRIGGER_DISABLED, false);
2251 case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
2252 ATExecEnableDisableTrigger(rel, NULL,
2253 TRIGGER_FIRES_ON_ORIGIN, true);
2255 case AT_DisableTrigUser: /* DISABLE TRIGGER USER */
2256 ATExecEnableDisableTrigger(rel, NULL,
2257 TRIGGER_DISABLED, true);
2260 case AT_EnableRule: /* ENABLE RULE name */
2261 ATExecEnableDisableRule(rel, cmd->name,
2262 RULE_FIRES_ON_ORIGIN);
2264 case AT_EnableAlwaysRule: /* ENABLE ALWAYS RULE name */
2265 ATExecEnableDisableRule(rel, cmd->name,
2268 case AT_EnableReplicaRule: /* ENABLE REPLICA RULE name */
2269 ATExecEnableDisableRule(rel, cmd->name,
2270 RULE_FIRES_ON_REPLICA);
2272 case AT_DisableRule: /* DISABLE RULE name */
2273 ATExecEnableDisableRule(rel, cmd->name,
2278 ATExecAddInherit(rel, (RangeVar *) cmd->def);
2280 case AT_DropInherit:
2281 ATExecDropInherit(rel, (RangeVar *) cmd->def);
2284 elog(ERROR, "unrecognized alter table type: %d",
2285 (int) cmd->subtype);
2290 * Bump the command counter to ensure the next subcommand in the sequence
2291 * can see the changes so far
2293 CommandCounterIncrement();
2297 * ATRewriteTables: ALTER TABLE phase 3
2300 ATRewriteTables(List **wqueue)
2304 /* Go through each table that needs to be checked or rewritten */
2305 foreach(ltab, *wqueue)
2307 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2310 * We only need to rewrite the table if at least one column needs to
2313 if (tab->newvals != NIL)
2315 /* Build a temporary relation and copy data */
2317 char NewHeapName[NAMEDATALEN];
2320 ObjectAddress object;
2322 OldHeap = heap_open(tab->relid, NoLock);
2325 * We can never allow rewriting of shared or nailed-in-cache
2326 * relations, because we can't support changing their relfilenode
2329 if (OldHeap->rd_rel->relisshared || OldHeap->rd_isnailed)
2331 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2332 errmsg("cannot rewrite system relation \"%s\"",
2333 RelationGetRelationName(OldHeap))));
2336 * Don't allow rewrite on temp tables of other backends ... their
2337 * local buffer manager is not going to cope.
2339 if (isOtherTempNamespace(RelationGetNamespace(OldHeap)))
2341 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2342 errmsg("cannot rewrite temporary tables of other sessions")));
2345 * Select destination tablespace (same as original unless user
2346 * requested a change)
2348 if (tab->newTableSpace)
2349 NewTableSpace = tab->newTableSpace;
2351 NewTableSpace = OldHeap->rd_rel->reltablespace;
2353 heap_close(OldHeap, NoLock);
2356 * Create the new heap, using a temporary name in the same
2357 * namespace as the existing table. NOTE: there is some risk of
2358 * collision with user relnames. Working around this seems more
2359 * trouble than it's worth; in particular, we can't create the new
2360 * heap in a different namespace from the old, or we will have
2361 * problems with the TEMP status of temp tables.
2363 snprintf(NewHeapName, sizeof(NewHeapName),
2364 "pg_temp_%u", tab->relid);
2366 OIDNewHeap = make_new_heap(tab->relid, NewHeapName, NewTableSpace);
2369 * Copy the heap data into the new table with the desired
2370 * modifications, and test the current data within the table
2371 * against new constraints generated by ALTER TABLE commands.
2373 ATRewriteTable(tab, OIDNewHeap);
2376 * Swap the physical files of the old and new heaps. Since we are
2377 * generating a new heap, we can use RecentXmin for the table's
2378 * new relfrozenxid because we rewrote all the tuples on
2379 * ATRewriteTable, so no older Xid remains on the table.
2381 swap_relation_files(tab->relid, OIDNewHeap, RecentXmin);
2383 CommandCounterIncrement();
2385 /* Destroy new heap with old filenode */
2386 object.classId = RelationRelationId;
2387 object.objectId = OIDNewHeap;
2388 object.objectSubId = 0;
2391 * The new relation is local to our transaction and we know
2392 * nothing depends on it, so DROP_RESTRICT should be OK.
2394 performDeletion(&object, DROP_RESTRICT);
2395 /* performDeletion does CommandCounterIncrement at end */
2398 * Rebuild each index on the relation (but not the toast table,
2399 * which is all-new anyway). We do not need
2400 * CommandCounterIncrement() because reindex_relation does it.
2402 reindex_relation(tab->relid, false);
2407 * Test the current data within the table against new constraints
2408 * generated by ALTER TABLE commands, but don't rebuild data.
2410 if (tab->constraints != NIL || tab->new_notnull)
2411 ATRewriteTable(tab, InvalidOid);
2414 * If we had SET TABLESPACE but no reason to reconstruct tuples,
2415 * just do a block-by-block copy.
2417 if (tab->newTableSpace)
2418 ATExecSetTableSpace(tab->relid, tab->newTableSpace);
2423 * Foreign key constraints are checked in a final pass, since (a) it's
2424 * generally best to examine each one separately, and (b) it's at least
2425 * theoretically possible that we have changed both relations of the
2426 * foreign key, and we'd better have finished both rewrites before we try
2427 * to read the tables.
2429 foreach(ltab, *wqueue)
2431 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2432 Relation rel = NULL;
2435 foreach(lcon, tab->constraints)
2437 NewConstraint *con = lfirst(lcon);
2439 if (con->contype == CONSTR_FOREIGN)
2441 FkConstraint *fkconstraint = (FkConstraint *) con->qual;
2446 /* Long since locked, no need for another */
2447 rel = heap_open(tab->relid, NoLock);
2450 refrel = heap_open(con->refrelid, RowShareLock);
2452 validateForeignKeyConstraint(fkconstraint, rel, refrel,
2455 heap_close(refrel, NoLock);
2460 heap_close(rel, NoLock);
2465 * ATRewriteTable: scan or rewrite one table
2467 * OIDNewHeap is InvalidOid if we don't need to rewrite
2470 ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap)
2474 TupleDesc oldTupDesc;
2475 TupleDesc newTupDesc;
2476 bool needscan = false;
2477 List *notnull_attrs;
2483 * Open the relation(s). We have surely already locked the existing
2486 oldrel = heap_open(tab->relid, NoLock);
2487 oldTupDesc = tab->oldDesc;
2488 newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
2490 if (OidIsValid(OIDNewHeap))
2491 newrel = heap_open(OIDNewHeap, AccessExclusiveLock);
2496 * If we need to rewrite the table, the operation has to be propagated to
2497 * tables that use this table's rowtype as a column type.
2499 * (Eventually this will probably become true for scans as well, but at
2500 * the moment a composite type does not enforce any constraints, so it's
2501 * not necessary/appropriate to enforce them just during ALTER.)
2504 find_composite_type_dependencies(oldrel->rd_rel->reltype,
2505 RelationGetRelationName(oldrel),
2509 * Generate the constraint and default execution states
2512 estate = CreateExecutorState();
2514 /* Build the needed expression execution states */
2515 foreach(l, tab->constraints)
2517 NewConstraint *con = lfirst(l);
2519 switch (con->contype)
2523 con->qualstate = (List *)
2524 ExecPrepareExpr((Expr *) con->qual, estate);
2526 case CONSTR_FOREIGN:
2527 /* Nothing to do here */
2530 elog(ERROR, "unrecognized constraint type: %d",
2531 (int) con->contype);
2535 foreach(l, tab->newvals)
2537 NewColumnValue *ex = lfirst(l);
2541 ex->exprstate = ExecPrepareExpr((Expr *) ex->expr, estate);
2544 notnull_attrs = NIL;
2545 if (newrel || tab->new_notnull)
2548 * If we are rebuilding the tuples OR if we added any new NOT NULL
2549 * constraints, check all not-null constraints. This is a bit of
2550 * overkill but it minimizes risk of bugs, and heap_attisnull is a
2551 * pretty cheap test anyway.
2553 for (i = 0; i < newTupDesc->natts; i++)
2555 if (newTupDesc->attrs[i]->attnotnull &&
2556 !newTupDesc->attrs[i]->attisdropped)
2557 notnull_attrs = lappend_int(notnull_attrs, i);
2565 ExprContext *econtext;
2568 TupleTableSlot *oldslot;
2569 TupleTableSlot *newslot;
2572 MemoryContext oldCxt;
2573 List *dropped_attrs = NIL;
2576 econtext = GetPerTupleExprContext(estate);
2579 * Make tuple slots for old and new tuples. Note that even when the
2580 * tuples are the same, the tupDescs might not be (consider ADD COLUMN
2581 * without a default).
2583 oldslot = MakeSingleTupleTableSlot(oldTupDesc);
2584 newslot = MakeSingleTupleTableSlot(newTupDesc);
2586 /* Preallocate values/isnull arrays */
2587 i = Max(newTupDesc->natts, oldTupDesc->natts);
2588 values = (Datum *) palloc(i * sizeof(Datum));
2589 isnull = (bool *) palloc(i * sizeof(bool));
2590 memset(values, 0, i * sizeof(Datum));
2591 memset(isnull, true, i * sizeof(bool));
2594 * Any attributes that are dropped according to the new tuple
2595 * descriptor can be set to NULL. We precompute the list of dropped
2596 * attributes to avoid needing to do so in the per-tuple loop.
2598 for (i = 0; i < newTupDesc->natts; i++)
2600 if (newTupDesc->attrs[i]->attisdropped)
2601 dropped_attrs = lappend_int(dropped_attrs, i);
2605 * Scan through the rows, generating a new row if needed and then
2606 * checking all the constraints.
2608 scan = heap_beginscan(oldrel, SnapshotNow, 0, NULL);
2611 * Switch to per-tuple memory context and reset it for each tuple
2612 * produced, so we don't leak memory.
2614 oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
2616 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2620 Oid tupOid = InvalidOid;
2622 /* Extract data from old tuple */
2623 heap_deform_tuple(tuple, oldTupDesc, values, isnull);
2624 if (oldTupDesc->tdhasoid)
2625 tupOid = HeapTupleGetOid(tuple);
2627 /* Set dropped attributes to null in new tuple */
2628 foreach(lc, dropped_attrs)
2629 isnull[lfirst_int(lc)] = true;
2632 * Process supplied expressions to replace selected columns.
2633 * Expression inputs come from the old tuple.
2635 ExecStoreTuple(tuple, oldslot, InvalidBuffer, false);
2636 econtext->ecxt_scantuple = oldslot;
2638 foreach(l, tab->newvals)
2640 NewColumnValue *ex = lfirst(l);
2642 values[ex->attnum - 1] = ExecEvalExpr(ex->exprstate,
2644 &isnull[ex->attnum - 1],
2649 * Form the new tuple. Note that we don't explicitly pfree it,
2650 * since the per-tuple memory context will be reset shortly.
2652 tuple = heap_form_tuple(newTupDesc, values, isnull);
2654 /* Preserve OID, if any */
2655 if (newTupDesc->tdhasoid)
2656 HeapTupleSetOid(tuple, tupOid);
2659 /* Now check any constraints on the possibly-changed tuple */
2660 ExecStoreTuple(tuple, newslot, InvalidBuffer, false);
2661 econtext->ecxt_scantuple = newslot;
2663 foreach(l, notnull_attrs)
2665 int attn = lfirst_int(l);
2667 if (heap_attisnull(tuple, attn + 1))
2669 (errcode(ERRCODE_NOT_NULL_VIOLATION),
2670 errmsg("column \"%s\" contains null values",
2671 NameStr(newTupDesc->attrs[attn]->attname))));
2674 foreach(l, tab->constraints)
2676 NewConstraint *con = lfirst(l);
2678 switch (con->contype)
2681 if (!ExecQual(con->qualstate, econtext, true))
2683 (errcode(ERRCODE_CHECK_VIOLATION),
2684 errmsg("check constraint \"%s\" is violated by some row",
2687 case CONSTR_FOREIGN:
2688 /* Nothing to do here */
2691 elog(ERROR, "unrecognized constraint type: %d",
2692 (int) con->contype);
2696 /* Write the tuple out to the new relation */
2698 simple_heap_insert(newrel, tuple);
2700 ResetExprContext(econtext);
2702 CHECK_FOR_INTERRUPTS();
2705 MemoryContextSwitchTo(oldCxt);
2708 ExecDropSingleTupleTableSlot(oldslot);
2709 ExecDropSingleTupleTableSlot(newslot);
2712 FreeExecutorState(estate);
2714 heap_close(oldrel, NoLock);
2716 heap_close(newrel, NoLock);
2720 * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
2722 static AlteredTableInfo *
2723 ATGetQueueEntry(List **wqueue, Relation rel)
2725 Oid relid = RelationGetRelid(rel);
2726 AlteredTableInfo *tab;
2729 foreach(ltab, *wqueue)
2731 tab = (AlteredTableInfo *) lfirst(ltab);
2732 if (tab->relid == relid)
2737 * Not there, so add it. Note that we make a copy of the relation's
2738 * existing descriptor before anything interesting can happen to it.
2740 tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
2742 tab->relkind = rel->rd_rel->relkind;
2743 tab->oldDesc = CreateTupleDescCopy(RelationGetDescr(rel));
2745 *wqueue = lappend(*wqueue, tab);
2751 * ATSimplePermissions
2753 * - Ensure that it is a relation (or possibly a view)
2754 * - Ensure this user is the owner
2755 * - Ensure that it is not a system table
2758 ATSimplePermissions(Relation rel, bool allowView)
2760 if (rel->rd_rel->relkind != RELKIND_RELATION)
2764 if (rel->rd_rel->relkind != RELKIND_VIEW)
2766 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2767 errmsg("\"%s\" is not a table or view",
2768 RelationGetRelationName(rel))));
2772 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2773 errmsg("\"%s\" is not a table",
2774 RelationGetRelationName(rel))));
2777 /* Permissions checks */
2778 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
2779 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
2780 RelationGetRelationName(rel));
2782 if (!allowSystemTableMods && IsSystemRelation(rel))
2784 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2785 errmsg("permission denied: \"%s\" is a system catalog",
2786 RelationGetRelationName(rel))));
2790 * ATSimplePermissionsRelationOrIndex
2792 * - Ensure that it is a relation or an index
2793 * - Ensure this user is the owner
2794 * - Ensure that it is not a system table
2797 ATSimplePermissionsRelationOrIndex(Relation rel)
2799 if (rel->rd_rel->relkind != RELKIND_RELATION &&
2800 rel->rd_rel->relkind != RELKIND_INDEX)
2802 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2803 errmsg("\"%s\" is not a table or index",
2804 RelationGetRelationName(rel))));
2806 /* Permissions checks */
2807 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
2808 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
2809 RelationGetRelationName(rel));
2811 if (!allowSystemTableMods && IsSystemRelation(rel))
2813 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2814 errmsg("permission denied: \"%s\" is a system catalog",
2815 RelationGetRelationName(rel))));
2821 * Simple table recursion sufficient for most ALTER TABLE operations.
2822 * All direct and indirect children are processed in an unspecified order.
2823 * Note that if a child inherits from the original table via multiple
2824 * inheritance paths, it will be visited just once.
2827 ATSimpleRecursion(List **wqueue, Relation rel,
2828 AlterTableCmd *cmd, bool recurse)
2831 * Propagate to children if desired. Non-table relations never have
2832 * children, so no need to search in that case.
2834 if (recurse && rel->rd_rel->relkind == RELKIND_RELATION)
2836 Oid relid = RelationGetRelid(rel);
2840 /* this routine is actually in the planner */
2841 children = find_all_inheritors(relid);
2844 * find_all_inheritors does the recursive search of the inheritance
2845 * hierarchy, so all we have to do is process all of the relids in the
2846 * list that it returns.
2848 foreach(child, children)
2850 Oid childrelid = lfirst_oid(child);
2853 if (childrelid == relid)
2855 childrel = relation_open(childrelid, AccessExclusiveLock);
2856 CheckTableNotInUse(childrel, "ALTER TABLE");
2857 ATPrepCmd(wqueue, childrel, cmd, false, true);
2858 relation_close(childrel, NoLock);
2864 * ATOneLevelRecursion
2866 * Here, we visit only direct inheritance children. It is expected that
2867 * the command's prep routine will recurse again to find indirect children.
2868 * When using this technique, a multiply-inheriting child will be visited
2872 ATOneLevelRecursion(List **wqueue, Relation rel,
2875 Oid relid = RelationGetRelid(rel);
2879 /* this routine is actually in the planner */
2880 children = find_inheritance_children(relid);
2882 foreach(child, children)
2884 Oid childrelid = lfirst_oid(child);
2887 childrel = relation_open(childrelid, AccessExclusiveLock);
2888 CheckTableNotInUse(childrel, "ALTER TABLE");
2889 ATPrepCmd(wqueue, childrel, cmd, true, true);
2890 relation_close(childrel, NoLock);
2896 * find_composite_type_dependencies
2898 * Check to see if a composite type is being used as a column in some
2899 * other table (possibly nested several levels deep in composite types!).
2900 * Eventually, we'd like to propagate the check or rewrite operation
2901 * into other such tables, but for now, just error out if we find any.
2903 * Caller should provide either a table name or a type name (not both) to
2904 * report in the error message, if any.
2906 * We assume that functions and views depending on the type are not reasons
2907 * to reject the ALTER. (How safe is this really?)
2910 find_composite_type_dependencies(Oid typeOid,
2911 const char *origTblName,
2912 const char *origTypeName)
2916 SysScanDesc depScan;
2921 * We scan pg_depend to find those things that depend on the rowtype. (We
2922 * assume we can ignore refobjsubid for a rowtype.)
2924 depRel = heap_open(DependRelationId, AccessShareLock);
2926 ScanKeyInit(&key[0],
2927 Anum_pg_depend_refclassid,
2928 BTEqualStrategyNumber, F_OIDEQ,
2929 ObjectIdGetDatum(TypeRelationId));
2930 ScanKeyInit(&key[1],
2931 Anum_pg_depend_refobjid,
2932 BTEqualStrategyNumber, F_OIDEQ,
2933 ObjectIdGetDatum(typeOid));
2935 depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
2936 SnapshotNow, 2, key);
2938 while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
2940 Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
2942 Form_pg_attribute att;
2944 /* Ignore dependees that aren't user columns of relations */
2945 /* (we assume system columns are never of rowtypes) */
2946 if (pg_depend->classid != RelationRelationId ||
2947 pg_depend->objsubid <= 0)
2950 rel = relation_open(pg_depend->objid, AccessShareLock);
2951 att = rel->rd_att->attrs[pg_depend->objsubid - 1];
2953 if (rel->rd_rel->relkind == RELKIND_RELATION)
2957 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2958 errmsg("cannot alter table \"%s\" because column \"%s\".\"%s\" uses its rowtype",
2960 RelationGetRelationName(rel),
2961 NameStr(att->attname))));
2964 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2965 errmsg("cannot alter type \"%s\" because column \"%s\".\"%s\" uses it",
2967 RelationGetRelationName(rel),
2968 NameStr(att->attname))));
2970 else if (OidIsValid(rel->rd_rel->reltype))
2973 * A view or composite type itself isn't a problem, but we must
2974 * recursively check for indirect dependencies via its rowtype.
2976 find_composite_type_dependencies(rel->rd_rel->reltype,
2977 origTblName, origTypeName);
2980 relation_close(rel, AccessShareLock);
2983 systable_endscan(depScan);
2985 relation_close(depRel, AccessShareLock);
2988 * If there's an array type for the rowtype, must check for uses of it,
2991 arrayOid = get_array_type(typeOid);
2992 if (OidIsValid(arrayOid))
2993 find_composite_type_dependencies(arrayOid, origTblName, origTypeName);
2998 * ALTER TABLE ADD COLUMN
3000 * Adds an additional attribute to a relation making the assumption that
3001 * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
3002 * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
3006 ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
3010 * Recurse to add the column to child classes, if requested.
3012 * We must recurse one level at a time, so that multiply-inheriting
3013 * children are visited the right number of times and end up with the
3014 * right attinhcount.
3018 AlterTableCmd *childCmd = copyObject(cmd);
3019 ColumnDef *colDefChild = (ColumnDef *) childCmd->def;
3021 /* Child should see column as singly inherited */
3022 colDefChild->inhcount = 1;
3023 colDefChild->is_local = false;
3025 ATOneLevelRecursion(wqueue, rel, childCmd);
3030 * If we are told not to recurse, there had better not be any child
3031 * tables; else the addition would put them out of step.
3033 if (find_inheritance_children(RelationGetRelid(rel)) != NIL)
3035 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3036 errmsg("column must be added to child tables too")));
3041 ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
3044 Oid myrelid = RelationGetRelid(rel);
3048 HeapTuple attributeTuple;
3049 Form_pg_attribute attribute;
3050 FormData_pg_attribute attributeD;
3054 HeapTuple typeTuple;
3060 attrdesc = heap_open(AttributeRelationId, RowExclusiveLock);
3063 * Are we adding the column to a recursion child? If so, check whether to
3064 * merge with an existing definition for the column.
3066 if (colDef->inhcount > 0)
3070 /* Does child already have a column by this name? */
3071 tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
3072 if (HeapTupleIsValid(tuple))
3074 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
3078 /* Okay if child matches by type */
3079 ctypeId = typenameTypeId(NULL, colDef->typename, &ctypmod);
3080 if (ctypeId != childatt->atttypid ||
3081 ctypmod != childatt->atttypmod)
3083 (errcode(ERRCODE_DATATYPE_MISMATCH),
3084 errmsg("child table \"%s\" has different type for column \"%s\"",
3085 RelationGetRelationName(rel), colDef->colname)));
3087 /* Bump the existing child att's inhcount */
3088 childatt->attinhcount++;
3089 simple_heap_update(attrdesc, &tuple->t_self, tuple);
3090 CatalogUpdateIndexes(attrdesc, tuple);
3092 heap_freetuple(tuple);
3094 /* Inform the user about the merge */
3096 (errmsg("merging definition of column \"%s\" for child \"%s\"",
3097 colDef->colname, RelationGetRelationName(rel))));
3099 heap_close(attrdesc, RowExclusiveLock);
3104 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
3106 reltup = SearchSysCacheCopy(RELOID,
3107 ObjectIdGetDatum(myrelid),
3109 if (!HeapTupleIsValid(reltup))
3110 elog(ERROR, "cache lookup failed for relation %u", myrelid);
3113 * this test is deliberately not attisdropped-aware, since if one tries to
3114 * add a column matching a dropped column name, it's gonna fail anyway.
3116 if (SearchSysCacheExists(ATTNAME,
3117 ObjectIdGetDatum(myrelid),
3118 PointerGetDatum(colDef->colname),
3121 (errcode(ERRCODE_DUPLICATE_COLUMN),
3122 errmsg("column \"%s\" of relation \"%s\" already exists",
3123 colDef->colname, RelationGetRelationName(rel))));
3125 minattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts;
3126 maxatts = minattnum + 1;
3127 if (maxatts > MaxHeapAttributeNumber)
3129 (errcode(ERRCODE_TOO_MANY_COLUMNS),
3130 errmsg("tables can have at most %d columns",
3131 MaxHeapAttributeNumber)));
3134 typeTuple = typenameType(NULL, colDef->typename, &typmod);
3135 tform = (Form_pg_type) GETSTRUCT(typeTuple);
3136 typeOid = HeapTupleGetOid(typeTuple);
3138 /* make sure datatype is legal for a column */
3139 CheckAttributeType(colDef->colname, typeOid);
3141 attributeTuple = heap_addheader(Natts_pg_attribute,
3143 ATTRIBUTE_TUPLE_SIZE,
3144 (void *) &attributeD);
3146 attribute = (Form_pg_attribute) GETSTRUCT(attributeTuple);
3148 attribute->attrelid = myrelid;
3149 namestrcpy(&(attribute->attname), colDef->colname);
3150 attribute->atttypid = typeOid;
3151 attribute->attstattarget = -1;
3152 attribute->attlen = tform->typlen;
3153 attribute->attcacheoff = -1;
3154 attribute->atttypmod = typmod;
3155 attribute->attnum = i;
3156 attribute->attbyval = tform->typbyval;
3157 attribute->attndims = list_length(colDef->typename->arrayBounds);
3158 attribute->attstorage = tform->typstorage;
3159 attribute->attalign = tform->typalign;
3160 attribute->attnotnull = colDef->is_not_null;
3161 attribute->atthasdef = false;
3162 attribute->attisdropped = false;
3163 attribute->attislocal = colDef->is_local;
3164 attribute->attinhcount = colDef->inhcount;
3166 ReleaseSysCache(typeTuple);
3168 simple_heap_insert(attrdesc, attributeTuple);
3170 /* Update indexes on pg_attribute */
3171 CatalogUpdateIndexes(attrdesc, attributeTuple);
3173 heap_close(attrdesc, RowExclusiveLock);
3176 * Update number of attributes in pg_class tuple
3178 ((Form_pg_class) GETSTRUCT(reltup))->relnatts = maxatts;
3180 simple_heap_update(pgclass, &reltup->t_self, reltup);
3182 /* keep catalog indexes current */
3183 CatalogUpdateIndexes(pgclass, reltup);
3185 heap_freetuple(reltup);
3187 heap_close(pgclass, RowExclusiveLock);
3189 /* Make the attribute's catalog entry visible */
3190 CommandCounterIncrement();
3193 * Store the DEFAULT, if any, in the catalogs
3195 if (colDef->raw_default)
3197 RawColumnDefault *rawEnt;
3199 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3200 rawEnt->attnum = attribute->attnum;
3201 rawEnt->raw_default = copyObject(colDef->raw_default);
3204 * This function is intended for CREATE TABLE, so it processes a
3205 * _list_ of defaults, but we just do one.
3207 AddRelationRawConstraints(rel, list_make1(rawEnt), NIL);
3209 /* Make the additional catalog changes visible */
3210 CommandCounterIncrement();
3214 * Tell Phase 3 to fill in the default expression, if there is one.
3216 * If there is no default, Phase 3 doesn't have to do anything, because
3217 * that effectively means that the default is NULL. The heap tuple access
3218 * routines always check for attnum > # of attributes in tuple, and return
3219 * NULL if so, so without any modification of the tuple data we will get
3220 * the effect of NULL values in the new column.
3222 * An exception occurs when the new column is of a domain type: the domain
3223 * might have a NOT NULL constraint, or a check constraint that indirectly
3224 * rejects nulls. If there are any domain constraints then we construct
3225 * an explicit NULL default value that will be passed through
3226 * CoerceToDomain processing. (This is a tad inefficient, since it causes
3227 * rewriting the table which we really don't have to do, but the present
3228 * design of domain processing doesn't offer any simple way of checking
3229 * the constraints more directly.)
3231 * Note: we use build_column_default, and not just the cooked default
3232 * returned by AddRelationRawConstraints, so that the right thing happens
3233 * when a datatype's default applies.
3235 defval = (Expr *) build_column_default(rel, attribute->attnum);
3237 if (!defval && GetDomainConstraints(typeOid) != NIL)
3242 baseTypeMod = typmod;
3243 baseTypeId = getBaseTypeAndTypmod(typeOid, &baseTypeMod);
3244 defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod);
3245 defval = (Expr *) coerce_to_target_type(NULL,
3250 COERCION_ASSIGNMENT,
3251 COERCE_IMPLICIT_CAST);
3252 if (defval == NULL) /* should not happen */
3253 elog(ERROR, "failed to coerce base type to domain");
3258 NewColumnValue *newval;
3260 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
3261 newval->attnum = attribute->attnum;
3262 newval->expr = defval;
3264 tab->newvals = lappend(tab->newvals, newval);
3268 * Add needed dependency entries for the new column.
3270 add_column_datatype_dependency(myrelid, i, attribute->atttypid);
3274 * Install a column's dependency on its datatype.
3277 add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
3279 ObjectAddress myself,
3282 myself.classId = RelationRelationId;
3283 myself.objectId = relid;
3284 myself.objectSubId = attnum;
3285 referenced.classId = TypeRelationId;
3286 referenced.objectId = typid;
3287 referenced.objectSubId = 0;
3288 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
3292 * ALTER TABLE ALTER COLUMN DROP NOT NULL
3295 ATExecDropNotNull(Relation rel, const char *colName)
3301 ListCell *indexoidscan;
3304 * lookup the attribute
3306 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3308 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3310 if (!HeapTupleIsValid(tuple))
3312 (errcode(ERRCODE_UNDEFINED_COLUMN),
3313 errmsg("column \"%s\" of relation \"%s\" does not exist",
3314 colName, RelationGetRelationName(rel))));
3316 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3318 /* Prevent them from altering a system attribute */
3321 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3322 errmsg("cannot alter system column \"%s\"",
3326 * Check that the attribute is not in a primary key
3329 /* Loop over all indexes on the relation */
3330 indexoidlist = RelationGetIndexList(rel);
3332 foreach(indexoidscan, indexoidlist)
3334 Oid indexoid = lfirst_oid(indexoidscan);
3335 HeapTuple indexTuple;
3336 Form_pg_index indexStruct;
3339 indexTuple = SearchSysCache(INDEXRELID,
3340 ObjectIdGetDatum(indexoid),
3342 if (!HeapTupleIsValid(indexTuple))
3343 elog(ERROR, "cache lookup failed for index %u", indexoid);
3344 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
3346 /* If the index is not a primary key, skip the check */
3347 if (indexStruct->indisprimary)
3350 * Loop over each attribute in the primary key and see if it
3351 * matches the to-be-altered attribute
3353 for (i = 0; i < indexStruct->indnatts; i++)
3355 if (indexStruct->indkey.values[i] == attnum)
3357 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3358 errmsg("column \"%s\" is in a primary key",
3363 ReleaseSysCache(indexTuple);
3366 list_free(indexoidlist);
3369 * Okay, actually perform the catalog change ... if needed
3371 if (((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3373 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = FALSE;
3375 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3377 /* keep the system catalog indexes current */
3378 CatalogUpdateIndexes(attr_rel, tuple);
3381 heap_close(attr_rel, RowExclusiveLock);
3385 * ALTER TABLE ALTER COLUMN SET NOT NULL
3388 ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
3389 const char *colName)
3396 * lookup the attribute
3398 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3400 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3402 if (!HeapTupleIsValid(tuple))
3404 (errcode(ERRCODE_UNDEFINED_COLUMN),
3405 errmsg("column \"%s\" of relation \"%s\" does not exist",
3406 colName, RelationGetRelationName(rel))));
3408 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3410 /* Prevent them from altering a system attribute */
3413 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3414 errmsg("cannot alter system column \"%s\"",
3418 * Okay, actually perform the catalog change ... if needed
3420 if (!((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3422 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = TRUE;
3424 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3426 /* keep the system catalog indexes current */
3427 CatalogUpdateIndexes(attr_rel, tuple);
3429 /* Tell Phase 3 it needs to test the constraint */
3430 tab->new_notnull = true;
3433 heap_close(attr_rel, RowExclusiveLock);
3437 * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
3440 ATExecColumnDefault(Relation rel, const char *colName,
3446 * get the number of the attribute
3448 attnum = get_attnum(RelationGetRelid(rel), colName);
3449 if (attnum == InvalidAttrNumber)
3451 (errcode(ERRCODE_UNDEFINED_COLUMN),
3452 errmsg("column \"%s\" of relation \"%s\" does not exist",
3453 colName, RelationGetRelationName(rel))));
3455 /* Prevent them from altering a system attribute */
3458 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3459 errmsg("cannot alter system column \"%s\"",
3463 * Remove any old default for the column. We use RESTRICT here for
3464 * safety, but at present we do not expect anything to depend on the
3467 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false);
3472 RawColumnDefault *rawEnt;
3474 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3475 rawEnt->attnum = attnum;
3476 rawEnt->raw_default = newDefault;
3479 * This function is intended for CREATE TABLE, so it processes a
3480 * _list_ of defaults, but we just do one.
3482 AddRelationRawConstraints(rel, list_make1(rawEnt), NIL);
3487 * ALTER TABLE ALTER COLUMN SET STATISTICS
3490 ATPrepSetStatistics(Relation rel, const char *colName, Node *flagValue)
3493 * We do our own permission checking because (a) we want to allow SET
3494 * STATISTICS on indexes (for expressional index columns), and (b) we want
3495 * to allow SET STATISTICS on system catalogs without requiring
3496 * allowSystemTableMods to be turned on.
3498 if (rel->rd_rel->relkind != RELKIND_RELATION &&
3499 rel->rd_rel->relkind != RELKIND_INDEX)
3501 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3502 errmsg("\"%s\" is not a table or index",
3503 RelationGetRelationName(rel))));
3505 /* Permissions checks */
3506 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3507 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3508 RelationGetRelationName(rel));
3512 ATExecSetStatistics(Relation rel, const char *colName, Node *newValue)
3515 Relation attrelation;
3517 Form_pg_attribute attrtuple;
3519 Assert(IsA(newValue, Integer));
3520 newtarget = intVal(newValue);
3523 * Limit target to a sane range
3528 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3529 errmsg("statistics target %d is too low",
3532 else if (newtarget > 1000)
3536 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3537 errmsg("lowering statistics target to %d",
3541 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
3543 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3545 if (!HeapTupleIsValid(tuple))
3547 (errcode(ERRCODE_UNDEFINED_COLUMN),
3548 errmsg("column \"%s\" of relation \"%s\" does not exist",
3549 colName, RelationGetRelationName(rel))));
3550 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
3552 if (attrtuple->attnum <= 0)
3554 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3555 errmsg("cannot alter system column \"%s\"",
3558 attrtuple->attstattarget = newtarget;
3560 simple_heap_update(attrelation, &tuple->t_self, tuple);
3562 /* keep system catalog indexes current */
3563 CatalogUpdateIndexes(attrelation, tuple);
3565 heap_freetuple(tuple);
3567 heap_close(attrelation, RowExclusiveLock);
3571 * ALTER TABLE ALTER COLUMN SET STORAGE
3574 ATExecSetStorage(Relation rel, const char *colName, Node *newValue)
3578 Relation attrelation;
3580 Form_pg_attribute attrtuple;
3582 Assert(IsA(newValue, String));
3583 storagemode = strVal(newValue);
3585 if (pg_strcasecmp(storagemode, "plain") == 0)
3587 else if (pg_strcasecmp(storagemode, "external") == 0)
3589 else if (pg_strcasecmp(storagemode, "extended") == 0)
3591 else if (pg_strcasecmp(storagemode, "main") == 0)
3596 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3597 errmsg("invalid storage type \"%s\"",
3599 newstorage = 0; /* keep compiler quiet */
3602 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
3604 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3606 if (!HeapTupleIsValid(tuple))
3608 (errcode(ERRCODE_UNDEFINED_COLUMN),
3609 errmsg("column \"%s\" of relation \"%s\" does not exist",
3610 colName, RelationGetRelationName(rel))));
3611 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
3613 if (attrtuple->attnum <= 0)
3615 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3616 errmsg("cannot alter system column \"%s\"",
3620 * safety check: do not allow toasted storage modes unless column datatype
3623 if (newstorage == 'p' || TypeIsToastable(attrtuple->atttypid))
3624 attrtuple->attstorage = newstorage;
3627 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3628 errmsg("column data type %s can only have storage PLAIN",
3629 format_type_be(attrtuple->atttypid))));
3631 simple_heap_update(attrelation, &tuple->t_self, tuple);
3633 /* keep system catalog indexes current */
3634 CatalogUpdateIndexes(attrelation, tuple);
3636 heap_freetuple(tuple);
3638 heap_close(attrelation, RowExclusiveLock);
3643 * ALTER TABLE DROP COLUMN
3645 * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
3646 * because we have to decide at runtime whether to recurse or not depending
3647 * on whether attinhcount goes to zero or not. (We can't check this in a
3648 * static pre-pass because it won't handle multiple inheritance situations
3649 * correctly.) Since DROP COLUMN doesn't need to create any work queue
3650 * entries for Phase 3, it's okay to recurse internally in this routine
3651 * without considering the work queue.
3654 ATExecDropColumn(Relation rel, const char *colName,
3655 DropBehavior behavior,
3656 bool recurse, bool recursing)
3659 Form_pg_attribute targetatt;
3662 ObjectAddress object;
3664 /* At top level, permission check was done in ATPrepCmd, else do it */
3666 ATSimplePermissions(rel, false);
3669 * get the number of the attribute
3671 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
3672 if (!HeapTupleIsValid(tuple))
3674 (errcode(ERRCODE_UNDEFINED_COLUMN),
3675 errmsg("column \"%s\" of relation \"%s\" does not exist",
3676 colName, RelationGetRelationName(rel))));
3677 targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
3679 attnum = targetatt->attnum;
3681 /* Can't drop a system attribute, except OID */
3682 if (attnum <= 0 && attnum != ObjectIdAttributeNumber)
3684 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3685 errmsg("cannot drop system column \"%s\"",
3688 /* Don't drop inherited columns */
3689 if (targetatt->attinhcount > 0 && !recursing)
3691 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3692 errmsg("cannot drop inherited column \"%s\"",
3695 ReleaseSysCache(tuple);
3698 * Propagate to children as appropriate. Unlike most other ALTER
3699 * routines, we have to do this one level of recursion at a time; we can't
3700 * use find_all_inheritors to do it in one pass.
3702 children = find_inheritance_children(RelationGetRelid(rel));
3709 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3710 foreach(child, children)
3712 Oid childrelid = lfirst_oid(child);
3714 Form_pg_attribute childatt;
3716 childrel = heap_open(childrelid, AccessExclusiveLock);
3717 CheckTableNotInUse(childrel, "ALTER TABLE");
3719 tuple = SearchSysCacheCopyAttName(childrelid, colName);
3720 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
3721 elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
3722 colName, childrelid);
3723 childatt = (Form_pg_attribute) GETSTRUCT(tuple);
3725 if (childatt->attinhcount <= 0) /* shouldn't happen */
3726 elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
3727 childrelid, colName);
3732 * If the child column has other definition sources, just
3733 * decrement its inheritance count; if not, recurse to delete
3736 if (childatt->attinhcount == 1 && !childatt->attislocal)
3738 /* Time to delete this child column, too */
3739 ATExecDropColumn(childrel, colName, behavior, true, true);
3743 /* Child column must survive my deletion */
3744 childatt->attinhcount--;
3746 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3748 /* keep the system catalog indexes current */
3749 CatalogUpdateIndexes(attr_rel, tuple);
3751 /* Make update visible */
3752 CommandCounterIncrement();
3758 * If we were told to drop ONLY in this table (no recursion),
3759 * we need to mark the inheritors' attribute as locally
3760 * defined rather than inherited.
3762 childatt->attinhcount--;
3763 childatt->attislocal = true;
3765 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3767 /* keep the system catalog indexes current */
3768 CatalogUpdateIndexes(attr_rel, tuple);
3770 /* Make update visible */
3771 CommandCounterIncrement();
3774 heap_freetuple(tuple);
3776 heap_close(childrel, NoLock);
3778 heap_close(attr_rel, RowExclusiveLock);
3782 * Perform the actual column deletion
3784 object.classId = RelationRelationId;
3785 object.objectId = RelationGetRelid(rel);
3786 object.objectSubId = attnum;
3788 performDeletion(&object, behavior);
3791 * If we dropped the OID column, must adjust pg_class.relhasoids
3793 if (attnum == ObjectIdAttributeNumber)
3796 Form_pg_class tuple_class;
3798 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
3800 tuple = SearchSysCacheCopy(RELOID,
3801 ObjectIdGetDatum(RelationGetRelid(rel)),
3803 if (!HeapTupleIsValid(tuple))
3804 elog(ERROR, "cache lookup failed for relation %u",
3805 RelationGetRelid(rel));
3806 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
3808 tuple_class->relhasoids = false;
3809 simple_heap_update(class_rel, &tuple->t_self, tuple);
3811 /* Keep the catalog indexes up to date */
3812 CatalogUpdateIndexes(class_rel, tuple);
3814 heap_close(class_rel, RowExclusiveLock);
3819 * ALTER TABLE ADD INDEX
3821 * There is no such command in the grammar, but parse_utilcmd.c converts
3822 * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands. This lets
3823 * us schedule creation of the index at the appropriate time during ALTER.
3826 ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
3827 IndexStmt *stmt, bool is_rebuild)
3833 Assert(IsA(stmt, IndexStmt));
3835 /* suppress schema rights check when rebuilding existing index */
3836 check_rights = !is_rebuild;
3837 /* skip index build if phase 3 will have to rewrite table anyway */
3838 skip_build = (tab->newvals != NIL);
3839 /* suppress notices when rebuilding existing index */
3842 /* The IndexStmt has already been through transformIndexStmt */
3844 DefineIndex(stmt->relation, /* relation */
3845 stmt->idxname, /* index name */
3846 InvalidOid, /* no predefined OID */
3847 stmt->accessMethod, /* am name */
3849 stmt->indexParams, /* parameters */
3850 (Expr *) stmt->whereClause,
3855 true, /* is_alter_table */
3863 * ALTER TABLE ADD CONSTRAINT
3866 ATExecAddConstraint(AlteredTableInfo *tab, Relation rel, Node *newConstraint)
3868 switch (nodeTag(newConstraint))
3872 Constraint *constr = (Constraint *) newConstraint;
3875 * Currently, we only expect to see CONSTR_CHECK nodes
3876 * arriving here (see the preprocessing done in
3877 * parse_utilcmd.c). Use a switch anyway to make it easier to
3878 * add more code later.
3880 switch (constr->contype)
3888 * Call AddRelationRawConstraints to do the work.
3889 * It returns a list of cooked constraints.
3891 newcons = AddRelationRawConstraints(rel, NIL,
3892 list_make1(constr));
3893 /* Add each constraint to Phase 3's queue */
3894 foreach(lcon, newcons)
3896 CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
3897 NewConstraint *newcon;
3899 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
3900 newcon->name = ccon->name;
3901 newcon->contype = ccon->contype;
3902 /* ExecQual wants implicit-AND format */
3903 newcon->qual = (Node *)
3904 make_ands_implicit((Expr *) ccon->expr);
3906 tab->constraints = lappend(tab->constraints,
3912 elog(ERROR, "unrecognized constraint type: %d",
3913 (int) constr->contype);
3917 case T_FkConstraint:
3919 FkConstraint *fkconstraint = (FkConstraint *) newConstraint;
3922 * Assign or validate constraint name
3924 if (fkconstraint->constr_name)
3926 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
3927 RelationGetRelid(rel),
3928 RelationGetNamespace(rel),
3929 fkconstraint->constr_name))
3931 (errcode(ERRCODE_DUPLICATE_OBJECT),
3932 errmsg("constraint \"%s\" for relation \"%s\" already exists",
3933 fkconstraint->constr_name,
3934 RelationGetRelationName(rel))));
3937 fkconstraint->constr_name =
3938 ChooseConstraintName(RelationGetRelationName(rel),
3939 strVal(linitial(fkconstraint->fk_attrs)),
3941 RelationGetNamespace(rel),
3944 ATAddForeignKeyConstraint(tab, rel, fkconstraint);
3949 elog(ERROR, "unrecognized node type: %d",
3950 (int) nodeTag(newConstraint));
3955 * Add a foreign-key constraint to a single table
3957 * Subroutine for ATExecAddConstraint. Must already hold exclusive
3958 * lock on the rel, and have done appropriate validity/permissions checks
3962 ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
3963 FkConstraint *fkconstraint)
3966 AclResult aclresult;
3967 int16 pkattnum[INDEX_MAX_KEYS];
3968 int16 fkattnum[INDEX_MAX_KEYS];
3969 Oid pktypoid[INDEX_MAX_KEYS];
3970 Oid fktypoid[INDEX_MAX_KEYS];
3971 Oid opclasses[INDEX_MAX_KEYS];
3972 Oid pfeqoperators[INDEX_MAX_KEYS];
3973 Oid ppeqoperators[INDEX_MAX_KEYS];
3974 Oid ffeqoperators[INDEX_MAX_KEYS];
3982 * Grab an exclusive lock on the pk table, so that someone doesn't delete
3983 * rows out from under us. (Although a lesser lock would do for that
3984 * purpose, we'll need exclusive lock anyway to add triggers to the pk
3985 * table; trying to start with a lesser lock will just create a risk of
3988 pkrel = heap_openrv(fkconstraint->pktable, AccessExclusiveLock);
3991 * Validity and permissions checks
3993 * Note: REFERENCES permissions checks are redundant with CREATE TRIGGER,
3994 * but we may as well error out sooner instead of later.
3996 if (pkrel->rd_rel->relkind != RELKIND_RELATION)
3998 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3999 errmsg("referenced relation \"%s\" is not a table",
4000 RelationGetRelationName(pkrel))));
4002 aclresult = pg_class_aclcheck(RelationGetRelid(pkrel), GetUserId(),
4004 if (aclresult != ACLCHECK_OK)
4005 aclcheck_error(aclresult, ACL_KIND_CLASS,
4006 RelationGetRelationName(pkrel));
4008 if (!allowSystemTableMods && IsSystemRelation(pkrel))
4010 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4011 errmsg("permission denied: \"%s\" is a system catalog",
4012 RelationGetRelationName(pkrel))));
4014 aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
4016 if (aclresult != ACLCHECK_OK)
4017 aclcheck_error(aclresult, ACL_KIND_CLASS,
4018 RelationGetRelationName(rel));
4021 * Disallow reference from permanent table to temp table or vice versa.
4022 * (The ban on perm->temp is for fairly obvious reasons. The ban on
4023 * temp->perm is because other backends might need to run the RI triggers
4024 * on the perm table, but they can't reliably see tuples the owning
4025 * backend has created in the temp table, because non-shared buffers are
4026 * used for temp tables.)
4028 if (isTempNamespace(RelationGetNamespace(pkrel)))
4030 if (!isTempNamespace(RelationGetNamespace(rel)))
4032 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4033 errmsg("cannot reference temporary table from permanent table constraint")));
4037 if (isTempNamespace(RelationGetNamespace(rel)))
4039 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4040 errmsg("cannot reference permanent table from temporary table constraint")));
4044 * Look up the referencing attributes to make sure they exist, and record
4045 * their attnums and type OIDs.
4047 MemSet(pkattnum, 0, sizeof(pkattnum));
4048 MemSet(fkattnum, 0, sizeof(fkattnum));
4049 MemSet(pktypoid, 0, sizeof(pktypoid));
4050 MemSet(fktypoid, 0, sizeof(fktypoid));
4051 MemSet(opclasses, 0, sizeof(opclasses));
4052 MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
4053 MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
4054 MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
4056 numfks = transformColumnNameList(RelationGetRelid(rel),
4057 fkconstraint->fk_attrs,
4058 fkattnum, fktypoid);
4061 * If the attribute list for the referenced table was omitted, lookup the
4062 * definition of the primary key and use it. Otherwise, validate the
4063 * supplied attribute list. In either case, discover the index OID and
4064 * index opclasses, and the attnums and type OIDs of the attributes.
4066 if (fkconstraint->pk_attrs == NIL)
4068 numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
4069 &fkconstraint->pk_attrs,
4075 numpks = transformColumnNameList(RelationGetRelid(pkrel),
4076 fkconstraint->pk_attrs,
4077 pkattnum, pktypoid);
4078 /* Look for an index matching the column list */
4079 indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
4084 * Look up the equality operators to use in the constraint.
4086 * Note that we have to be careful about the difference between the actual
4087 * PK column type and the opclass' declared input type, which might be
4088 * only binary-compatible with it. The declared opcintype is the right
4089 * thing to probe pg_amop with.
4091 if (numfks != numpks)
4093 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4094 errmsg("number of referencing and referenced columns for foreign key disagree")));
4096 for (i = 0; i < numpks; i++)
4098 Oid pktype = pktypoid[i];
4099 Oid fktype = fktypoid[i];
4102 Form_pg_opclass cla_tup;
4111 /* We need several fields out of the pg_opclass entry */
4112 cla_ht = SearchSysCache(CLAOID,
4113 ObjectIdGetDatum(opclasses[i]),
4115 if (!HeapTupleIsValid(cla_ht))
4116 elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
4117 cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
4118 amid = cla_tup->opcmethod;
4119 opfamily = cla_tup->opcfamily;
4120 opcintype = cla_tup->opcintype;
4121 ReleaseSysCache(cla_ht);
4124 * Check it's a btree; currently this can never fail since no other
4125 * index AMs support unique indexes. If we ever did have other types
4126 * of unique indexes, we'd need a way to determine which operator
4127 * strategy number is equality. (Is it reasonable to insist that
4128 * every such index AM use btree's number for equality?)
4130 if (amid != BTREE_AM_OID)
4131 elog(ERROR, "only b-tree indexes are supported for foreign keys");
4132 eqstrategy = BTEqualStrategyNumber;
4135 * There had better be a primary equality operator for the index.
4136 * We'll use it for PK = PK comparisons.
4138 ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
4141 if (!OidIsValid(ppeqop))
4142 elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
4143 eqstrategy, opcintype, opcintype, opfamily);
4146 * Are there equality operators that take exactly the FK type? Assume
4147 * we should look through any domain here.
4149 fktyped = getBaseType(fktype);
4151 pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
4153 if (OidIsValid(pfeqop))
4154 ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
4157 ffeqop = InvalidOid; /* keep compiler quiet */
4159 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4162 * Otherwise, look for an implicit cast from the FK type to the
4163 * opcintype, and if found, use the primary equality operator.
4164 * This is a bit tricky because opcintype might be a generic type
4165 * such as ANYARRAY, and so what we have to test is whether the
4166 * two actual column types can be concurrently cast to that type.
4167 * (Otherwise, we'd fail to reject combinations such as int[] and
4170 Oid input_typeids[2];
4171 Oid target_typeids[2];
4173 input_typeids[0] = pktype;
4174 input_typeids[1] = fktype;
4175 target_typeids[0] = opcintype;
4176 target_typeids[1] = opcintype;
4177 if (can_coerce_type(2, input_typeids, target_typeids,
4179 pfeqop = ffeqop = ppeqop;
4182 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4184 (errcode(ERRCODE_DATATYPE_MISMATCH),
4185 errmsg("foreign key constraint \"%s\" "
4186 "cannot be implemented",
4187 fkconstraint->constr_name),
4188 errdetail("Key columns \"%s\" and \"%s\" "
4189 "are of incompatible types: %s and %s.",
4190 strVal(list_nth(fkconstraint->fk_attrs, i)),
4191 strVal(list_nth(fkconstraint->pk_attrs, i)),
4192 format_type_be(fktype),
4193 format_type_be(pktype))));
4195 pfeqoperators[i] = pfeqop;
4196 ppeqoperators[i] = ppeqop;
4197 ffeqoperators[i] = ffeqop;
4201 * Record the FK constraint in pg_constraint.
4203 constrOid = CreateConstraintEntry(fkconstraint->constr_name,
4204 RelationGetNamespace(rel),
4206 fkconstraint->deferrable,
4207 fkconstraint->initdeferred,
4208 RelationGetRelid(rel),
4211 InvalidOid, /* not a domain
4213 RelationGetRelid(pkrel),
4219 fkconstraint->fk_upd_action,
4220 fkconstraint->fk_del_action,
4221 fkconstraint->fk_matchtype,
4223 NULL, /* no check constraint */
4228 * Create the triggers that will enforce the constraint.
4230 createForeignKeyTriggers(rel, fkconstraint, constrOid);
4233 * Tell Phase 3 to check that the constraint is satisfied by existing rows
4234 * (we can skip this during table creation).
4236 if (!fkconstraint->skip_validation)
4238 NewConstraint *newcon;
4240 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
4241 newcon->name = fkconstraint->constr_name;
4242 newcon->contype = CONSTR_FOREIGN;
4243 newcon->refrelid = RelationGetRelid(pkrel);
4244 newcon->conid = constrOid;
4245 newcon->qual = (Node *) fkconstraint;
4247 tab->constraints = lappend(tab->constraints, newcon);
4251 * Close pk table, but keep lock until we've committed.
4253 heap_close(pkrel, NoLock);
4258 * transformColumnNameList - transform list of column names
4260 * Lookup each name and return its attnum and type OID
4263 transformColumnNameList(Oid relId, List *colList,
4264 int16 *attnums, Oid *atttypids)
4272 char *attname = strVal(lfirst(l));
4275 atttuple = SearchSysCacheAttName(relId, attname);
4276 if (!HeapTupleIsValid(atttuple))
4278 (errcode(ERRCODE_UNDEFINED_COLUMN),
4279 errmsg("column \"%s\" referenced in foreign key constraint does not exist",
4281 if (attnum >= INDEX_MAX_KEYS)
4283 (errcode(ERRCODE_TOO_MANY_COLUMNS),
4284 errmsg("cannot have more than %d keys in a foreign key",
4286 attnums[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->attnum;
4287 atttypids[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->atttypid;
4288 ReleaseSysCache(atttuple);
4296 * transformFkeyGetPrimaryKey -
4298 * Look up the names, attnums, and types of the primary key attributes
4299 * for the pkrel. Also return the index OID and index opclasses of the
4300 * index supporting the primary key.
4302 * All parameters except pkrel are output parameters. Also, the function
4303 * return value is the number of attributes in the primary key.
4305 * Used when the column list in the REFERENCES specification is omitted.
4308 transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
4310 int16 *attnums, Oid *atttypids,
4314 ListCell *indexoidscan;
4315 HeapTuple indexTuple = NULL;
4316 Form_pg_index indexStruct = NULL;
4317 Datum indclassDatum;
4319 oidvector *indclass;
4323 * Get the list of index OIDs for the table from the relcache, and look up
4324 * each one in the pg_index syscache until we find one marked primary key
4325 * (hopefully there isn't more than one such).
4327 *indexOid = InvalidOid;
4329 indexoidlist = RelationGetIndexList(pkrel);
4331 foreach(indexoidscan, indexoidlist)
4333 Oid indexoid = lfirst_oid(indexoidscan);
4335 indexTuple = SearchSysCache(INDEXRELID,
4336 ObjectIdGetDatum(indexoid),
4338 if (!HeapTupleIsValid(indexTuple))
4339 elog(ERROR, "cache lookup failed for index %u", indexoid);
4340 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4341 if (indexStruct->indisprimary)
4343 *indexOid = indexoid;
4346 ReleaseSysCache(indexTuple);
4349 list_free(indexoidlist);
4352 * Check that we found it
4354 if (!OidIsValid(*indexOid))
4356 (errcode(ERRCODE_UNDEFINED_OBJECT),
4357 errmsg("there is no primary key for referenced table \"%s\"",
4358 RelationGetRelationName(pkrel))));
4360 /* Must get indclass the hard way */
4361 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4362 Anum_pg_index_indclass, &isnull);
4364 indclass = (oidvector *) DatumGetPointer(indclassDatum);
4367 * Now build the list of PK attributes from the indkey definition (we
4368 * assume a primary key cannot have expressional elements)
4371 for (i = 0; i < indexStruct->indnatts; i++)
4373 int pkattno = indexStruct->indkey.values[i];
4375 attnums[i] = pkattno;
4376 atttypids[i] = attnumTypeId(pkrel, pkattno);
4377 opclasses[i] = indclass->values[i];
4378 *attnamelist = lappend(*attnamelist,
4379 makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
4382 ReleaseSysCache(indexTuple);
4388 * transformFkeyCheckAttrs -
4390 * Make sure that the attributes of a referenced table belong to a unique
4391 * (or primary key) constraint. Return the OID of the index supporting
4392 * the constraint, as well as the opclasses associated with the index
4396 transformFkeyCheckAttrs(Relation pkrel,
4397 int numattrs, int16 *attnums,
4398 Oid *opclasses) /* output parameter */
4400 Oid indexoid = InvalidOid;
4403 ListCell *indexoidscan;
4406 * Get the list of index OIDs for the table from the relcache, and look up
4407 * each one in the pg_index syscache, and match unique indexes to the list
4408 * of attnums we are given.
4410 indexoidlist = RelationGetIndexList(pkrel);
4412 foreach(indexoidscan, indexoidlist)
4414 HeapTuple indexTuple;
4415 Form_pg_index indexStruct;
4419 indexoid = lfirst_oid(indexoidscan);
4420 indexTuple = SearchSysCache(INDEXRELID,
4421 ObjectIdGetDatum(indexoid),
4423 if (!HeapTupleIsValid(indexTuple))
4424 elog(ERROR, "cache lookup failed for index %u", indexoid);
4425 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4428 * Must have the right number of columns; must be unique and not a
4429 * partial index; forget it if there are any expressions, too
4431 if (indexStruct->indnatts == numattrs &&
4432 indexStruct->indisunique &&
4433 heap_attisnull(indexTuple, Anum_pg_index_indpred) &&
4434 heap_attisnull(indexTuple, Anum_pg_index_indexprs))
4436 /* Must get indclass the hard way */
4437 Datum indclassDatum;
4439 oidvector *indclass;
4441 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4442 Anum_pg_index_indclass, &isnull);
4444 indclass = (oidvector *) DatumGetPointer(indclassDatum);
4447 * The given attnum list may match the index columns in any order.
4448 * Check that each list is a subset of the other.
4450 for (i = 0; i < numattrs; i++)
4453 for (j = 0; j < numattrs; j++)
4455 if (attnums[i] == indexStruct->indkey.values[j])
4466 for (i = 0; i < numattrs; i++)
4469 for (j = 0; j < numattrs; j++)
4471 if (attnums[j] == indexStruct->indkey.values[i])
4473 opclasses[j] = indclass->values[i];
4483 ReleaseSysCache(indexTuple);
4490 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4491 errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
4492 RelationGetRelationName(pkrel))));
4494 list_free(indexoidlist);
4500 * Scan the existing rows in a table to verify they meet a proposed FK
4503 * Caller must have opened and locked both relations.
4506 validateForeignKeyConstraint(FkConstraint *fkconstraint,
4516 * Build a trigger call structure; we'll need it either way.
4518 MemSet(&trig, 0, sizeof(trig));
4519 trig.tgoid = InvalidOid;
4520 trig.tgname = fkconstraint->constr_name;
4521 trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
4522 trig.tgisconstraint = TRUE;
4523 trig.tgconstrrelid = RelationGetRelid(pkrel);
4524 trig.tgconstraint = constraintOid;
4525 trig.tgdeferrable = FALSE;
4526 trig.tginitdeferred = FALSE;
4527 /* we needn't fill in tgargs */
4530 * See if we can do it with a single LEFT JOIN query. A FALSE result
4531 * indicates we must proceed with the fire-the-trigger method.
4533 if (RI_Initial_Check(&trig, rel, pkrel))
4537 * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
4538 * if that tuple had just been inserted. If any of those fail, it should
4539 * ereport(ERROR) and that's that.
4541 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
4543 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
4545 FunctionCallInfoData fcinfo;
4546 TriggerData trigdata;
4549 * Make a call to the trigger function
4551 * No parameters are passed, but we do set a context
4553 MemSet(&fcinfo, 0, sizeof(fcinfo));
4556 * We assume RI_FKey_check_ins won't look at flinfo...
4558 trigdata.type = T_TriggerData;
4559 trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
4560 trigdata.tg_relation = rel;
4561 trigdata.tg_trigtuple = tuple;
4562 trigdata.tg_newtuple = NULL;
4563 trigdata.tg_trigger = &trig;
4564 trigdata.tg_trigtuplebuf = scan->rs_cbuf;
4565 trigdata.tg_newtuplebuf = InvalidBuffer;
4567 fcinfo.context = (Node *) &trigdata;
4569 RI_FKey_check_ins(&fcinfo);
4576 CreateFKCheckTrigger(RangeVar *myRel, FkConstraint *fkconstraint,
4577 Oid constraintOid, bool on_insert)
4579 CreateTrigStmt *fk_trigger;
4581 fk_trigger = makeNode(CreateTrigStmt);
4582 fk_trigger->trigname = fkconstraint->constr_name;
4583 fk_trigger->relation = myRel;
4584 fk_trigger->before = false;
4585 fk_trigger->row = true;
4587 /* Either ON INSERT or ON UPDATE */
4590 fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
4591 fk_trigger->actions[0] = 'i';
4595 fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
4596 fk_trigger->actions[0] = 'u';
4598 fk_trigger->actions[1] = '\0';
4600 fk_trigger->isconstraint = true;
4601 fk_trigger->deferrable = fkconstraint->deferrable;
4602 fk_trigger->initdeferred = fkconstraint->initdeferred;
4603 fk_trigger->constrrel = fkconstraint->pktable;
4604 fk_trigger->args = NIL;
4606 (void) CreateTrigger(fk_trigger, constraintOid);
4608 /* Make changes-so-far visible */
4609 CommandCounterIncrement();
4613 * Create the triggers that implement an FK constraint.
4616 createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
4620 CreateTrigStmt *fk_trigger;
4623 * Reconstruct a RangeVar for my relation (not passed in, unfortunately).
4625 myRel = makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
4626 pstrdup(RelationGetRelationName(rel)));
4628 /* Make changes-so-far visible */
4629 CommandCounterIncrement();
4632 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the CHECK
4633 * action for both INSERTs and UPDATEs on the referencing table.
4635 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, true);
4636 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, false);
4639 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
4640 * DELETE action on the referenced table.
4642 fk_trigger = makeNode(CreateTrigStmt);
4643 fk_trigger->trigname = fkconstraint->constr_name;
4644 fk_trigger->relation = fkconstraint->pktable;
4645 fk_trigger->before = false;
4646 fk_trigger->row = true;
4647 fk_trigger->actions[0] = 'd';
4648 fk_trigger->actions[1] = '\0';
4650 fk_trigger->isconstraint = true;
4651 fk_trigger->constrrel = myRel;
4652 switch (fkconstraint->fk_del_action)
4654 case FKCONSTR_ACTION_NOACTION:
4655 fk_trigger->deferrable = fkconstraint->deferrable;
4656 fk_trigger->initdeferred = fkconstraint->initdeferred;
4657 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
4659 case FKCONSTR_ACTION_RESTRICT:
4660 fk_trigger->deferrable = false;
4661 fk_trigger->initdeferred = false;
4662 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
4664 case FKCONSTR_ACTION_CASCADE:
4665 fk_trigger->deferrable = false;
4666 fk_trigger->initdeferred = false;
4667 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
4669 case FKCONSTR_ACTION_SETNULL:
4670 fk_trigger->deferrable = false;
4671 fk_trigger->initdeferred = false;
4672 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
4674 case FKCONSTR_ACTION_SETDEFAULT:
4675 fk_trigger->deferrable = false;
4676 fk_trigger->initdeferred = false;
4677 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
4680 elog(ERROR, "unrecognized FK action type: %d",
4681 (int) fkconstraint->fk_del_action);
4684 fk_trigger->args = NIL;
4686 (void) CreateTrigger(fk_trigger, constraintOid);
4688 /* Make changes-so-far visible */
4689 CommandCounterIncrement();
4692 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
4693 * UPDATE action on the referenced table.
4695 fk_trigger = makeNode(CreateTrigStmt);
4696 fk_trigger->trigname = fkconstraint->constr_name;
4697 fk_trigger->relation = fkconstraint->pktable;
4698 fk_trigger->before = false;
4699 fk_trigger->row = true;
4700 fk_trigger->actions[0] = 'u';
4701 fk_trigger->actions[1] = '\0';
4702 fk_trigger->isconstraint = true;
4703 fk_trigger->constrrel = myRel;
4704 switch (fkconstraint->fk_upd_action)
4706 case FKCONSTR_ACTION_NOACTION:
4707 fk_trigger->deferrable = fkconstraint->deferrable;
4708 fk_trigger->initdeferred = fkconstraint->initdeferred;
4709 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
4711 case FKCONSTR_ACTION_RESTRICT:
4712 fk_trigger->deferrable = false;
4713 fk_trigger->initdeferred = false;
4714 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
4716 case FKCONSTR_ACTION_CASCADE:
4717 fk_trigger->deferrable = false;
4718 fk_trigger->initdeferred = false;
4719 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
4721 case FKCONSTR_ACTION_SETNULL:
4722 fk_trigger->deferrable = false;
4723 fk_trigger->initdeferred = false;
4724 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
4726 case FKCONSTR_ACTION_SETDEFAULT:
4727 fk_trigger->deferrable = false;
4728 fk_trigger->initdeferred = false;
4729 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
4732 elog(ERROR, "unrecognized FK action type: %d",
4733 (int) fkconstraint->fk_upd_action);
4736 fk_trigger->args = NIL;
4738 (void) CreateTrigger(fk_trigger, constraintOid);
4742 * ALTER TABLE DROP CONSTRAINT
4745 ATPrepDropConstraint(List **wqueue, Relation rel,
4746 bool recurse, AlterTableCmd *cmd)
4749 * We don't want errors or noise from child tables, so we have to pass
4750 * down a modified command.
4754 AlterTableCmd *childCmd = copyObject(cmd);
4756 childCmd->subtype = AT_DropConstraintQuietly;
4757 ATSimpleRecursion(wqueue, rel, childCmd, recurse);
4762 ATExecDropConstraint(Relation rel, const char *constrName,
4763 DropBehavior behavior, bool quiet)
4767 deleted = RemoveRelConstraints(rel, constrName, behavior);
4771 /* If zero constraints deleted, complain */
4774 (errcode(ERRCODE_UNDEFINED_OBJECT),
4775 errmsg("constraint \"%s\" does not exist",
4777 /* Otherwise if more than one constraint deleted, notify */
4778 else if (deleted > 1)
4780 (errmsg("multiple constraints named \"%s\" were dropped",
4789 ATPrepAlterColumnType(List **wqueue,
4790 AlteredTableInfo *tab, Relation rel,
4791 bool recurse, bool recursing,
4794 char *colName = cmd->name;
4795 TypeName *typename = (TypeName *) cmd->def;
4797 Form_pg_attribute attTup;
4802 NewColumnValue *newval;
4803 ParseState *pstate = make_parsestate(NULL);
4805 /* lookup the attribute so we can check inheritance status */
4806 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
4807 if (!HeapTupleIsValid(tuple))
4809 (errcode(ERRCODE_UNDEFINED_COLUMN),
4810 errmsg("column \"%s\" of relation \"%s\" does not exist",
4811 colName, RelationGetRelationName(rel))));
4812 attTup = (Form_pg_attribute) GETSTRUCT(tuple);
4813 attnum = attTup->attnum;
4815 /* Can't alter a system attribute */
4818 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4819 errmsg("cannot alter system column \"%s\"",
4822 /* Don't alter inherited columns */
4823 if (attTup->attinhcount > 0 && !recursing)
4825 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4826 errmsg("cannot alter inherited column \"%s\"",
4829 /* Look up the target type */
4830 targettype = typenameTypeId(NULL, typename, &targettypmod);
4832 /* make sure datatype is legal for a column */
4833 CheckAttributeType(colName, targettype);
4836 * Set up an expression to transform the old data value to the new type.
4837 * If a USING option was given, transform and use that expression, else
4838 * just take the old value and try to coerce it. We do this first so that
4839 * type incompatibility can be detected before we waste effort, and
4840 * because we need the expression to be parsed against the original table
4847 /* Expression must be able to access vars of old table */
4848 rte = addRangeTableEntryForRelation(pstate,
4853 addRTEtoQuery(pstate, rte, false, true, true);
4855 transform = transformExpr(pstate, cmd->transform);
4857 /* It can't return a set */
4858 if (expression_returns_set(transform))
4860 (errcode(ERRCODE_DATATYPE_MISMATCH),
4861 errmsg("transform expression must not return a set")));
4863 /* No subplans or aggregates, either... */
4864 if (pstate->p_hasSubLinks)
4866 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4867 errmsg("cannot use subquery in transform expression")));
4868 if (pstate->p_hasAggs)
4870 (errcode(ERRCODE_GROUPING_ERROR),
4871 errmsg("cannot use aggregate function in transform expression")));
4875 transform = (Node *) makeVar(1, attnum,
4876 attTup->atttypid, attTup->atttypmod,
4880 transform = coerce_to_target_type(pstate,
4881 transform, exprType(transform),
4882 targettype, targettypmod,
4883 COERCION_ASSIGNMENT,
4884 COERCE_IMPLICIT_CAST);
4885 if (transform == NULL)
4887 (errcode(ERRCODE_DATATYPE_MISMATCH),
4888 errmsg("column \"%s\" cannot be cast to type \"%s\"",
4889 colName, TypeNameToString(typename))));
4892 * Add a work queue item to make ATRewriteTable update the column
4895 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
4896 newval->attnum = attnum;
4897 newval->expr = (Expr *) transform;
4899 tab->newvals = lappend(tab->newvals, newval);
4901 ReleaseSysCache(tuple);
4904 * The recursion case is handled by ATSimpleRecursion. However, if we are
4905 * told not to recurse, there had better not be any child tables; else the
4906 * alter would put them out of step.
4909 ATSimpleRecursion(wqueue, rel, cmd, recurse);
4910 else if (!recursing &&
4911 find_inheritance_children(RelationGetRelid(rel)) != NIL)
4913 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4914 errmsg("type of inherited column \"%s\" must be changed in child tables too",
4919 ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
4920 const char *colName, TypeName *typename)
4923 Form_pg_attribute attTup;
4925 HeapTuple typeTuple;
4930 Relation attrelation;
4936 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
4938 /* Look up the target column */
4939 heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4940 if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
4942 (errcode(ERRCODE_UNDEFINED_COLUMN),
4943 errmsg("column \"%s\" of relation \"%s\" does not exist",
4944 colName, RelationGetRelationName(rel))));
4945 attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
4946 attnum = attTup->attnum;
4948 /* Check for multiple ALTER TYPE on same column --- can't cope */
4949 if (attTup->atttypid != tab->oldDesc->attrs[attnum - 1]->atttypid ||
4950 attTup->atttypmod != tab->oldDesc->attrs[attnum - 1]->atttypmod)
4952 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4953 errmsg("cannot alter type of column \"%s\" twice",
4956 /* Look up the target type (should not fail, since prep found it) */
4957 typeTuple = typenameType(NULL, typename, &targettypmod);
4958 tform = (Form_pg_type) GETSTRUCT(typeTuple);
4959 targettype = HeapTupleGetOid(typeTuple);
4962 * If there is a default expression for the column, get it and ensure we
4963 * can coerce it to the new datatype. (We must do this before changing
4964 * the column type, because build_column_default itself will try to
4965 * coerce, and will not issue the error message we want if it fails.)
4967 * We remove any implicit coercion steps at the top level of the old
4968 * default expression; this has been agreed to satisfy the principle of
4969 * least surprise. (The conversion to the new column type should act like
4970 * it started from what the user sees as the stored expression, and the
4971 * implicit coercions aren't going to be shown.)
4973 if (attTup->atthasdef)
4975 defaultexpr = build_column_default(rel, attnum);
4976 Assert(defaultexpr);
4977 defaultexpr = strip_implicit_coercions(defaultexpr);
4978 defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
4979 defaultexpr, exprType(defaultexpr),
4980 targettype, targettypmod,
4981 COERCION_ASSIGNMENT,
4982 COERCE_IMPLICIT_CAST);
4983 if (defaultexpr == NULL)
4985 (errcode(ERRCODE_DATATYPE_MISMATCH),
4986 errmsg("default for column \"%s\" cannot be cast to type \"%s\"",
4987 colName, TypeNameToString(typename))));
4993 * Find everything that depends on the column (constraints, indexes, etc),
4994 * and record enough information to let us recreate the objects.
4996 * The actual recreation does not happen here, but only after we have
4997 * performed all the individual ALTER TYPE operations. We have to save
4998 * the info before executing ALTER TYPE, though, else the deparser will
5001 * There could be multiple entries for the same object, so we must check
5002 * to ensure we process each one only once. Note: we assume that an index
5003 * that implements a constraint will not show a direct dependency on the
5006 depRel = heap_open(DependRelationId, RowExclusiveLock);
5008 ScanKeyInit(&key[0],
5009 Anum_pg_depend_refclassid,
5010 BTEqualStrategyNumber, F_OIDEQ,
5011 ObjectIdGetDatum(RelationRelationId));
5012 ScanKeyInit(&key[1],
5013 Anum_pg_depend_refobjid,
5014 BTEqualStrategyNumber, F_OIDEQ,
5015 ObjectIdGetDatum(RelationGetRelid(rel)));
5016 ScanKeyInit(&key[2],
5017 Anum_pg_depend_refobjsubid,
5018 BTEqualStrategyNumber, F_INT4EQ,
5019 Int32GetDatum((int32) attnum));
5021 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
5022 SnapshotNow, 3, key);
5024 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5026 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5027 ObjectAddress foundObject;
5029 /* We don't expect any PIN dependencies on columns */
5030 if (foundDep->deptype == DEPENDENCY_PIN)
5031 elog(ERROR, "cannot alter type of a pinned column");
5033 foundObject.classId = foundDep->classid;
5034 foundObject.objectId = foundDep->objid;
5035 foundObject.objectSubId = foundDep->objsubid;
5037 switch (getObjectClass(&foundObject))
5041 char relKind = get_rel_relkind(foundObject.objectId);
5043 if (relKind == RELKIND_INDEX)
5045 Assert(foundObject.objectSubId == 0);
5046 if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
5048 tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
5049 foundObject.objectId);
5050 tab->changedIndexDefs = lappend(tab->changedIndexDefs,
5051 pg_get_indexdef_string(foundObject.objectId));
5054 else if (relKind == RELKIND_SEQUENCE)
5057 * This must be a SERIAL column's sequence. We need
5058 * not do anything to it.
5060 Assert(foundObject.objectSubId == 0);
5064 /* Not expecting any other direct dependencies... */
5065 elog(ERROR, "unexpected object depending on column: %s",
5066 getObjectDescription(&foundObject));
5071 case OCLASS_CONSTRAINT:
5072 Assert(foundObject.objectSubId == 0);
5073 if (!list_member_oid(tab->changedConstraintOids,
5074 foundObject.objectId))
5076 char *defstring = pg_get_constraintdef_string(foundObject.objectId);
5079 * Put NORMAL dependencies at the front of the list and
5080 * AUTO dependencies at the back. This makes sure that
5081 * foreign-key constraints depending on this column will
5082 * be dropped before unique or primary-key constraints of
5083 * the column; which we must have because the FK
5084 * constraints depend on the indexes belonging to the
5085 * unique constraints.
5087 if (foundDep->deptype == DEPENDENCY_NORMAL)
5089 tab->changedConstraintOids =
5090 lcons_oid(foundObject.objectId,
5091 tab->changedConstraintOids);
5092 tab->changedConstraintDefs =
5094 tab->changedConstraintDefs);
5098 tab->changedConstraintOids =
5099 lappend_oid(tab->changedConstraintOids,
5100 foundObject.objectId);
5101 tab->changedConstraintDefs =
5102 lappend(tab->changedConstraintDefs,
5108 case OCLASS_REWRITE:
5109 /* XXX someday see if we can cope with revising views */
5111 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5112 errmsg("cannot alter type of a column used by a view or rule"),
5113 errdetail("%s depends on column \"%s\"",
5114 getObjectDescription(&foundObject),
5118 case OCLASS_DEFAULT:
5121 * Ignore the column's default expression, since we will fix
5124 Assert(defaultexpr);
5130 case OCLASS_CONVERSION:
5131 case OCLASS_LANGUAGE:
5132 case OCLASS_OPERATOR:
5133 case OCLASS_OPCLASS:
5134 case OCLASS_OPFAMILY:
5135 case OCLASS_TRIGGER:
5137 case OCLASS_TSPARSER:
5139 case OCLASS_TSTEMPLATE:
5140 case OCLASS_TSCONFIG:
5143 * We don't expect any of these sorts of objects to depend on
5146 elog(ERROR, "unexpected object depending on column: %s",
5147 getObjectDescription(&foundObject));
5151 elog(ERROR, "unrecognized object class: %u",
5152 foundObject.classId);
5156 systable_endscan(scan);
5159 * Now scan for dependencies of this column on other things. The only
5160 * thing we should find is the dependency on the column datatype, which we
5163 ScanKeyInit(&key[0],
5164 Anum_pg_depend_classid,
5165 BTEqualStrategyNumber, F_OIDEQ,
5166 ObjectIdGetDatum(RelationRelationId));
5167 ScanKeyInit(&key[1],
5168 Anum_pg_depend_objid,
5169 BTEqualStrategyNumber, F_OIDEQ,
5170 ObjectIdGetDatum(RelationGetRelid(rel)));
5171 ScanKeyInit(&key[2],
5172 Anum_pg_depend_objsubid,
5173 BTEqualStrategyNumber, F_INT4EQ,
5174 Int32GetDatum((int32) attnum));
5176 scan = systable_beginscan(depRel, DependDependerIndexId, true,
5177 SnapshotNow, 3, key);
5179 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5181 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5183 if (foundDep->deptype != DEPENDENCY_NORMAL)
5184 elog(ERROR, "found unexpected dependency type '%c'",
5186 if (foundDep->refclassid != TypeRelationId ||
5187 foundDep->refobjid != attTup->atttypid)
5188 elog(ERROR, "found unexpected dependency for column");
5190 simple_heap_delete(depRel, &depTup->t_self);
5193 systable_endscan(scan);
5195 heap_close(depRel, RowExclusiveLock);
5198 * Here we go --- change the recorded column type. (Note heapTup is a
5199 * copy of the syscache entry, so okay to scribble on.)
5201 attTup->atttypid = targettype;
5202 attTup->atttypmod = targettypmod;
5203 attTup->attndims = list_length(typename->arrayBounds);
5204 attTup->attlen = tform->typlen;
5205 attTup->attbyval = tform->typbyval;
5206 attTup->attalign = tform->typalign;
5207 attTup->attstorage = tform->typstorage;
5209 ReleaseSysCache(typeTuple);
5211 simple_heap_update(attrelation, &heapTup->t_self, heapTup);
5213 /* keep system catalog indexes current */
5214 CatalogUpdateIndexes(attrelation, heapTup);
5216 heap_close(attrelation, RowExclusiveLock);
5218 /* Install dependency on new datatype */
5219 add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
5222 * Drop any pg_statistic entry for the column, since it's now wrong type
5224 RemoveStatistics(RelationGetRelid(rel), attnum);
5227 * Update the default, if present, by brute force --- remove and re-add
5228 * the default. Probably unsafe to take shortcuts, since the new version
5229 * may well have additional dependencies. (It's okay to do this now,
5230 * rather than after other ALTER TYPE commands, since the default won't
5231 * depend on other column types.)
5235 /* Must make new row visible since it will be updated again */
5236 CommandCounterIncrement();
5239 * We use RESTRICT here for safety, but at present we do not expect
5240 * anything to depend on the default.
5242 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true);
5244 StoreAttrDefault(rel, attnum, nodeToString(defaultexpr));
5248 heap_freetuple(heapTup);
5252 * Cleanup after we've finished all the ALTER TYPE operations for a
5253 * particular relation. We have to drop and recreate all the indexes
5254 * and constraints that depend on the altered columns.
5257 ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab)
5263 * Re-parse the index and constraint definitions, and attach them to the
5264 * appropriate work queue entries. We do this before dropping because in
5265 * the case of a FOREIGN KEY constraint, we might not yet have exclusive
5266 * lock on the table the constraint is attached to, and we need to get
5267 * that before dropping. It's safe because the parser won't actually look
5268 * at the catalogs to detect the existing entry.
5270 foreach(l, tab->changedIndexDefs)
5271 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
5272 foreach(l, tab->changedConstraintDefs)
5273 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
5276 * Now we can drop the existing constraints and indexes --- constraints
5277 * first, since some of them might depend on the indexes. In fact, we
5278 * have to delete FOREIGN KEY constraints before UNIQUE constraints, but
5279 * we already ordered the constraint list to ensure that would happen. It
5280 * should be okay to use DROP_RESTRICT here, since nothing else should be
5281 * depending on these objects.
5283 foreach(l, tab->changedConstraintOids)
5285 obj.classId = ConstraintRelationId;
5286 obj.objectId = lfirst_oid(l);
5287 obj.objectSubId = 0;
5288 performDeletion(&obj, DROP_RESTRICT);
5291 foreach(l, tab->changedIndexOids)
5293 obj.classId = RelationRelationId;
5294 obj.objectId = lfirst_oid(l);
5295 obj.objectSubId = 0;
5296 performDeletion(&obj, DROP_RESTRICT);
5300 * The objects will get recreated during subsequent passes over the work
5306 ATPostAlterTypeParse(char *cmd, List **wqueue)
5308 List *raw_parsetree_list;
5309 List *querytree_list;
5310 ListCell *list_item;
5313 * We expect that we will get only ALTER TABLE and CREATE INDEX
5314 * statements. Hence, there is no need to pass them through
5315 * parse_analyze() or the rewriter, but instead we need to pass them
5316 * through parse_utilcmd.c to make them ready for execution.
5318 raw_parsetree_list = raw_parser(cmd);
5319 querytree_list = NIL;
5320 foreach(list_item, raw_parsetree_list)
5322 Node *stmt = (Node *) lfirst(list_item);
5324 if (IsA(stmt, IndexStmt))
5325 querytree_list = lappend(querytree_list,
5326 transformIndexStmt((IndexStmt *) stmt,
5328 else if (IsA(stmt, AlterTableStmt))
5329 querytree_list = list_concat(querytree_list,
5330 transformAlterTableStmt((AlterTableStmt *) stmt,
5333 querytree_list = lappend(querytree_list, stmt);
5337 * Attach each generated command to the proper place in the work queue.
5338 * Note this could result in creation of entirely new work-queue entries.
5340 foreach(list_item, querytree_list)
5342 Node *stm = (Node *) lfirst(list_item);
5344 AlteredTableInfo *tab;
5346 switch (nodeTag(stm))
5350 IndexStmt *stmt = (IndexStmt *) stm;
5351 AlterTableCmd *newcmd;
5353 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
5354 tab = ATGetQueueEntry(wqueue, rel);
5355 newcmd = makeNode(AlterTableCmd);
5356 newcmd->subtype = AT_ReAddIndex;
5357 newcmd->def = (Node *) stmt;
5358 tab->subcmds[AT_PASS_OLD_INDEX] =
5359 lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
5360 relation_close(rel, NoLock);
5363 case T_AlterTableStmt:
5365 AlterTableStmt *stmt = (AlterTableStmt *) stm;
5368 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
5369 tab = ATGetQueueEntry(wqueue, rel);
5370 foreach(lcmd, stmt->cmds)
5372 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
5374 switch (cmd->subtype)
5377 cmd->subtype = AT_ReAddIndex;
5378 tab->subcmds[AT_PASS_OLD_INDEX] =
5379 lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
5381 case AT_AddConstraint:
5382 tab->subcmds[AT_PASS_OLD_CONSTR] =
5383 lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
5386 elog(ERROR, "unexpected statement type: %d",
5387 (int) cmd->subtype);
5390 relation_close(rel, NoLock);
5394 elog(ERROR, "unexpected statement type: %d",
5395 (int) nodeTag(stm));
5404 * recursing is true if we are recursing from a table to its indexes,
5405 * sequences, or toast table. We don't allow the ownership of those things to
5406 * be changed separately from the parent table. Also, we can skip permission
5407 * checks (this is necessary not just an optimization, else we'd fail to
5408 * handle toast tables properly).
5410 * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
5411 * free-standing composite type.
5414 ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing)
5416 Relation target_rel;
5419 Form_pg_class tuple_class;
5422 * Get exclusive lock till end of transaction on the target table. Use
5423 * relation_open so that we can work on indexes and sequences.
5425 target_rel = relation_open(relationOid, AccessExclusiveLock);
5427 /* Get its pg_class tuple, too */
5428 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
5430 tuple = SearchSysCache(RELOID,
5431 ObjectIdGetDatum(relationOid),
5433 if (!HeapTupleIsValid(tuple))
5434 elog(ERROR, "cache lookup failed for relation %u", relationOid);
5435 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
5437 /* Can we change the ownership of this tuple? */
5438 switch (tuple_class->relkind)
5440 case RELKIND_RELATION:
5442 /* ok to change owner */
5448 * Because ALTER INDEX OWNER used to be allowed, and in fact
5449 * is generated by old versions of pg_dump, we give a warning
5450 * and do nothing rather than erroring out. Also, to avoid
5451 * unnecessary chatter while restoring those old dumps, say
5452 * nothing at all if the command would be a no-op anyway.
5454 if (tuple_class->relowner != newOwnerId)
5456 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5457 errmsg("cannot change owner of index \"%s\"",
5458 NameStr(tuple_class->relname)),
5459 errhint("Change the ownership of the index's table, instead.")));
5460 /* quick hack to exit via the no-op path */
5461 newOwnerId = tuple_class->relowner;
5464 case RELKIND_SEQUENCE:
5466 tuple_class->relowner != newOwnerId)
5468 /* if it's an owned sequence, disallow changing it by itself */
5472 if (sequenceIsOwned(relationOid, &tableId, &colId))
5474 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5475 errmsg("cannot change owner of sequence \"%s\"",
5476 NameStr(tuple_class->relname)),
5477 errdetail("Sequence \"%s\" is linked to table \"%s\".",
5478 NameStr(tuple_class->relname),
5479 get_rel_name(tableId))));
5482 case RELKIND_COMPOSITE_TYPE:
5486 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5487 errmsg("\"%s\" is a composite type",
5488 NameStr(tuple_class->relname)),
5489 errhint("Use ALTER TYPE instead.")));
5491 case RELKIND_TOASTVALUE:
5497 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5498 errmsg("\"%s\" is not a table, view, or sequence",
5499 NameStr(tuple_class->relname))));
5503 * If the new owner is the same as the existing owner, consider the
5504 * command to have succeeded. This is for dump restoration purposes.
5506 if (tuple_class->relowner != newOwnerId)
5508 Datum repl_val[Natts_pg_class];
5509 char repl_null[Natts_pg_class];
5510 char repl_repl[Natts_pg_class];
5516 /* skip permission checks when recursing to index or toast table */
5519 /* Superusers can always do it */
5522 Oid namespaceOid = tuple_class->relnamespace;
5523 AclResult aclresult;
5525 /* Otherwise, must be owner of the existing object */
5526 if (!pg_class_ownercheck(relationOid, GetUserId()))
5527 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
5528 RelationGetRelationName(target_rel));
5530 /* Must be able to become new owner */
5531 check_is_member_of_role(GetUserId(), newOwnerId);
5533 /* New owner must have CREATE privilege on namespace */
5534 aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
5536 if (aclresult != ACLCHECK_OK)
5537 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
5538 get_namespace_name(namespaceOid));
5542 memset(repl_null, ' ', sizeof(repl_null));
5543 memset(repl_repl, ' ', sizeof(repl_repl));
5545 repl_repl[Anum_pg_class_relowner - 1] = 'r';
5546 repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
5549 * Determine the modified ACL for the new owner. This is only
5550 * necessary when the ACL is non-null.
5552 aclDatum = SysCacheGetAttr(RELOID, tuple,
5553 Anum_pg_class_relacl,
5557 newAcl = aclnewowner(DatumGetAclP(aclDatum),
5558 tuple_class->relowner, newOwnerId);
5559 repl_repl[Anum_pg_class_relacl - 1] = 'r';
5560 repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
5563 newtuple = heap_modifytuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
5565 simple_heap_update(class_rel, &newtuple->t_self, newtuple);
5566 CatalogUpdateIndexes(class_rel, newtuple);
5568 heap_freetuple(newtuple);
5571 * Update owner dependency reference, if any. A composite type has
5572 * none, because it's tracked for the pg_type entry instead of here;
5573 * indexes and TOAST tables don't have their own entries either.
5575 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
5576 tuple_class->relkind != RELKIND_INDEX &&
5577 tuple_class->relkind != RELKIND_TOASTVALUE)
5578 changeDependencyOnOwner(RelationRelationId, relationOid,
5582 * Also change the ownership of the table's rowtype, if it has one
5584 if (tuple_class->relkind != RELKIND_INDEX)
5585 AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId,
5586 tuple_class->relkind == RELKIND_COMPOSITE_TYPE);
5589 * If we are operating on a table, also change the ownership of any
5590 * indexes and sequences that belong to the table, as well as the
5591 * table's toast table (if it has one)
5593 if (tuple_class->relkind == RELKIND_RELATION ||
5594 tuple_class->relkind == RELKIND_TOASTVALUE)
5596 List *index_oid_list;
5599 /* Find all the indexes belonging to this relation */
5600 index_oid_list = RelationGetIndexList(target_rel);
5602 /* For each index, recursively change its ownership */
5603 foreach(i, index_oid_list)
5604 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true);
5606 list_free(index_oid_list);
5609 if (tuple_class->relkind == RELKIND_RELATION)
5611 /* If it has a toast table, recurse to change its ownership */
5612 if (tuple_class->reltoastrelid != InvalidOid)
5613 ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
5616 /* If it has dependent sequences, recurse to change them too */
5617 change_owner_recurse_to_sequences(relationOid, newOwnerId);
5621 ReleaseSysCache(tuple);
5622 heap_close(class_rel, RowExclusiveLock);
5623 relation_close(target_rel, NoLock);
5627 * change_owner_recurse_to_sequences
5629 * Helper function for ATExecChangeOwner. Examines pg_depend searching
5630 * for sequences that are dependent on serial columns, and changes their
5634 change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId)
5642 * SERIAL sequences are those having an auto dependency on one of the
5643 * table's columns (we don't care *which* column, exactly).
5645 depRel = heap_open(DependRelationId, AccessShareLock);
5647 ScanKeyInit(&key[0],
5648 Anum_pg_depend_refclassid,
5649 BTEqualStrategyNumber, F_OIDEQ,
5650 ObjectIdGetDatum(RelationRelationId));
5651 ScanKeyInit(&key[1],
5652 Anum_pg_depend_refobjid,
5653 BTEqualStrategyNumber, F_OIDEQ,
5654 ObjectIdGetDatum(relationOid));
5655 /* we leave refobjsubid unspecified */
5657 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
5658 SnapshotNow, 2, key);
5660 while (HeapTupleIsValid(tup = systable_getnext(scan)))
5662 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
5665 /* skip dependencies other than auto dependencies on columns */
5666 if (depForm->refobjsubid == 0 ||
5667 depForm->classid != RelationRelationId ||
5668 depForm->objsubid != 0 ||
5669 depForm->deptype != DEPENDENCY_AUTO)
5672 /* Use relation_open just in case it's an index */
5673 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
5675 /* skip non-sequence relations */
5676 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
5678 /* No need to keep the lock */
5679 relation_close(seqRel, AccessExclusiveLock);
5683 /* We don't need to close the sequence while we alter it. */
5684 ATExecChangeOwner(depForm->objid, newOwnerId, true);
5686 /* Now we can close it. Keep the lock till end of transaction. */
5687 relation_close(seqRel, NoLock);
5690 systable_endscan(scan);
5692 relation_close(depRel, AccessShareLock);
5696 * ALTER TABLE CLUSTER ON
5698 * The only thing we have to do is to change the indisclustered bits.
5701 ATExecClusterOn(Relation rel, const char *indexName)
5705 indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
5707 if (!OidIsValid(indexOid))
5709 (errcode(ERRCODE_UNDEFINED_OBJECT),
5710 errmsg("index \"%s\" for table \"%s\" does not exist",
5711 indexName, RelationGetRelationName(rel))));
5713 /* Check index is valid to cluster on */
5714 check_index_is_clusterable(rel, indexOid, false);
5716 /* And do the work */
5717 mark_index_clustered(rel, indexOid);
5721 * ALTER TABLE SET WITHOUT CLUSTER
5723 * We have to find any indexes on the table that have indisclustered bit
5724 * set and turn it off.
5727 ATExecDropCluster(Relation rel)
5729 mark_index_clustered(rel, InvalidOid);
5733 * ALTER TABLE SET TABLESPACE
5736 ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, char *tablespacename)
5739 AclResult aclresult;
5741 /* Check that the tablespace exists */
5742 tablespaceId = get_tablespace_oid(tablespacename);
5743 if (!OidIsValid(tablespaceId))
5745 (errcode(ERRCODE_UNDEFINED_OBJECT),
5746 errmsg("tablespace \"%s\" does not exist", tablespacename)));
5748 /* Check its permissions */
5749 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(), ACL_CREATE);
5750 if (aclresult != ACLCHECK_OK)
5751 aclcheck_error(aclresult, ACL_KIND_TABLESPACE, tablespacename);
5753 /* Save info for Phase 3 to do the real work */
5754 if (OidIsValid(tab->newTableSpace))
5756 (errcode(ERRCODE_SYNTAX_ERROR),
5757 errmsg("cannot have multiple SET TABLESPACE subcommands")));
5758 tab->newTableSpace = tablespaceId;
5762 * ALTER TABLE/INDEX SET (...) or RESET (...)
5765 ATExecSetRelOptions(Relation rel, List *defList, bool isReset)
5774 Datum repl_val[Natts_pg_class];
5775 char repl_null[Natts_pg_class];
5776 char repl_repl[Natts_pg_class];
5779 return; /* nothing to do */
5781 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
5783 /* Get the old reloptions */
5784 relid = RelationGetRelid(rel);
5785 tuple = SearchSysCache(RELOID,
5786 ObjectIdGetDatum(relid),
5788 if (!HeapTupleIsValid(tuple))
5789 elog(ERROR, "cache lookup failed for relation %u", relid);
5791 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions, &isnull);
5793 /* Generate new proposed reloptions (text array) */
5794 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
5795 defList, false, isReset);
5798 switch (rel->rd_rel->relkind)
5800 case RELKIND_RELATION:
5801 case RELKIND_TOASTVALUE:
5802 (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
5805 (void) index_reloptions(rel->rd_am->amoptions, newOptions, true);
5809 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5810 errmsg("\"%s\" is not a table, index, or TOAST table",
5811 RelationGetRelationName(rel))));
5816 * All we need do here is update the pg_class row; the new options will be
5817 * propagated into relcaches during post-commit cache inval.
5819 memset(repl_val, 0, sizeof(repl_val));
5820 memset(repl_null, ' ', sizeof(repl_null));
5821 memset(repl_repl, ' ', sizeof(repl_repl));
5823 if (newOptions != (Datum) 0)
5824 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
5826 repl_null[Anum_pg_class_reloptions - 1] = 'n';
5828 repl_repl[Anum_pg_class_reloptions - 1] = 'r';
5830 newtuple = heap_modifytuple(tuple, RelationGetDescr(pgclass),
5831 repl_val, repl_null, repl_repl);
5833 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
5835 CatalogUpdateIndexes(pgclass, newtuple);
5837 heap_freetuple(newtuple);
5839 ReleaseSysCache(tuple);
5841 heap_close(pgclass, RowExclusiveLock);
5845 * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
5846 * rewriting to be done, so we just want to copy the data as fast as possible.
5849 ATExecSetTableSpace(Oid tableOid, Oid newTableSpace)
5855 RelFileNode newrnode;
5856 SMgrRelation dstrel;
5859 Form_pg_class rd_rel;
5862 * Need lock here in case we are recursing to toast table or index
5864 rel = relation_open(tableOid, AccessExclusiveLock);
5867 * We can never allow moving of shared or nailed-in-cache relations,
5868 * because we can't support changing their reltablespace values.
5870 if (rel->rd_rel->relisshared || rel->rd_isnailed)
5872 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5873 errmsg("cannot move system relation \"%s\"",
5874 RelationGetRelationName(rel))));
5876 /* Can't move a non-shared relation into pg_global */
5877 if (newTableSpace == GLOBALTABLESPACE_OID)
5879 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5880 errmsg("only shared relations can be placed in pg_global tablespace")));
5883 * Don't allow moving temp tables of other backends ... their local buffer
5884 * manager is not going to cope.
5886 if (isOtherTempNamespace(RelationGetNamespace(rel)))
5888 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5889 errmsg("cannot move temporary tables of other sessions")));
5892 * No work if no change in tablespace.
5894 oldTableSpace = rel->rd_rel->reltablespace;
5895 if (newTableSpace == oldTableSpace ||
5896 (newTableSpace == MyDatabaseTableSpace && oldTableSpace == 0))
5898 relation_close(rel, NoLock);
5902 reltoastrelid = rel->rd_rel->reltoastrelid;
5903 reltoastidxid = rel->rd_rel->reltoastidxid;
5905 /* Get a modifiable copy of the relation's pg_class row */
5906 pg_class = heap_open(RelationRelationId, RowExclusiveLock);
5908 tuple = SearchSysCacheCopy(RELOID,
5909 ObjectIdGetDatum(tableOid),
5911 if (!HeapTupleIsValid(tuple))
5912 elog(ERROR, "cache lookup failed for relation %u", tableOid);
5913 rd_rel = (Form_pg_class) GETSTRUCT(tuple);
5915 /* create another storage file. Is it a little ugly ? */
5916 /* NOTE: any conflict in relfilenode value will be caught here */
5917 newrnode = rel->rd_node;
5918 newrnode.spcNode = newTableSpace;
5920 dstrel = smgropen(newrnode);
5921 smgrcreate(dstrel, rel->rd_istemp, false);
5923 /* copy relation data to the new physical file */
5924 copy_relation_data(rel, dstrel);
5926 /* schedule unlinking old physical file */
5927 RelationOpenSmgr(rel);
5928 smgrscheduleunlink(rel->rd_smgr, rel->rd_istemp);
5931 * Now drop smgr references. The source was already dropped by
5932 * smgrscheduleunlink.
5936 /* update the pg_class row */
5937 rd_rel->reltablespace = (newTableSpace == MyDatabaseTableSpace) ? InvalidOid : newTableSpace;
5938 simple_heap_update(pg_class, &tuple->t_self, tuple);
5939 CatalogUpdateIndexes(pg_class, tuple);
5941 heap_freetuple(tuple);
5943 heap_close(pg_class, RowExclusiveLock);
5945 relation_close(rel, NoLock);
5947 /* Make sure the reltablespace change is visible */
5948 CommandCounterIncrement();
5950 /* Move associated toast relation and/or index, too */
5951 if (OidIsValid(reltoastrelid))
5952 ATExecSetTableSpace(reltoastrelid, newTableSpace);
5953 if (OidIsValid(reltoastidxid))
5954 ATExecSetTableSpace(reltoastidxid, newTableSpace);
5958 * Copy data, block by block
5961 copy_relation_data(Relation rel, SMgrRelation dst)
5965 BlockNumber nblocks;
5968 Page page = (Page) buf;
5971 * Since we copy the file directly without looking at the shared buffers,
5972 * we'd better first flush out any pages of the source relation that are
5973 * in shared buffers. We assume no new changes will be made while we are
5974 * holding exclusive lock on the rel.
5976 FlushRelationBuffers(rel);
5979 * We need to log the copied data in WAL iff WAL archiving is enabled AND
5980 * it's not a temp rel.
5982 use_wal = XLogArchivingActive() && !rel->rd_istemp;
5984 nblocks = RelationGetNumberOfBlocks(rel);
5985 /* RelationGetNumberOfBlocks will certainly have opened rd_smgr */
5988 for (blkno = 0; blkno < nblocks; blkno++)
5990 smgrread(src, blkno, buf);
5994 log_newpage(&dst->smgr_rnode, blkno, page);
5997 * Now write the page. We say isTemp = true even if it's not a temp
5998 * rel, because there's no need for smgr to schedule an fsync for this
5999 * write; we'll do it ourselves below.
6001 smgrextend(dst, blkno, buf, true);
6005 * If the rel isn't temp, we must fsync it down to disk before it's safe
6006 * to commit the transaction. (For a temp rel we don't care since the rel
6007 * will be uninteresting after a crash anyway.)
6009 * It's obvious that we must do this when not WAL-logging the copy. It's
6010 * less obvious that we have to do it even if we did WAL-log the copied
6011 * pages. The reason is that since we're copying outside shared buffers, a
6012 * CHECKPOINT occurring during the copy has no way to flush the previously
6013 * written data to disk (indeed it won't know the new rel even exists). A
6014 * crash later on would replay WAL from the checkpoint, therefore it
6015 * wouldn't replay our earlier WAL entries. If we do not fsync those pages
6016 * here, they might still not be on disk when the crash occurs.
6018 if (!rel->rd_istemp)
6023 * ALTER TABLE ENABLE/DISABLE TRIGGER
6025 * We just pass this off to trigger.c.
6028 ATExecEnableDisableTrigger(Relation rel, char *trigname,
6029 char fires_when, bool skip_system)
6031 EnableDisableTrigger(rel, trigname, fires_when, skip_system);
6035 * ALTER TABLE ENABLE/DISABLE RULE
6037 * We just pass this off to rewriteDefine.c.
6040 ATExecEnableDisableRule(Relation rel, char *trigname,
6043 EnableDisableRule(rel, trigname, fires_when);
6047 * ALTER TABLE INHERIT
6049 * Add a parent to the child's parents. This verifies that all the columns and
6050 * check constraints of the parent appear in the child and that they have the
6051 * same data types and expressions.
6054 ATExecAddInherit(Relation child_rel, RangeVar *parent)
6056 Relation parent_rel,
6060 HeapTuple inheritsTuple;
6065 * AccessShareLock on the parent is what's obtained during normal CREATE
6066 * TABLE ... INHERITS ..., so should be enough here.
6068 parent_rel = heap_openrv(parent, AccessShareLock);
6071 * Must be owner of both parent and child -- child was checked by
6072 * ATSimplePermissions call in ATPrepCmd
6074 ATSimplePermissions(parent_rel, false);
6076 /* Permanent rels cannot inherit from temporary ones */
6077 if (!isTempNamespace(RelationGetNamespace(child_rel)) &&
6078 isTempNamespace(RelationGetNamespace(parent_rel)))
6080 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6081 errmsg("cannot inherit from temporary relation \"%s\"",
6082 RelationGetRelationName(parent_rel))));
6085 * Check for duplicates in the list of parents, and determine the highest
6086 * inhseqno already present; we'll use the next one for the new parent.
6087 * (Note: get RowExclusiveLock because we will write pg_inherits below.)
6089 * Note: we do not reject the case where the child already inherits from
6090 * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
6092 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
6094 Anum_pg_inherits_inhrelid,
6095 BTEqualStrategyNumber, F_OIDEQ,
6096 ObjectIdGetDatum(RelationGetRelid(child_rel)));
6097 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
6098 true, SnapshotNow, 1, &key);
6100 /* inhseqno sequences start at 1 */
6102 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
6104 Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
6106 if (inh->inhparent == RelationGetRelid(parent_rel))
6108 (errcode(ERRCODE_DUPLICATE_TABLE),
6109 errmsg("relation \"%s\" would be inherited from more than once",
6110 RelationGetRelationName(parent_rel))));
6111 if (inh->inhseqno > inhseqno)
6112 inhseqno = inh->inhseqno;
6114 systable_endscan(scan);
6117 * Prevent circularity by seeing if proposed parent inherits from child.
6118 * (In particular, this disallows making a rel inherit from itself.)
6120 * This is not completely bulletproof because of race conditions: in
6121 * multi-level inheritance trees, someone else could concurrently be
6122 * making another inheritance link that closes the loop but does not join
6123 * either of the rels we have locked. Preventing that seems to require
6124 * exclusive locks on the entire inheritance tree, which is a cure worse
6125 * than the disease. find_all_inheritors() will cope with circularity
6126 * anyway, so don't sweat it too much.
6128 children = find_all_inheritors(RelationGetRelid(child_rel));
6130 if (list_member_oid(children, RelationGetRelid(parent_rel)))
6132 (errcode(ERRCODE_DUPLICATE_TABLE),
6133 errmsg("circular inheritance not allowed"),
6134 errdetail("\"%s\" is already a child of \"%s\".",
6136 RelationGetRelationName(child_rel))));
6138 /* If parent has OIDs then child must have OIDs */
6139 if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
6141 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6142 errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
6143 RelationGetRelationName(child_rel),
6144 RelationGetRelationName(parent_rel))));
6146 /* Match up the columns and bump attinhcount and attislocal */
6147 MergeAttributesIntoExisting(child_rel, parent_rel);
6149 /* Match up the constraints and make sure they're present in child */
6150 MergeConstraintsIntoExisting(child_rel, parent_rel);
6153 * OK, it looks valid. Make the catalog entries that show inheritance.
6155 StoreCatalogInheritance1(RelationGetRelid(child_rel),
6156 RelationGetRelid(parent_rel),
6160 /* Now we're done with pg_inherits */
6161 heap_close(catalogRelation, RowExclusiveLock);
6163 /* keep our lock on the parent relation until commit */
6164 heap_close(parent_rel, NoLock);
6168 * Obtain the source-text form of the constraint expression for a check
6169 * constraint, given its pg_constraint tuple
6172 decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
6174 Form_pg_constraint con;
6179 con = (Form_pg_constraint) GETSTRUCT(contup);
6180 attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
6182 elog(ERROR, "null conbin for constraint %u", HeapTupleGetOid(contup));
6184 expr = DirectFunctionCall2(pg_get_expr, attr,
6185 ObjectIdGetDatum(con->conrelid));
6186 return TextDatumGetCString(expr);
6190 * Check columns in child table match up with columns in parent, and increment
6191 * their attinhcount.
6193 * Called by ATExecAddInherit
6195 * Currently all parent columns must be found in child. Missing columns are an
6196 * error. One day we might consider creating new columns like CREATE TABLE
6197 * does. However, that is widely unpopular --- in the common use case of
6198 * partitioned tables it's a foot-gun.
6200 * The data type must match exactly. If the parent column is NOT NULL then
6201 * the child must be as well. Defaults are not compared, however.
6204 MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel)
6207 AttrNumber parent_attno;
6209 TupleDesc tupleDesc;
6210 TupleConstr *constr;
6213 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
6215 tupleDesc = RelationGetDescr(parent_rel);
6216 parent_natts = tupleDesc->natts;
6217 constr = tupleDesc->constr;
6219 for (parent_attno = 1; parent_attno <= parent_natts; parent_attno++)
6221 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
6222 char *attributeName = NameStr(attribute->attname);
6224 /* Ignore dropped columns in the parent. */
6225 if (attribute->attisdropped)
6228 /* Find same column in child (matching on column name). */
6229 tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel),
6231 if (HeapTupleIsValid(tuple))
6233 /* Check they are same type and typmod */
6234 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
6236 if (attribute->atttypid != childatt->atttypid ||
6237 attribute->atttypmod != childatt->atttypmod)
6239 (errcode(ERRCODE_DATATYPE_MISMATCH),
6240 errmsg("child table \"%s\" has different type for column \"%s\"",
6241 RelationGetRelationName(child_rel),
6244 if (attribute->attnotnull && !childatt->attnotnull)
6246 (errcode(ERRCODE_DATATYPE_MISMATCH),
6247 errmsg("column \"%s\" in child table must be marked NOT NULL",
6251 * OK, bump the child column's inheritance count. (If we fail
6252 * later on, this change will just roll back.)
6254 childatt->attinhcount++;
6255 simple_heap_update(attrrel, &tuple->t_self, tuple);
6256 CatalogUpdateIndexes(attrrel, tuple);
6257 heap_freetuple(tuple);
6262 (errcode(ERRCODE_DATATYPE_MISMATCH),
6263 errmsg("child table is missing column \"%s\"",
6268 heap_close(attrrel, RowExclusiveLock);
6272 * Check constraints in child table match up with constraints in parent
6274 * Called by ATExecAddInherit
6276 * Currently all constraints in parent must be present in the child. One day we
6277 * may consider adding new constraints like CREATE TABLE does. We may also want
6278 * to allow an optional flag on parent table constraints indicating they are
6279 * intended to ONLY apply to the master table, not to the children. That would
6280 * make it possible to ensure no records are mistakenly inserted into the
6281 * master in partitioned tables rather than the appropriate child.
6283 * XXX This is O(N^2) which may be an issue with tables with hundreds of
6284 * constraints. As long as tables have more like 10 constraints it shouldn't be
6285 * a problem though. Even 100 constraints ought not be the end of the world.
6288 MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
6290 Relation catalogRelation;
6291 TupleDesc tupleDesc;
6294 HeapTuple constraintTuple;
6298 /* First gather up the child's constraint definitions */
6299 catalogRelation = heap_open(ConstraintRelationId, AccessShareLock);
6300 tupleDesc = RelationGetDescr(catalogRelation);
6303 Anum_pg_constraint_conrelid,
6304 BTEqualStrategyNumber, F_OIDEQ,
6305 ObjectIdGetDatum(RelationGetRelid(child_rel)));
6306 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
6307 true, SnapshotNow, 1, &key);
6310 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
6312 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
6314 if (con->contype != CONSTRAINT_CHECK)
6317 constraints = lappend(constraints, heap_copytuple(constraintTuple));
6320 systable_endscan(scan);
6322 /* Then scan through the parent's constraints looking for matches */
6324 Anum_pg_constraint_conrelid,
6325 BTEqualStrategyNumber, F_OIDEQ,
6326 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
6327 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId, true,
6328 SnapshotNow, 1, &key);
6330 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
6332 Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
6334 Form_pg_constraint child_con = NULL;
6335 HeapTuple child_contuple = NULL;
6337 if (parent_con->contype != CONSTRAINT_CHECK)
6340 foreach(elem, constraints)
6342 child_contuple = (HeapTuple) lfirst(elem);
6343 child_con = (Form_pg_constraint) GETSTRUCT(child_contuple);
6344 if (strcmp(NameStr(parent_con->conname),
6345 NameStr(child_con->conname)) == 0)
6354 (errcode(ERRCODE_DATATYPE_MISMATCH),
6355 errmsg("child table is missing constraint \"%s\"",
6356 NameStr(parent_con->conname))));
6358 if (parent_con->condeferrable != child_con->condeferrable ||
6359 parent_con->condeferred != child_con->condeferred ||
6360 strcmp(decompile_conbin(constraintTuple, tupleDesc),
6361 decompile_conbin(child_contuple, tupleDesc)) != 0)
6363 (errcode(ERRCODE_DATATYPE_MISMATCH),
6364 errmsg("constraint definition for check constraint \"%s\" does not match",
6365 NameStr(parent_con->conname))));
6368 * TODO: add conislocal,coninhcount to constraints. This is where we
6369 * would have to bump them just like attributes
6373 systable_endscan(scan);
6374 heap_close(catalogRelation, AccessShareLock);
6378 * ALTER TABLE NO INHERIT
6380 * Drop a parent from the child's parents. This just adjusts the attinhcount
6381 * and attislocal of the columns and removes the pg_inherit and pg_depend
6384 * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
6385 * up attislocal stays true, which means if a child is ever removed from a
6386 * parent then its columns will never be automatically dropped which may
6387 * surprise. But at least we'll never surprise by dropping columns someone
6388 * isn't expecting to be dropped which would actually mean data loss.
6391 ATExecDropInherit(Relation rel, RangeVar *parent)
6393 Relation parent_rel;
6394 Relation catalogRelation;
6397 HeapTuple inheritsTuple,
6403 * AccessShareLock on the parent is probably enough, seeing that DROP
6404 * TABLE doesn't lock parent tables at all. We need some lock since we'll
6405 * be inspecting the parent's schema.
6407 parent_rel = heap_openrv(parent, AccessShareLock);
6410 * We don't bother to check ownership of the parent table --- ownership of
6411 * the child is presumed enough rights.
6415 * Find and destroy the pg_inherits entry linking the two, or error out if
6418 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
6419 ScanKeyInit(&key[0],
6420 Anum_pg_inherits_inhrelid,
6421 BTEqualStrategyNumber, F_OIDEQ,
6422 ObjectIdGetDatum(RelationGetRelid(rel)));
6423 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
6424 true, SnapshotNow, 1, key);
6426 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
6430 inhparent = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
6431 if (inhparent == RelationGetRelid(parent_rel))
6433 simple_heap_delete(catalogRelation, &inheritsTuple->t_self);
6439 systable_endscan(scan);
6440 heap_close(catalogRelation, RowExclusiveLock);
6444 (errcode(ERRCODE_UNDEFINED_TABLE),
6445 errmsg("relation \"%s\" is not a parent of relation \"%s\"",
6446 RelationGetRelationName(parent_rel),
6447 RelationGetRelationName(rel))));
6450 * Search through child columns looking for ones matching parent rel
6452 catalogRelation = heap_open(AttributeRelationId, RowExclusiveLock);
6453 ScanKeyInit(&key[0],
6454 Anum_pg_attribute_attrelid,
6455 BTEqualStrategyNumber, F_OIDEQ,
6456 ObjectIdGetDatum(RelationGetRelid(rel)));
6457 scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
6458 true, SnapshotNow, 1, key);
6459 while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
6461 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
6463 /* Ignore if dropped or not inherited */
6464 if (att->attisdropped)
6466 if (att->attinhcount <= 0)
6469 if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
6470 NameStr(att->attname)))
6472 /* Decrement inhcount and possibly set islocal to true */
6473 HeapTuple copyTuple = heap_copytuple(attributeTuple);
6474 Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
6476 copy_att->attinhcount--;
6477 if (copy_att->attinhcount == 0)
6478 copy_att->attislocal = true;
6480 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
6481 CatalogUpdateIndexes(catalogRelation, copyTuple);
6482 heap_freetuple(copyTuple);
6485 systable_endscan(scan);
6486 heap_close(catalogRelation, RowExclusiveLock);
6489 * Drop the dependency
6491 * There's no convenient way to do this, so go trawling through pg_depend
6493 catalogRelation = heap_open(DependRelationId, RowExclusiveLock);
6495 ScanKeyInit(&key[0],
6496 Anum_pg_depend_classid,
6497 BTEqualStrategyNumber, F_OIDEQ,
6498 ObjectIdGetDatum(RelationRelationId));
6499 ScanKeyInit(&key[1],
6500 Anum_pg_depend_objid,
6501 BTEqualStrategyNumber, F_OIDEQ,
6502 ObjectIdGetDatum(RelationGetRelid(rel)));
6503 ScanKeyInit(&key[2],
6504 Anum_pg_depend_objsubid,
6505 BTEqualStrategyNumber, F_INT4EQ,
6508 scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
6509 SnapshotNow, 3, key);
6511 while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
6513 Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
6515 if (dep->refclassid == RelationRelationId &&
6516 dep->refobjid == RelationGetRelid(parent_rel) &&
6517 dep->refobjsubid == 0 &&
6518 dep->deptype == DEPENDENCY_NORMAL)
6519 simple_heap_delete(catalogRelation, &depTuple->t_self);
6522 systable_endscan(scan);
6523 heap_close(catalogRelation, RowExclusiveLock);
6525 /* keep our lock on the parent relation until commit */
6526 heap_close(parent_rel, NoLock);
6531 * Execute ALTER TABLE SET SCHEMA
6533 * Note: caller must have checked ownership of the relation already
6536 AlterTableNamespace(RangeVar *relation, const char *newschema)
6544 rel = relation_openrv(relation, AccessExclusiveLock);
6546 relid = RelationGetRelid(rel);
6547 oldNspOid = RelationGetNamespace(rel);
6549 /* Can we change the schema of this tuple? */
6550 switch (rel->rd_rel->relkind)
6552 case RELKIND_RELATION:
6554 /* ok to change schema */
6556 case RELKIND_SEQUENCE:
6558 /* if it's an owned sequence, disallow moving it by itself */
6562 if (sequenceIsOwned(relid, &tableId, &colId))
6564 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6565 errmsg("cannot move an owned sequence into another schema"),
6566 errdetail("Sequence \"%s\" is linked to table \"%s\".",
6567 RelationGetRelationName(rel),
6568 get_rel_name(tableId))));
6571 case RELKIND_COMPOSITE_TYPE:
6573 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6574 errmsg("\"%s\" is a composite type",
6575 RelationGetRelationName(rel)),
6576 errhint("Use ALTER TYPE instead.")));
6579 case RELKIND_TOASTVALUE:
6583 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6584 errmsg("\"%s\" is not a table, view, or sequence",
6585 RelationGetRelationName(rel))));
6588 /* get schema OID and check its permissions */
6589 nspOid = LookupCreationNamespace(newschema);
6591 if (oldNspOid == nspOid)
6593 (errcode(ERRCODE_DUPLICATE_TABLE),
6594 errmsg("relation \"%s\" is already in schema \"%s\"",
6595 RelationGetRelationName(rel),
6598 /* disallow renaming into or out of temp schemas */
6599 if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
6601 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6602 errmsg("cannot move objects into or out of temporary schemas")));
6604 /* same for TOAST schema */
6605 if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
6607 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6608 errmsg("cannot move objects into or out of TOAST schema")));
6610 /* OK, modify the pg_class row and pg_depend entry */
6611 classRel = heap_open(RelationRelationId, RowExclusiveLock);
6613 AlterRelationNamespaceInternal(classRel, relid, oldNspOid, nspOid, true);
6615 /* Fix the table's rowtype too */
6616 AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid, false, false);
6618 /* Fix other dependent stuff */
6619 if (rel->rd_rel->relkind == RELKIND_RELATION)
6621 AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid);
6622 AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid, newschema);
6623 AlterConstraintNamespaces(relid, oldNspOid, nspOid, false);
6626 heap_close(classRel, RowExclusiveLock);
6628 /* close rel, but keep lock until commit */
6629 relation_close(rel, NoLock);
6633 * The guts of relocating a relation to another namespace: fix the pg_class
6634 * entry, and the pg_depend entry if any. Caller must already have
6635 * opened and write-locked pg_class.
6638 AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
6639 Oid oldNspOid, Oid newNspOid,
6640 bool hasDependEntry)
6643 Form_pg_class classForm;
6645 classTup = SearchSysCacheCopy(RELOID,
6646 ObjectIdGetDatum(relOid),
6648 if (!HeapTupleIsValid(classTup))
6649 elog(ERROR, "cache lookup failed for relation %u", relOid);
6650 classForm = (Form_pg_class) GETSTRUCT(classTup);
6652 Assert(classForm->relnamespace == oldNspOid);
6654 /* check for duplicate name (more friendly than unique-index failure) */
6655 if (get_relname_relid(NameStr(classForm->relname),
6656 newNspOid) != InvalidOid)
6658 (errcode(ERRCODE_DUPLICATE_TABLE),
6659 errmsg("relation \"%s\" already exists in schema \"%s\"",
6660 NameStr(classForm->relname),
6661 get_namespace_name(newNspOid))));
6663 /* classTup is a copy, so OK to scribble on */
6664 classForm->relnamespace = newNspOid;
6666 simple_heap_update(classRel, &classTup->t_self, classTup);
6667 CatalogUpdateIndexes(classRel, classTup);
6669 /* Update dependency on schema if caller said so */
6670 if (hasDependEntry &&
6671 changeDependencyFor(RelationRelationId, relOid,
6672 NamespaceRelationId, oldNspOid, newNspOid) != 1)
6673 elog(ERROR, "failed to change schema dependency for relation \"%s\"",
6674 NameStr(classForm->relname));
6676 heap_freetuple(classTup);
6680 * Move all indexes for the specified relation to another namespace.
6682 * Note: we assume adequate permission checking was done by the caller,
6683 * and that the caller has a suitable lock on the owning relation.
6686 AlterIndexNamespaces(Relation classRel, Relation rel,
6687 Oid oldNspOid, Oid newNspOid)
6692 indexList = RelationGetIndexList(rel);
6694 foreach(l, indexList)
6696 Oid indexOid = lfirst_oid(l);
6699 * Note: currently, the index will not have its own dependency on the
6700 * namespace, so we don't need to do changeDependencyFor(). There's no
6701 * rowtype in pg_type, either.
6703 AlterRelationNamespaceInternal(classRel, indexOid,
6704 oldNspOid, newNspOid,
6708 list_free(indexList);
6712 * Move all SERIAL-column sequences of the specified relation to another
6715 * Note: we assume adequate permission checking was done by the caller,
6716 * and that the caller has a suitable lock on the owning relation.
6719 AlterSeqNamespaces(Relation classRel, Relation rel,
6720 Oid oldNspOid, Oid newNspOid, const char *newNspName)
6728 * SERIAL sequences are those having an auto dependency on one of the
6729 * table's columns (we don't care *which* column, exactly).
6731 depRel = heap_open(DependRelationId, AccessShareLock);
6733 ScanKeyInit(&key[0],
6734 Anum_pg_depend_refclassid,
6735 BTEqualStrategyNumber, F_OIDEQ,
6736 ObjectIdGetDatum(RelationRelationId));
6737 ScanKeyInit(&key[1],
6738 Anum_pg_depend_refobjid,
6739 BTEqualStrategyNumber, F_OIDEQ,
6740 ObjectIdGetDatum(RelationGetRelid(rel)));
6741 /* we leave refobjsubid unspecified */
6743 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
6744 SnapshotNow, 2, key);
6746 while (HeapTupleIsValid(tup = systable_getnext(scan)))
6748 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
6751 /* skip dependencies other than auto dependencies on columns */
6752 if (depForm->refobjsubid == 0 ||
6753 depForm->classid != RelationRelationId ||
6754 depForm->objsubid != 0 ||
6755 depForm->deptype != DEPENDENCY_AUTO)
6758 /* Use relation_open just in case it's an index */
6759 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
6761 /* skip non-sequence relations */
6762 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
6764 /* No need to keep the lock */
6765 relation_close(seqRel, AccessExclusiveLock);
6769 /* Fix the pg_class and pg_depend entries */
6770 AlterRelationNamespaceInternal(classRel, depForm->objid,
6771 oldNspOid, newNspOid,
6775 * Sequences have entries in pg_type. We need to be careful to move
6776 * them to the new namespace, too.
6778 AlterTypeNamespaceInternal(RelationGetForm(seqRel)->reltype,
6779 newNspOid, false, false);
6781 /* Now we can close it. Keep the lock till end of transaction. */
6782 relation_close(seqRel, NoLock);
6785 systable_endscan(scan);
6787 relation_close(depRel, AccessShareLock);
6792 * This code supports
6793 * CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
6795 * Because we only support this for TEMP tables, it's sufficient to remember
6796 * the state in a backend-local data structure.
6800 * Register a newly-created relation's ON COMMIT action.
6803 register_on_commit_action(Oid relid, OnCommitAction action)
6806 MemoryContext oldcxt;
6809 * We needn't bother registering the relation unless there is an ON COMMIT
6810 * action we need to take.
6812 if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
6815 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
6817 oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
6819 oc->oncommit = action;
6820 oc->creating_subid = GetCurrentSubTransactionId();
6821 oc->deleting_subid = InvalidSubTransactionId;
6823 on_commits = lcons(oc, on_commits);
6825 MemoryContextSwitchTo(oldcxt);
6829 * Unregister any ON COMMIT action when a relation is deleted.
6831 * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
6834 remove_on_commit_action(Oid relid)
6838 foreach(l, on_commits)
6840 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
6842 if (oc->relid == relid)
6844 oc->deleting_subid = GetCurrentSubTransactionId();
6851 * Perform ON COMMIT actions.
6853 * This is invoked just before actually committing, since it's possible
6854 * to encounter errors.
6857 PreCommit_on_commit_actions(void)
6860 List *oids_to_truncate = NIL;
6862 foreach(l, on_commits)
6864 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
6866 /* Ignore entry if already dropped in this xact */
6867 if (oc->deleting_subid != InvalidSubTransactionId)
6870 switch (oc->oncommit)
6873 case ONCOMMIT_PRESERVE_ROWS:
6874 /* Do nothing (there shouldn't be such entries, actually) */
6876 case ONCOMMIT_DELETE_ROWS:
6877 oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
6881 ObjectAddress object;
6883 object.classId = RelationRelationId;
6884 object.objectId = oc->relid;
6885 object.objectSubId = 0;
6886 performDeletion(&object, DROP_CASCADE);
6889 * Note that table deletion will call
6890 * remove_on_commit_action, so the entry should get marked
6893 Assert(oc->deleting_subid != InvalidSubTransactionId);
6898 if (oids_to_truncate != NIL)
6900 heap_truncate(oids_to_truncate);
6901 CommandCounterIncrement(); /* XXX needed? */
6906 * Post-commit or post-abort cleanup for ON COMMIT management.
6908 * All we do here is remove no-longer-needed OnCommitItem entries.
6910 * During commit, remove entries that were deleted during this transaction;
6911 * during abort, remove those created during this transaction.
6914 AtEOXact_on_commit_actions(bool isCommit)
6917 ListCell *prev_item;
6920 cur_item = list_head(on_commits);
6922 while (cur_item != NULL)
6924 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
6926 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
6927 oc->creating_subid != InvalidSubTransactionId)
6929 /* cur_item must be removed */
6930 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
6933 cur_item = lnext(prev_item);
6935 cur_item = list_head(on_commits);
6939 /* cur_item must be preserved */
6940 oc->creating_subid = InvalidSubTransactionId;
6941 oc->deleting_subid = InvalidSubTransactionId;
6942 prev_item = cur_item;
6943 cur_item = lnext(prev_item);
6949 * Post-subcommit or post-subabort cleanup for ON COMMIT management.
6951 * During subabort, we can immediately remove entries created during this
6952 * subtransaction. During subcommit, just relabel entries marked during
6953 * this subtransaction as being the parent's responsibility.
6956 AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
6957 SubTransactionId parentSubid)
6960 ListCell *prev_item;
6963 cur_item = list_head(on_commits);
6965 while (cur_item != NULL)
6967 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
6969 if (!isCommit && oc->creating_subid == mySubid)
6971 /* cur_item must be removed */
6972 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
6975 cur_item = lnext(prev_item);
6977 cur_item = list_head(on_commits);
6981 /* cur_item must be preserved */
6982 if (oc->creating_subid == mySubid)
6983 oc->creating_subid = parentSubid;
6984 if (oc->deleting_subid == mySubid)
6985 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
6986 prev_item = cur_item;
6987 cur_item = lnext(prev_item);