1 /*-------------------------------------------------------------------------
4 * Commands for creating and altering table structures and settings
6 * Portions Copyright (c) 1996-2009, 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.297 2009/08/12 23:00:12 tgl Exp $
13 *-------------------------------------------------------------------------
17 #include "access/genam.h"
18 #include "access/heapam.h"
19 #include "access/reloptions.h"
20 #include "access/relscan.h"
21 #include "access/sysattr.h"
22 #include "access/xact.h"
23 #include "catalog/catalog.h"
24 #include "catalog/dependency.h"
25 #include "catalog/heap.h"
26 #include "catalog/index.h"
27 #include "catalog/indexing.h"
28 #include "catalog/namespace.h"
29 #include "catalog/pg_constraint.h"
30 #include "catalog/pg_depend.h"
31 #include "catalog/pg_inherits.h"
32 #include "catalog/pg_inherits_fn.h"
33 #include "catalog/pg_namespace.h"
34 #include "catalog/pg_opclass.h"
35 #include "catalog/pg_tablespace.h"
36 #include "catalog/pg_trigger.h"
37 #include "catalog/pg_type.h"
38 #include "catalog/pg_type_fn.h"
39 #include "catalog/storage.h"
40 #include "catalog/toasting.h"
41 #include "commands/cluster.h"
42 #include "commands/defrem.h"
43 #include "commands/sequence.h"
44 #include "commands/tablecmds.h"
45 #include "commands/tablespace.h"
46 #include "commands/trigger.h"
47 #include "commands/typecmds.h"
48 #include "executor/executor.h"
49 #include "miscadmin.h"
50 #include "nodes/makefuncs.h"
51 #include "nodes/nodeFuncs.h"
52 #include "nodes/parsenodes.h"
53 #include "optimizer/clauses.h"
54 #include "parser/parse_clause.h"
55 #include "parser/parse_coerce.h"
56 #include "parser/parse_expr.h"
57 #include "parser/parse_oper.h"
58 #include "parser/parse_relation.h"
59 #include "parser/parse_type.h"
60 #include "parser/parse_utilcmd.h"
61 #include "parser/parser.h"
62 #include "rewrite/rewriteDefine.h"
63 #include "rewrite/rewriteHandler.h"
64 #include "storage/bufmgr.h"
65 #include "storage/lmgr.h"
66 #include "storage/smgr.h"
67 #include "utils/acl.h"
68 #include "utils/builtins.h"
69 #include "utils/fmgroids.h"
70 #include "utils/inval.h"
71 #include "utils/lsyscache.h"
72 #include "utils/memutils.h"
73 #include "utils/relcache.h"
74 #include "utils/snapmgr.h"
75 #include "utils/syscache.h"
76 #include "utils/tqual.h"
80 * ON COMMIT action list
82 typedef struct OnCommitItem
84 Oid relid; /* relid of relation */
85 OnCommitAction oncommit; /* what to do at end of xact */
88 * If this entry was created during the current transaction,
89 * creating_subid is the ID of the creating subxact; if created in a prior
90 * transaction, creating_subid is zero. If deleted during the current
91 * transaction, deleting_subid is the ID of the deleting subxact; if no
92 * deletion request is pending, deleting_subid is zero.
94 SubTransactionId creating_subid;
95 SubTransactionId deleting_subid;
98 static List *on_commits = NIL;
102 * State information for ALTER TABLE
104 * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
105 * structs, one for each table modified by the operation (the named table
106 * plus any child tables that are affected). We save lists of subcommands
107 * to apply to this table (possibly modified by parse transformation steps);
108 * these lists will be executed in Phase 2. If a Phase 3 step is needed,
109 * necessary information is stored in the constraints and newvals lists.
111 * Phase 2 is divided into multiple passes; subcommands are executed in
112 * a pass determined by subcommand type.
115 #define AT_PASS_DROP 0 /* DROP (all flavors) */
116 #define AT_PASS_ALTER_TYPE 1 /* ALTER COLUMN TYPE */
117 #define AT_PASS_OLD_INDEX 2 /* re-add existing indexes */
118 #define AT_PASS_OLD_CONSTR 3 /* re-add existing constraints */
119 #define AT_PASS_COL_ATTRS 4 /* set other column attributes */
120 /* We could support a RENAME COLUMN pass here, but not currently used */
121 #define AT_PASS_ADD_COL 5 /* ADD COLUMN */
122 #define AT_PASS_ADD_INDEX 6 /* ADD indexes */
123 #define AT_PASS_ADD_CONSTR 7 /* ADD constraints, defaults */
124 #define AT_PASS_MISC 8 /* other stuff */
125 #define AT_NUM_PASSES 9
127 typedef struct AlteredTableInfo
129 /* Information saved before any work commences: */
130 Oid relid; /* Relation to work on */
131 char relkind; /* Its relkind */
132 TupleDesc oldDesc; /* Pre-modification tuple descriptor */
133 /* Information saved by Phase 1 for Phase 2: */
134 List *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
135 /* Information saved by Phases 1/2 for Phase 3: */
136 List *constraints; /* List of NewConstraint */
137 List *newvals; /* List of NewColumnValue */
138 bool new_notnull; /* T if we added new NOT NULL constraints */
139 bool new_changeoids; /* T if we added/dropped the OID column */
140 Oid newTableSpace; /* new tablespace; 0 means no change */
141 /* Objects to rebuild after completing ALTER TYPE operations */
142 List *changedConstraintOids; /* OIDs of constraints to rebuild */
143 List *changedConstraintDefs; /* string definitions of same */
144 List *changedIndexOids; /* OIDs of indexes to rebuild */
145 List *changedIndexDefs; /* string definitions of same */
148 /* Struct describing one new constraint to check in Phase 3 scan */
149 /* Note: new NOT NULL constraints are handled elsewhere */
150 typedef struct NewConstraint
152 char *name; /* Constraint name, or NULL if none */
153 ConstrType contype; /* CHECK or FOREIGN */
154 Oid refrelid; /* PK rel, if FOREIGN */
155 Oid refindid; /* OID of PK's index, if FOREIGN */
156 Oid conid; /* OID of pg_constraint entry, if FOREIGN */
157 Node *qual; /* Check expr or CONSTR_FOREIGN Constraint */
158 List *qualstate; /* Execution state for CHECK */
162 * Struct describing one new column value that needs to be computed during
163 * Phase 3 copy (this could be either a new column with a non-null default, or
164 * a column that we're changing the type of). Columns without such an entry
165 * are just copied from the old table during ATRewriteTable. Note that the
166 * expr is an expression over *old* table values.
168 typedef struct NewColumnValue
170 AttrNumber attnum; /* which column */
171 Expr *expr; /* expression to compute */
172 ExprState *exprstate; /* execution state */
176 * Error-reporting support for RemoveRelations
178 struct dropmsgstrings
181 int nonexistent_code;
182 const char *nonexistent_msg;
183 const char *skipping_msg;
184 const char *nota_msg;
185 const char *drophint_msg;
188 static const struct dropmsgstrings dropmsgstringarray[] = {
190 ERRCODE_UNDEFINED_TABLE,
191 gettext_noop("table \"%s\" does not exist"),
192 gettext_noop("table \"%s\" does not exist, skipping"),
193 gettext_noop("\"%s\" is not a table"),
194 gettext_noop("Use DROP TABLE to remove a table.")},
196 ERRCODE_UNDEFINED_TABLE,
197 gettext_noop("sequence \"%s\" does not exist"),
198 gettext_noop("sequence \"%s\" does not exist, skipping"),
199 gettext_noop("\"%s\" is not a sequence"),
200 gettext_noop("Use DROP SEQUENCE to remove a sequence.")},
202 ERRCODE_UNDEFINED_TABLE,
203 gettext_noop("view \"%s\" does not exist"),
204 gettext_noop("view \"%s\" does not exist, skipping"),
205 gettext_noop("\"%s\" is not a view"),
206 gettext_noop("Use DROP VIEW to remove a view.")},
208 ERRCODE_UNDEFINED_OBJECT,
209 gettext_noop("index \"%s\" does not exist"),
210 gettext_noop("index \"%s\" does not exist, skipping"),
211 gettext_noop("\"%s\" is not an index"),
212 gettext_noop("Use DROP INDEX to remove an index.")},
213 {RELKIND_COMPOSITE_TYPE,
214 ERRCODE_UNDEFINED_OBJECT,
215 gettext_noop("type \"%s\" does not exist"),
216 gettext_noop("type \"%s\" does not exist, skipping"),
217 gettext_noop("\"%s\" is not a type"),
218 gettext_noop("Use DROP TYPE to remove a type.")},
219 {'\0', 0, NULL, NULL, NULL, NULL}
223 static void truncate_check_rel(Relation rel);
224 static List *MergeAttributes(List *schema, List *supers, bool istemp,
225 List **supOids, List **supconstr, int *supOidCount);
226 static bool MergeCheckConstraint(List *constraints, char *name, Node *expr);
227 static bool change_varattnos_walker(Node *node, const AttrNumber *newattno);
228 static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel);
229 static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
230 static void StoreCatalogInheritance(Oid relationId, List *supers);
231 static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
232 int16 seqNumber, Relation inhRelation);
233 static int findAttrByName(const char *attributeName, List *schema);
234 static void setRelhassubclassInRelation(Oid relationId, bool relhassubclass);
235 static void AlterIndexNamespaces(Relation classRel, Relation rel,
236 Oid oldNspOid, Oid newNspOid);
237 static void AlterSeqNamespaces(Relation classRel, Relation rel,
238 Oid oldNspOid, Oid newNspOid,
239 const char *newNspName);
240 static int transformColumnNameList(Oid relId, List *colList,
241 int16 *attnums, Oid *atttypids);
242 static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
244 int16 *attnums, Oid *atttypids,
246 static Oid transformFkeyCheckAttrs(Relation pkrel,
247 int numattrs, int16 *attnums,
249 static void checkFkeyPermissions(Relation rel, int16 *attnums, int natts);
250 static void validateForeignKeyConstraint(Constraint *fkconstraint,
251 Relation rel, Relation pkrel,
252 Oid pkindOid, Oid constraintOid);
253 static void createForeignKeyTriggers(Relation rel, Constraint *fkconstraint,
254 Oid constraintOid, Oid indexOid);
255 static void ATController(Relation rel, List *cmds, bool recurse);
256 static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
257 bool recurse, bool recursing);
258 static void ATRewriteCatalogs(List **wqueue);
259 static void ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
261 static void ATRewriteTables(List **wqueue);
262 static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap);
263 static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
264 static void ATSimplePermissions(Relation rel, bool allowView);
265 static void ATSimplePermissionsRelationOrIndex(Relation rel);
266 static void ATSimpleRecursion(List **wqueue, Relation rel,
267 AlterTableCmd *cmd, bool recurse);
268 static void ATOneLevelRecursion(List **wqueue, Relation rel,
270 static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
272 static void ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
273 ColumnDef *colDef, bool isOid);
274 static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
275 static void ATPrepAddOids(List **wqueue, Relation rel, bool recurse,
277 static void ATExecDropNotNull(Relation rel, const char *colName);
278 static void ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
279 const char *colName);
280 static void ATExecColumnDefault(Relation rel, const char *colName,
282 static void ATPrepSetStatistics(Relation rel, const char *colName,
284 static void ATExecSetStatistics(Relation rel, const char *colName,
286 static void ATPrepSetDistinct(Relation rel, const char *colName,
288 static void ATExecSetDistinct(Relation rel, const char *colName,
290 static void ATExecSetStorage(Relation rel, const char *colName,
292 static void ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
293 DropBehavior behavior,
294 bool recurse, bool recursing,
296 static void ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
297 IndexStmt *stmt, bool is_rebuild);
298 static void ATExecAddConstraint(List **wqueue,
299 AlteredTableInfo *tab, Relation rel,
300 Constraint *newConstraint, bool recurse);
301 static void ATAddCheckConstraint(List **wqueue,
302 AlteredTableInfo *tab, Relation rel,
304 bool recurse, bool recursing);
305 static void ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
306 Constraint *fkconstraint);
307 static void ATExecDropConstraint(Relation rel, const char *constrName,
308 DropBehavior behavior,
309 bool recurse, bool recursing,
311 static void ATPrepAlterColumnType(List **wqueue,
312 AlteredTableInfo *tab, Relation rel,
313 bool recurse, bool recursing,
315 static void ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
316 const char *colName, TypeName *typeName);
317 static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab);
318 static void ATPostAlterTypeParse(char *cmd, List **wqueue);
319 static void change_owner_recurse_to_sequences(Oid relationOid,
321 static void ATExecClusterOn(Relation rel, const char *indexName);
322 static void ATExecDropCluster(Relation rel);
323 static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
324 char *tablespacename);
325 static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace);
326 static void ATExecSetRelOptions(Relation rel, List *defList, bool isReset);
327 static void ATExecEnableDisableTrigger(Relation rel, char *trigname,
328 char fires_when, bool skip_system);
329 static void ATExecEnableDisableRule(Relation rel, char *rulename,
331 static void ATExecAddInherit(Relation rel, RangeVar *parent);
332 static void ATExecDropInherit(Relation rel, RangeVar *parent);
333 static void copy_relation_data(SMgrRelation rel, SMgrRelation dst,
334 ForkNumber forkNum, bool istemp);
337 /* ----------------------------------------------------------------
339 * Creates a new relation.
341 * If successful, returns the OID of the new relation.
342 * ----------------------------------------------------------------
345 DefineRelation(CreateStmt *stmt, char relkind)
347 char relname[NAMEDATALEN];
349 List *schema = stmt->tableElts;
353 TupleDesc descriptor;
355 List *old_constraints;
359 List *cookedDefaults;
363 static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
366 * Truncate relname to appropriate length (probably a waste of time, as
367 * parser should have done this already).
369 StrNCpy(relname, stmt->relation->relname, NAMEDATALEN);
372 * Check consistency of arguments
374 if (stmt->oncommit != ONCOMMIT_NOOP && !stmt->relation->istemp)
376 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
377 errmsg("ON COMMIT can only be used on temporary tables")));
380 * Look up the namespace in which we are supposed to create the relation.
381 * Check we have permission to create there. Skip check if bootstrapping,
382 * since permissions machinery may not be working yet.
384 namespaceId = RangeVarGetCreationNamespace(stmt->relation);
386 if (!IsBootstrapProcessingMode())
390 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
392 if (aclresult != ACLCHECK_OK)
393 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
394 get_namespace_name(namespaceId));
398 * Select tablespace to use. If not specified, use default tablespace
399 * (which may in turn default to database's default).
401 if (stmt->tablespacename)
403 tablespaceId = get_tablespace_oid(stmt->tablespacename);
404 if (!OidIsValid(tablespaceId))
406 (errcode(ERRCODE_UNDEFINED_OBJECT),
407 errmsg("tablespace \"%s\" does not exist",
408 stmt->tablespacename)));
412 tablespaceId = GetDefaultTablespace(stmt->relation->istemp);
413 /* note InvalidOid is OK in this case */
416 /* Check permissions except when using database's default */
417 if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
421 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
423 if (aclresult != ACLCHECK_OK)
424 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
425 get_tablespace_name(tablespaceId));
429 * Parse and validate reloptions, if any.
431 reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, validnsps,
434 (void) heap_reloptions(relkind, reloptions, true);
437 * Look up inheritance ancestors and generate relation schema, including
438 * inherited attributes.
440 schema = MergeAttributes(schema, stmt->inhRelations,
441 stmt->relation->istemp,
442 &inheritOids, &old_constraints, &parentOidCount);
445 * Create a tuple descriptor from the relation schema. Note that this
446 * deals with column names, types, and NOT NULL constraints, but not
447 * default values or CHECK constraints; we handle those below.
449 descriptor = BuildDescForRelation(schema);
451 localHasOids = interpretOidsOption(stmt->options);
452 descriptor->tdhasoid = (localHasOids || parentOidCount > 0);
455 * Find columns with default values and prepare for insertion of the
456 * defaults. Pre-cooked (that is, inherited) defaults go into a list of
457 * CookedConstraint structs that we'll pass to heap_create_with_catalog,
458 * while raw defaults go into a list of RawColumnDefault structs that will
459 * be processed by AddRelationNewConstraints. (We can't deal with raw
460 * expressions until we can do transformExpr.)
462 * We can set the atthasdef flags now in the tuple descriptor; this just
463 * saves StoreAttrDefault from having to do an immediate update of the
467 cookedDefaults = NIL;
470 foreach(listptr, schema)
472 ColumnDef *colDef = lfirst(listptr);
476 if (colDef->raw_default != NULL)
478 RawColumnDefault *rawEnt;
480 Assert(colDef->cooked_default == NULL);
482 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
483 rawEnt->attnum = attnum;
484 rawEnt->raw_default = colDef->raw_default;
485 rawDefaults = lappend(rawDefaults, rawEnt);
486 descriptor->attrs[attnum - 1]->atthasdef = true;
488 else if (colDef->cooked_default != NULL)
490 CookedConstraint *cooked;
492 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
493 cooked->contype = CONSTR_DEFAULT;
495 cooked->attnum = attnum;
496 cooked->expr = stringToNode(colDef->cooked_default);
497 cooked->is_local = true; /* not used for defaults */
498 cooked->inhcount = 0; /* ditto */
499 cookedDefaults = lappend(cookedDefaults, cooked);
500 descriptor->attrs[attnum - 1]->atthasdef = true;
505 * Create the relation. Inherited defaults and constraints are passed in
506 * for immediate handling --- since they don't need parsing, they can be
507 * stored immediately.
509 relationId = heap_create_with_catalog(relname,
515 list_concat(cookedDefaults,
523 allowSystemTableMods);
525 StoreCatalogInheritance(relationId, inheritOids);
528 * We must bump the command counter to make the newly-created relation
529 * tuple visible for opening.
531 CommandCounterIncrement();
534 * Open the new relation and acquire exclusive lock on it. This isn't
535 * really necessary for locking out other backends (since they can't see
536 * the new rel anyway until we commit), but it keeps the lock manager from
537 * complaining about deadlock risks.
539 rel = relation_open(relationId, AccessExclusiveLock);
542 * Now add any newly specified column default values and CHECK constraints
543 * to the new relation. These are passed to us in the form of raw
544 * parsetrees; we need to transform them to executable expression trees
545 * before they can be added. The most convenient way to do that is to
546 * apply the parser's transformExpr routine, but transformExpr doesn't
547 * work unless we have a pre-existing relation. So, the transformation has
548 * to be postponed to this final step of CREATE TABLE.
550 if (rawDefaults || stmt->constraints)
551 AddRelationNewConstraints(rel, rawDefaults, stmt->constraints,
555 * Clean up. We keep lock on new relation (although it shouldn't be
556 * visible to anyone else anyway, until commit).
558 relation_close(rel, NoLock);
564 * Emit the right error or warning message for a "DROP" command issued on a
565 * non-existent relation
568 DropErrorMsgNonExistent(const char *relname, char rightkind, bool missing_ok)
570 const struct dropmsgstrings *rentry;
572 for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
574 if (rentry->kind == rightkind)
579 (errcode(rentry->nonexistent_code),
580 errmsg(rentry->nonexistent_msg, relname)));
584 ereport(NOTICE, (errmsg(rentry->skipping_msg, relname)));
590 Assert(rentry->kind != '\0'); /* Should be impossible */
594 * Emit the right error message for a "DROP" command issued on a
595 * relation of the wrong type
598 DropErrorMsgWrongType(const char *relname, char wrongkind, char rightkind)
600 const struct dropmsgstrings *rentry;
601 const struct dropmsgstrings *wentry;
603 for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
604 if (rentry->kind == rightkind)
606 Assert(rentry->kind != '\0');
608 for (wentry = dropmsgstringarray; wentry->kind != '\0'; wentry++)
609 if (wentry->kind == wrongkind)
611 /* wrongkind could be something we don't have in our table... */
614 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
615 errmsg(rentry->nota_msg, relname),
616 (wentry->kind != '\0') ? errhint("%s", _(wentry->drophint_msg)) : 0));
621 * Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW
624 RemoveRelations(DropStmt *drop)
626 ObjectAddresses *objects;
631 * First we identify all the relations, then we delete them in a single
632 * performMultipleDeletions() call. This is to avoid unwanted DROP
633 * RESTRICT errors if one of the relations depends on another.
636 /* Determine required relkind */
637 switch (drop->removeType)
640 relkind = RELKIND_RELATION;
644 relkind = RELKIND_INDEX;
647 case OBJECT_SEQUENCE:
648 relkind = RELKIND_SEQUENCE;
652 relkind = RELKIND_VIEW;
656 elog(ERROR, "unrecognized drop object type: %d",
657 (int) drop->removeType);
658 relkind = 0; /* keep compiler quiet */
662 /* Lock and validate each relation; build a list of object addresses */
663 objects = new_object_addresses();
665 foreach(cell, drop->objects)
667 RangeVar *rel = makeRangeVarFromNameList((List *) lfirst(cell));
670 Form_pg_class classform;
674 * These next few steps are a great deal like relation_openrv, but we
675 * don't bother building a relcache entry since we don't need it.
677 * Check for shared-cache-inval messages before trying to access the
678 * relation. This is needed to cover the case where the name
679 * identifies a rel that has been dropped and recreated since the
680 * start of our transaction: if we don't flush the old syscache entry,
681 * then we'll latch onto that entry and suffer an error later.
683 AcceptInvalidationMessages();
685 /* Look up the appropriate relation using namespace search */
686 relOid = RangeVarGetRelid(rel, true);
689 if (!OidIsValid(relOid))
691 DropErrorMsgNonExistent(rel->relname, relkind, drop->missing_ok);
696 * In DROP INDEX, attempt to acquire lock on the parent table before
697 * locking the index. index_drop() will need this anyway, and since
698 * regular queries lock tables before their indexes, we risk deadlock
699 * if we do it the other way around. No error if we don't find a
700 * pg_index entry, though --- that most likely means it isn't an
701 * index, and we'll fail below.
703 if (relkind == RELKIND_INDEX)
705 tuple = SearchSysCache(INDEXRELID,
706 ObjectIdGetDatum(relOid),
708 if (HeapTupleIsValid(tuple))
710 Form_pg_index index = (Form_pg_index) GETSTRUCT(tuple);
712 LockRelationOid(index->indrelid, AccessExclusiveLock);
713 ReleaseSysCache(tuple);
717 /* Get the lock before trying to fetch the syscache entry */
718 LockRelationOid(relOid, AccessExclusiveLock);
720 tuple = SearchSysCache(RELOID,
721 ObjectIdGetDatum(relOid),
723 if (!HeapTupleIsValid(tuple))
724 elog(ERROR, "cache lookup failed for relation %u", relOid);
725 classform = (Form_pg_class) GETSTRUCT(tuple);
727 if (classform->relkind != relkind)
728 DropErrorMsgWrongType(rel->relname, classform->relkind, relkind);
730 /* Allow DROP to either table owner or schema owner */
731 if (!pg_class_ownercheck(relOid, GetUserId()) &&
732 !pg_namespace_ownercheck(classform->relnamespace, GetUserId()))
733 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
736 if (!allowSystemTableMods && IsSystemClass(classform))
738 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
739 errmsg("permission denied: \"%s\" is a system catalog",
742 /* OK, we're ready to delete this one */
743 obj.classId = RelationRelationId;
744 obj.objectId = relOid;
747 add_exact_object_address(&obj, objects);
749 ReleaseSysCache(tuple);
752 performMultipleDeletions(objects, drop->behavior);
754 free_object_addresses(objects);
759 * Executes a TRUNCATE command.
761 * This is a multi-relation truncate. We first open and grab exclusive
762 * lock on all relations involved, checking permissions and otherwise
763 * verifying that the relation is OK for truncation. In CASCADE mode,
764 * relations having FK references to the targeted relations are automatically
765 * added to the group; in RESTRICT mode, we check that all FK references are
766 * internal to the group that's being truncated. Finally all the relations
767 * are truncated and reindexed.
770 ExecuteTruncate(TruncateStmt *stmt)
774 List *seq_relids = NIL;
776 ResultRelInfo *resultRelInfos;
777 ResultRelInfo *resultRelInfo;
781 * Open, exclusive-lock, and check all the explicitly-specified relations
783 foreach(cell, stmt->relations)
785 RangeVar *rv = lfirst(cell);
787 bool recurse = interpretInhOption(rv->inhOpt);
790 rel = heap_openrv(rv, AccessExclusiveLock);
791 myrelid = RelationGetRelid(rel);
792 /* don't throw error for "TRUNCATE foo, foo" */
793 if (list_member_oid(relids, myrelid))
795 heap_close(rel, AccessExclusiveLock);
798 truncate_check_rel(rel);
799 rels = lappend(rels, rel);
800 relids = lappend_oid(relids, myrelid);
807 children = find_all_inheritors(myrelid, AccessExclusiveLock);
809 foreach(child, children)
811 Oid childrelid = lfirst_oid(child);
813 if (list_member_oid(relids, childrelid))
816 /* find_all_inheritors already got lock */
817 rel = heap_open(childrelid, NoLock);
818 truncate_check_rel(rel);
819 rels = lappend(rels, rel);
820 relids = lappend_oid(relids, childrelid);
826 * In CASCADE mode, suck in all referencing relations as well. This
827 * requires multiple iterations to find indirectly-dependent relations. At
828 * each phase, we need to exclusive-lock new rels before looking for their
829 * dependencies, else we might miss something. Also, we check each rel as
830 * soon as we open it, to avoid a faux pas such as holding lock for a long
831 * time on a rel we have no permissions for.
833 if (stmt->behavior == DROP_CASCADE)
839 newrelids = heap_truncate_find_FKs(relids);
840 if (newrelids == NIL)
841 break; /* nothing else to add */
843 foreach(cell, newrelids)
845 Oid relid = lfirst_oid(cell);
848 rel = heap_open(relid, AccessExclusiveLock);
850 (errmsg("truncate cascades to table \"%s\"",
851 RelationGetRelationName(rel))));
852 truncate_check_rel(rel);
853 rels = lappend(rels, rel);
854 relids = lappend_oid(relids, relid);
860 * Check foreign key references. In CASCADE mode, this should be
861 * unnecessary since we just pulled in all the references; but as a
862 * cross-check, do it anyway if in an Assert-enabled build.
864 #ifdef USE_ASSERT_CHECKING
865 heap_truncate_check_FKs(rels, false);
867 if (stmt->behavior == DROP_RESTRICT)
868 heap_truncate_check_FKs(rels, false);
872 * If we are asked to restart sequences, find all the sequences, lock them
873 * (we only need AccessShareLock because that's all that ALTER SEQUENCE
874 * takes), and check permissions. We want to do this early since it's
875 * pointless to do all the truncation work only to fail on sequence
878 if (stmt->restart_seqs)
882 Relation rel = (Relation) lfirst(cell);
883 List *seqlist = getOwnedSequences(RelationGetRelid(rel));
886 foreach(seqcell, seqlist)
888 Oid seq_relid = lfirst_oid(seqcell);
891 seq_rel = relation_open(seq_relid, AccessShareLock);
893 /* This check must match AlterSequence! */
894 if (!pg_class_ownercheck(seq_relid, GetUserId()))
895 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
896 RelationGetRelationName(seq_rel));
898 seq_relids = lappend_oid(seq_relids, seq_relid);
900 relation_close(seq_rel, NoLock);
905 /* Prepare to catch AFTER triggers. */
906 AfterTriggerBeginQuery();
909 * To fire triggers, we'll need an EState as well as a ResultRelInfo for
912 estate = CreateExecutorState();
913 resultRelInfos = (ResultRelInfo *)
914 palloc(list_length(rels) * sizeof(ResultRelInfo));
915 resultRelInfo = resultRelInfos;
918 Relation rel = (Relation) lfirst(cell);
920 InitResultRelInfo(resultRelInfo,
922 0, /* dummy rangetable index */
923 CMD_DELETE, /* don't need any index info */
927 estate->es_result_relations = resultRelInfos;
928 estate->es_num_result_relations = list_length(rels);
931 * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
932 * truncating (this is because one of them might throw an error). Also, if
933 * we were to allow them to prevent statement execution, that would need
934 * to be handled here.
936 resultRelInfo = resultRelInfos;
939 estate->es_result_relation_info = resultRelInfo;
940 ExecBSTruncateTriggers(estate, resultRelInfo);
945 * OK, truncate each table.
949 Relation rel = (Relation) lfirst(cell);
954 * Create a new empty storage file for the relation, and assign it as
955 * the relfilenode value. The old storage file is scheduled for
956 * deletion at commit.
958 setNewRelfilenode(rel, RecentXmin);
960 heap_relid = RelationGetRelid(rel);
961 toast_relid = rel->rd_rel->reltoastrelid;
964 * The same for the toast table, if any.
966 if (OidIsValid(toast_relid))
968 rel = relation_open(toast_relid, AccessExclusiveLock);
969 setNewRelfilenode(rel, RecentXmin);
970 heap_close(rel, NoLock);
974 * Reconstruct the indexes to match, and we're done.
976 reindex_relation(heap_relid, true);
980 * Process all AFTER STATEMENT TRUNCATE triggers.
982 resultRelInfo = resultRelInfos;
985 estate->es_result_relation_info = resultRelInfo;
986 ExecASTruncateTriggers(estate, resultRelInfo);
990 /* Handle queued AFTER triggers */
991 AfterTriggerEndQuery(estate);
993 /* We can clean up the EState now */
994 FreeExecutorState(estate);
996 /* And close the rels (can't do this while EState still holds refs) */
999 Relation rel = (Relation) lfirst(cell);
1001 heap_close(rel, NoLock);
1005 * Lastly, restart any owned sequences if we were asked to. This is done
1006 * last because it's nontransactional: restarts will not roll back if we
1007 * abort later. Hence it's important to postpone them as long as
1008 * possible. (This is also a big reason why we locked and
1009 * permission-checked the sequences beforehand.)
1011 if (stmt->restart_seqs)
1013 List *options = list_make1(makeDefElem("restart", NULL));
1015 foreach(cell, seq_relids)
1017 Oid seq_relid = lfirst_oid(cell);
1019 AlterSequenceInternal(seq_relid, options);
1025 * Check that a given rel is safe to truncate. Subroutine for ExecuteTruncate
1028 truncate_check_rel(Relation rel)
1030 AclResult aclresult;
1032 /* Only allow truncate on regular tables */
1033 if (rel->rd_rel->relkind != RELKIND_RELATION)
1035 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1036 errmsg("\"%s\" is not a table",
1037 RelationGetRelationName(rel))));
1039 /* Permissions checks */
1040 aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
1042 if (aclresult != ACLCHECK_OK)
1043 aclcheck_error(aclresult, ACL_KIND_CLASS,
1044 RelationGetRelationName(rel));
1046 if (!allowSystemTableMods && IsSystemRelation(rel))
1048 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1049 errmsg("permission denied: \"%s\" is a system catalog",
1050 RelationGetRelationName(rel))));
1053 * We can never allow truncation of shared or nailed-in-cache relations,
1054 * because we can't support changing their relfilenode values.
1056 if (rel->rd_rel->relisshared || rel->rd_isnailed)
1058 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1059 errmsg("cannot truncate system relation \"%s\"",
1060 RelationGetRelationName(rel))));
1063 * Don't allow truncate on temp tables of other backends ... their local
1064 * buffer manager is not going to cope.
1066 if (RELATION_IS_OTHER_TEMP(rel))
1068 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1069 errmsg("cannot truncate temporary tables of other sessions")));
1072 * Also check for active uses of the relation in the current transaction,
1073 * including open scans and pending AFTER trigger events.
1075 CheckTableNotInUse(rel, "TRUNCATE");
1080 * Returns new schema given initial schema and superclasses.
1083 * 'schema' is the column/attribute definition for the table. (It's a list
1084 * of ColumnDef's.) It is destructively changed.
1085 * 'supers' is a list of names (as RangeVar nodes) of parent relations.
1086 * 'istemp' is TRUE if we are creating a temp relation.
1089 * 'supOids' receives a list of the OIDs of the parent relations.
1090 * 'supconstr' receives a list of constraints belonging to the parents,
1091 * updated as necessary to be valid for the child.
1092 * 'supOidCount' is set to the number of parents that have OID columns.
1095 * Completed schema list.
1098 * The order in which the attributes are inherited is very important.
1099 * Intuitively, the inherited attributes should come first. If a table
1100 * inherits from multiple parents, the order of those attributes are
1101 * according to the order of the parents specified in CREATE TABLE.
1103 * Here's an example:
1105 * create table person (name text, age int4, location point);
1106 * create table emp (salary int4, manager text) inherits(person);
1107 * create table student (gpa float8) inherits (person);
1108 * create table stud_emp (percent int4) inherits (emp, student);
1110 * The order of the attributes of stud_emp is:
1112 * person {1:name, 2:age, 3:location}
1114 * {6:gpa} student emp {4:salary, 5:manager}
1116 * stud_emp {7:percent}
1118 * If the same attribute name appears multiple times, then it appears
1119 * in the result table in the proper location for its first appearance.
1121 * Constraints (including NOT NULL constraints) for the child table
1122 * are the union of all relevant constraints, from both the child schema
1123 * and parent tables.
1125 * The default value for a child column is defined as:
1126 * (1) If the child schema specifies a default, that value is used.
1127 * (2) If neither the child nor any parent specifies a default, then
1128 * the column will not have a default.
1129 * (3) If conflicting defaults are inherited from different parents
1130 * (and not overridden by the child), an error is raised.
1131 * (4) Otherwise the inherited default is used.
1132 * Rule (3) is new in Postgres 7.1; in earlier releases you got a
1133 * rather arbitrary choice of which parent default to use.
1137 MergeAttributes(List *schema, List *supers, bool istemp,
1138 List **supOids, List **supconstr, int *supOidCount)
1141 List *inhSchema = NIL;
1142 List *parentOids = NIL;
1143 List *constraints = NIL;
1144 int parentsWithOids = 0;
1145 bool have_bogus_defaults = false;
1146 char *bogus_marker = "Bogus!"; /* marks conflicting defaults */
1150 * Check for and reject tables with too many columns. We perform this
1151 * check relatively early for two reasons: (a) we don't run the risk of
1152 * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
1153 * okay if we're processing <= 1600 columns, but could take minutes to
1154 * execute if the user attempts to create a table with hundreds of
1155 * thousands of columns.
1157 * Note that we also need to check that any we do not exceed this figure
1158 * after including columns from inherited relations.
1160 if (list_length(schema) > MaxHeapAttributeNumber)
1162 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1163 errmsg("tables can have at most %d columns",
1164 MaxHeapAttributeNumber)));
1167 * Check for duplicate names in the explicit list of attributes.
1169 * Although we might consider merging such entries in the same way that we
1170 * handle name conflicts for inherited attributes, it seems to make more
1171 * sense to assume such conflicts are errors.
1173 foreach(entry, schema)
1175 ColumnDef *coldef = lfirst(entry);
1178 for_each_cell(rest, lnext(entry))
1180 ColumnDef *restdef = lfirst(rest);
1182 if (strcmp(coldef->colname, restdef->colname) == 0)
1184 (errcode(ERRCODE_DUPLICATE_COLUMN),
1185 errmsg("column \"%s\" specified more than once",
1191 * Scan the parents left-to-right, and merge their attributes to form a
1192 * list of inherited attributes (inhSchema). Also check to see if we need
1193 * to inherit an OID column.
1196 foreach(entry, supers)
1198 RangeVar *parent = (RangeVar *) lfirst(entry);
1200 TupleDesc tupleDesc;
1201 TupleConstr *constr;
1202 AttrNumber *newattno;
1203 AttrNumber parent_attno;
1205 relation = heap_openrv(parent, AccessShareLock);
1207 if (relation->rd_rel->relkind != RELKIND_RELATION)
1209 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1210 errmsg("inherited relation \"%s\" is not a table",
1212 /* Permanent rels cannot inherit from temporary ones */
1213 if (!istemp && relation->rd_istemp)
1215 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1216 errmsg("cannot inherit from temporary relation \"%s\"",
1220 * We should have an UNDER permission flag for this, but for now,
1221 * demand that creator of a child table own the parent.
1223 if (!pg_class_ownercheck(RelationGetRelid(relation), GetUserId()))
1224 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1225 RelationGetRelationName(relation));
1228 * Reject duplications in the list of parents.
1230 if (list_member_oid(parentOids, RelationGetRelid(relation)))
1232 (errcode(ERRCODE_DUPLICATE_TABLE),
1233 errmsg("relation \"%s\" would be inherited from more than once",
1236 parentOids = lappend_oid(parentOids, RelationGetRelid(relation));
1238 if (relation->rd_rel->relhasoids)
1241 tupleDesc = RelationGetDescr(relation);
1242 constr = tupleDesc->constr;
1245 * newattno[] will contain the child-table attribute numbers for the
1246 * attributes of this parent table. (They are not the same for
1247 * parents after the first one, nor if we have dropped columns.)
1249 newattno = (AttrNumber *)
1250 palloc(tupleDesc->natts * sizeof(AttrNumber));
1252 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1255 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
1256 char *attributeName = NameStr(attribute->attname);
1261 * Ignore dropped columns in the parent.
1263 if (attribute->attisdropped)
1266 * change_varattnos_of_a_node asserts that this is greater
1267 * than zero, so if anything tries to use it, we should find
1270 newattno[parent_attno - 1] = 0;
1275 * Does it conflict with some previously inherited column?
1277 exist_attno = findAttrByName(attributeName, inhSchema);
1278 if (exist_attno > 0)
1284 * Yes, try to merge the two column definitions. They must
1285 * have the same type and typmod.
1288 (errmsg("merging multiple inherited definitions of column \"%s\"",
1290 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1291 defTypeId = typenameTypeId(NULL, def->typeName, &deftypmod);
1292 if (defTypeId != attribute->atttypid ||
1293 deftypmod != attribute->atttypmod)
1295 (errcode(ERRCODE_DATATYPE_MISMATCH),
1296 errmsg("inherited column \"%s\" has a type conflict",
1298 errdetail("%s versus %s",
1299 TypeNameToString(def->typeName),
1300 format_type_be(attribute->atttypid))));
1302 /* Merge of NOT NULL constraints = OR 'em together */
1303 def->is_not_null |= attribute->attnotnull;
1304 /* Default and other constraints are handled below */
1305 newattno[parent_attno - 1] = exist_attno;
1310 * No, create a new inherited column
1312 def = makeNode(ColumnDef);
1313 def->colname = pstrdup(attributeName);
1314 def->typeName = makeTypeNameFromOid(attribute->atttypid,
1315 attribute->atttypmod);
1317 def->is_local = false;
1318 def->is_not_null = attribute->attnotnull;
1319 def->raw_default = NULL;
1320 def->cooked_default = NULL;
1321 def->constraints = NIL;
1322 inhSchema = lappend(inhSchema, def);
1323 newattno[parent_attno - 1] = ++child_attno;
1327 * Copy default if any
1329 if (attribute->atthasdef)
1331 char *this_default = NULL;
1332 AttrDefault *attrdef;
1335 /* Find default in constraint structure */
1336 Assert(constr != NULL);
1337 attrdef = constr->defval;
1338 for (i = 0; i < constr->num_defval; i++)
1340 if (attrdef[i].adnum == parent_attno)
1342 this_default = attrdef[i].adbin;
1346 Assert(this_default != NULL);
1349 * If default expr could contain any vars, we'd need to fix
1350 * 'em, but it can't; so default is ready to apply to child.
1352 * If we already had a default from some prior parent, check
1353 * to see if they are the same. If so, no problem; if not,
1354 * mark the column as having a bogus default. Below, we will
1355 * complain if the bogus default isn't overridden by the child
1358 Assert(def->raw_default == NULL);
1359 if (def->cooked_default == NULL)
1360 def->cooked_default = pstrdup(this_default);
1361 else if (strcmp(def->cooked_default, this_default) != 0)
1363 def->cooked_default = bogus_marker;
1364 have_bogus_defaults = true;
1370 * Now copy the CHECK constraints of this parent, adjusting attnos
1371 * using the completed newattno[] map. Identically named constraints
1372 * are merged if possible, else we throw error.
1374 if (constr && constr->num_check > 0)
1376 ConstrCheck *check = constr->check;
1379 for (i = 0; i < constr->num_check; i++)
1381 char *name = check[i].ccname;
1384 /* adjust varattnos of ccbin here */
1385 expr = stringToNode(check[i].ccbin);
1386 change_varattnos_of_a_node(expr, newattno);
1388 /* check for duplicate */
1389 if (!MergeCheckConstraint(constraints, name, expr))
1391 /* nope, this is a new one */
1392 CookedConstraint *cooked;
1394 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1395 cooked->contype = CONSTR_CHECK;
1396 cooked->name = pstrdup(name);
1397 cooked->attnum = 0; /* not used for constraints */
1398 cooked->expr = expr;
1399 cooked->is_local = false;
1400 cooked->inhcount = 1;
1401 constraints = lappend(constraints, cooked);
1409 * Close the parent rel, but keep our AccessShareLock on it until xact
1410 * commit. That will prevent someone else from deleting or ALTERing
1411 * the parent before the child is committed.
1413 heap_close(relation, NoLock);
1417 * If we had no inherited attributes, the result schema is just the
1418 * explicitly declared columns. Otherwise, we need to merge the declared
1419 * columns into the inherited schema list.
1421 if (inhSchema != NIL)
1423 foreach(entry, schema)
1425 ColumnDef *newdef = lfirst(entry);
1426 char *attributeName = newdef->colname;
1430 * Does it conflict with some previously inherited column?
1432 exist_attno = findAttrByName(attributeName, inhSchema);
1433 if (exist_attno > 0)
1442 * Yes, try to merge the two column definitions. They must
1443 * have the same type and typmod.
1446 (errmsg("merging column \"%s\" with inherited definition",
1448 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1449 defTypeId = typenameTypeId(NULL, def->typeName, &deftypmod);
1450 newTypeId = typenameTypeId(NULL, newdef->typeName, &newtypmod);
1451 if (defTypeId != newTypeId || deftypmod != newtypmod)
1453 (errcode(ERRCODE_DATATYPE_MISMATCH),
1454 errmsg("column \"%s\" has a type conflict",
1456 errdetail("%s versus %s",
1457 TypeNameToString(def->typeName),
1458 TypeNameToString(newdef->typeName))));
1459 /* Mark the column as locally defined */
1460 def->is_local = true;
1461 /* Merge of NOT NULL constraints = OR 'em together */
1462 def->is_not_null |= newdef->is_not_null;
1463 /* If new def has a default, override previous default */
1464 if (newdef->raw_default != NULL)
1466 def->raw_default = newdef->raw_default;
1467 def->cooked_default = newdef->cooked_default;
1473 * No, attach new column to result schema
1475 inhSchema = lappend(inhSchema, newdef);
1482 * Check that we haven't exceeded the legal # of columns after merging
1483 * in inherited columns.
1485 if (list_length(schema) > MaxHeapAttributeNumber)
1487 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1488 errmsg("tables can have at most %d columns",
1489 MaxHeapAttributeNumber)));
1493 * If we found any conflicting parent default values, check to make sure
1494 * they were overridden by the child.
1496 if (have_bogus_defaults)
1498 foreach(entry, schema)
1500 ColumnDef *def = lfirst(entry);
1502 if (def->cooked_default == bogus_marker)
1504 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
1505 errmsg("column \"%s\" inherits conflicting default values",
1507 errhint("To resolve the conflict, specify a default explicitly.")));
1511 *supOids = parentOids;
1512 *supconstr = constraints;
1513 *supOidCount = parentsWithOids;
1519 * MergeCheckConstraint
1520 * Try to merge an inherited CHECK constraint with previous ones
1522 * If we inherit identically-named constraints from multiple parents, we must
1523 * merge them, or throw an error if they don't have identical definitions.
1525 * constraints is a list of CookedConstraint structs for previous constraints.
1527 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
1528 * got a so-far-unique name, or throws error if conflict.
1531 MergeCheckConstraint(List *constraints, char *name, Node *expr)
1535 foreach(lc, constraints)
1537 CookedConstraint *ccon = (CookedConstraint *) lfirst(lc);
1539 Assert(ccon->contype == CONSTR_CHECK);
1541 /* Non-matching names never conflict */
1542 if (strcmp(ccon->name, name) != 0)
1545 if (equal(expr, ccon->expr))
1553 (errcode(ERRCODE_DUPLICATE_OBJECT),
1554 errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
1563 * Replace varattno values in an expression tree according to the given
1564 * map array, that is, varattno N is replaced by newattno[N-1]. It is
1565 * caller's responsibility to ensure that the array is long enough to
1566 * define values for all user varattnos present in the tree. System column
1567 * attnos remain unchanged.
1569 * Note that the passed node tree is modified in-place!
1572 change_varattnos_of_a_node(Node *node, const AttrNumber *newattno)
1574 /* no setup needed, so away we go */
1575 (void) change_varattnos_walker(node, newattno);
1579 change_varattnos_walker(Node *node, const AttrNumber *newattno)
1585 Var *var = (Var *) node;
1587 if (var->varlevelsup == 0 && var->varno == 1 &&
1591 * ??? the following may be a problem when the node is multiply
1592 * referenced though stringToNode() doesn't create such a node
1595 Assert(newattno[var->varattno - 1] > 0);
1596 var->varattno = var->varoattno = newattno[var->varattno - 1];
1600 return expression_tree_walker(node, change_varattnos_walker,
1605 * Generate a map for change_varattnos_of_a_node from old and new TupleDesc's,
1606 * matching according to column name.
1609 varattnos_map(TupleDesc olddesc, TupleDesc newdesc)
1615 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * olddesc->natts);
1616 for (i = 1; i <= olddesc->natts; i++)
1618 if (olddesc->attrs[i - 1]->attisdropped)
1619 continue; /* leave the entry as zero */
1621 for (j = 1; j <= newdesc->natts; j++)
1623 if (strcmp(NameStr(olddesc->attrs[i - 1]->attname),
1624 NameStr(newdesc->attrs[j - 1]->attname)) == 0)
1635 * Generate a map for change_varattnos_of_a_node from a TupleDesc and a list
1639 varattnos_map_schema(TupleDesc old, List *schema)
1644 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * old->natts);
1645 for (i = 1; i <= old->natts; i++)
1647 if (old->attrs[i - 1]->attisdropped)
1648 continue; /* leave the entry as zero */
1650 attmap[i - 1] = findAttrByName(NameStr(old->attrs[i - 1]->attname),
1658 * StoreCatalogInheritance
1659 * Updates the system catalogs with proper inheritance information.
1661 * supers is a list of the OIDs of the new relation's direct ancestors.
1664 StoreCatalogInheritance(Oid relationId, List *supers)
1673 AssertArg(OidIsValid(relationId));
1679 * Store INHERITS information in pg_inherits using direct ancestors only.
1680 * Also enter dependencies on the direct ancestors, and make sure they are
1681 * marked with relhassubclass = true.
1683 * (Once upon a time, both direct and indirect ancestors were found here
1684 * and then entered into pg_ipl. Since that catalog doesn't exist
1685 * anymore, there's no need to look for indirect ancestors.)
1687 relation = heap_open(InheritsRelationId, RowExclusiveLock);
1690 foreach(entry, supers)
1692 Oid parentOid = lfirst_oid(entry);
1694 StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation);
1698 heap_close(relation, RowExclusiveLock);
1702 * Make catalog entries showing relationId as being an inheritance child
1703 * of parentOid. inhRelation is the already-opened pg_inherits catalog.
1706 StoreCatalogInheritance1(Oid relationId, Oid parentOid,
1707 int16 seqNumber, Relation inhRelation)
1709 TupleDesc desc = RelationGetDescr(inhRelation);
1710 Datum datum[Natts_pg_inherits];
1711 bool nullarr[Natts_pg_inherits];
1712 ObjectAddress childobject,
1717 * Make the pg_inherits entry
1719 datum[0] = ObjectIdGetDatum(relationId); /* inhrelid */
1720 datum[1] = ObjectIdGetDatum(parentOid); /* inhparent */
1721 datum[2] = Int16GetDatum(seqNumber); /* inhseqno */
1727 tuple = heap_form_tuple(desc, datum, nullarr);
1729 simple_heap_insert(inhRelation, tuple);
1731 CatalogUpdateIndexes(inhRelation, tuple);
1733 heap_freetuple(tuple);
1736 * Store a dependency too
1738 parentobject.classId = RelationRelationId;
1739 parentobject.objectId = parentOid;
1740 parentobject.objectSubId = 0;
1741 childobject.classId = RelationRelationId;
1742 childobject.objectId = relationId;
1743 childobject.objectSubId = 0;
1745 recordDependencyOn(&childobject, &parentobject, DEPENDENCY_NORMAL);
1748 * Mark the parent as having subclasses.
1750 setRelhassubclassInRelation(parentOid, true);
1754 * Look for an existing schema entry with the given name.
1756 * Returns the index (starting with 1) if attribute already exists in schema,
1760 findAttrByName(const char *attributeName, List *schema)
1767 ColumnDef *def = lfirst(s);
1769 if (strcmp(attributeName, def->colname) == 0)
1778 * Update a relation's pg_class.relhassubclass entry to the given value
1781 setRelhassubclassInRelation(Oid relationId, bool relhassubclass)
1783 Relation relationRelation;
1785 Form_pg_class classtuple;
1788 * Fetch a modifiable copy of the tuple, modify it, update pg_class.
1790 * If the tuple already has the right relhassubclass setting, we don't
1791 * need to update it, but we still need to issue an SI inval message.
1793 relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
1794 tuple = SearchSysCacheCopy(RELOID,
1795 ObjectIdGetDatum(relationId),
1797 if (!HeapTupleIsValid(tuple))
1798 elog(ERROR, "cache lookup failed for relation %u", relationId);
1799 classtuple = (Form_pg_class) GETSTRUCT(tuple);
1801 if (classtuple->relhassubclass != relhassubclass)
1803 classtuple->relhassubclass = relhassubclass;
1804 simple_heap_update(relationRelation, &tuple->t_self, tuple);
1806 /* keep the catalog indexes up to date */
1807 CatalogUpdateIndexes(relationRelation, tuple);
1811 /* no need to change tuple, but force relcache rebuild anyway */
1812 CacheInvalidateRelcacheByTuple(tuple);
1815 heap_freetuple(tuple);
1816 heap_close(relationRelation, RowExclusiveLock);
1821 * renameatt - changes the name of a attribute in a relation
1823 * Attname attribute is changed in attribute catalog.
1824 * No record of the previous attname is kept (correct?).
1826 * get proper relrelation from relation catalog (if not arg)
1827 * scan attribute catalog
1828 * for name conflict (within rel)
1829 * for original attribute (if not arg)
1830 * modify attname in attribute tuple
1831 * insert modified attribute in attribute catalog
1832 * delete original attribute from attribute catalog
1835 renameatt(Oid myrelid,
1836 const char *oldattname,
1837 const char *newattname,
1841 Relation targetrelation;
1842 Relation attrelation;
1844 Form_pg_attribute attform;
1847 ListCell *indexoidscan;
1850 * Grab an exclusive lock on the target table, which we will NOT release
1851 * until end of transaction.
1853 targetrelation = relation_open(myrelid, AccessExclusiveLock);
1856 * permissions checking. this would normally be done in utility.c, but
1857 * this particular routine is recursive.
1859 * normally, only the owner of a class can change its schema.
1861 if (!pg_class_ownercheck(myrelid, GetUserId()))
1862 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1863 RelationGetRelationName(targetrelation));
1864 if (!allowSystemTableMods && IsSystemRelation(targetrelation))
1866 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1867 errmsg("permission denied: \"%s\" is a system catalog",
1868 RelationGetRelationName(targetrelation))));
1871 * if the 'recurse' flag is set then we are supposed to rename this
1872 * attribute in all classes that inherit from 'relname' (as well as in
1875 * any permissions or problems with duplicate attributes will cause the
1876 * whole transaction to abort, which is what we want -- all or nothing.
1883 children = find_all_inheritors(myrelid, AccessExclusiveLock);
1886 * find_all_inheritors does the recursive search of the inheritance
1887 * hierarchy, so all we have to do is process all of the relids in the
1888 * list that it returns.
1890 foreach(child, children)
1892 Oid childrelid = lfirst_oid(child);
1894 if (childrelid == myrelid)
1896 /* note we need not recurse again */
1897 renameatt(childrelid, oldattname, newattname, false, true);
1903 * If we are told not to recurse, there had better not be any child
1904 * tables; else the rename would put them out of step.
1907 find_inheritance_children(myrelid, NoLock) != NIL)
1909 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1910 errmsg("inherited column \"%s\" must be renamed in child tables too",
1914 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
1916 atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
1917 if (!HeapTupleIsValid(atttup))
1919 (errcode(ERRCODE_UNDEFINED_COLUMN),
1920 errmsg("column \"%s\" does not exist",
1922 attform = (Form_pg_attribute) GETSTRUCT(atttup);
1924 attnum = attform->attnum;
1927 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1928 errmsg("cannot rename system column \"%s\"",
1932 * if the attribute is inherited, forbid the renaming, unless we are
1933 * already inside a recursive rename.
1935 if (attform->attinhcount > 0 && !recursing)
1937 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1938 errmsg("cannot rename inherited column \"%s\"",
1941 /* should not already exist */
1942 /* this test is deliberately not attisdropped-aware */
1943 if (SearchSysCacheExists(ATTNAME,
1944 ObjectIdGetDatum(myrelid),
1945 PointerGetDatum(newattname),
1948 (errcode(ERRCODE_DUPLICATE_COLUMN),
1949 errmsg("column \"%s\" of relation \"%s\" already exists",
1950 newattname, RelationGetRelationName(targetrelation))));
1952 namestrcpy(&(attform->attname), newattname);
1954 simple_heap_update(attrelation, &atttup->t_self, atttup);
1956 /* keep system catalog indexes current */
1957 CatalogUpdateIndexes(attrelation, atttup);
1959 heap_freetuple(atttup);
1962 * Update column names of indexes that refer to the column being renamed.
1964 indexoidlist = RelationGetIndexList(targetrelation);
1966 foreach(indexoidscan, indexoidlist)
1968 Oid indexoid = lfirst_oid(indexoidscan);
1970 Form_pg_index indexform;
1974 * Scan through index columns to see if there's any simple index
1975 * entries for this attribute. We ignore expressional entries.
1977 indextup = SearchSysCache(INDEXRELID,
1978 ObjectIdGetDatum(indexoid),
1980 if (!HeapTupleIsValid(indextup))
1981 elog(ERROR, "cache lookup failed for index %u", indexoid);
1982 indexform = (Form_pg_index) GETSTRUCT(indextup);
1984 for (i = 0; i < indexform->indnatts; i++)
1986 if (attnum != indexform->indkey.values[i])
1990 * Found one, rename it.
1992 atttup = SearchSysCacheCopy(ATTNUM,
1993 ObjectIdGetDatum(indexoid),
1994 Int16GetDatum(i + 1),
1996 if (!HeapTupleIsValid(atttup))
1997 continue; /* should we raise an error? */
2000 * Update the (copied) attribute tuple.
2002 namestrcpy(&(((Form_pg_attribute) GETSTRUCT(atttup))->attname),
2005 simple_heap_update(attrelation, &atttup->t_self, atttup);
2007 /* keep system catalog indexes current */
2008 CatalogUpdateIndexes(attrelation, atttup);
2010 heap_freetuple(atttup);
2013 ReleaseSysCache(indextup);
2016 list_free(indexoidlist);
2018 heap_close(attrelation, RowExclusiveLock);
2020 relation_close(targetrelation, NoLock); /* close rel but keep lock */
2025 * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW RENAME
2027 * Caller has already done permissions checks.
2030 RenameRelation(Oid myrelid, const char *newrelname, ObjectType reltype)
2032 Relation targetrelation;
2037 * Grab an exclusive lock on the target table, index, sequence or view,
2038 * which we will NOT release until end of transaction.
2040 targetrelation = relation_open(myrelid, AccessExclusiveLock);
2042 namespaceId = RelationGetNamespace(targetrelation);
2043 relkind = targetrelation->rd_rel->relkind;
2046 * For compatibility with prior releases, we don't complain if ALTER TABLE
2047 * or ALTER INDEX is used to rename a sequence or view.
2049 if (reltype == OBJECT_SEQUENCE && relkind != RELKIND_SEQUENCE)
2051 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2052 errmsg("\"%s\" is not a sequence",
2053 RelationGetRelationName(targetrelation))));
2055 if (reltype == OBJECT_VIEW && relkind != RELKIND_VIEW)
2057 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2058 errmsg("\"%s\" is not a view",
2059 RelationGetRelationName(targetrelation))));
2062 * Don't allow ALTER TABLE on composite types. We want people to use ALTER
2065 if (relkind == RELKIND_COMPOSITE_TYPE)
2067 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2068 errmsg("\"%s\" is a composite type",
2069 RelationGetRelationName(targetrelation)),
2070 errhint("Use ALTER TYPE instead.")));
2073 RenameRelationInternal(myrelid, newrelname, namespaceId);
2076 * Close rel, but keep exclusive lock!
2078 relation_close(targetrelation, NoLock);
2082 * RenameRelationInternal - change the name of a relation
2084 * XXX - When renaming sequences, we don't bother to modify the
2085 * sequence name that is stored within the sequence itself
2086 * (this would cause problems with MVCC). In the future,
2087 * the sequence name should probably be removed from the
2088 * sequence, AFAIK there's no need for it to be there.
2091 RenameRelationInternal(Oid myrelid, const char *newrelname, Oid namespaceId)
2093 Relation targetrelation;
2094 Relation relrelation; /* for RELATION relation */
2096 Form_pg_class relform;
2099 * Grab an exclusive lock on the target table, index, sequence or view,
2100 * which we will NOT release until end of transaction.
2102 targetrelation = relation_open(myrelid, AccessExclusiveLock);
2105 * Find relation's pg_class tuple, and make sure newrelname isn't in use.
2107 relrelation = heap_open(RelationRelationId, RowExclusiveLock);
2109 reltup = SearchSysCacheCopy(RELOID,
2110 ObjectIdGetDatum(myrelid),
2112 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
2113 elog(ERROR, "cache lookup failed for relation %u", myrelid);
2114 relform = (Form_pg_class) GETSTRUCT(reltup);
2116 if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
2118 (errcode(ERRCODE_DUPLICATE_TABLE),
2119 errmsg("relation \"%s\" already exists",
2123 * Update pg_class tuple with new relname. (Scribbling on reltup is OK
2124 * because it's a copy...)
2126 namestrcpy(&(relform->relname), newrelname);
2128 simple_heap_update(relrelation, &reltup->t_self, reltup);
2130 /* keep the system catalog indexes current */
2131 CatalogUpdateIndexes(relrelation, reltup);
2133 heap_freetuple(reltup);
2134 heap_close(relrelation, RowExclusiveLock);
2137 * Also rename the associated type, if any.
2139 if (OidIsValid(targetrelation->rd_rel->reltype))
2140 RenameTypeInternal(targetrelation->rd_rel->reltype,
2141 newrelname, namespaceId);
2144 * Also rename the associated constraint, if any.
2146 if (targetrelation->rd_rel->relkind == RELKIND_INDEX)
2148 Oid constraintId = get_index_constraint(myrelid);
2150 if (OidIsValid(constraintId))
2151 RenameConstraintById(constraintId, newrelname);
2155 * Close rel, but keep exclusive lock!
2157 relation_close(targetrelation, NoLock);
2161 * Disallow ALTER TABLE (and similar commands) when the current backend has
2162 * any open reference to the target table besides the one just acquired by
2163 * the calling command; this implies there's an open cursor or active plan.
2164 * We need this check because our AccessExclusiveLock doesn't protect us
2165 * against stomping on our own foot, only other people's feet!
2167 * For ALTER TABLE, the only case known to cause serious trouble is ALTER
2168 * COLUMN TYPE, and some changes are obviously pretty benign, so this could
2169 * possibly be relaxed to only error out for certain types of alterations.
2170 * But the use-case for allowing any of these things is not obvious, so we
2171 * won't work hard at it for now.
2173 * We also reject these commands if there are any pending AFTER trigger events
2174 * for the rel. This is certainly necessary for the rewriting variants of
2175 * ALTER TABLE, because they don't preserve tuple TIDs and so the pending
2176 * events would try to fetch the wrong tuples. It might be overly cautious
2177 * in other cases, but again it seems better to err on the side of paranoia.
2179 * REINDEX calls this with "rel" referencing the index to be rebuilt; here
2180 * we are worried about active indexscans on the index. The trigger-event
2181 * check can be skipped, since we are doing no damage to the parent table.
2183 * The statement name (eg, "ALTER TABLE") is passed for use in error messages.
2186 CheckTableNotInUse(Relation rel, const char *stmt)
2188 int expected_refcnt;
2190 expected_refcnt = rel->rd_isnailed ? 2 : 1;
2191 if (rel->rd_refcnt != expected_refcnt)
2193 (errcode(ERRCODE_OBJECT_IN_USE),
2194 /* translator: first %s is a SQL command, eg ALTER TABLE */
2195 errmsg("cannot %s \"%s\" because "
2196 "it is being used by active queries in this session",
2197 stmt, RelationGetRelationName(rel))));
2199 if (rel->rd_rel->relkind != RELKIND_INDEX &&
2200 AfterTriggerPendingOnRel(RelationGetRelid(rel)))
2202 (errcode(ERRCODE_OBJECT_IN_USE),
2203 /* translator: first %s is a SQL command, eg ALTER TABLE */
2204 errmsg("cannot %s \"%s\" because "
2205 "it has pending trigger events",
2206 stmt, RelationGetRelationName(rel))));
2211 * Execute ALTER TABLE, which can be a list of subcommands
2213 * ALTER TABLE is performed in three phases:
2214 * 1. Examine subcommands and perform pre-transformation checking.
2215 * 2. Update system catalogs.
2216 * 3. Scan table(s) to check new constraints, and optionally recopy
2217 * the data into new table(s).
2218 * Phase 3 is not performed unless one or more of the subcommands requires
2219 * it. The intention of this design is to allow multiple independent
2220 * updates of the table schema to be performed with only one pass over the
2223 * ATPrepCmd performs phase 1. A "work queue" entry is created for
2224 * each table to be affected (there may be multiple affected tables if the
2225 * commands traverse a table inheritance hierarchy). Also we do preliminary
2226 * validation of the subcommands, including parse transformation of those
2227 * expressions that need to be evaluated with respect to the old table
2230 * ATRewriteCatalogs performs phase 2 for each affected table. (Note that
2231 * phases 2 and 3 normally do no explicit recursion, since phase 1 already
2232 * did it --- although some subcommands have to recurse in phase 2 instead.)
2233 * Certain subcommands need to be performed before others to avoid
2234 * unnecessary conflicts; for example, DROP COLUMN should come before
2235 * ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
2236 * lists, one for each logical "pass" of phase 2.
2238 * ATRewriteTables performs phase 3 for those tables that need it.
2240 * Thanks to the magic of MVCC, an error anywhere along the way rolls back
2241 * the whole operation; we don't have to do anything special to clean up.
2244 AlterTable(AlterTableStmt *stmt)
2246 Relation rel = relation_openrv(stmt->relation, AccessExclusiveLock);
2248 CheckTableNotInUse(rel, "ALTER TABLE");
2250 /* Check relation type against type specified in the ALTER command */
2251 switch (stmt->relkind)
2256 * For mostly-historical reasons, we allow ALTER TABLE to apply to
2257 * all relation types.
2262 if (rel->rd_rel->relkind != RELKIND_INDEX)
2264 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2265 errmsg("\"%s\" is not an index",
2266 RelationGetRelationName(rel))));
2269 case OBJECT_SEQUENCE:
2270 if (rel->rd_rel->relkind != RELKIND_SEQUENCE)
2272 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2273 errmsg("\"%s\" is not a sequence",
2274 RelationGetRelationName(rel))));
2278 if (rel->rd_rel->relkind != RELKIND_VIEW)
2280 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2281 errmsg("\"%s\" is not a view",
2282 RelationGetRelationName(rel))));
2286 elog(ERROR, "unrecognized object type: %d", (int) stmt->relkind);
2289 ATController(rel, stmt->cmds, interpretInhOption(stmt->relation->inhOpt));
2293 * AlterTableInternal
2295 * ALTER TABLE with target specified by OID
2297 * We do not reject if the relation is already open, because it's quite
2298 * likely that one or more layers of caller have it open. That means it
2299 * is unsafe to use this entry point for alterations that could break
2300 * existing query plans. On the assumption it's not used for such, we
2301 * don't have to reject pending AFTER triggers, either.
2304 AlterTableInternal(Oid relid, List *cmds, bool recurse)
2306 Relation rel = relation_open(relid, AccessExclusiveLock);
2308 ATController(rel, cmds, recurse);
2312 ATController(Relation rel, List *cmds, bool recurse)
2317 /* Phase 1: preliminary examination of commands, create work queue */
2320 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2322 ATPrepCmd(&wqueue, rel, cmd, recurse, false);
2325 /* Close the relation, but keep lock until commit */
2326 relation_close(rel, NoLock);
2328 /* Phase 2: update system catalogs */
2329 ATRewriteCatalogs(&wqueue);
2331 /* Phase 3: scan/rewrite tables as needed */
2332 ATRewriteTables(&wqueue);
2338 * Traffic cop for ALTER TABLE Phase 1 operations, including simple
2339 * recursion and permission checks.
2341 * Caller must have acquired AccessExclusiveLock on relation already.
2342 * This lock should be held until commit.
2345 ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
2346 bool recurse, bool recursing)
2348 AlteredTableInfo *tab;
2351 /* Find or create work queue entry for this table */
2352 tab = ATGetQueueEntry(wqueue, rel);
2355 * Copy the original subcommand for each table. This avoids conflicts
2356 * when different child tables need to make different parse
2357 * transformations (for example, the same column may have different column
2358 * numbers in different children).
2360 cmd = copyObject(cmd);
2363 * Do permissions checking, recursion to child tables if needed, and any
2364 * additional phase-1 processing needed.
2366 switch (cmd->subtype)
2368 case AT_AddColumn: /* ADD COLUMN */
2369 ATSimplePermissions(rel, false);
2370 /* Performs own recursion */
2371 ATPrepAddColumn(wqueue, rel, recurse, cmd);
2372 pass = AT_PASS_ADD_COL;
2374 case AT_AddColumnToView: /* add column via CREATE OR REPLACE
2376 ATSimplePermissions(rel, true);
2377 /* Performs own recursion */
2378 ATPrepAddColumn(wqueue, rel, recurse, cmd);
2379 pass = AT_PASS_ADD_COL;
2381 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
2384 * We allow defaults on views so that INSERT into a view can have
2385 * default-ish behavior. This works because the rewriter
2386 * substitutes default values into INSERTs before it expands
2389 ATSimplePermissions(rel, true);
2390 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2391 /* No command-specific prep needed */
2392 pass = cmd->def ? AT_PASS_ADD_CONSTR : AT_PASS_DROP;
2394 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
2395 ATSimplePermissions(rel, false);
2396 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2397 /* No command-specific prep needed */
2398 pass = AT_PASS_DROP;
2400 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
2401 ATSimplePermissions(rel, false);
2402 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2403 /* No command-specific prep needed */
2404 pass = AT_PASS_ADD_CONSTR;
2406 case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
2407 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2408 /* Performs own permission checks */
2409 ATPrepSetStatistics(rel, cmd->name, cmd->def);
2410 pass = AT_PASS_COL_ATTRS;
2412 case AT_SetDistinct: /* ALTER COLUMN SET STATISTICS DISTINCT */
2413 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2414 /* Performs own permission checks */
2415 ATPrepSetDistinct(rel, cmd->name, cmd->def);
2416 pass = AT_PASS_COL_ATTRS;
2418 case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
2419 ATSimplePermissions(rel, false);
2420 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2421 /* No command-specific prep needed */
2422 pass = AT_PASS_COL_ATTRS;
2424 case AT_DropColumn: /* DROP COLUMN */
2425 ATSimplePermissions(rel, false);
2426 /* Recursion occurs during execution phase */
2427 /* No command-specific prep needed except saving recurse flag */
2429 cmd->subtype = AT_DropColumnRecurse;
2430 pass = AT_PASS_DROP;
2432 case AT_AddIndex: /* ADD INDEX */
2433 ATSimplePermissions(rel, false);
2434 /* This command never recurses */
2435 /* No command-specific prep needed */
2436 pass = AT_PASS_ADD_INDEX;
2438 case AT_AddConstraint: /* ADD CONSTRAINT */
2439 ATSimplePermissions(rel, false);
2440 /* Recursion occurs during execution phase */
2441 /* No command-specific prep needed except saving recurse flag */
2443 cmd->subtype = AT_AddConstraintRecurse;
2444 pass = AT_PASS_ADD_CONSTR;
2446 case AT_DropConstraint: /* DROP CONSTRAINT */
2447 ATSimplePermissions(rel, false);
2448 /* Recursion occurs during execution phase */
2449 /* No command-specific prep needed except saving recurse flag */
2451 cmd->subtype = AT_DropConstraintRecurse;
2452 pass = AT_PASS_DROP;
2454 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
2455 ATSimplePermissions(rel, false);
2456 /* Performs own recursion */
2457 ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd);
2458 pass = AT_PASS_ALTER_TYPE;
2460 case AT_ChangeOwner: /* ALTER OWNER */
2461 /* This command never recurses */
2462 /* No command-specific prep needed */
2463 pass = AT_PASS_MISC;
2465 case AT_ClusterOn: /* CLUSTER ON */
2466 case AT_DropCluster: /* SET WITHOUT CLUSTER */
2467 ATSimplePermissions(rel, false);
2468 /* These commands never recurse */
2469 /* No command-specific prep needed */
2470 pass = AT_PASS_MISC;
2472 case AT_AddOids: /* SET WITH OIDS */
2473 ATSimplePermissions(rel, false);
2474 /* Performs own recursion */
2475 if (!rel->rd_rel->relhasoids || recursing)
2476 ATPrepAddOids(wqueue, rel, recurse, cmd);
2477 pass = AT_PASS_ADD_COL;
2479 case AT_DropOids: /* SET WITHOUT OIDS */
2480 ATSimplePermissions(rel, false);
2481 /* Performs own recursion */
2482 if (rel->rd_rel->relhasoids)
2484 AlterTableCmd *dropCmd = makeNode(AlterTableCmd);
2486 dropCmd->subtype = AT_DropColumn;
2487 dropCmd->name = pstrdup("oid");
2488 dropCmd->behavior = cmd->behavior;
2489 ATPrepCmd(wqueue, rel, dropCmd, recurse, false);
2491 pass = AT_PASS_DROP;
2493 case AT_SetTableSpace: /* SET TABLESPACE */
2494 ATSimplePermissionsRelationOrIndex(rel);
2495 /* This command never recurses */
2496 ATPrepSetTableSpace(tab, rel, cmd->name);
2497 pass = AT_PASS_MISC; /* doesn't actually matter */
2499 case AT_SetRelOptions: /* SET (...) */
2500 case AT_ResetRelOptions: /* RESET (...) */
2501 ATSimplePermissionsRelationOrIndex(rel);
2502 /* This command never recurses */
2503 /* No command-specific prep needed */
2504 pass = AT_PASS_MISC;
2506 case AT_EnableTrig: /* ENABLE TRIGGER variants */
2507 case AT_EnableAlwaysTrig:
2508 case AT_EnableReplicaTrig:
2509 case AT_EnableTrigAll:
2510 case AT_EnableTrigUser:
2511 case AT_DisableTrig: /* DISABLE TRIGGER variants */
2512 case AT_DisableTrigAll:
2513 case AT_DisableTrigUser:
2514 case AT_EnableRule: /* ENABLE/DISABLE RULE variants */
2515 case AT_EnableAlwaysRule:
2516 case AT_EnableReplicaRule:
2517 case AT_DisableRule:
2518 case AT_AddInherit: /* INHERIT / NO INHERIT */
2519 case AT_DropInherit:
2520 ATSimplePermissions(rel, false);
2521 /* These commands never recurse */
2522 /* No command-specific prep needed */
2523 pass = AT_PASS_MISC;
2526 elog(ERROR, "unrecognized alter table type: %d",
2527 (int) cmd->subtype);
2528 pass = 0; /* keep compiler quiet */
2532 /* Add the subcommand to the appropriate list for phase 2 */
2533 tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
2539 * Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
2540 * dispatched in a "safe" execution order (designed to avoid unnecessary
2544 ATRewriteCatalogs(List **wqueue)
2550 * We process all the tables "in parallel", one pass at a time. This is
2551 * needed because we may have to propagate work from one table to another
2552 * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
2553 * re-adding of the foreign key constraint to the other table). Work can
2554 * only be propagated into later passes, however.
2556 for (pass = 0; pass < AT_NUM_PASSES; pass++)
2558 /* Go through each table that needs to be processed */
2559 foreach(ltab, *wqueue)
2561 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2562 List *subcmds = tab->subcmds[pass];
2570 * Exclusive lock was obtained by phase 1, needn't get it again
2572 rel = relation_open(tab->relid, NoLock);
2574 foreach(lcmd, subcmds)
2575 ATExecCmd(wqueue, tab, rel, (AlterTableCmd *) lfirst(lcmd));
2578 * After the ALTER TYPE pass, do cleanup work (this is not done in
2579 * ATExecAlterColumnType since it should be done only once if
2580 * multiple columns of a table are altered).
2582 if (pass == AT_PASS_ALTER_TYPE)
2583 ATPostAlterTypeCleanup(wqueue, tab);
2585 relation_close(rel, NoLock);
2590 * Check to see if a toast table must be added, if we executed any
2591 * subcommands that might have added a column or changed column storage.
2593 foreach(ltab, *wqueue)
2595 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2597 if (tab->relkind == RELKIND_RELATION &&
2598 (tab->subcmds[AT_PASS_ADD_COL] ||
2599 tab->subcmds[AT_PASS_ALTER_TYPE] ||
2600 tab->subcmds[AT_PASS_COL_ATTRS]))
2601 AlterTableCreateToastTable(tab->relid, InvalidOid,
2607 * ATExecCmd: dispatch a subcommand to appropriate execution routine
2610 ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
2613 switch (cmd->subtype)
2615 case AT_AddColumn: /* ADD COLUMN */
2616 case AT_AddColumnToView: /* add column via CREATE OR REPLACE
2618 ATExecAddColumn(tab, rel, (ColumnDef *) cmd->def, false);
2620 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
2621 ATExecColumnDefault(rel, cmd->name, cmd->def);
2623 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
2624 ATExecDropNotNull(rel, cmd->name);
2626 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
2627 ATExecSetNotNull(tab, rel, cmd->name);
2629 case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
2630 ATExecSetStatistics(rel, cmd->name, cmd->def);
2632 case AT_SetDistinct: /* ALTER COLUMN SET STATISTICS DISTINCT */
2633 ATExecSetDistinct(rel, cmd->name, cmd->def);
2635 case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
2636 ATExecSetStorage(rel, cmd->name, cmd->def);
2638 case AT_DropColumn: /* DROP COLUMN */
2639 ATExecDropColumn(wqueue, rel, cmd->name,
2640 cmd->behavior, false, false, cmd->missing_ok);
2642 case AT_DropColumnRecurse: /* DROP COLUMN with recursion */
2643 ATExecDropColumn(wqueue, rel, cmd->name,
2644 cmd->behavior, true, false, cmd->missing_ok);
2646 case AT_AddIndex: /* ADD INDEX */
2647 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false);
2649 case AT_ReAddIndex: /* ADD INDEX */
2650 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true);
2652 case AT_AddConstraint: /* ADD CONSTRAINT */
2653 ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
2656 case AT_AddConstraintRecurse: /* ADD CONSTRAINT with recursion */
2657 ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
2660 case AT_DropConstraint: /* DROP CONSTRAINT */
2661 ATExecDropConstraint(rel, cmd->name, cmd->behavior,
2665 case AT_DropConstraintRecurse: /* DROP CONSTRAINT with recursion */
2666 ATExecDropConstraint(rel, cmd->name, cmd->behavior,
2670 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
2671 ATExecAlterColumnType(tab, rel, cmd->name, (TypeName *) cmd->def);
2673 case AT_ChangeOwner: /* ALTER OWNER */
2674 ATExecChangeOwner(RelationGetRelid(rel),
2675 get_roleid_checked(cmd->name),
2678 case AT_ClusterOn: /* CLUSTER ON */
2679 ATExecClusterOn(rel, cmd->name);
2681 case AT_DropCluster: /* SET WITHOUT CLUSTER */
2682 ATExecDropCluster(rel);
2684 case AT_AddOids: /* SET WITH OIDS */
2685 /* Use the ADD COLUMN code, unless prep decided to do nothing */
2686 if (cmd->def != NULL)
2687 ATExecAddColumn(tab, rel, (ColumnDef *) cmd->def, true);
2689 case AT_DropOids: /* SET WITHOUT OIDS */
2692 * Nothing to do here; we'll have generated a DropColumn
2693 * subcommand to do the real work
2696 case AT_SetTableSpace: /* SET TABLESPACE */
2699 * Nothing to do here; Phase 3 does the work
2702 case AT_SetRelOptions: /* SET (...) */
2703 ATExecSetRelOptions(rel, (List *) cmd->def, false);
2705 case AT_ResetRelOptions: /* RESET (...) */
2706 ATExecSetRelOptions(rel, (List *) cmd->def, true);
2709 case AT_EnableTrig: /* ENABLE TRIGGER name */
2710 ATExecEnableDisableTrigger(rel, cmd->name,
2711 TRIGGER_FIRES_ON_ORIGIN, false);
2713 case AT_EnableAlwaysTrig: /* ENABLE ALWAYS TRIGGER name */
2714 ATExecEnableDisableTrigger(rel, cmd->name,
2715 TRIGGER_FIRES_ALWAYS, false);
2717 case AT_EnableReplicaTrig: /* ENABLE REPLICA TRIGGER name */
2718 ATExecEnableDisableTrigger(rel, cmd->name,
2719 TRIGGER_FIRES_ON_REPLICA, false);
2721 case AT_DisableTrig: /* DISABLE TRIGGER name */
2722 ATExecEnableDisableTrigger(rel, cmd->name,
2723 TRIGGER_DISABLED, false);
2725 case AT_EnableTrigAll: /* ENABLE TRIGGER ALL */
2726 ATExecEnableDisableTrigger(rel, NULL,
2727 TRIGGER_FIRES_ON_ORIGIN, false);
2729 case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
2730 ATExecEnableDisableTrigger(rel, NULL,
2731 TRIGGER_DISABLED, false);
2733 case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
2734 ATExecEnableDisableTrigger(rel, NULL,
2735 TRIGGER_FIRES_ON_ORIGIN, true);
2737 case AT_DisableTrigUser: /* DISABLE TRIGGER USER */
2738 ATExecEnableDisableTrigger(rel, NULL,
2739 TRIGGER_DISABLED, true);
2742 case AT_EnableRule: /* ENABLE RULE name */
2743 ATExecEnableDisableRule(rel, cmd->name,
2744 RULE_FIRES_ON_ORIGIN);
2746 case AT_EnableAlwaysRule: /* ENABLE ALWAYS RULE name */
2747 ATExecEnableDisableRule(rel, cmd->name,
2750 case AT_EnableReplicaRule: /* ENABLE REPLICA RULE name */
2751 ATExecEnableDisableRule(rel, cmd->name,
2752 RULE_FIRES_ON_REPLICA);
2754 case AT_DisableRule: /* DISABLE RULE name */
2755 ATExecEnableDisableRule(rel, cmd->name,
2760 ATExecAddInherit(rel, (RangeVar *) cmd->def);
2762 case AT_DropInherit:
2763 ATExecDropInherit(rel, (RangeVar *) cmd->def);
2766 elog(ERROR, "unrecognized alter table type: %d",
2767 (int) cmd->subtype);
2772 * Bump the command counter to ensure the next subcommand in the sequence
2773 * can see the changes so far
2775 CommandCounterIncrement();
2779 * ATRewriteTables: ALTER TABLE phase 3
2782 ATRewriteTables(List **wqueue)
2786 /* Go through each table that needs to be checked or rewritten */
2787 foreach(ltab, *wqueue)
2789 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2792 * We only need to rewrite the table if at least one column needs to
2793 * be recomputed, or we are adding/removing the OID column.
2795 if (tab->newvals != NIL || tab->new_changeoids)
2797 /* Build a temporary relation and copy data */
2799 char NewHeapName[NAMEDATALEN];
2802 ObjectAddress object;
2804 OldHeap = heap_open(tab->relid, NoLock);
2807 * We can never allow rewriting of shared or nailed-in-cache
2808 * relations, because we can't support changing their relfilenode
2811 if (OldHeap->rd_rel->relisshared || OldHeap->rd_isnailed)
2813 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2814 errmsg("cannot rewrite system relation \"%s\"",
2815 RelationGetRelationName(OldHeap))));
2818 * Don't allow rewrite on temp tables of other backends ... their
2819 * local buffer manager is not going to cope.
2821 if (RELATION_IS_OTHER_TEMP(OldHeap))
2823 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2824 errmsg("cannot rewrite temporary tables of other sessions")));
2827 * Select destination tablespace (same as original unless user
2828 * requested a change)
2830 if (tab->newTableSpace)
2831 NewTableSpace = tab->newTableSpace;
2833 NewTableSpace = OldHeap->rd_rel->reltablespace;
2835 heap_close(OldHeap, NoLock);
2838 * Create the new heap, using a temporary name in the same
2839 * namespace as the existing table. NOTE: there is some risk of
2840 * collision with user relnames. Working around this seems more
2841 * trouble than it's worth; in particular, we can't create the new
2842 * heap in a different namespace from the old, or we will have
2843 * problems with the TEMP status of temp tables.
2845 snprintf(NewHeapName, sizeof(NewHeapName),
2846 "pg_temp_%u", tab->relid);
2848 OIDNewHeap = make_new_heap(tab->relid, NewHeapName, NewTableSpace);
2851 * Copy the heap data into the new table with the desired
2852 * modifications, and test the current data within the table
2853 * against new constraints generated by ALTER TABLE commands.
2855 ATRewriteTable(tab, OIDNewHeap);
2858 * Swap the physical files of the old and new heaps. Since we are
2859 * generating a new heap, we can use RecentXmin for the table's
2860 * new relfrozenxid because we rewrote all the tuples on
2861 * ATRewriteTable, so no older Xid remains on the table.
2863 swap_relation_files(tab->relid, OIDNewHeap, RecentXmin);
2865 CommandCounterIncrement();
2867 /* Destroy new heap with old filenode */
2868 object.classId = RelationRelationId;
2869 object.objectId = OIDNewHeap;
2870 object.objectSubId = 0;
2873 * The new relation is local to our transaction and we know
2874 * nothing depends on it, so DROP_RESTRICT should be OK.
2876 performDeletion(&object, DROP_RESTRICT);
2877 /* performDeletion does CommandCounterIncrement at end */
2880 * Rebuild each index on the relation (but not the toast table,
2881 * which is all-new anyway). We do not need
2882 * CommandCounterIncrement() because reindex_relation does it.
2884 reindex_relation(tab->relid, false);
2889 * Test the current data within the table against new constraints
2890 * generated by ALTER TABLE commands, but don't rebuild data.
2892 if (tab->constraints != NIL || tab->new_notnull)
2893 ATRewriteTable(tab, InvalidOid);
2896 * If we had SET TABLESPACE but no reason to reconstruct tuples,
2897 * just do a block-by-block copy.
2899 if (tab->newTableSpace)
2900 ATExecSetTableSpace(tab->relid, tab->newTableSpace);
2905 * Foreign key constraints are checked in a final pass, since (a) it's
2906 * generally best to examine each one separately, and (b) it's at least
2907 * theoretically possible that we have changed both relations of the
2908 * foreign key, and we'd better have finished both rewrites before we try
2909 * to read the tables.
2911 foreach(ltab, *wqueue)
2913 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2914 Relation rel = NULL;
2917 foreach(lcon, tab->constraints)
2919 NewConstraint *con = lfirst(lcon);
2921 if (con->contype == CONSTR_FOREIGN)
2923 Constraint *fkconstraint = (Constraint *) con->qual;
2928 /* Long since locked, no need for another */
2929 rel = heap_open(tab->relid, NoLock);
2932 refrel = heap_open(con->refrelid, RowShareLock);
2934 validateForeignKeyConstraint(fkconstraint, rel, refrel,
2938 heap_close(refrel, NoLock);
2943 heap_close(rel, NoLock);
2948 * ATRewriteTable: scan or rewrite one table
2950 * OIDNewHeap is InvalidOid if we don't need to rewrite
2953 ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap)
2957 TupleDesc oldTupDesc;
2958 TupleDesc newTupDesc;
2959 bool needscan = false;
2960 List *notnull_attrs;
2966 * Open the relation(s). We have surely already locked the existing
2969 oldrel = heap_open(tab->relid, NoLock);
2970 oldTupDesc = tab->oldDesc;
2971 newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
2973 if (OidIsValid(OIDNewHeap))
2974 newrel = heap_open(OIDNewHeap, AccessExclusiveLock);
2979 * If we need to rewrite the table, the operation has to be propagated to
2980 * tables that use this table's rowtype as a column type.
2982 * (Eventually this will probably become true for scans as well, but at
2983 * the moment a composite type does not enforce any constraints, so it's
2984 * not necessary/appropriate to enforce them just during ALTER.)
2987 find_composite_type_dependencies(oldrel->rd_rel->reltype,
2988 RelationGetRelationName(oldrel),
2992 * Generate the constraint and default execution states
2995 estate = CreateExecutorState();
2997 /* Build the needed expression execution states */
2998 foreach(l, tab->constraints)
3000 NewConstraint *con = lfirst(l);
3002 switch (con->contype)
3006 con->qualstate = (List *)
3007 ExecPrepareExpr((Expr *) con->qual, estate);
3009 case CONSTR_FOREIGN:
3010 /* Nothing to do here */
3013 elog(ERROR, "unrecognized constraint type: %d",
3014 (int) con->contype);
3018 foreach(l, tab->newvals)
3020 NewColumnValue *ex = lfirst(l);
3022 ex->exprstate = ExecPrepareExpr((Expr *) ex->expr, estate);
3025 notnull_attrs = NIL;
3026 if (newrel || tab->new_notnull)
3029 * If we are rebuilding the tuples OR if we added any new NOT NULL
3030 * constraints, check all not-null constraints. This is a bit of
3031 * overkill but it minimizes risk of bugs, and heap_attisnull is a
3032 * pretty cheap test anyway.
3034 for (i = 0; i < newTupDesc->natts; i++)
3036 if (newTupDesc->attrs[i]->attnotnull &&
3037 !newTupDesc->attrs[i]->attisdropped)
3038 notnull_attrs = lappend_int(notnull_attrs, i);
3044 if (newrel || needscan)
3046 ExprContext *econtext;
3049 TupleTableSlot *oldslot;
3050 TupleTableSlot *newslot;
3053 MemoryContext oldCxt;
3054 List *dropped_attrs = NIL;
3057 econtext = GetPerTupleExprContext(estate);
3060 * Make tuple slots for old and new tuples. Note that even when the
3061 * tuples are the same, the tupDescs might not be (consider ADD COLUMN
3062 * without a default).
3064 oldslot = MakeSingleTupleTableSlot(oldTupDesc);
3065 newslot = MakeSingleTupleTableSlot(newTupDesc);
3067 /* Preallocate values/isnull arrays */
3068 i = Max(newTupDesc->natts, oldTupDesc->natts);
3069 values = (Datum *) palloc(i * sizeof(Datum));
3070 isnull = (bool *) palloc(i * sizeof(bool));
3071 memset(values, 0, i * sizeof(Datum));
3072 memset(isnull, true, i * sizeof(bool));
3075 * Any attributes that are dropped according to the new tuple
3076 * descriptor can be set to NULL. We precompute the list of dropped
3077 * attributes to avoid needing to do so in the per-tuple loop.
3079 for (i = 0; i < newTupDesc->natts; i++)
3081 if (newTupDesc->attrs[i]->attisdropped)
3082 dropped_attrs = lappend_int(dropped_attrs, i);
3086 * Scan through the rows, generating a new row if needed and then
3087 * checking all the constraints.
3089 scan = heap_beginscan(oldrel, SnapshotNow, 0, NULL);
3092 * Switch to per-tuple memory context and reset it for each tuple
3093 * produced, so we don't leak memory.
3095 oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
3097 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
3101 Oid tupOid = InvalidOid;
3103 /* Extract data from old tuple */
3104 heap_deform_tuple(tuple, oldTupDesc, values, isnull);
3105 if (oldTupDesc->tdhasoid)
3106 tupOid = HeapTupleGetOid(tuple);
3108 /* Set dropped attributes to null in new tuple */
3109 foreach(lc, dropped_attrs)
3110 isnull[lfirst_int(lc)] = true;
3113 * Process supplied expressions to replace selected columns.
3114 * Expression inputs come from the old tuple.
3116 ExecStoreTuple(tuple, oldslot, InvalidBuffer, false);
3117 econtext->ecxt_scantuple = oldslot;
3119 foreach(l, tab->newvals)
3121 NewColumnValue *ex = lfirst(l);
3123 values[ex->attnum - 1] = ExecEvalExpr(ex->exprstate,
3125 &isnull[ex->attnum - 1],
3130 * Form the new tuple. Note that we don't explicitly pfree it,
3131 * since the per-tuple memory context will be reset shortly.
3133 tuple = heap_form_tuple(newTupDesc, values, isnull);
3135 /* Preserve OID, if any */
3136 if (newTupDesc->tdhasoid)
3137 HeapTupleSetOid(tuple, tupOid);
3140 /* Now check any constraints on the possibly-changed tuple */
3141 ExecStoreTuple(tuple, newslot, InvalidBuffer, false);
3142 econtext->ecxt_scantuple = newslot;
3144 foreach(l, notnull_attrs)
3146 int attn = lfirst_int(l);
3148 if (heap_attisnull(tuple, attn + 1))
3150 (errcode(ERRCODE_NOT_NULL_VIOLATION),
3151 errmsg("column \"%s\" contains null values",
3152 NameStr(newTupDesc->attrs[attn]->attname))));
3155 foreach(l, tab->constraints)
3157 NewConstraint *con = lfirst(l);
3159 switch (con->contype)
3162 if (!ExecQual(con->qualstate, econtext, true))
3164 (errcode(ERRCODE_CHECK_VIOLATION),
3165 errmsg("check constraint \"%s\" is violated by some row",
3168 case CONSTR_FOREIGN:
3169 /* Nothing to do here */
3172 elog(ERROR, "unrecognized constraint type: %d",
3173 (int) con->contype);
3177 /* Write the tuple out to the new relation */
3179 simple_heap_insert(newrel, tuple);
3181 ResetExprContext(econtext);
3183 CHECK_FOR_INTERRUPTS();
3186 MemoryContextSwitchTo(oldCxt);
3189 ExecDropSingleTupleTableSlot(oldslot);
3190 ExecDropSingleTupleTableSlot(newslot);
3193 FreeExecutorState(estate);
3195 heap_close(oldrel, NoLock);
3197 heap_close(newrel, NoLock);
3201 * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
3203 static AlteredTableInfo *
3204 ATGetQueueEntry(List **wqueue, Relation rel)
3206 Oid relid = RelationGetRelid(rel);
3207 AlteredTableInfo *tab;
3210 foreach(ltab, *wqueue)
3212 tab = (AlteredTableInfo *) lfirst(ltab);
3213 if (tab->relid == relid)
3218 * Not there, so add it. Note that we make a copy of the relation's
3219 * existing descriptor before anything interesting can happen to it.
3221 tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
3223 tab->relkind = rel->rd_rel->relkind;
3224 tab->oldDesc = CreateTupleDescCopy(RelationGetDescr(rel));
3226 *wqueue = lappend(*wqueue, tab);
3232 * ATSimplePermissions
3234 * - Ensure that it is a relation (or possibly a view)
3235 * - Ensure this user is the owner
3236 * - Ensure that it is not a system table
3239 ATSimplePermissions(Relation rel, bool allowView)
3241 if (rel->rd_rel->relkind != RELKIND_RELATION)
3245 if (rel->rd_rel->relkind != RELKIND_VIEW)
3247 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3248 errmsg("\"%s\" is not a table or view",
3249 RelationGetRelationName(rel))));
3253 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3254 errmsg("\"%s\" is not a table",
3255 RelationGetRelationName(rel))));
3258 /* Permissions checks */
3259 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3260 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3261 RelationGetRelationName(rel));
3263 if (!allowSystemTableMods && IsSystemRelation(rel))
3265 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3266 errmsg("permission denied: \"%s\" is a system catalog",
3267 RelationGetRelationName(rel))));
3271 * ATSimplePermissionsRelationOrIndex
3273 * - Ensure that it is a relation or an index
3274 * - Ensure this user is the owner
3275 * - Ensure that it is not a system table
3278 ATSimplePermissionsRelationOrIndex(Relation rel)
3280 if (rel->rd_rel->relkind != RELKIND_RELATION &&
3281 rel->rd_rel->relkind != RELKIND_INDEX)
3283 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3284 errmsg("\"%s\" is not a table or index",
3285 RelationGetRelationName(rel))));
3287 /* Permissions checks */
3288 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3289 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3290 RelationGetRelationName(rel));
3292 if (!allowSystemTableMods && IsSystemRelation(rel))
3294 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3295 errmsg("permission denied: \"%s\" is a system catalog",
3296 RelationGetRelationName(rel))));
3302 * Simple table recursion sufficient for most ALTER TABLE operations.
3303 * All direct and indirect children are processed in an unspecified order.
3304 * Note that if a child inherits from the original table via multiple
3305 * inheritance paths, it will be visited just once.
3308 ATSimpleRecursion(List **wqueue, Relation rel,
3309 AlterTableCmd *cmd, bool recurse)
3312 * Propagate to children if desired. Non-table relations never have
3313 * children, so no need to search in that case.
3315 if (recurse && rel->rd_rel->relkind == RELKIND_RELATION)
3317 Oid relid = RelationGetRelid(rel);
3321 children = find_all_inheritors(relid, AccessExclusiveLock);
3324 * find_all_inheritors does the recursive search of the inheritance
3325 * hierarchy, so all we have to do is process all of the relids in the
3326 * list that it returns.
3328 foreach(child, children)
3330 Oid childrelid = lfirst_oid(child);
3333 if (childrelid == relid)
3335 /* find_all_inheritors already got lock */
3336 childrel = relation_open(childrelid, NoLock);
3337 CheckTableNotInUse(childrel, "ALTER TABLE");
3338 ATPrepCmd(wqueue, childrel, cmd, false, true);
3339 relation_close(childrel, NoLock);
3345 * ATOneLevelRecursion
3347 * Here, we visit only direct inheritance children. It is expected that
3348 * the command's prep routine will recurse again to find indirect children.
3349 * When using this technique, a multiply-inheriting child will be visited
3353 ATOneLevelRecursion(List **wqueue, Relation rel,
3356 Oid relid = RelationGetRelid(rel);
3360 children = find_inheritance_children(relid, AccessExclusiveLock);
3362 foreach(child, children)
3364 Oid childrelid = lfirst_oid(child);
3367 /* find_inheritance_children already got lock */
3368 childrel = relation_open(childrelid, NoLock);
3369 CheckTableNotInUse(childrel, "ALTER TABLE");
3370 ATPrepCmd(wqueue, childrel, cmd, true, true);
3371 relation_close(childrel, NoLock);
3377 * find_composite_type_dependencies
3379 * Check to see if a composite type is being used as a column in some
3380 * other table (possibly nested several levels deep in composite types!).
3381 * Eventually, we'd like to propagate the check or rewrite operation
3382 * into other such tables, but for now, just error out if we find any.
3384 * Caller should provide either a table name or a type name (not both) to
3385 * report in the error message, if any.
3387 * We assume that functions and views depending on the type are not reasons
3388 * to reject the ALTER. (How safe is this really?)
3391 find_composite_type_dependencies(Oid typeOid,
3392 const char *origTblName,
3393 const char *origTypeName)
3397 SysScanDesc depScan;
3402 * We scan pg_depend to find those things that depend on the rowtype. (We
3403 * assume we can ignore refobjsubid for a rowtype.)
3405 depRel = heap_open(DependRelationId, AccessShareLock);
3407 ScanKeyInit(&key[0],
3408 Anum_pg_depend_refclassid,
3409 BTEqualStrategyNumber, F_OIDEQ,
3410 ObjectIdGetDatum(TypeRelationId));
3411 ScanKeyInit(&key[1],
3412 Anum_pg_depend_refobjid,
3413 BTEqualStrategyNumber, F_OIDEQ,
3414 ObjectIdGetDatum(typeOid));
3416 depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
3417 SnapshotNow, 2, key);
3419 while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
3421 Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
3423 Form_pg_attribute att;
3425 /* Ignore dependees that aren't user columns of relations */
3426 /* (we assume system columns are never of rowtypes) */
3427 if (pg_depend->classid != RelationRelationId ||
3428 pg_depend->objsubid <= 0)
3431 rel = relation_open(pg_depend->objid, AccessShareLock);
3432 att = rel->rd_att->attrs[pg_depend->objsubid - 1];
3434 if (rel->rd_rel->relkind == RELKIND_RELATION)
3438 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3439 errmsg("cannot alter table \"%s\" because column \"%s\".\"%s\" uses its rowtype",
3441 RelationGetRelationName(rel),
3442 NameStr(att->attname))));
3445 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3446 errmsg("cannot alter type \"%s\" because column \"%s\".\"%s\" uses it",
3448 RelationGetRelationName(rel),
3449 NameStr(att->attname))));
3451 else if (OidIsValid(rel->rd_rel->reltype))
3454 * A view or composite type itself isn't a problem, but we must
3455 * recursively check for indirect dependencies via its rowtype.
3457 find_composite_type_dependencies(rel->rd_rel->reltype,
3458 origTblName, origTypeName);
3461 relation_close(rel, AccessShareLock);
3464 systable_endscan(depScan);
3466 relation_close(depRel, AccessShareLock);
3469 * If there's an array type for the rowtype, must check for uses of it,
3472 arrayOid = get_array_type(typeOid);
3473 if (OidIsValid(arrayOid))
3474 find_composite_type_dependencies(arrayOid, origTblName, origTypeName);
3479 * ALTER TABLE ADD COLUMN
3481 * Adds an additional attribute to a relation making the assumption that
3482 * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
3483 * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
3487 ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
3491 * Recurse to add the column to child classes, if requested.
3493 * We must recurse one level at a time, so that multiply-inheriting
3494 * children are visited the right number of times and end up with the
3495 * right attinhcount.
3499 AlterTableCmd *childCmd = copyObject(cmd);
3500 ColumnDef *colDefChild = (ColumnDef *) childCmd->def;
3502 /* Child should see column as singly inherited */
3503 colDefChild->inhcount = 1;
3504 colDefChild->is_local = false;
3506 ATOneLevelRecursion(wqueue, rel, childCmd);
3511 * If we are told not to recurse, there had better not be any child
3512 * tables; else the addition would put them out of step.
3514 if (find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL)
3516 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3517 errmsg("column must be added to child tables too")));
3522 ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
3523 ColumnDef *colDef, bool isOid)
3525 Oid myrelid = RelationGetRelid(rel);
3529 FormData_pg_attribute attribute;
3532 HeapTuple typeTuple;
3538 attrdesc = heap_open(AttributeRelationId, RowExclusiveLock);
3541 * Are we adding the column to a recursion child? If so, check whether to
3542 * merge with an existing definition for the column.
3544 if (colDef->inhcount > 0)
3548 /* Does child already have a column by this name? */
3549 tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
3550 if (HeapTupleIsValid(tuple))
3552 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
3556 /* Child column must match by type */
3557 ctypeId = typenameTypeId(NULL, colDef->typeName, &ctypmod);
3558 if (ctypeId != childatt->atttypid ||
3559 ctypmod != childatt->atttypmod)
3561 (errcode(ERRCODE_DATATYPE_MISMATCH),
3562 errmsg("child table \"%s\" has different type for column \"%s\"",
3563 RelationGetRelationName(rel), colDef->colname)));
3565 /* If it's OID, child column must actually be OID */
3566 if (isOid && childatt->attnum != ObjectIdAttributeNumber)
3568 (errcode(ERRCODE_DATATYPE_MISMATCH),
3569 errmsg("child table \"%s\" has a conflicting \"%s\" column",
3570 RelationGetRelationName(rel), colDef->colname)));
3572 /* Bump the existing child att's inhcount */
3573 childatt->attinhcount++;
3574 simple_heap_update(attrdesc, &tuple->t_self, tuple);
3575 CatalogUpdateIndexes(attrdesc, tuple);
3577 heap_freetuple(tuple);
3579 /* Inform the user about the merge */
3581 (errmsg("merging definition of column \"%s\" for child \"%s\"",
3582 colDef->colname, RelationGetRelationName(rel))));
3584 heap_close(attrdesc, RowExclusiveLock);
3589 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
3591 reltup = SearchSysCacheCopy(RELOID,
3592 ObjectIdGetDatum(myrelid),
3594 if (!HeapTupleIsValid(reltup))
3595 elog(ERROR, "cache lookup failed for relation %u", myrelid);
3596 relkind = ((Form_pg_class) GETSTRUCT(reltup))->relkind;
3599 * this test is deliberately not attisdropped-aware, since if one tries to
3600 * add a column matching a dropped column name, it's gonna fail anyway.
3602 if (SearchSysCacheExists(ATTNAME,
3603 ObjectIdGetDatum(myrelid),
3604 PointerGetDatum(colDef->colname),
3607 (errcode(ERRCODE_DUPLICATE_COLUMN),
3608 errmsg("column \"%s\" of relation \"%s\" already exists",
3609 colDef->colname, RelationGetRelationName(rel))));
3611 /* Determine the new attribute's number */
3613 newattnum = ObjectIdAttributeNumber;
3616 newattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts + 1;
3617 if (newattnum > MaxHeapAttributeNumber)
3619 (errcode(ERRCODE_TOO_MANY_COLUMNS),
3620 errmsg("tables can have at most %d columns",
3621 MaxHeapAttributeNumber)));
3624 typeTuple = typenameType(NULL, colDef->typeName, &typmod);
3625 tform = (Form_pg_type) GETSTRUCT(typeTuple);
3626 typeOid = HeapTupleGetOid(typeTuple);
3628 /* make sure datatype is legal for a column */
3629 CheckAttributeType(colDef->colname, typeOid);
3631 /* construct new attribute's pg_attribute entry */
3632 attribute.attrelid = myrelid;
3633 namestrcpy(&(attribute.attname), colDef->colname);
3634 attribute.atttypid = typeOid;
3635 attribute.attstattarget = (newattnum > 0) ? -1 : 0;
3636 attribute.attdistinct = 0;
3637 attribute.attlen = tform->typlen;
3638 attribute.attcacheoff = -1;
3639 attribute.atttypmod = typmod;
3640 attribute.attnum = newattnum;
3641 attribute.attbyval = tform->typbyval;
3642 attribute.attndims = list_length(colDef->typeName->arrayBounds);
3643 attribute.attstorage = tform->typstorage;
3644 attribute.attalign = tform->typalign;
3645 attribute.attnotnull = colDef->is_not_null;
3646 attribute.atthasdef = false;
3647 attribute.attisdropped = false;
3648 attribute.attislocal = colDef->is_local;
3649 attribute.attinhcount = colDef->inhcount;
3650 /* attribute.attacl is handled by InsertPgAttributeTuple */
3652 ReleaseSysCache(typeTuple);
3654 InsertPgAttributeTuple(attrdesc, &attribute, NULL);
3656 heap_close(attrdesc, RowExclusiveLock);
3659 * Update pg_class tuple as appropriate
3662 ((Form_pg_class) GETSTRUCT(reltup))->relhasoids = true;
3664 ((Form_pg_class) GETSTRUCT(reltup))->relnatts = newattnum;
3666 simple_heap_update(pgclass, &reltup->t_self, reltup);
3668 /* keep catalog indexes current */
3669 CatalogUpdateIndexes(pgclass, reltup);
3671 heap_freetuple(reltup);
3673 heap_close(pgclass, RowExclusiveLock);
3675 /* Make the attribute's catalog entry visible */
3676 CommandCounterIncrement();
3679 * Store the DEFAULT, if any, in the catalogs
3681 if (colDef->raw_default)
3683 RawColumnDefault *rawEnt;
3685 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3686 rawEnt->attnum = attribute.attnum;
3687 rawEnt->raw_default = copyObject(colDef->raw_default);
3690 * This function is intended for CREATE TABLE, so it processes a
3691 * _list_ of defaults, but we just do one.
3693 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL, false, true);
3695 /* Make the additional catalog changes visible */
3696 CommandCounterIncrement();
3700 * Tell Phase 3 to fill in the default expression, if there is one.
3702 * If there is no default, Phase 3 doesn't have to do anything, because
3703 * that effectively means that the default is NULL. The heap tuple access
3704 * routines always check for attnum > # of attributes in tuple, and return
3705 * NULL if so, so without any modification of the tuple data we will get
3706 * the effect of NULL values in the new column.
3708 * An exception occurs when the new column is of a domain type: the domain
3709 * might have a NOT NULL constraint, or a check constraint that indirectly
3710 * rejects nulls. If there are any domain constraints then we construct
3711 * an explicit NULL default value that will be passed through
3712 * CoerceToDomain processing. (This is a tad inefficient, since it causes
3713 * rewriting the table which we really don't have to do, but the present
3714 * design of domain processing doesn't offer any simple way of checking
3715 * the constraints more directly.)
3717 * Note: we use build_column_default, and not just the cooked default
3718 * returned by AddRelationNewConstraints, so that the right thing happens
3719 * when a datatype's default applies.
3721 * We skip this step completely for views. For a view, we can only get
3722 * here from CREATE OR REPLACE VIEW, which historically doesn't set up
3723 * defaults, not even for domain-typed columns. And in any case we
3724 * mustn't invoke Phase 3 on a view, since it has no storage.
3726 if (relkind != RELKIND_VIEW && attribute.attnum > 0)
3728 defval = (Expr *) build_column_default(rel, attribute.attnum);
3730 if (!defval && GetDomainConstraints(typeOid) != NIL)
3735 baseTypeMod = typmod;
3736 baseTypeId = getBaseTypeAndTypmod(typeOid, &baseTypeMod);
3737 defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod);
3738 defval = (Expr *) coerce_to_target_type(NULL,
3743 COERCION_ASSIGNMENT,
3744 COERCE_IMPLICIT_CAST,
3746 if (defval == NULL) /* should not happen */
3747 elog(ERROR, "failed to coerce base type to domain");
3752 NewColumnValue *newval;
3754 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
3755 newval->attnum = attribute.attnum;
3756 newval->expr = defval;
3758 tab->newvals = lappend(tab->newvals, newval);
3762 * If the new column is NOT NULL, tell Phase 3 it needs to test that.
3763 * (Note we don't do this for an OID column. OID will be marked not
3764 * null, but since it's filled specially, there's no need to test
3767 tab->new_notnull |= colDef->is_not_null;
3771 * If we are adding an OID column, we have to tell Phase 3 to rewrite the
3772 * table to fix that.
3775 tab->new_changeoids = true;
3778 * Add needed dependency entries for the new column.
3780 add_column_datatype_dependency(myrelid, newattnum, attribute.atttypid);
3784 * Install a column's dependency on its datatype.
3787 add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
3789 ObjectAddress myself,
3792 myself.classId = RelationRelationId;
3793 myself.objectId = relid;
3794 myself.objectSubId = attnum;
3795 referenced.classId = TypeRelationId;
3796 referenced.objectId = typid;
3797 referenced.objectSubId = 0;
3798 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
3802 * ALTER TABLE SET WITH OIDS
3804 * Basically this is an ADD COLUMN for the special OID column. We have
3805 * to cons up a ColumnDef node because the ADD COLUMN code needs one.
3808 ATPrepAddOids(List **wqueue, Relation rel, bool recurse, AlterTableCmd *cmd)
3810 /* If we're recursing to a child table, the ColumnDef is already set up */
3811 if (cmd->def == NULL)
3813 ColumnDef *cdef = makeNode(ColumnDef);
3815 cdef->colname = pstrdup("oid");
3816 cdef->typeName = makeTypeNameFromOid(OIDOID, -1);
3818 cdef->is_local = true;
3819 cdef->is_not_null = true;
3820 cmd->def = (Node *) cdef;
3822 ATPrepAddColumn(wqueue, rel, recurse, cmd);
3826 * ALTER TABLE ALTER COLUMN DROP NOT NULL
3829 ATExecDropNotNull(Relation rel, const char *colName)
3835 ListCell *indexoidscan;
3838 * lookup the attribute
3840 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3842 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3844 if (!HeapTupleIsValid(tuple))
3846 (errcode(ERRCODE_UNDEFINED_COLUMN),
3847 errmsg("column \"%s\" of relation \"%s\" does not exist",
3848 colName, RelationGetRelationName(rel))));
3850 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3852 /* Prevent them from altering a system attribute */
3855 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3856 errmsg("cannot alter system column \"%s\"",
3860 * Check that the attribute is not in a primary key
3863 /* Loop over all indexes on the relation */
3864 indexoidlist = RelationGetIndexList(rel);
3866 foreach(indexoidscan, indexoidlist)
3868 Oid indexoid = lfirst_oid(indexoidscan);
3869 HeapTuple indexTuple;
3870 Form_pg_index indexStruct;
3873 indexTuple = SearchSysCache(INDEXRELID,
3874 ObjectIdGetDatum(indexoid),
3876 if (!HeapTupleIsValid(indexTuple))
3877 elog(ERROR, "cache lookup failed for index %u", indexoid);
3878 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
3880 /* If the index is not a primary key, skip the check */
3881 if (indexStruct->indisprimary)
3884 * Loop over each attribute in the primary key and see if it
3885 * matches the to-be-altered attribute
3887 for (i = 0; i < indexStruct->indnatts; i++)
3889 if (indexStruct->indkey.values[i] == attnum)
3891 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3892 errmsg("column \"%s\" is in a primary key",
3897 ReleaseSysCache(indexTuple);
3900 list_free(indexoidlist);
3903 * Okay, actually perform the catalog change ... if needed
3905 if (((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3907 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = FALSE;
3909 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3911 /* keep the system catalog indexes current */
3912 CatalogUpdateIndexes(attr_rel, tuple);
3915 heap_close(attr_rel, RowExclusiveLock);
3919 * ALTER TABLE ALTER COLUMN SET NOT NULL
3922 ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
3923 const char *colName)
3930 * lookup the attribute
3932 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3934 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3936 if (!HeapTupleIsValid(tuple))
3938 (errcode(ERRCODE_UNDEFINED_COLUMN),
3939 errmsg("column \"%s\" of relation \"%s\" does not exist",
3940 colName, RelationGetRelationName(rel))));
3942 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3944 /* Prevent them from altering a system attribute */
3947 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3948 errmsg("cannot alter system column \"%s\"",
3952 * Okay, actually perform the catalog change ... if needed
3954 if (!((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3956 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = TRUE;
3958 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3960 /* keep the system catalog indexes current */
3961 CatalogUpdateIndexes(attr_rel, tuple);
3963 /* Tell Phase 3 it needs to test the constraint */
3964 tab->new_notnull = true;
3967 heap_close(attr_rel, RowExclusiveLock);
3971 * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
3974 ATExecColumnDefault(Relation rel, const char *colName,
3980 * get the number of the attribute
3982 attnum = get_attnum(RelationGetRelid(rel), colName);
3983 if (attnum == InvalidAttrNumber)
3985 (errcode(ERRCODE_UNDEFINED_COLUMN),
3986 errmsg("column \"%s\" of relation \"%s\" does not exist",
3987 colName, RelationGetRelationName(rel))));
3989 /* Prevent them from altering a system attribute */
3992 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3993 errmsg("cannot alter system column \"%s\"",
3997 * Remove any old default for the column. We use RESTRICT here for
3998 * safety, but at present we do not expect anything to depend on the
4001 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false);
4006 RawColumnDefault *rawEnt;
4008 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
4009 rawEnt->attnum = attnum;
4010 rawEnt->raw_default = newDefault;
4013 * This function is intended for CREATE TABLE, so it processes a
4014 * _list_ of defaults, but we just do one.
4016 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL, false, true);
4021 * ALTER TABLE ALTER COLUMN SET STATISTICS
4024 ATPrepSetStatistics(Relation rel, const char *colName, Node *newValue)
4027 * We do our own permission checking because (a) we want to allow SET
4028 * STATISTICS on indexes (for expressional index columns), and (b) we want
4029 * to allow SET STATISTICS on system catalogs without requiring
4030 * allowSystemTableMods to be turned on.
4032 if (rel->rd_rel->relkind != RELKIND_RELATION &&
4033 rel->rd_rel->relkind != RELKIND_INDEX)
4035 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4036 errmsg("\"%s\" is not a table or index",
4037 RelationGetRelationName(rel))));
4039 /* Permissions checks */
4040 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
4041 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
4042 RelationGetRelationName(rel));
4046 ATExecSetStatistics(Relation rel, const char *colName, Node *newValue)
4049 Relation attrelation;
4051 Form_pg_attribute attrtuple;
4053 Assert(IsA(newValue, Integer));
4054 newtarget = intVal(newValue);
4057 * Limit target to a sane range
4062 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4063 errmsg("statistics target %d is too low",
4066 else if (newtarget > 10000)
4070 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4071 errmsg("lowering statistics target to %d",
4075 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
4077 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4079 if (!HeapTupleIsValid(tuple))
4081 (errcode(ERRCODE_UNDEFINED_COLUMN),
4082 errmsg("column \"%s\" of relation \"%s\" does not exist",
4083 colName, RelationGetRelationName(rel))));
4084 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
4086 if (attrtuple->attnum <= 0)
4088 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4089 errmsg("cannot alter system column \"%s\"",
4092 attrtuple->attstattarget = newtarget;
4094 simple_heap_update(attrelation, &tuple->t_self, tuple);
4096 /* keep system catalog indexes current */
4097 CatalogUpdateIndexes(attrelation, tuple);
4099 heap_freetuple(tuple);
4101 heap_close(attrelation, RowExclusiveLock);
4105 * ALTER TABLE ALTER COLUMN SET STATISTICS DISTINCT
4108 ATPrepSetDistinct(Relation rel, const char *colName, Node *newValue)
4111 * We do our own permission checking because (a) we want to allow SET
4112 * DISTINCT on indexes (for expressional index columns), and (b) we want
4113 * to allow SET DISTINCT on system catalogs without requiring
4114 * allowSystemTableMods to be turned on.
4116 if (rel->rd_rel->relkind != RELKIND_RELATION &&
4117 rel->rd_rel->relkind != RELKIND_INDEX)
4119 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4120 errmsg("\"%s\" is not a table or index",
4121 RelationGetRelationName(rel))));
4123 /* Permissions checks */
4124 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
4125 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
4126 RelationGetRelationName(rel));
4130 ATExecSetDistinct(Relation rel, const char *colName, Node *newValue)
4133 Relation attrelation;
4135 Form_pg_attribute attrtuple;
4137 switch (nodeTag(newValue))
4140 newdistinct = intVal(newValue);
4143 newdistinct = floatVal(newValue);
4146 elog(ERROR, "unrecognized node type: %d",
4147 (int) nodeTag(newValue));
4148 newdistinct = 0; /* keep compiler quiet */
4153 * Limit ndistinct to sane values
4155 if (newdistinct < -1.0)
4158 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4159 errmsg("number of distinct values %g is too low",
4163 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
4165 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4167 if (!HeapTupleIsValid(tuple))
4169 (errcode(ERRCODE_UNDEFINED_COLUMN),
4170 errmsg("column \"%s\" of relation \"%s\" does not exist",
4171 colName, RelationGetRelationName(rel))));
4172 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
4174 if (attrtuple->attnum <= 0)
4176 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4177 errmsg("cannot alter system column \"%s\"",
4180 attrtuple->attdistinct = newdistinct;
4182 simple_heap_update(attrelation, &tuple->t_self, tuple);
4184 /* keep system catalog indexes current */
4185 CatalogUpdateIndexes(attrelation, tuple);
4187 heap_freetuple(tuple);
4189 heap_close(attrelation, RowExclusiveLock);
4193 * ALTER TABLE ALTER COLUMN SET STORAGE
4196 ATExecSetStorage(Relation rel, const char *colName, Node *newValue)
4200 Relation attrelation;
4202 Form_pg_attribute attrtuple;
4204 Assert(IsA(newValue, String));
4205 storagemode = strVal(newValue);
4207 if (pg_strcasecmp(storagemode, "plain") == 0)
4209 else if (pg_strcasecmp(storagemode, "external") == 0)
4211 else if (pg_strcasecmp(storagemode, "extended") == 0)
4213 else if (pg_strcasecmp(storagemode, "main") == 0)
4218 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4219 errmsg("invalid storage type \"%s\"",
4221 newstorage = 0; /* keep compiler quiet */
4224 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
4226 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4228 if (!HeapTupleIsValid(tuple))
4230 (errcode(ERRCODE_UNDEFINED_COLUMN),
4231 errmsg("column \"%s\" of relation \"%s\" does not exist",
4232 colName, RelationGetRelationName(rel))));
4233 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
4235 if (attrtuple->attnum <= 0)
4237 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4238 errmsg("cannot alter system column \"%s\"",
4242 * safety check: do not allow toasted storage modes unless column datatype
4245 if (newstorage == 'p' || TypeIsToastable(attrtuple->atttypid))
4246 attrtuple->attstorage = newstorage;
4249 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4250 errmsg("column data type %s can only have storage PLAIN",
4251 format_type_be(attrtuple->atttypid))));
4253 simple_heap_update(attrelation, &tuple->t_self, tuple);
4255 /* keep system catalog indexes current */
4256 CatalogUpdateIndexes(attrelation, tuple);
4258 heap_freetuple(tuple);
4260 heap_close(attrelation, RowExclusiveLock);
4265 * ALTER TABLE DROP COLUMN
4267 * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
4268 * because we have to decide at runtime whether to recurse or not depending
4269 * on whether attinhcount goes to zero or not. (We can't check this in a
4270 * static pre-pass because it won't handle multiple inheritance situations
4274 ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
4275 DropBehavior behavior,
4276 bool recurse, bool recursing,
4280 Form_pg_attribute targetatt;
4283 ObjectAddress object;
4285 /* At top level, permission check was done in ATPrepCmd, else do it */
4287 ATSimplePermissions(rel, false);
4290 * get the number of the attribute
4292 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
4293 if (!HeapTupleIsValid(tuple)){
4296 (errcode(ERRCODE_UNDEFINED_COLUMN),
4297 errmsg("column \"%s\" of relation \"%s\" does not exist",
4298 colName, RelationGetRelationName(rel))));
4303 (errmsg("column \"%s\" of relation \"%s\" does not exist, skipping",
4304 colName, RelationGetRelationName(rel))));
4308 targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
4310 attnum = targetatt->attnum;
4312 /* Can't drop a system attribute, except OID */
4313 if (attnum <= 0 && attnum != ObjectIdAttributeNumber)
4315 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4316 errmsg("cannot drop system column \"%s\"",
4319 /* Don't drop inherited columns */
4320 if (targetatt->attinhcount > 0 && !recursing)
4322 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4323 errmsg("cannot drop inherited column \"%s\"",
4326 ReleaseSysCache(tuple);
4329 * Propagate to children as appropriate. Unlike most other ALTER
4330 * routines, we have to do this one level of recursion at a time; we can't
4331 * use find_all_inheritors to do it in one pass.
4333 children = find_inheritance_children(RelationGetRelid(rel),
4334 AccessExclusiveLock);
4341 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
4342 foreach(child, children)
4344 Oid childrelid = lfirst_oid(child);
4346 Form_pg_attribute childatt;
4348 /* find_inheritance_children already got lock */
4349 childrel = heap_open(childrelid, NoLock);
4350 CheckTableNotInUse(childrel, "ALTER TABLE");
4352 tuple = SearchSysCacheCopyAttName(childrelid, colName);
4353 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
4354 elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
4355 colName, childrelid);
4356 childatt = (Form_pg_attribute) GETSTRUCT(tuple);
4358 if (childatt->attinhcount <= 0) /* shouldn't happen */
4359 elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
4360 childrelid, colName);
4365 * If the child column has other definition sources, just
4366 * decrement its inheritance count; if not, recurse to delete
4369 if (childatt->attinhcount == 1 && !childatt->attislocal)
4371 /* Time to delete this child column, too */
4372 ATExecDropColumn(wqueue, childrel, colName,
4373 behavior, true, true,
4378 /* Child column must survive my deletion */
4379 childatt->attinhcount--;
4381 simple_heap_update(attr_rel, &tuple->t_self, tuple);
4383 /* keep the system catalog indexes current */
4384 CatalogUpdateIndexes(attr_rel, tuple);
4386 /* Make update visible */
4387 CommandCounterIncrement();
4393 * If we were told to drop ONLY in this table (no recursion),
4394 * we need to mark the inheritors' attributes as locally
4395 * defined rather than inherited.
4397 childatt->attinhcount--;
4398 childatt->attislocal = true;
4400 simple_heap_update(attr_rel, &tuple->t_self, tuple);
4402 /* keep the system catalog indexes current */
4403 CatalogUpdateIndexes(attr_rel, tuple);
4405 /* Make update visible */
4406 CommandCounterIncrement();
4409 heap_freetuple(tuple);
4411 heap_close(childrel, NoLock);
4413 heap_close(attr_rel, RowExclusiveLock);
4417 * Perform the actual column deletion
4419 object.classId = RelationRelationId;
4420 object.objectId = RelationGetRelid(rel);
4421 object.objectSubId = attnum;
4423 performDeletion(&object, behavior);
4426 * If we dropped the OID column, must adjust pg_class.relhasoids and tell
4427 * Phase 3 to physically get rid of the column.
4429 if (attnum == ObjectIdAttributeNumber)
4432 Form_pg_class tuple_class;
4433 AlteredTableInfo *tab;
4435 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
4437 tuple = SearchSysCacheCopy(RELOID,
4438 ObjectIdGetDatum(RelationGetRelid(rel)),
4440 if (!HeapTupleIsValid(tuple))
4441 elog(ERROR, "cache lookup failed for relation %u",
4442 RelationGetRelid(rel));
4443 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
4445 tuple_class->relhasoids = false;
4446 simple_heap_update(class_rel, &tuple->t_self, tuple);
4448 /* Keep the catalog indexes up to date */
4449 CatalogUpdateIndexes(class_rel, tuple);
4451 heap_close(class_rel, RowExclusiveLock);
4453 /* Find or create work queue entry for this table */
4454 tab = ATGetQueueEntry(wqueue, rel);
4456 /* Tell Phase 3 to physically remove the OID column */
4457 tab->new_changeoids = true;
4462 * ALTER TABLE ADD INDEX
4464 * There is no such command in the grammar, but parse_utilcmd.c converts
4465 * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands. This lets
4466 * us schedule creation of the index at the appropriate time during ALTER.
4469 ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
4470 IndexStmt *stmt, bool is_rebuild)
4476 Assert(IsA(stmt, IndexStmt));
4478 /* suppress schema rights check when rebuilding existing index */
4479 check_rights = !is_rebuild;
4480 /* skip index build if phase 3 will have to rewrite table anyway */
4481 skip_build = (tab->newvals != NIL);
4482 /* suppress notices when rebuilding existing index */
4485 /* The IndexStmt has already been through transformIndexStmt */
4487 DefineIndex(stmt->relation, /* relation */
4488 stmt->idxname, /* index name */
4489 InvalidOid, /* no predefined OID */
4490 stmt->accessMethod, /* am name */
4492 stmt->indexParams, /* parameters */
4493 (Expr *) stmt->whereClause,
4500 true, /* is_alter_table */
4508 * ALTER TABLE ADD CONSTRAINT
4511 ATExecAddConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
4512 Constraint *newConstraint, bool recurse)
4514 Assert(IsA(newConstraint, Constraint));
4517 * Currently, we only expect to see CONSTR_CHECK and CONSTR_FOREIGN nodes
4518 * arriving here (see the preprocessing done in parse_utilcmd.c). Use a
4519 * switch anyway to make it easier to add more code later.
4521 switch (newConstraint->contype)
4524 ATAddCheckConstraint(wqueue, tab, rel,
4525 newConstraint, recurse, false);
4528 case CONSTR_FOREIGN:
4530 * Note that we currently never recurse for FK constraints, so
4531 * the "recurse" flag is silently ignored.
4533 * Assign or validate constraint name
4535 if (newConstraint->conname)
4537 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
4538 RelationGetRelid(rel),
4539 RelationGetNamespace(rel),
4540 newConstraint->conname))
4542 (errcode(ERRCODE_DUPLICATE_OBJECT),
4543 errmsg("constraint \"%s\" for relation \"%s\" already exists",
4544 newConstraint->conname,
4545 RelationGetRelationName(rel))));
4548 newConstraint->conname =
4549 ChooseConstraintName(RelationGetRelationName(rel),
4550 strVal(linitial(newConstraint->fk_attrs)),
4552 RelationGetNamespace(rel),
4555 ATAddForeignKeyConstraint(tab, rel, newConstraint);
4559 elog(ERROR, "unrecognized constraint type: %d",
4560 (int) newConstraint->contype);
4565 * Add a check constraint to a single table and its children
4567 * Subroutine for ATExecAddConstraint.
4569 * We must recurse to child tables during execution, rather than using
4570 * ALTER TABLE's normal prep-time recursion. The reason is that all the
4571 * constraints *must* be given the same name, else they won't be seen as
4572 * related later. If the user didn't explicitly specify a name, then
4573 * AddRelationNewConstraints would normally assign different names to the
4574 * child constraints. To fix that, we must capture the name assigned at
4575 * the parent table and pass that down.
4578 ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
4579 Constraint *constr, bool recurse, bool recursing)
4586 /* At top level, permission check was done in ATPrepCmd, else do it */
4588 ATSimplePermissions(rel, false);
4591 * Call AddRelationNewConstraints to do the work, making sure it works on
4592 * a copy of the Constraint so transformExpr can't modify the original. It
4593 * returns a list of cooked constraints.
4595 * If the constraint ends up getting merged with a pre-existing one, it's
4596 * omitted from the returned list, which is what we want: we do not need
4597 * to do any validation work. That can only happen at child tables,
4598 * though, since we disallow merging at the top level.
4600 newcons = AddRelationNewConstraints(rel, NIL,
4601 list_make1(copyObject(constr)),
4602 recursing, !recursing);
4604 /* Add each constraint to Phase 3's queue */
4605 foreach(lcon, newcons)
4607 CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
4608 NewConstraint *newcon;
4610 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
4611 newcon->name = ccon->name;
4612 newcon->contype = ccon->contype;
4613 /* ExecQual wants implicit-AND format */
4614 newcon->qual = (Node *) make_ands_implicit((Expr *) ccon->expr);
4616 tab->constraints = lappend(tab->constraints, newcon);
4618 /* Save the actually assigned name if it was defaulted */
4619 if (constr->conname == NULL)
4620 constr->conname = ccon->name;
4623 /* At this point we must have a locked-down name to use */
4624 Assert(constr->conname != NULL);
4626 /* Advance command counter in case same table is visited multiple times */
4627 CommandCounterIncrement();
4630 * Propagate to children as appropriate. Unlike most other ALTER
4631 * routines, we have to do this one level of recursion at a time; we can't
4632 * use find_all_inheritors to do it in one pass.
4634 children = find_inheritance_children(RelationGetRelid(rel),
4635 AccessExclusiveLock);
4638 * If we are told not to recurse, there had better not be any child
4639 * tables; else the addition would put them out of step.
4641 if (children && !recurse)
4643 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4644 errmsg("constraint must be added to child tables too")));
4646 foreach(child, children)
4648 Oid childrelid = lfirst_oid(child);
4650 AlteredTableInfo *childtab;
4652 /* find_inheritance_children already got lock */
4653 childrel = heap_open(childrelid, NoLock);
4654 CheckTableNotInUse(childrel, "ALTER TABLE");
4656 /* Find or create work queue entry for this table */
4657 childtab = ATGetQueueEntry(wqueue, childrel);
4659 /* Recurse to child */
4660 ATAddCheckConstraint(wqueue, childtab, childrel,
4661 constr, recurse, true);
4663 heap_close(childrel, NoLock);
4668 * Add a foreign-key constraint to a single table
4670 * Subroutine for ATExecAddConstraint. Must already hold exclusive
4671 * lock on the rel, and have done appropriate validity checks for it.
4672 * We do permissions checks here, however.
4675 ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
4676 Constraint *fkconstraint)
4679 int16 pkattnum[INDEX_MAX_KEYS];
4680 int16 fkattnum[INDEX_MAX_KEYS];
4681 Oid pktypoid[INDEX_MAX_KEYS];
4682 Oid fktypoid[INDEX_MAX_KEYS];
4683 Oid opclasses[INDEX_MAX_KEYS];
4684 Oid pfeqoperators[INDEX_MAX_KEYS];
4685 Oid ppeqoperators[INDEX_MAX_KEYS];
4686 Oid ffeqoperators[INDEX_MAX_KEYS];
4694 * Grab an exclusive lock on the pk table, so that someone doesn't delete
4695 * rows out from under us. (Although a lesser lock would do for that
4696 * purpose, we'll need exclusive lock anyway to add triggers to the pk
4697 * table; trying to start with a lesser lock will just create a risk of
4700 pkrel = heap_openrv(fkconstraint->pktable, AccessExclusiveLock);
4703 * Validity checks (permission checks wait till we have the column
4706 if (pkrel->rd_rel->relkind != RELKIND_RELATION)
4708 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4709 errmsg("referenced relation \"%s\" is not a table",
4710 RelationGetRelationName(pkrel))));
4712 if (!allowSystemTableMods && IsSystemRelation(pkrel))
4714 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4715 errmsg("permission denied: \"%s\" is a system catalog",
4716 RelationGetRelationName(pkrel))));
4719 * Disallow reference from permanent table to temp table or vice versa.
4720 * (The ban on perm->temp is for fairly obvious reasons. The ban on
4721 * temp->perm is because other backends might need to run the RI triggers
4722 * on the perm table, but they can't reliably see tuples the owning
4723 * backend has created in the temp table, because non-shared buffers are
4724 * used for temp tables.)
4726 if (pkrel->rd_istemp)
4728 if (!rel->rd_istemp)
4730 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4731 errmsg("cannot reference temporary table from permanent table constraint")));
4737 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4738 errmsg("cannot reference permanent table from temporary table constraint")));
4742 * Look up the referencing attributes to make sure they exist, and record
4743 * their attnums and type OIDs.
4745 MemSet(pkattnum, 0, sizeof(pkattnum));
4746 MemSet(fkattnum, 0, sizeof(fkattnum));
4747 MemSet(pktypoid, 0, sizeof(pktypoid));
4748 MemSet(fktypoid, 0, sizeof(fktypoid));
4749 MemSet(opclasses, 0, sizeof(opclasses));
4750 MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
4751 MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
4752 MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
4754 numfks = transformColumnNameList(RelationGetRelid(rel),
4755 fkconstraint->fk_attrs,
4756 fkattnum, fktypoid);
4759 * If the attribute list for the referenced table was omitted, lookup the
4760 * definition of the primary key and use it. Otherwise, validate the
4761 * supplied attribute list. In either case, discover the index OID and
4762 * index opclasses, and the attnums and type OIDs of the attributes.
4764 if (fkconstraint->pk_attrs == NIL)
4766 numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
4767 &fkconstraint->pk_attrs,
4773 numpks = transformColumnNameList(RelationGetRelid(pkrel),
4774 fkconstraint->pk_attrs,
4775 pkattnum, pktypoid);
4776 /* Look for an index matching the column list */
4777 indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
4782 * Now we can check permissions.
4784 checkFkeyPermissions(pkrel, pkattnum, numpks);
4785 checkFkeyPermissions(rel, fkattnum, numfks);
4788 * Look up the equality operators to use in the constraint.
4790 * Note that we have to be careful about the difference between the actual
4791 * PK column type and the opclass' declared input type, which might be
4792 * only binary-compatible with it. The declared opcintype is the right
4793 * thing to probe pg_amop with.
4795 if (numfks != numpks)
4797 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4798 errmsg("number of referencing and referenced columns for foreign key disagree")));
4800 for (i = 0; i < numpks; i++)
4802 Oid pktype = pktypoid[i];
4803 Oid fktype = fktypoid[i];
4806 Form_pg_opclass cla_tup;
4815 /* We need several fields out of the pg_opclass entry */
4816 cla_ht = SearchSysCache(CLAOID,
4817 ObjectIdGetDatum(opclasses[i]),
4819 if (!HeapTupleIsValid(cla_ht))
4820 elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
4821 cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
4822 amid = cla_tup->opcmethod;
4823 opfamily = cla_tup->opcfamily;
4824 opcintype = cla_tup->opcintype;
4825 ReleaseSysCache(cla_ht);
4828 * Check it's a btree; currently this can never fail since no other
4829 * index AMs support unique indexes. If we ever did have other types
4830 * of unique indexes, we'd need a way to determine which operator
4831 * strategy number is equality. (Is it reasonable to insist that
4832 * every such index AM use btree's number for equality?)
4834 if (amid != BTREE_AM_OID)
4835 elog(ERROR, "only b-tree indexes are supported for foreign keys");
4836 eqstrategy = BTEqualStrategyNumber;
4839 * There had better be a primary equality operator for the index.
4840 * We'll use it for PK = PK comparisons.
4842 ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
4845 if (!OidIsValid(ppeqop))
4846 elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
4847 eqstrategy, opcintype, opcintype, opfamily);
4850 * Are there equality operators that take exactly the FK type? Assume
4851 * we should look through any domain here.
4853 fktyped = getBaseType(fktype);
4855 pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
4857 if (OidIsValid(pfeqop))
4858 ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
4861 ffeqop = InvalidOid; /* keep compiler quiet */
4863 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4866 * Otherwise, look for an implicit cast from the FK type to the
4867 * opcintype, and if found, use the primary equality operator.
4868 * This is a bit tricky because opcintype might be a polymorphic
4869 * type such as ANYARRAY or ANYENUM; so what we have to test is
4870 * whether the two actual column types can be concurrently cast to
4871 * that type. (Otherwise, we'd fail to reject combinations such
4872 * as int[] and point[].)
4874 Oid input_typeids[2];
4875 Oid target_typeids[2];
4877 input_typeids[0] = pktype;
4878 input_typeids[1] = fktype;
4879 target_typeids[0] = opcintype;
4880 target_typeids[1] = opcintype;
4881 if (can_coerce_type(2, input_typeids, target_typeids,
4883 pfeqop = ffeqop = ppeqop;
4886 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4888 (errcode(ERRCODE_DATATYPE_MISMATCH),
4889 errmsg("foreign key constraint \"%s\" "
4890 "cannot be implemented",
4891 fkconstraint->conname),
4892 errdetail("Key columns \"%s\" and \"%s\" "
4893 "are of incompatible types: %s and %s.",
4894 strVal(list_nth(fkconstraint->fk_attrs, i)),
4895 strVal(list_nth(fkconstraint->pk_attrs, i)),
4896 format_type_be(fktype),
4897 format_type_be(pktype))));
4899 pfeqoperators[i] = pfeqop;
4900 ppeqoperators[i] = ppeqop;
4901 ffeqoperators[i] = ffeqop;
4905 * Record the FK constraint in pg_constraint.
4907 constrOid = CreateConstraintEntry(fkconstraint->conname,
4908 RelationGetNamespace(rel),
4910 fkconstraint->deferrable,
4911 fkconstraint->initdeferred,
4912 RelationGetRelid(rel),
4915 InvalidOid, /* not a domain
4918 RelationGetRelid(pkrel),
4924 fkconstraint->fk_upd_action,
4925 fkconstraint->fk_del_action,
4926 fkconstraint->fk_matchtype,
4927 NULL, /* no check constraint */
4934 * Create the triggers that will enforce the constraint.
4936 createForeignKeyTriggers(rel, fkconstraint, constrOid, indexOid);
4939 * Tell Phase 3 to check that the constraint is satisfied by existing rows
4940 * (we can skip this during table creation).
4942 if (!fkconstraint->skip_validation)
4944 NewConstraint *newcon;
4946 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
4947 newcon->name = fkconstraint->conname;
4948 newcon->contype = CONSTR_FOREIGN;
4949 newcon->refrelid = RelationGetRelid(pkrel);
4950 newcon->refindid = indexOid;
4951 newcon->conid = constrOid;
4952 newcon->qual = (Node *) fkconstraint;
4954 tab->constraints = lappend(tab->constraints, newcon);
4958 * Close pk table, but keep lock until we've committed.
4960 heap_close(pkrel, NoLock);
4965 * transformColumnNameList - transform list of column names
4967 * Lookup each name and return its attnum and type OID
4970 transformColumnNameList(Oid relId, List *colList,
4971 int16 *attnums, Oid *atttypids)
4979 char *attname = strVal(lfirst(l));
4982 atttuple = SearchSysCacheAttName(relId, attname);
4983 if (!HeapTupleIsValid(atttuple))
4985 (errcode(ERRCODE_UNDEFINED_COLUMN),
4986 errmsg("column \"%s\" referenced in foreign key constraint does not exist",
4988 if (attnum >= INDEX_MAX_KEYS)
4990 (errcode(ERRCODE_TOO_MANY_COLUMNS),
4991 errmsg("cannot have more than %d keys in a foreign key",
4993 attnums[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->attnum;
4994 atttypids[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->atttypid;
4995 ReleaseSysCache(atttuple);
5003 * transformFkeyGetPrimaryKey -
5005 * Look up the names, attnums, and types of the primary key attributes
5006 * for the pkrel. Also return the index OID and index opclasses of the
5007 * index supporting the primary key.
5009 * All parameters except pkrel are output parameters. Also, the function
5010 * return value is the number of attributes in the primary key.
5012 * Used when the column list in the REFERENCES specification is omitted.
5015 transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
5017 int16 *attnums, Oid *atttypids,
5021 ListCell *indexoidscan;
5022 HeapTuple indexTuple = NULL;
5023 Form_pg_index indexStruct = NULL;
5024 Datum indclassDatum;
5026 oidvector *indclass;
5030 * Get the list of index OIDs for the table from the relcache, and look up
5031 * each one in the pg_index syscache until we find one marked primary key
5032 * (hopefully there isn't more than one such).
5034 *indexOid = InvalidOid;
5036 indexoidlist = RelationGetIndexList(pkrel);
5038 foreach(indexoidscan, indexoidlist)
5040 Oid indexoid = lfirst_oid(indexoidscan);
5042 indexTuple = SearchSysCache(INDEXRELID,
5043 ObjectIdGetDatum(indexoid),
5045 if (!HeapTupleIsValid(indexTuple))
5046 elog(ERROR, "cache lookup failed for index %u", indexoid);
5047 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
5048 if (indexStruct->indisprimary)
5051 * Refuse to use a deferrable primary key. This is per SQL spec,
5052 * and there would be a lot of interesting semantic problems if
5053 * we tried to allow it.
5055 if (!indexStruct->indimmediate)
5057 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5058 errmsg("cannot use a deferrable primary key for referenced table \"%s\"",
5059 RelationGetRelationName(pkrel))));
5061 *indexOid = indexoid;
5064 ReleaseSysCache(indexTuple);
5067 list_free(indexoidlist);
5070 * Check that we found it
5072 if (!OidIsValid(*indexOid))
5074 (errcode(ERRCODE_UNDEFINED_OBJECT),
5075 errmsg("there is no primary key for referenced table \"%s\"",
5076 RelationGetRelationName(pkrel))));
5078 /* Must get indclass the hard way */
5079 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
5080 Anum_pg_index_indclass, &isnull);
5082 indclass = (oidvector *) DatumGetPointer(indclassDatum);
5085 * Now build the list of PK attributes from the indkey definition (we
5086 * assume a primary key cannot have expressional elements)
5089 for (i = 0; i < indexStruct->indnatts; i++)
5091 int pkattno = indexStruct->indkey.values[i];
5093 attnums[i] = pkattno;
5094 atttypids[i] = attnumTypeId(pkrel, pkattno);
5095 opclasses[i] = indclass->values[i];
5096 *attnamelist = lappend(*attnamelist,
5097 makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
5100 ReleaseSysCache(indexTuple);
5106 * transformFkeyCheckAttrs -
5108 * Make sure that the attributes of a referenced table belong to a unique
5109 * (or primary key) constraint. Return the OID of the index supporting
5110 * the constraint, as well as the opclasses associated with the index
5114 transformFkeyCheckAttrs(Relation pkrel,
5115 int numattrs, int16 *attnums,
5116 Oid *opclasses) /* output parameter */
5118 Oid indexoid = InvalidOid;
5120 bool found_deferrable = false;
5122 ListCell *indexoidscan;
5125 * Get the list of index OIDs for the table from the relcache, and look up
5126 * each one in the pg_index syscache, and match unique indexes to the list
5127 * of attnums we are given.
5129 indexoidlist = RelationGetIndexList(pkrel);
5131 foreach(indexoidscan, indexoidlist)
5133 HeapTuple indexTuple;
5134 Form_pg_index indexStruct;
5138 indexoid = lfirst_oid(indexoidscan);
5139 indexTuple = SearchSysCache(INDEXRELID,
5140 ObjectIdGetDatum(indexoid),
5142 if (!HeapTupleIsValid(indexTuple))
5143 elog(ERROR, "cache lookup failed for index %u", indexoid);
5144 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
5147 * Must have the right number of columns; must be unique and not a
5148 * partial index; forget it if there are any expressions, too
5150 if (indexStruct->indnatts == numattrs &&
5151 indexStruct->indisunique &&
5152 heap_attisnull(indexTuple, Anum_pg_index_indpred) &&
5153 heap_attisnull(indexTuple, Anum_pg_index_indexprs))
5155 /* Must get indclass the hard way */
5156 Datum indclassDatum;
5158 oidvector *indclass;
5160 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
5161 Anum_pg_index_indclass, &isnull);
5163 indclass = (oidvector *) DatumGetPointer(indclassDatum);
5166 * The given attnum list may match the index columns in any order.
5167 * Check that each list is a subset of the other.
5169 for (i = 0; i < numattrs; i++)
5172 for (j = 0; j < numattrs; j++)
5174 if (attnums[i] == indexStruct->indkey.values[j])
5185 for (i = 0; i < numattrs; i++)
5188 for (j = 0; j < numattrs; j++)
5190 if (attnums[j] == indexStruct->indkey.values[i])
5192 opclasses[j] = indclass->values[i];
5203 * Refuse to use a deferrable unique/primary key. This is per
5204 * SQL spec, and there would be a lot of interesting semantic
5205 * problems if we tried to allow it.
5207 if (found && !indexStruct->indimmediate)
5210 * Remember that we found an otherwise matching index, so
5211 * that we can generate a more appropriate error message.
5213 found_deferrable = true;
5217 ReleaseSysCache(indexTuple);
5224 if (found_deferrable)
5226 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5227 errmsg("cannot use a deferrable unique constraint for referenced table \"%s\"",
5228 RelationGetRelationName(pkrel))));
5231 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
5232 errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
5233 RelationGetRelationName(pkrel))));
5236 list_free(indexoidlist);
5241 /* Permissions checks for ADD FOREIGN KEY */
5243 checkFkeyPermissions(Relation rel, int16 *attnums, int natts)
5245 Oid roleid = GetUserId();
5246 AclResult aclresult;
5249 /* Okay if we have relation-level REFERENCES permission */
5250 aclresult = pg_class_aclcheck(RelationGetRelid(rel), roleid,
5252 if (aclresult == ACLCHECK_OK)
5254 /* Else we must have REFERENCES on each column */
5255 for (i = 0; i < natts; i++)
5257 aclresult = pg_attribute_aclcheck(RelationGetRelid(rel), attnums[i],
5258 roleid, ACL_REFERENCES);
5259 if (aclresult != ACLCHECK_OK)
5260 aclcheck_error(aclresult, ACL_KIND_CLASS,
5261 RelationGetRelationName(rel));
5266 * Scan the existing rows in a table to verify they meet a proposed FK
5269 * Caller must have opened and locked both relations.
5272 validateForeignKeyConstraint(Constraint *fkconstraint,
5283 * Build a trigger call structure; we'll need it either way.
5285 MemSet(&trig, 0, sizeof(trig));
5286 trig.tgoid = InvalidOid;
5287 trig.tgname = fkconstraint->conname;
5288 trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
5289 trig.tgisconstraint = TRUE;
5290 trig.tgconstrrelid = RelationGetRelid(pkrel);
5291 trig.tgconstrindid = pkindOid;
5292 trig.tgconstraint = constraintOid;
5293 trig.tgdeferrable = FALSE;
5294 trig.tginitdeferred = FALSE;
5295 /* we needn't fill in tgargs */
5298 * See if we can do it with a single LEFT JOIN query. A FALSE result
5299 * indicates we must proceed with the fire-the-trigger method.
5301 if (RI_Initial_Check(&trig, rel, pkrel))
5305 * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
5306 * if that tuple had just been inserted. If any of those fail, it should
5307 * ereport(ERROR) and that's that.
5309 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
5311 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
5313 FunctionCallInfoData fcinfo;
5314 TriggerData trigdata;
5317 * Make a call to the trigger function
5319 * No parameters are passed, but we do set a context
5321 MemSet(&fcinfo, 0, sizeof(fcinfo));
5324 * We assume RI_FKey_check_ins won't look at flinfo...
5326 trigdata.type = T_TriggerData;
5327 trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
5328 trigdata.tg_relation = rel;
5329 trigdata.tg_trigtuple = tuple;
5330 trigdata.tg_newtuple = NULL;
5331 trigdata.tg_trigger = &trig;
5332 trigdata.tg_trigtuplebuf = scan->rs_cbuf;
5333 trigdata.tg_newtuplebuf = InvalidBuffer;
5335 fcinfo.context = (Node *) &trigdata;
5337 RI_FKey_check_ins(&fcinfo);
5344 CreateFKCheckTrigger(RangeVar *myRel, Constraint *fkconstraint,
5345 Oid constraintOid, Oid indexOid, bool on_insert)
5347 CreateTrigStmt *fk_trigger;
5349 fk_trigger = makeNode(CreateTrigStmt);
5350 fk_trigger->trigname = fkconstraint->conname;
5351 fk_trigger->relation = myRel;
5352 fk_trigger->before = false;
5353 fk_trigger->row = true;
5355 /* Either ON INSERT or ON UPDATE */
5358 fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
5359 fk_trigger->events = TRIGGER_TYPE_INSERT;
5363 fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
5364 fk_trigger->events = TRIGGER_TYPE_UPDATE;
5367 fk_trigger->isconstraint = true;
5368 fk_trigger->deferrable = fkconstraint->deferrable;
5369 fk_trigger->initdeferred = fkconstraint->initdeferred;
5370 fk_trigger->constrrel = fkconstraint->pktable;
5371 fk_trigger->args = NIL;
5373 (void) CreateTrigger(fk_trigger, constraintOid, indexOid,
5374 "RI_ConstraintTrigger", false);
5376 /* Make changes-so-far visible */
5377 CommandCounterIncrement();
5381 * Create the triggers that implement an FK constraint.
5384 createForeignKeyTriggers(Relation rel, Constraint *fkconstraint,
5385 Oid constraintOid, Oid indexOid)
5388 CreateTrigStmt *fk_trigger;
5391 * Reconstruct a RangeVar for my relation (not passed in, unfortunately).
5393 myRel = makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
5394 pstrdup(RelationGetRelationName(rel)),
5397 /* Make changes-so-far visible */
5398 CommandCounterIncrement();
5401 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the CHECK
5402 * action for both INSERTs and UPDATEs on the referencing table.
5404 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, indexOid, true);
5405 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, indexOid, false);
5408 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
5409 * DELETE action on the referenced table.
5411 fk_trigger = makeNode(CreateTrigStmt);
5412 fk_trigger->trigname = fkconstraint->conname;
5413 fk_trigger->relation = fkconstraint->pktable;
5414 fk_trigger->before = false;
5415 fk_trigger->row = true;
5416 fk_trigger->events = TRIGGER_TYPE_DELETE;
5417 fk_trigger->isconstraint = true;
5418 fk_trigger->constrrel = myRel;
5419 switch (fkconstraint->fk_del_action)
5421 case FKCONSTR_ACTION_NOACTION:
5422 fk_trigger->deferrable = fkconstraint->deferrable;
5423 fk_trigger->initdeferred = fkconstraint->initdeferred;
5424 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
5426 case FKCONSTR_ACTION_RESTRICT:
5427 fk_trigger->deferrable = false;
5428 fk_trigger->initdeferred = false;
5429 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
5431 case FKCONSTR_ACTION_CASCADE:
5432 fk_trigger->deferrable = false;
5433 fk_trigger->initdeferred = false;
5434 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
5436 case FKCONSTR_ACTION_SETNULL:
5437 fk_trigger->deferrable = false;
5438 fk_trigger->initdeferred = false;
5439 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
5441 case FKCONSTR_ACTION_SETDEFAULT:
5442 fk_trigger->deferrable = false;
5443 fk_trigger->initdeferred = false;
5444 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
5447 elog(ERROR, "unrecognized FK action type: %d",
5448 (int) fkconstraint->fk_del_action);
5451 fk_trigger->args = NIL;
5453 (void) CreateTrigger(fk_trigger, constraintOid, indexOid,
5454 "RI_ConstraintTrigger", false);
5456 /* Make changes-so-far visible */
5457 CommandCounterIncrement();
5460 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
5461 * UPDATE action on the referenced table.
5463 fk_trigger = makeNode(CreateTrigStmt);
5464 fk_trigger->trigname = fkconstraint->conname;
5465 fk_trigger->relation = fkconstraint->pktable;
5466 fk_trigger->before = false;
5467 fk_trigger->row = true;
5468 fk_trigger->events = TRIGGER_TYPE_UPDATE;
5469 fk_trigger->isconstraint = true;
5470 fk_trigger->constrrel = myRel;
5471 switch (fkconstraint->fk_upd_action)
5473 case FKCONSTR_ACTION_NOACTION:
5474 fk_trigger->deferrable = fkconstraint->deferrable;
5475 fk_trigger->initdeferred = fkconstraint->initdeferred;
5476 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
5478 case FKCONSTR_ACTION_RESTRICT:
5479 fk_trigger->deferrable = false;
5480 fk_trigger->initdeferred = false;
5481 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
5483 case FKCONSTR_ACTION_CASCADE:
5484 fk_trigger->deferrable = false;
5485 fk_trigger->initdeferred = false;
5486 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
5488 case FKCONSTR_ACTION_SETNULL:
5489 fk_trigger->deferrable = false;
5490 fk_trigger->initdeferred = false;
5491 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
5493 case FKCONSTR_ACTION_SETDEFAULT:
5494 fk_trigger->deferrable = false;
5495 fk_trigger->initdeferred = false;
5496 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
5499 elog(ERROR, "unrecognized FK action type: %d",
5500 (int) fkconstraint->fk_upd_action);
5503 fk_trigger->args = NIL;
5505 (void) CreateTrigger(fk_trigger, constraintOid, indexOid,
5506 "RI_ConstraintTrigger", false);
5510 * ALTER TABLE DROP CONSTRAINT
5512 * Like DROP COLUMN, we can't use the normal ALTER TABLE recursion mechanism.
5515 ATExecDropConstraint(Relation rel, const char *constrName,
5516 DropBehavior behavior,
5517 bool recurse, bool recursing,
5523 Form_pg_constraint con;
5528 bool is_check_constraint = false;
5530 /* At top level, permission check was done in ATPrepCmd, else do it */
5532 ATSimplePermissions(rel, false);
5534 conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
5537 * Find and drop the target constraint
5540 Anum_pg_constraint_conrelid,
5541 BTEqualStrategyNumber, F_OIDEQ,
5542 ObjectIdGetDatum(RelationGetRelid(rel)));
5543 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
5544 true, SnapshotNow, 1, &key);
5546 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
5548 ObjectAddress conobj;
5550 con = (Form_pg_constraint) GETSTRUCT(tuple);
5552 if (strcmp(NameStr(con->conname), constrName) != 0)
5555 /* Don't drop inherited constraints */
5556 if (con->coninhcount > 0 && !recursing)
5558 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5559 errmsg("cannot drop inherited constraint \"%s\" of relation \"%s\"",
5560 constrName, RelationGetRelationName(rel))));
5562 /* Right now only CHECK constraints can be inherited */
5563 if (con->contype == CONSTRAINT_CHECK)
5564 is_check_constraint = true;
5567 * Perform the actual constraint deletion
5569 conobj.classId = ConstraintRelationId;
5570 conobj.objectId = HeapTupleGetOid(tuple);
5571 conobj.objectSubId = 0;
5573 performDeletion(&conobj, behavior);
5578 systable_endscan(scan);
5583 (errcode(ERRCODE_UNDEFINED_OBJECT),
5584 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
5585 constrName, RelationGetRelationName(rel))));
5590 (errmsg("constraint \"%s\" of relation \"%s\" does not exist, skipping",
5591 constrName, RelationGetRelationName(rel))));
5592 heap_close(conrel, RowExclusiveLock);
5597 * Propagate to children as appropriate. Unlike most other ALTER
5598 * routines, we have to do this one level of recursion at a time; we can't
5599 * use find_all_inheritors to do it in one pass.
5601 if (is_check_constraint)
5602 children = find_inheritance_children(RelationGetRelid(rel),
5603 AccessExclusiveLock);
5607 foreach(child, children)
5609 Oid childrelid = lfirst_oid(child);
5612 /* find_inheritance_children already got lock */
5613 childrel = heap_open(childrelid, NoLock);
5614 CheckTableNotInUse(childrel, "ALTER TABLE");
5617 Anum_pg_constraint_conrelid,
5618 BTEqualStrategyNumber, F_OIDEQ,
5619 ObjectIdGetDatum(childrelid));
5620 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
5621 true, SnapshotNow, 1, &key);
5625 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
5627 HeapTuple copy_tuple;
5629 con = (Form_pg_constraint) GETSTRUCT(tuple);
5631 /* Right now only CHECK constraints can be inherited */
5632 if (con->contype != CONSTRAINT_CHECK)
5635 if (strcmp(NameStr(con->conname), constrName) != 0)
5640 if (con->coninhcount <= 0) /* shouldn't happen */
5641 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
5642 childrelid, constrName);
5644 copy_tuple = heap_copytuple(tuple);
5645 con = (Form_pg_constraint) GETSTRUCT(copy_tuple);
5650 * If the child constraint has other definition sources, just
5651 * decrement its inheritance count; if not, recurse to delete
5654 if (con->coninhcount == 1 && !con->conislocal)
5656 /* Time to delete this child constraint, too */
5657 ATExecDropConstraint(childrel, constrName, behavior,
5663 /* Child constraint must survive my deletion */
5665 simple_heap_update(conrel, ©_tuple->t_self, copy_tuple);
5666 CatalogUpdateIndexes(conrel, copy_tuple);
5668 /* Make update visible */
5669 CommandCounterIncrement();
5675 * If we were told to drop ONLY in this table (no recursion),
5676 * we need to mark the inheritors' constraints as locally
5677 * defined rather than inherited.
5680 con->conislocal = true;
5682 simple_heap_update(conrel, ©_tuple->t_self, copy_tuple);
5683 CatalogUpdateIndexes(conrel, copy_tuple);
5685 /* Make update visible */
5686 CommandCounterIncrement();
5689 heap_freetuple(copy_tuple);
5692 systable_endscan(scan);
5696 (errcode(ERRCODE_UNDEFINED_OBJECT),
5697 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
5699 RelationGetRelationName(childrel))));
5701 heap_close(childrel, NoLock);
5704 heap_close(conrel, RowExclusiveLock);
5711 ATPrepAlterColumnType(List **wqueue,
5712 AlteredTableInfo *tab, Relation rel,
5713 bool recurse, bool recursing,
5716 char *colName = cmd->name;
5717 TypeName *typeName = (TypeName *) cmd->def;
5719 Form_pg_attribute attTup;
5724 NewColumnValue *newval;
5725 ParseState *pstate = make_parsestate(NULL);
5727 /* lookup the attribute so we can check inheritance status */
5728 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
5729 if (!HeapTupleIsValid(tuple))
5731 (errcode(ERRCODE_UNDEFINED_COLUMN),
5732 errmsg("column \"%s\" of relation \"%s\" does not exist",
5733 colName, RelationGetRelationName(rel))));
5734 attTup = (Form_pg_attribute) GETSTRUCT(tuple);
5735 attnum = attTup->attnum;
5737 /* Can't alter a system attribute */
5740 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5741 errmsg("cannot alter system column \"%s\"",
5744 /* Don't alter inherited columns */
5745 if (attTup->attinhcount > 0 && !recursing)
5747 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5748 errmsg("cannot alter inherited column \"%s\"",
5751 /* Look up the target type */
5752 targettype = typenameTypeId(NULL, typeName, &targettypmod);
5754 /* make sure datatype is legal for a column */
5755 CheckAttributeType(colName, targettype);
5758 * Set up an expression to transform the old data value to the new type.
5759 * If a USING option was given, transform and use that expression, else
5760 * just take the old value and try to coerce it. We do this first so that
5761 * type incompatibility can be detected before we waste effort, and
5762 * because we need the expression to be parsed against the original table
5769 /* Expression must be able to access vars of old table */
5770 rte = addRangeTableEntryForRelation(pstate,
5775 addRTEtoQuery(pstate, rte, false, true, true);
5777 transform = transformExpr(pstate, cmd->transform);
5779 /* It can't return a set */
5780 if (expression_returns_set(transform))
5782 (errcode(ERRCODE_DATATYPE_MISMATCH),
5783 errmsg("transform expression must not return a set")));
5785 /* No subplans or aggregates, either... */
5786 if (pstate->p_hasSubLinks)
5788 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5789 errmsg("cannot use subquery in transform expression")));
5790 if (pstate->p_hasAggs)
5792 (errcode(ERRCODE_GROUPING_ERROR),
5793 errmsg("cannot use aggregate function in transform expression")));
5794 if (pstate->p_hasWindowFuncs)
5796 (errcode(ERRCODE_WINDOWING_ERROR),
5797 errmsg("cannot use window function in transform expression")));
5801 transform = (Node *) makeVar(1, attnum,
5802 attTup->atttypid, attTup->atttypmod,
5806 transform = coerce_to_target_type(pstate,
5807 transform, exprType(transform),
5808 targettype, targettypmod,
5809 COERCION_ASSIGNMENT,
5810 COERCE_IMPLICIT_CAST,
5812 if (transform == NULL)
5814 (errcode(ERRCODE_DATATYPE_MISMATCH),
5815 errmsg("column \"%s\" cannot be cast to type %s",
5816 colName, format_type_be(targettype))));
5819 * Add a work queue item to make ATRewriteTable update the column
5822 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
5823 newval->attnum = attnum;
5824 newval->expr = (Expr *) transform;
5826 tab->newvals = lappend(tab->newvals, newval);
5828 ReleaseSysCache(tuple);
5831 * The recursion case is handled by ATSimpleRecursion. However, if we are
5832 * told not to recurse, there had better not be any child tables; else the
5833 * alter would put them out of step.
5836 ATSimpleRecursion(wqueue, rel, cmd, recurse);
5837 else if (!recursing &&
5838 find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL)
5840 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5841 errmsg("type of inherited column \"%s\" must be changed in child tables too",
5846 ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
5847 const char *colName, TypeName *typeName)
5850 Form_pg_attribute attTup;
5852 HeapTuple typeTuple;
5857 Relation attrelation;
5863 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
5865 /* Look up the target column */
5866 heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5867 if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
5869 (errcode(ERRCODE_UNDEFINED_COLUMN),
5870 errmsg("column \"%s\" of relation \"%s\" does not exist",
5871 colName, RelationGetRelationName(rel))));
5872 attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
5873 attnum = attTup->attnum;
5875 /* Check for multiple ALTER TYPE on same column --- can't cope */
5876 if (attTup->atttypid != tab->oldDesc->attrs[attnum - 1]->atttypid ||
5877 attTup->atttypmod != tab->oldDesc->attrs[attnum - 1]->atttypmod)
5879 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5880 errmsg("cannot alter type of column \"%s\" twice",
5883 /* Look up the target type (should not fail, since prep found it) */
5884 typeTuple = typenameType(NULL, typeName, &targettypmod);
5885 tform = (Form_pg_type) GETSTRUCT(typeTuple);
5886 targettype = HeapTupleGetOid(typeTuple);
5889 * If there is a default expression for the column, get it and ensure we
5890 * can coerce it to the new datatype. (We must do this before changing
5891 * the column type, because build_column_default itself will try to
5892 * coerce, and will not issue the error message we want if it fails.)
5894 * We remove any implicit coercion steps at the top level of the old
5895 * default expression; this has been agreed to satisfy the principle of
5896 * least surprise. (The conversion to the new column type should act like
5897 * it started from what the user sees as the stored expression, and the
5898 * implicit coercions aren't going to be shown.)
5900 if (attTup->atthasdef)
5902 defaultexpr = build_column_default(rel, attnum);
5903 Assert(defaultexpr);
5904 defaultexpr = strip_implicit_coercions(defaultexpr);
5905 defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
5906 defaultexpr, exprType(defaultexpr),
5907 targettype, targettypmod,
5908 COERCION_ASSIGNMENT,
5909 COERCE_IMPLICIT_CAST,
5911 if (defaultexpr == NULL)
5913 (errcode(ERRCODE_DATATYPE_MISMATCH),
5914 errmsg("default for column \"%s\" cannot be cast to type %s",
5915 colName, format_type_be(targettype))));
5921 * Find everything that depends on the column (constraints, indexes, etc),
5922 * and record enough information to let us recreate the objects.
5924 * The actual recreation does not happen here, but only after we have
5925 * performed all the individual ALTER TYPE operations. We have to save
5926 * the info before executing ALTER TYPE, though, else the deparser will
5929 * There could be multiple entries for the same object, so we must check
5930 * to ensure we process each one only once. Note: we assume that an index
5931 * that implements a constraint will not show a direct dependency on the
5934 depRel = heap_open(DependRelationId, RowExclusiveLock);
5936 ScanKeyInit(&key[0],
5937 Anum_pg_depend_refclassid,
5938 BTEqualStrategyNumber, F_OIDEQ,
5939 ObjectIdGetDatum(RelationRelationId));
5940 ScanKeyInit(&key[1],
5941 Anum_pg_depend_refobjid,
5942 BTEqualStrategyNumber, F_OIDEQ,
5943 ObjectIdGetDatum(RelationGetRelid(rel)));
5944 ScanKeyInit(&key[2],
5945 Anum_pg_depend_refobjsubid,
5946 BTEqualStrategyNumber, F_INT4EQ,
5947 Int32GetDatum((int32) attnum));
5949 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
5950 SnapshotNow, 3, key);
5952 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5954 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5955 ObjectAddress foundObject;
5957 /* We don't expect any PIN dependencies on columns */
5958 if (foundDep->deptype == DEPENDENCY_PIN)
5959 elog(ERROR, "cannot alter type of a pinned column");
5961 foundObject.classId = foundDep->classid;
5962 foundObject.objectId = foundDep->objid;
5963 foundObject.objectSubId = foundDep->objsubid;
5965 switch (getObjectClass(&foundObject))
5969 char relKind = get_rel_relkind(foundObject.objectId);
5971 if (relKind == RELKIND_INDEX)
5973 Assert(foundObject.objectSubId == 0);
5974 if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
5976 tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
5977 foundObject.objectId);
5978 tab->changedIndexDefs = lappend(tab->changedIndexDefs,
5979 pg_get_indexdef_string(foundObject.objectId));
5982 else if (relKind == RELKIND_SEQUENCE)
5985 * This must be a SERIAL column's sequence. We need
5986 * not do anything to it.
5988 Assert(foundObject.objectSubId == 0);
5992 /* Not expecting any other direct dependencies... */
5993 elog(ERROR, "unexpected object depending on column: %s",
5994 getObjectDescription(&foundObject));
5999 case OCLASS_CONSTRAINT:
6000 Assert(foundObject.objectSubId == 0);
6001 if (!list_member_oid(tab->changedConstraintOids,
6002 foundObject.objectId))
6004 char *defstring = pg_get_constraintdef_string(foundObject.objectId);
6007 * Put NORMAL dependencies at the front of the list and
6008 * AUTO dependencies at the back. This makes sure that
6009 * foreign-key constraints depending on this column will
6010 * be dropped before unique or primary-key constraints of
6011 * the column; which we must have because the FK
6012 * constraints depend on the indexes belonging to the
6013 * unique constraints.
6015 if (foundDep->deptype == DEPENDENCY_NORMAL)
6017 tab->changedConstraintOids =
6018 lcons_oid(foundObject.objectId,
6019 tab->changedConstraintOids);
6020 tab->changedConstraintDefs =
6022 tab->changedConstraintDefs);
6026 tab->changedConstraintOids =
6027 lappend_oid(tab->changedConstraintOids,
6028 foundObject.objectId);
6029 tab->changedConstraintDefs =
6030 lappend(tab->changedConstraintDefs,
6036 case OCLASS_REWRITE:
6037 /* XXX someday see if we can cope with revising views */
6039 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6040 errmsg("cannot alter type of a column used by a view or rule"),
6041 errdetail("%s depends on column \"%s\"",
6042 getObjectDescription(&foundObject),
6046 case OCLASS_DEFAULT:
6049 * Ignore the column's default expression, since we will fix
6052 Assert(defaultexpr);
6058 case OCLASS_CONVERSION:
6059 case OCLASS_LANGUAGE:
6060 case OCLASS_OPERATOR:
6061 case OCLASS_OPCLASS:
6062 case OCLASS_OPFAMILY:
6065 case OCLASS_TRIGGER:
6067 case OCLASS_TSPARSER:
6069 case OCLASS_TSTEMPLATE:
6070 case OCLASS_TSCONFIG:
6072 case OCLASS_DATABASE:
6073 case OCLASS_TBLSPACE:
6075 case OCLASS_FOREIGN_SERVER:
6076 case OCLASS_USER_MAPPING:
6079 * We don't expect any of these sorts of objects to depend on
6082 elog(ERROR, "unexpected object depending on column: %s",
6083 getObjectDescription(&foundObject));
6087 elog(ERROR, "unrecognized object class: %u",
6088 foundObject.classId);
6092 systable_endscan(scan);
6095 * Now scan for dependencies of this column on other things. The only
6096 * thing we should find is the dependency on the column datatype, which we
6099 ScanKeyInit(&key[0],
6100 Anum_pg_depend_classid,
6101 BTEqualStrategyNumber, F_OIDEQ,
6102 ObjectIdGetDatum(RelationRelationId));
6103 ScanKeyInit(&key[1],
6104 Anum_pg_depend_objid,
6105 BTEqualStrategyNumber, F_OIDEQ,
6106 ObjectIdGetDatum(RelationGetRelid(rel)));
6107 ScanKeyInit(&key[2],
6108 Anum_pg_depend_objsubid,
6109 BTEqualStrategyNumber, F_INT4EQ,
6110 Int32GetDatum((int32) attnum));
6112 scan = systable_beginscan(depRel, DependDependerIndexId, true,
6113 SnapshotNow, 3, key);
6115 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
6117 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
6119 if (foundDep->deptype != DEPENDENCY_NORMAL)
6120 elog(ERROR, "found unexpected dependency type '%c'",
6122 if (foundDep->refclassid != TypeRelationId ||
6123 foundDep->refobjid != attTup->atttypid)
6124 elog(ERROR, "found unexpected dependency for column");
6126 simple_heap_delete(depRel, &depTup->t_self);
6129 systable_endscan(scan);
6131 heap_close(depRel, RowExclusiveLock);
6134 * Here we go --- change the recorded column type. (Note heapTup is a
6135 * copy of the syscache entry, so okay to scribble on.)
6137 attTup->atttypid = targettype;
6138 attTup->atttypmod = targettypmod;
6139 attTup->attndims = list_length(typeName->arrayBounds);
6140 attTup->attlen = tform->typlen;
6141 attTup->attbyval = tform->typbyval;
6142 attTup->attalign = tform->typalign;
6143 attTup->attstorage = tform->typstorage;
6145 ReleaseSysCache(typeTuple);
6147 simple_heap_update(attrelation, &heapTup->t_self, heapTup);
6149 /* keep system catalog indexes current */
6150 CatalogUpdateIndexes(attrelation, heapTup);
6152 heap_close(attrelation, RowExclusiveLock);
6154 /* Install dependency on new datatype */
6155 add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
6158 * Drop any pg_statistic entry for the column, since it's now wrong type
6160 RemoveStatistics(RelationGetRelid(rel), attnum);
6163 * Update the default, if present, by brute force --- remove and re-add
6164 * the default. Probably unsafe to take shortcuts, since the new version
6165 * may well have additional dependencies. (It's okay to do this now,
6166 * rather than after other ALTER TYPE commands, since the default won't
6167 * depend on other column types.)
6171 /* Must make new row visible since it will be updated again */
6172 CommandCounterIncrement();
6175 * We use RESTRICT here for safety, but at present we do not expect
6176 * anything to depend on the default.
6178 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true);
6180 StoreAttrDefault(rel, attnum, defaultexpr);
6184 heap_freetuple(heapTup);
6188 * Cleanup after we've finished all the ALTER TYPE operations for a
6189 * particular relation. We have to drop and recreate all the indexes
6190 * and constraints that depend on the altered columns.
6193 ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab)
6199 * Re-parse the index and constraint definitions, and attach them to the
6200 * appropriate work queue entries. We do this before dropping because in
6201 * the case of a FOREIGN KEY constraint, we might not yet have exclusive
6202 * lock on the table the constraint is attached to, and we need to get
6203 * that before dropping. It's safe because the parser won't actually look
6204 * at the catalogs to detect the existing entry.
6206 foreach(l, tab->changedIndexDefs)
6207 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
6208 foreach(l, tab->changedConstraintDefs)
6209 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
6212 * Now we can drop the existing constraints and indexes --- constraints
6213 * first, since some of them might depend on the indexes. In fact, we
6214 * have to delete FOREIGN KEY constraints before UNIQUE constraints, but
6215 * we already ordered the constraint list to ensure that would happen. It
6216 * should be okay to use DROP_RESTRICT here, since nothing else should be
6217 * depending on these objects.
6219 foreach(l, tab->changedConstraintOids)
6221 obj.classId = ConstraintRelationId;
6222 obj.objectId = lfirst_oid(l);
6223 obj.objectSubId = 0;
6224 performDeletion(&obj, DROP_RESTRICT);
6227 foreach(l, tab->changedIndexOids)
6229 obj.classId = RelationRelationId;
6230 obj.objectId = lfirst_oid(l);
6231 obj.objectSubId = 0;
6232 performDeletion(&obj, DROP_RESTRICT);
6236 * The objects will get recreated during subsequent passes over the work
6242 ATPostAlterTypeParse(char *cmd, List **wqueue)
6244 List *raw_parsetree_list;
6245 List *querytree_list;
6246 ListCell *list_item;
6249 * We expect that we will get only ALTER TABLE and CREATE INDEX
6250 * statements. Hence, there is no need to pass them through
6251 * parse_analyze() or the rewriter, but instead we need to pass them
6252 * through parse_utilcmd.c to make them ready for execution.
6254 raw_parsetree_list = raw_parser(cmd);
6255 querytree_list = NIL;
6256 foreach(list_item, raw_parsetree_list)
6258 Node *stmt = (Node *) lfirst(list_item);
6260 if (IsA(stmt, IndexStmt))
6261 querytree_list = lappend(querytree_list,
6262 transformIndexStmt((IndexStmt *) stmt,
6264 else if (IsA(stmt, AlterTableStmt))
6265 querytree_list = list_concat(querytree_list,
6266 transformAlterTableStmt((AlterTableStmt *) stmt,
6269 querytree_list = lappend(querytree_list, stmt);
6273 * Attach each generated command to the proper place in the work queue.
6274 * Note this could result in creation of entirely new work-queue entries.
6276 foreach(list_item, querytree_list)
6278 Node *stm = (Node *) lfirst(list_item);
6280 AlteredTableInfo *tab;
6282 switch (nodeTag(stm))
6286 IndexStmt *stmt = (IndexStmt *) stm;
6287 AlterTableCmd *newcmd;
6289 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
6290 tab = ATGetQueueEntry(wqueue, rel);
6291 newcmd = makeNode(AlterTableCmd);
6292 newcmd->subtype = AT_ReAddIndex;
6293 newcmd->def = (Node *) stmt;
6294 tab->subcmds[AT_PASS_OLD_INDEX] =
6295 lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
6296 relation_close(rel, NoLock);
6299 case T_AlterTableStmt:
6301 AlterTableStmt *stmt = (AlterTableStmt *) stm;
6304 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
6305 tab = ATGetQueueEntry(wqueue, rel);
6306 foreach(lcmd, stmt->cmds)
6308 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
6310 switch (cmd->subtype)
6313 cmd->subtype = AT_ReAddIndex;
6314 tab->subcmds[AT_PASS_OLD_INDEX] =
6315 lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
6317 case AT_AddConstraint:
6318 tab->subcmds[AT_PASS_OLD_CONSTR] =
6319 lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
6322 elog(ERROR, "unexpected statement type: %d",
6323 (int) cmd->subtype);
6326 relation_close(rel, NoLock);
6330 elog(ERROR, "unexpected statement type: %d",
6331 (int) nodeTag(stm));
6340 * recursing is true if we are recursing from a table to its indexes,
6341 * sequences, or toast table. We don't allow the ownership of those things to
6342 * be changed separately from the parent table. Also, we can skip permission
6343 * checks (this is necessary not just an optimization, else we'd fail to
6344 * handle toast tables properly).
6346 * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
6347 * free-standing composite type.
6350 ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing)
6352 Relation target_rel;
6355 Form_pg_class tuple_class;
6358 * Get exclusive lock till end of transaction on the target table. Use
6359 * relation_open so that we can work on indexes and sequences.
6361 target_rel = relation_open(relationOid, AccessExclusiveLock);
6363 /* Get its pg_class tuple, too */
6364 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
6366 tuple = SearchSysCache(RELOID,
6367 ObjectIdGetDatum(relationOid),
6369 if (!HeapTupleIsValid(tuple))
6370 elog(ERROR, "cache lookup failed for relation %u", relationOid);
6371 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
6373 /* Can we change the ownership of this tuple? */
6374 switch (tuple_class->relkind)
6376 case RELKIND_RELATION:
6378 /* ok to change owner */
6384 * Because ALTER INDEX OWNER used to be allowed, and in fact
6385 * is generated by old versions of pg_dump, we give a warning
6386 * and do nothing rather than erroring out. Also, to avoid
6387 * unnecessary chatter while restoring those old dumps, say
6388 * nothing at all if the command would be a no-op anyway.
6390 if (tuple_class->relowner != newOwnerId)
6392 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6393 errmsg("cannot change owner of index \"%s\"",
6394 NameStr(tuple_class->relname)),
6395 errhint("Change the ownership of the index's table, instead.")));
6396 /* quick hack to exit via the no-op path */
6397 newOwnerId = tuple_class->relowner;
6400 case RELKIND_SEQUENCE:
6402 tuple_class->relowner != newOwnerId)
6404 /* if it's an owned sequence, disallow changing it by itself */
6408 if (sequenceIsOwned(relationOid, &tableId, &colId))
6410 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6411 errmsg("cannot change owner of sequence \"%s\"",
6412 NameStr(tuple_class->relname)),
6413 errdetail("Sequence \"%s\" is linked to table \"%s\".",
6414 NameStr(tuple_class->relname),
6415 get_rel_name(tableId))));
6418 case RELKIND_COMPOSITE_TYPE:
6422 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6423 errmsg("\"%s\" is a composite type",
6424 NameStr(tuple_class->relname)),
6425 errhint("Use ALTER TYPE instead.")));
6427 case RELKIND_TOASTVALUE:
6433 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6434 errmsg("\"%s\" is not a table, view, or sequence",
6435 NameStr(tuple_class->relname))));
6439 * If the new owner is the same as the existing owner, consider the
6440 * command to have succeeded. This is for dump restoration purposes.
6442 if (tuple_class->relowner != newOwnerId)
6444 Datum repl_val[Natts_pg_class];
6445 bool repl_null[Natts_pg_class];
6446 bool repl_repl[Natts_pg_class];
6452 /* skip permission checks when recursing to index or toast table */
6455 /* Superusers can always do it */
6458 Oid namespaceOid = tuple_class->relnamespace;
6459 AclResult aclresult;
6461 /* Otherwise, must be owner of the existing object */
6462 if (!pg_class_ownercheck(relationOid, GetUserId()))
6463 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
6464 RelationGetRelationName(target_rel));
6466 /* Must be able to become new owner */
6467 check_is_member_of_role(GetUserId(), newOwnerId);
6469 /* New owner must have CREATE privilege on namespace */
6470 aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
6472 if (aclresult != ACLCHECK_OK)
6473 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
6474 get_namespace_name(namespaceOid));
6478 memset(repl_null, false, sizeof(repl_null));
6479 memset(repl_repl, false, sizeof(repl_repl));
6481 repl_repl[Anum_pg_class_relowner - 1] = true;
6482 repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
6485 * Determine the modified ACL for the new owner. This is only
6486 * necessary when the ACL is non-null.
6488 aclDatum = SysCacheGetAttr(RELOID, tuple,
6489 Anum_pg_class_relacl,
6493 newAcl = aclnewowner(DatumGetAclP(aclDatum),
6494 tuple_class->relowner, newOwnerId);
6495 repl_repl[Anum_pg_class_relacl - 1] = true;
6496 repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
6499 newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
6501 simple_heap_update(class_rel, &newtuple->t_self, newtuple);
6502 CatalogUpdateIndexes(class_rel, newtuple);
6504 heap_freetuple(newtuple);
6507 * Update owner dependency reference, if any. A composite type has
6508 * none, because it's tracked for the pg_type entry instead of here;
6509 * indexes and TOAST tables don't have their own entries either.
6511 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
6512 tuple_class->relkind != RELKIND_INDEX &&
6513 tuple_class->relkind != RELKIND_TOASTVALUE)
6514 changeDependencyOnOwner(RelationRelationId, relationOid,
6518 * Also change the ownership of the table's rowtype, if it has one
6520 if (tuple_class->relkind != RELKIND_INDEX)
6521 AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId,
6522 tuple_class->relkind == RELKIND_COMPOSITE_TYPE);
6525 * If we are operating on a table, also change the ownership of any
6526 * indexes and sequences that belong to the table, as well as the
6527 * table's toast table (if it has one)
6529 if (tuple_class->relkind == RELKIND_RELATION ||
6530 tuple_class->relkind == RELKIND_TOASTVALUE)
6532 List *index_oid_list;
6535 /* Find all the indexes belonging to this relation */
6536 index_oid_list = RelationGetIndexList(target_rel);
6538 /* For each index, recursively change its ownership */
6539 foreach(i, index_oid_list)
6540 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true);
6542 list_free(index_oid_list);
6545 if (tuple_class->relkind == RELKIND_RELATION)
6547 /* If it has a toast table, recurse to change its ownership */
6548 if (tuple_class->reltoastrelid != InvalidOid)
6549 ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
6552 /* If it has dependent sequences, recurse to change them too */
6553 change_owner_recurse_to_sequences(relationOid, newOwnerId);
6557 ReleaseSysCache(tuple);
6558 heap_close(class_rel, RowExclusiveLock);
6559 relation_close(target_rel, NoLock);
6563 * change_owner_recurse_to_sequences
6565 * Helper function for ATExecChangeOwner. Examines pg_depend searching
6566 * for sequences that are dependent on serial columns, and changes their
6570 change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId)
6578 * SERIAL sequences are those having an auto dependency on one of the
6579 * table's columns (we don't care *which* column, exactly).
6581 depRel = heap_open(DependRelationId, AccessShareLock);
6583 ScanKeyInit(&key[0],
6584 Anum_pg_depend_refclassid,
6585 BTEqualStrategyNumber, F_OIDEQ,
6586 ObjectIdGetDatum(RelationRelationId));
6587 ScanKeyInit(&key[1],
6588 Anum_pg_depend_refobjid,
6589 BTEqualStrategyNumber, F_OIDEQ,
6590 ObjectIdGetDatum(relationOid));
6591 /* we leave refobjsubid unspecified */
6593 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
6594 SnapshotNow, 2, key);
6596 while (HeapTupleIsValid(tup = systable_getnext(scan)))
6598 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
6601 /* skip dependencies other than auto dependencies on columns */
6602 if (depForm->refobjsubid == 0 ||
6603 depForm->classid != RelationRelationId ||
6604 depForm->objsubid != 0 ||
6605 depForm->deptype != DEPENDENCY_AUTO)
6608 /* Use relation_open just in case it's an index */
6609 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
6611 /* skip non-sequence relations */
6612 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
6614 /* No need to keep the lock */
6615 relation_close(seqRel, AccessExclusiveLock);
6619 /* We don't need to close the sequence while we alter it. */
6620 ATExecChangeOwner(depForm->objid, newOwnerId, true);
6622 /* Now we can close it. Keep the lock till end of transaction. */
6623 relation_close(seqRel, NoLock);
6626 systable_endscan(scan);
6628 relation_close(depRel, AccessShareLock);
6632 * ALTER TABLE CLUSTER ON
6634 * The only thing we have to do is to change the indisclustered bits.
6637 ATExecClusterOn(Relation rel, const char *indexName)
6641 indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
6643 if (!OidIsValid(indexOid))
6645 (errcode(ERRCODE_UNDEFINED_OBJECT),
6646 errmsg("index \"%s\" for table \"%s\" does not exist",
6647 indexName, RelationGetRelationName(rel))));
6649 /* Check index is valid to cluster on */
6650 check_index_is_clusterable(rel, indexOid, false);
6652 /* And do the work */
6653 mark_index_clustered(rel, indexOid);
6657 * ALTER TABLE SET WITHOUT CLUSTER
6659 * We have to find any indexes on the table that have indisclustered bit
6660 * set and turn it off.
6663 ATExecDropCluster(Relation rel)
6665 mark_index_clustered(rel, InvalidOid);
6669 * ALTER TABLE SET TABLESPACE
6672 ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, char *tablespacename)
6675 AclResult aclresult;
6677 /* Check that the tablespace exists */
6678 tablespaceId = get_tablespace_oid(tablespacename);
6679 if (!OidIsValid(tablespaceId))
6681 (errcode(ERRCODE_UNDEFINED_OBJECT),
6682 errmsg("tablespace \"%s\" does not exist", tablespacename)));
6684 /* Check its permissions */
6685 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(), ACL_CREATE);
6686 if (aclresult != ACLCHECK_OK)
6687 aclcheck_error(aclresult, ACL_KIND_TABLESPACE, tablespacename);
6689 /* Save info for Phase 3 to do the real work */
6690 if (OidIsValid(tab->newTableSpace))
6692 (errcode(ERRCODE_SYNTAX_ERROR),
6693 errmsg("cannot have multiple SET TABLESPACE subcommands")));
6694 tab->newTableSpace = tablespaceId;
6698 * ALTER TABLE/INDEX SET (...) or RESET (...)
6701 ATExecSetRelOptions(Relation rel, List *defList, bool isReset)
6710 Datum repl_val[Natts_pg_class];
6711 bool repl_null[Natts_pg_class];
6712 bool repl_repl[Natts_pg_class];
6713 static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
6716 return; /* nothing to do */
6718 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
6720 /* Get the old reloptions */
6721 relid = RelationGetRelid(rel);
6722 tuple = SearchSysCache(RELOID,
6723 ObjectIdGetDatum(relid),
6725 if (!HeapTupleIsValid(tuple))
6726 elog(ERROR, "cache lookup failed for relation %u", relid);
6728 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions, &isnull);
6730 /* Generate new proposed reloptions (text array) */
6731 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
6732 defList, NULL, validnsps, false, isReset);
6735 switch (rel->rd_rel->relkind)
6737 case RELKIND_RELATION:
6738 case RELKIND_TOASTVALUE:
6739 (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
6742 (void) index_reloptions(rel->rd_am->amoptions, newOptions, true);
6746 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6747 errmsg("\"%s\" is not a table, index, or TOAST table",
6748 RelationGetRelationName(rel))));
6753 * All we need do here is update the pg_class row; the new options will be
6754 * propagated into relcaches during post-commit cache inval.
6756 memset(repl_val, 0, sizeof(repl_val));
6757 memset(repl_null, false, sizeof(repl_null));
6758 memset(repl_repl, false, sizeof(repl_repl));
6760 if (newOptions != (Datum) 0)
6761 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
6763 repl_null[Anum_pg_class_reloptions - 1] = true;
6765 repl_repl[Anum_pg_class_reloptions - 1] = true;
6767 newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
6768 repl_val, repl_null, repl_repl);
6770 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
6772 CatalogUpdateIndexes(pgclass, newtuple);
6774 heap_freetuple(newtuple);
6776 ReleaseSysCache(tuple);
6778 /* repeat the whole exercise for the toast table, if there's one */
6779 if (OidIsValid(rel->rd_rel->reltoastrelid))
6782 Oid toastid = rel->rd_rel->reltoastrelid;
6784 toastrel = heap_open(toastid, AccessExclusiveLock);
6786 /* Get the old reloptions */
6787 tuple = SearchSysCache(RELOID,
6788 ObjectIdGetDatum(toastid),
6790 if (!HeapTupleIsValid(tuple))
6791 elog(ERROR, "cache lookup failed for relation %u", toastid);
6793 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions, &isnull);
6795 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
6796 defList, "toast", validnsps, false, isReset);
6798 (void) heap_reloptions(RELKIND_TOASTVALUE, newOptions, true);
6800 memset(repl_val, 0, sizeof(repl_val));
6801 memset(repl_null, false, sizeof(repl_null));
6802 memset(repl_repl, false, sizeof(repl_repl));
6804 if (newOptions != (Datum) 0)
6805 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
6807 repl_null[Anum_pg_class_reloptions - 1] = true;
6809 repl_repl[Anum_pg_class_reloptions - 1] = true;
6811 newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
6812 repl_val, repl_null, repl_repl);
6814 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
6816 CatalogUpdateIndexes(pgclass, newtuple);
6818 heap_freetuple(newtuple);
6820 ReleaseSysCache(tuple);
6822 heap_close(toastrel, NoLock);
6825 heap_close(pgclass, RowExclusiveLock);
6829 * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
6830 * rewriting to be done, so we just want to copy the data as fast as possible.
6833 ATExecSetTableSpace(Oid tableOid, Oid newTableSpace)
6840 RelFileNode newrnode;
6841 SMgrRelation dstrel;
6844 Form_pg_class rd_rel;
6848 * Need lock here in case we are recursing to toast table or index
6850 rel = relation_open(tableOid, AccessExclusiveLock);
6853 * We can never allow moving of shared or nailed-in-cache relations,
6854 * because we can't support changing their reltablespace values.
6856 if (rel->rd_rel->relisshared || rel->rd_isnailed)
6858 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6859 errmsg("cannot move system relation \"%s\"",
6860 RelationGetRelationName(rel))));
6862 /* Can't move a non-shared relation into pg_global */
6863 if (newTableSpace == GLOBALTABLESPACE_OID)
6865 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6866 errmsg("only shared relations can be placed in pg_global tablespace")));
6869 * Don't allow moving temp tables of other backends ... their local buffer
6870 * manager is not going to cope.
6872 if (RELATION_IS_OTHER_TEMP(rel))
6874 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6875 errmsg("cannot move temporary tables of other sessions")));
6878 * No work if no change in tablespace.
6880 oldTableSpace = rel->rd_rel->reltablespace;
6881 if (newTableSpace == oldTableSpace ||
6882 (newTableSpace == MyDatabaseTableSpace && oldTableSpace == 0))
6884 relation_close(rel, NoLock);
6888 reltoastrelid = rel->rd_rel->reltoastrelid;
6889 reltoastidxid = rel->rd_rel->reltoastidxid;
6891 /* Get a modifiable copy of the relation's pg_class row */
6892 pg_class = heap_open(RelationRelationId, RowExclusiveLock);
6894 tuple = SearchSysCacheCopy(RELOID,
6895 ObjectIdGetDatum(tableOid),
6897 if (!HeapTupleIsValid(tuple))
6898 elog(ERROR, "cache lookup failed for relation %u", tableOid);
6899 rd_rel = (Form_pg_class) GETSTRUCT(tuple);
6902 * Since we copy the file directly without looking at the shared buffers,
6903 * we'd better first flush out any pages of the source relation that are
6904 * in shared buffers. We assume no new changes will be made while we are
6905 * holding exclusive lock on the rel.
6907 FlushRelationBuffers(rel);
6910 * Relfilenodes are not unique across tablespaces, so we need to allocate
6911 * a new one in the new tablespace.
6913 newrelfilenode = GetNewRelFileNode(newTableSpace,
6914 rel->rd_rel->relisshared,
6917 /* Open old and new relation */
6918 newrnode = rel->rd_node;
6919 newrnode.relNode = newrelfilenode;
6920 newrnode.spcNode = newTableSpace;
6921 dstrel = smgropen(newrnode);
6923 RelationOpenSmgr(rel);
6926 * Create and copy all forks of the relation, and schedule unlinking of
6927 * old physical files.
6929 * NOTE: any conflict in relfilenode value will be caught in
6930 * RelationCreateStorage().
6932 RelationCreateStorage(newrnode, rel->rd_istemp);
6934 /* copy main fork */
6935 copy_relation_data(rel->rd_smgr, dstrel, MAIN_FORKNUM, rel->rd_istemp);
6937 /* copy those extra forks that exist */
6938 for (forkNum = MAIN_FORKNUM + 1; forkNum <= MAX_FORKNUM; forkNum++)
6940 if (smgrexists(rel->rd_smgr, forkNum))
6942 smgrcreate(dstrel, forkNum, false);
6943 copy_relation_data(rel->rd_smgr, dstrel, forkNum, rel->rd_istemp);
6947 /* drop old relation, and close new one */
6948 RelationDropStorage(rel);
6951 /* update the pg_class row */
6952 rd_rel->reltablespace = (newTableSpace == MyDatabaseTableSpace) ? InvalidOid : newTableSpace;
6953 rd_rel->relfilenode = newrelfilenode;
6954 simple_heap_update(pg_class, &tuple->t_self, tuple);
6955 CatalogUpdateIndexes(pg_class, tuple);
6957 heap_freetuple(tuple);
6959 heap_close(pg_class, RowExclusiveLock);
6961 relation_close(rel, NoLock);
6963 /* Make sure the reltablespace change is visible */
6964 CommandCounterIncrement();
6966 /* Move associated toast relation and/or index, too */
6967 if (OidIsValid(reltoastrelid))
6968 ATExecSetTableSpace(reltoastrelid, newTableSpace);
6969 if (OidIsValid(reltoastidxid))
6970 ATExecSetTableSpace(reltoastidxid, newTableSpace);
6974 * Copy data, block by block
6977 copy_relation_data(SMgrRelation src, SMgrRelation dst,
6978 ForkNumber forkNum, bool istemp)
6981 BlockNumber nblocks;
6984 Page page = (Page) buf;
6987 * We need to log the copied data in WAL iff WAL archiving is enabled AND
6988 * it's not a temp rel.
6990 use_wal = XLogArchivingActive() && !istemp;
6992 nblocks = smgrnblocks(src, forkNum);
6994 for (blkno = 0; blkno < nblocks; blkno++)
6996 smgrread(src, forkNum, blkno, buf);
7000 log_newpage(&dst->smgr_rnode, forkNum, blkno, page);
7003 * Now write the page. We say isTemp = true even if it's not a temp
7004 * rel, because there's no need for smgr to schedule an fsync for this
7005 * write; we'll do it ourselves below.
7007 smgrextend(dst, forkNum, blkno, buf, true);
7011 * If the rel isn't temp, we must fsync it down to disk before it's safe
7012 * to commit the transaction. (For a temp rel we don't care since the rel
7013 * will be uninteresting after a crash anyway.)
7015 * It's obvious that we must do this when not WAL-logging the copy. It's
7016 * less obvious that we have to do it even if we did WAL-log the copied
7017 * pages. The reason is that since we're copying outside shared buffers, a
7018 * CHECKPOINT occurring during the copy has no way to flush the previously
7019 * written data to disk (indeed it won't know the new rel even exists). A
7020 * crash later on would replay WAL from the checkpoint, therefore it
7021 * wouldn't replay our earlier WAL entries. If we do not fsync those pages
7022 * here, they might still not be on disk when the crash occurs.
7025 smgrimmedsync(dst, forkNum);
7029 * ALTER TABLE ENABLE/DISABLE TRIGGER
7031 * We just pass this off to trigger.c.
7034 ATExecEnableDisableTrigger(Relation rel, char *trigname,
7035 char fires_when, bool skip_system)
7037 EnableDisableTrigger(rel, trigname, fires_when, skip_system);
7041 * ALTER TABLE ENABLE/DISABLE RULE
7043 * We just pass this off to rewriteDefine.c.
7046 ATExecEnableDisableRule(Relation rel, char *trigname,
7049 EnableDisableRule(rel, trigname, fires_when);
7053 * ALTER TABLE INHERIT
7055 * Add a parent to the child's parents. This verifies that all the columns and
7056 * check constraints of the parent appear in the child and that they have the
7057 * same data types and expressions.
7060 ATExecAddInherit(Relation child_rel, RangeVar *parent)
7062 Relation parent_rel,
7066 HeapTuple inheritsTuple;
7071 * AccessShareLock on the parent is what's obtained during normal CREATE
7072 * TABLE ... INHERITS ..., so should be enough here.
7074 parent_rel = heap_openrv(parent, AccessShareLock);
7077 * Must be owner of both parent and child -- child was checked by
7078 * ATSimplePermissions call in ATPrepCmd
7080 ATSimplePermissions(parent_rel, false);
7082 /* Permanent rels cannot inherit from temporary ones */
7083 if (parent_rel->rd_istemp && !child_rel->rd_istemp)
7085 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7086 errmsg("cannot inherit from temporary relation \"%s\"",
7087 RelationGetRelationName(parent_rel))));
7090 * Check for duplicates in the list of parents, and determine the highest
7091 * inhseqno already present; we'll use the next one for the new parent.
7092 * (Note: get RowExclusiveLock because we will write pg_inherits below.)
7094 * Note: we do not reject the case where the child already inherits from
7095 * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
7097 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
7099 Anum_pg_inherits_inhrelid,
7100 BTEqualStrategyNumber, F_OIDEQ,
7101 ObjectIdGetDatum(RelationGetRelid(child_rel)));
7102 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
7103 true, SnapshotNow, 1, &key);
7105 /* inhseqno sequences start at 1 */
7107 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
7109 Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
7111 if (inh->inhparent == RelationGetRelid(parent_rel))
7113 (errcode(ERRCODE_DUPLICATE_TABLE),
7114 errmsg("relation \"%s\" would be inherited from more than once",
7115 RelationGetRelationName(parent_rel))));
7116 if (inh->inhseqno > inhseqno)
7117 inhseqno = inh->inhseqno;
7119 systable_endscan(scan);
7122 * Prevent circularity by seeing if proposed parent inherits from child.
7123 * (In particular, this disallows making a rel inherit from itself.)
7125 * This is not completely bulletproof because of race conditions: in
7126 * multi-level inheritance trees, someone else could concurrently be
7127 * making another inheritance link that closes the loop but does not join
7128 * either of the rels we have locked. Preventing that seems to require
7129 * exclusive locks on the entire inheritance tree, which is a cure worse
7130 * than the disease. find_all_inheritors() will cope with circularity
7131 * anyway, so don't sweat it too much.
7133 * We use weakest lock we can on child's children, namely AccessShareLock.
7135 children = find_all_inheritors(RelationGetRelid(child_rel),
7138 if (list_member_oid(children, RelationGetRelid(parent_rel)))
7140 (errcode(ERRCODE_DUPLICATE_TABLE),
7141 errmsg("circular inheritance not allowed"),
7142 errdetail("\"%s\" is already a child of \"%s\".",
7144 RelationGetRelationName(child_rel))));
7146 /* If parent has OIDs then child must have OIDs */
7147 if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
7149 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7150 errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
7151 RelationGetRelationName(child_rel),
7152 RelationGetRelationName(parent_rel))));
7154 /* Match up the columns and bump attinhcount as needed */
7155 MergeAttributesIntoExisting(child_rel, parent_rel);
7157 /* Match up the constraints and bump coninhcount as needed */
7158 MergeConstraintsIntoExisting(child_rel, parent_rel);
7161 * OK, it looks valid. Make the catalog entries that show inheritance.
7163 StoreCatalogInheritance1(RelationGetRelid(child_rel),
7164 RelationGetRelid(parent_rel),
7168 /* Now we're done with pg_inherits */
7169 heap_close(catalogRelation, RowExclusiveLock);
7171 /* keep our lock on the parent relation until commit */
7172 heap_close(parent_rel, NoLock);
7176 * Obtain the source-text form of the constraint expression for a check
7177 * constraint, given its pg_constraint tuple
7180 decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
7182 Form_pg_constraint con;
7187 con = (Form_pg_constraint) GETSTRUCT(contup);
7188 attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
7190 elog(ERROR, "null conbin for constraint %u", HeapTupleGetOid(contup));
7192 expr = DirectFunctionCall2(pg_get_expr, attr,
7193 ObjectIdGetDatum(con->conrelid));
7194 return TextDatumGetCString(expr);
7198 * Determine whether two check constraints are functionally equivalent
7200 * The test we apply is to see whether they reverse-compile to the same
7201 * source string. This insulates us from issues like whether attributes
7202 * have the same physical column numbers in parent and child relations.
7205 constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
7207 Form_pg_constraint acon = (Form_pg_constraint) GETSTRUCT(a);
7208 Form_pg_constraint bcon = (Form_pg_constraint) GETSTRUCT(b);
7210 if (acon->condeferrable != bcon->condeferrable ||
7211 acon->condeferred != bcon->condeferred ||
7212 strcmp(decompile_conbin(a, tupleDesc),
7213 decompile_conbin(b, tupleDesc)) != 0)
7220 * Check columns in child table match up with columns in parent, and increment
7221 * their attinhcount.
7223 * Called by ATExecAddInherit
7225 * Currently all parent columns must be found in child. Missing columns are an
7226 * error. One day we might consider creating new columns like CREATE TABLE
7227 * does. However, that is widely unpopular --- in the common use case of
7228 * partitioned tables it's a foot-gun.
7230 * The data type must match exactly. If the parent column is NOT NULL then
7231 * the child must be as well. Defaults are not compared, however.
7234 MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel)
7237 AttrNumber parent_attno;
7239 TupleDesc tupleDesc;
7240 TupleConstr *constr;
7243 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
7245 tupleDesc = RelationGetDescr(parent_rel);
7246 parent_natts = tupleDesc->natts;
7247 constr = tupleDesc->constr;
7249 for (parent_attno = 1; parent_attno <= parent_natts; parent_attno++)
7251 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
7252 char *attributeName = NameStr(attribute->attname);
7254 /* Ignore dropped columns in the parent. */
7255 if (attribute->attisdropped)
7258 /* Find same column in child (matching on column name). */
7259 tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel),
7261 if (HeapTupleIsValid(tuple))
7263 /* Check they are same type and typmod */
7264 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
7266 if (attribute->atttypid != childatt->atttypid ||
7267 attribute->atttypmod != childatt->atttypmod)
7269 (errcode(ERRCODE_DATATYPE_MISMATCH),
7270 errmsg("child table \"%s\" has different type for column \"%s\"",
7271 RelationGetRelationName(child_rel),
7274 if (attribute->attnotnull && !childatt->attnotnull)
7276 (errcode(ERRCODE_DATATYPE_MISMATCH),
7277 errmsg("column \"%s\" in child table must be marked NOT NULL",
7281 * OK, bump the child column's inheritance count. (If we fail
7282 * later on, this change will just roll back.)
7284 childatt->attinhcount++;
7285 simple_heap_update(attrrel, &tuple->t_self, tuple);
7286 CatalogUpdateIndexes(attrrel, tuple);
7287 heap_freetuple(tuple);
7292 (errcode(ERRCODE_DATATYPE_MISMATCH),
7293 errmsg("child table is missing column \"%s\"",
7298 heap_close(attrrel, RowExclusiveLock);
7302 * Check constraints in child table match up with constraints in parent,
7303 * and increment their coninhcount.
7305 * Called by ATExecAddInherit
7307 * Currently all constraints in parent must be present in the child. One day we
7308 * may consider adding new constraints like CREATE TABLE does. We may also want
7309 * to allow an optional flag on parent table constraints indicating they are
7310 * intended to ONLY apply to the master table, not to the children. That would
7311 * make it possible to ensure no records are mistakenly inserted into the
7312 * master in partitioned tables rather than the appropriate child.
7314 * XXX This is O(N^2) which may be an issue with tables with hundreds of
7315 * constraints. As long as tables have more like 10 constraints it shouldn't be
7316 * a problem though. Even 100 constraints ought not be the end of the world.
7319 MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
7321 Relation catalog_relation;
7322 TupleDesc tuple_desc;
7323 SysScanDesc parent_scan;
7324 ScanKeyData parent_key;
7325 HeapTuple parent_tuple;
7327 catalog_relation = heap_open(ConstraintRelationId, RowExclusiveLock);
7328 tuple_desc = RelationGetDescr(catalog_relation);
7330 /* Outer loop scans through the parent's constraint definitions */
7331 ScanKeyInit(&parent_key,
7332 Anum_pg_constraint_conrelid,
7333 BTEqualStrategyNumber, F_OIDEQ,
7334 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
7335 parent_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
7336 true, SnapshotNow, 1, &parent_key);
7338 while (HeapTupleIsValid(parent_tuple = systable_getnext(parent_scan)))
7340 Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(parent_tuple);
7341 SysScanDesc child_scan;
7342 ScanKeyData child_key;
7343 HeapTuple child_tuple;
7346 if (parent_con->contype != CONSTRAINT_CHECK)
7349 /* Search for a child constraint matching this one */
7350 ScanKeyInit(&child_key,
7351 Anum_pg_constraint_conrelid,
7352 BTEqualStrategyNumber, F_OIDEQ,
7353 ObjectIdGetDatum(RelationGetRelid(child_rel)));
7354 child_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
7355 true, SnapshotNow, 1, &child_key);
7357 while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
7359 Form_pg_constraint child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
7360 HeapTuple child_copy;
7362 if (child_con->contype != CONSTRAINT_CHECK)
7365 if (strcmp(NameStr(parent_con->conname),
7366 NameStr(child_con->conname)) != 0)
7369 if (!constraints_equivalent(parent_tuple, child_tuple, tuple_desc))
7371 (errcode(ERRCODE_DATATYPE_MISMATCH),
7372 errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
7373 RelationGetRelationName(child_rel),
7374 NameStr(parent_con->conname))));
7377 * OK, bump the child constraint's inheritance count. (If we fail
7378 * later on, this change will just roll back.)
7380 child_copy = heap_copytuple(child_tuple);
7381 child_con = (Form_pg_constraint) GETSTRUCT(child_copy);
7382 child_con->coninhcount++;
7383 simple_heap_update(catalog_relation, &child_copy->t_self, child_copy);
7384 CatalogUpdateIndexes(catalog_relation, child_copy);
7385 heap_freetuple(child_copy);
7391 systable_endscan(child_scan);
7395 (errcode(ERRCODE_DATATYPE_MISMATCH),
7396 errmsg("child table is missing constraint \"%s\"",
7397 NameStr(parent_con->conname))));
7400 systable_endscan(parent_scan);
7401 heap_close(catalog_relation, RowExclusiveLock);
7405 * ALTER TABLE NO INHERIT
7407 * Drop a parent from the child's parents. This just adjusts the attinhcount
7408 * and attislocal of the columns and removes the pg_inherit and pg_depend
7411 * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
7412 * up attislocal stays true, which means if a child is ever removed from a
7413 * parent then its columns will never be automatically dropped which may
7414 * surprise. But at least we'll never surprise by dropping columns someone
7415 * isn't expecting to be dropped which would actually mean data loss.
7417 * coninhcount and conislocal for inherited constraints are adjusted in
7418 * exactly the same way.
7421 ATExecDropInherit(Relation rel, RangeVar *parent)
7423 Relation parent_rel;
7424 Relation catalogRelation;
7427 HeapTuple inheritsTuple,
7435 * AccessShareLock on the parent is probably enough, seeing that DROP
7436 * TABLE doesn't lock parent tables at all. We need some lock since we'll
7437 * be inspecting the parent's schema.
7439 parent_rel = heap_openrv(parent, AccessShareLock);
7442 * We don't bother to check ownership of the parent table --- ownership of
7443 * the child is presumed enough rights.
7447 * Find and destroy the pg_inherits entry linking the two, or error out if
7450 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
7451 ScanKeyInit(&key[0],
7452 Anum_pg_inherits_inhrelid,
7453 BTEqualStrategyNumber, F_OIDEQ,
7454 ObjectIdGetDatum(RelationGetRelid(rel)));
7455 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
7456 true, SnapshotNow, 1, key);
7458 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
7462 inhparent = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
7463 if (inhparent == RelationGetRelid(parent_rel))
7465 simple_heap_delete(catalogRelation, &inheritsTuple->t_self);
7471 systable_endscan(scan);
7472 heap_close(catalogRelation, RowExclusiveLock);
7476 (errcode(ERRCODE_UNDEFINED_TABLE),
7477 errmsg("relation \"%s\" is not a parent of relation \"%s\"",
7478 RelationGetRelationName(parent_rel),
7479 RelationGetRelationName(rel))));
7482 * Search through child columns looking for ones matching parent rel
7484 catalogRelation = heap_open(AttributeRelationId, RowExclusiveLock);
7485 ScanKeyInit(&key[0],
7486 Anum_pg_attribute_attrelid,
7487 BTEqualStrategyNumber, F_OIDEQ,
7488 ObjectIdGetDatum(RelationGetRelid(rel)));
7489 scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
7490 true, SnapshotNow, 1, key);
7491 while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
7493 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
7495 /* Ignore if dropped or not inherited */
7496 if (att->attisdropped)
7498 if (att->attinhcount <= 0)
7501 if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
7502 NameStr(att->attname)))
7504 /* Decrement inhcount and possibly set islocal to true */
7505 HeapTuple copyTuple = heap_copytuple(attributeTuple);
7506 Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
7508 copy_att->attinhcount--;
7509 if (copy_att->attinhcount == 0)
7510 copy_att->attislocal = true;
7512 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
7513 CatalogUpdateIndexes(catalogRelation, copyTuple);
7514 heap_freetuple(copyTuple);
7517 systable_endscan(scan);
7518 heap_close(catalogRelation, RowExclusiveLock);
7521 * Likewise, find inherited check constraints and disinherit them. To do
7522 * this, we first need a list of the names of the parent's check
7523 * constraints. (We cheat a bit by only checking for name matches,
7524 * assuming that the expressions will match.)
7526 catalogRelation = heap_open(ConstraintRelationId, RowExclusiveLock);
7527 ScanKeyInit(&key[0],
7528 Anum_pg_constraint_conrelid,
7529 BTEqualStrategyNumber, F_OIDEQ,
7530 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
7531 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
7532 true, SnapshotNow, 1, key);
7536 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
7538 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
7540 if (con->contype == CONSTRAINT_CHECK)
7541 connames = lappend(connames, pstrdup(NameStr(con->conname)));
7544 systable_endscan(scan);
7546 /* Now scan the child's constraints */
7547 ScanKeyInit(&key[0],
7548 Anum_pg_constraint_conrelid,
7549 BTEqualStrategyNumber, F_OIDEQ,
7550 ObjectIdGetDatum(RelationGetRelid(rel)));
7551 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
7552 true, SnapshotNow, 1, key);
7554 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
7556 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
7560 if (con->contype != CONSTRAINT_CHECK)
7564 foreach(lc, connames)
7566 if (strcmp(NameStr(con->conname), (char *) lfirst(lc)) == 0)
7575 /* Decrement inhcount and possibly set islocal to true */
7576 HeapTuple copyTuple = heap_copytuple(constraintTuple);
7577 Form_pg_constraint copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
7579 if (copy_con->coninhcount <= 0) /* shouldn't happen */
7580 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
7581 RelationGetRelid(rel), NameStr(copy_con->conname));
7583 copy_con->coninhcount--;
7584 if (copy_con->coninhcount == 0)
7585 copy_con->conislocal = true;
7587 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
7588 CatalogUpdateIndexes(catalogRelation, copyTuple);
7589 heap_freetuple(copyTuple);
7593 systable_endscan(scan);
7594 heap_close(catalogRelation, RowExclusiveLock);
7597 * Drop the dependency
7599 * There's no convenient way to do this, so go trawling through pg_depend
7601 catalogRelation = heap_open(DependRelationId, RowExclusiveLock);
7603 ScanKeyInit(&key[0],
7604 Anum_pg_depend_classid,
7605 BTEqualStrategyNumber, F_OIDEQ,
7606 ObjectIdGetDatum(RelationRelationId));
7607 ScanKeyInit(&key[1],
7608 Anum_pg_depend_objid,
7609 BTEqualStrategyNumber, F_OIDEQ,
7610 ObjectIdGetDatum(RelationGetRelid(rel)));
7611 ScanKeyInit(&key[2],
7612 Anum_pg_depend_objsubid,
7613 BTEqualStrategyNumber, F_INT4EQ,
7616 scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
7617 SnapshotNow, 3, key);
7619 while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
7621 Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
7623 if (dep->refclassid == RelationRelationId &&
7624 dep->refobjid == RelationGetRelid(parent_rel) &&
7625 dep->refobjsubid == 0 &&
7626 dep->deptype == DEPENDENCY_NORMAL)
7627 simple_heap_delete(catalogRelation, &depTuple->t_self);
7630 systable_endscan(scan);
7631 heap_close(catalogRelation, RowExclusiveLock);
7633 /* keep our lock on the parent relation until commit */
7634 heap_close(parent_rel, NoLock);
7639 * Execute ALTER TABLE SET SCHEMA
7641 * Note: caller must have checked ownership of the relation already
7644 AlterTableNamespace(RangeVar *relation, const char *newschema,
7645 ObjectType stmttype)
7653 rel = relation_openrv(relation, AccessExclusiveLock);
7655 relid = RelationGetRelid(rel);
7656 oldNspOid = RelationGetNamespace(rel);
7658 /* Check relation type against type specified in the ALTER command */
7664 * For mostly-historical reasons, we allow ALTER TABLE to apply to
7665 * all relation types.
7669 case OBJECT_SEQUENCE:
7670 if (rel->rd_rel->relkind != RELKIND_SEQUENCE)
7672 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7673 errmsg("\"%s\" is not a sequence",
7674 RelationGetRelationName(rel))));
7678 if (rel->rd_rel->relkind != RELKIND_VIEW)
7680 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7681 errmsg("\"%s\" is not a view",
7682 RelationGetRelationName(rel))));
7686 elog(ERROR, "unrecognized object type: %d", (int) stmttype);
7689 /* Can we change the schema of this tuple? */
7690 switch (rel->rd_rel->relkind)
7692 case RELKIND_RELATION:
7694 /* ok to change schema */
7696 case RELKIND_SEQUENCE:
7698 /* if it's an owned sequence, disallow moving it by itself */
7702 if (sequenceIsOwned(relid, &tableId, &colId))
7704 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7705 errmsg("cannot move an owned sequence into another schema"),
7706 errdetail("Sequence \"%s\" is linked to table \"%s\".",
7707 RelationGetRelationName(rel),
7708 get_rel_name(tableId))));
7711 case RELKIND_COMPOSITE_TYPE:
7713 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7714 errmsg("\"%s\" is a composite type",
7715 RelationGetRelationName(rel)),
7716 errhint("Use ALTER TYPE instead.")));
7719 case RELKIND_TOASTVALUE:
7723 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7724 errmsg("\"%s\" is not a table, view, or sequence",
7725 RelationGetRelationName(rel))));
7728 /* get schema OID and check its permissions */
7729 nspOid = LookupCreationNamespace(newschema);
7731 if (oldNspOid == nspOid)
7733 (errcode(ERRCODE_DUPLICATE_TABLE),
7734 errmsg("relation \"%s\" is already in schema \"%s\"",
7735 RelationGetRelationName(rel),
7738 /* disallow renaming into or out of temp schemas */
7739 if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
7741 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7742 errmsg("cannot move objects into or out of temporary schemas")));
7744 /* same for TOAST schema */
7745 if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
7747 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7748 errmsg("cannot move objects into or out of TOAST schema")));
7750 /* OK, modify the pg_class row and pg_depend entry */
7751 classRel = heap_open(RelationRelationId, RowExclusiveLock);
7753 AlterRelationNamespaceInternal(classRel, relid, oldNspOid, nspOid, true);
7755 /* Fix the table's rowtype too */
7756 AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid, false, false);
7758 /* Fix other dependent stuff */
7759 if (rel->rd_rel->relkind == RELKIND_RELATION)
7761 AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid);
7762 AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid, newschema);
7763 AlterConstraintNamespaces(relid, oldNspOid, nspOid, false);
7766 heap_close(classRel, RowExclusiveLock);
7768 /* close rel, but keep lock until commit */
7769 relation_close(rel, NoLock);
7773 * The guts of relocating a relation to another namespace: fix the pg_class
7774 * entry, and the pg_depend entry if any. Caller must already have
7775 * opened and write-locked pg_class.
7778 AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
7779 Oid oldNspOid, Oid newNspOid,
7780 bool hasDependEntry)
7783 Form_pg_class classForm;
7785 classTup = SearchSysCacheCopy(RELOID,
7786 ObjectIdGetDatum(relOid),
7788 if (!HeapTupleIsValid(classTup))
7789 elog(ERROR, "cache lookup failed for relation %u", relOid);
7790 classForm = (Form_pg_class) GETSTRUCT(classTup);
7792 Assert(classForm->relnamespace == oldNspOid);
7794 /* check for duplicate name (more friendly than unique-index failure) */
7795 if (get_relname_relid(NameStr(classForm->relname),
7796 newNspOid) != InvalidOid)
7798 (errcode(ERRCODE_DUPLICATE_TABLE),
7799 errmsg("relation \"%s\" already exists in schema \"%s\"",
7800 NameStr(classForm->relname),
7801 get_namespace_name(newNspOid))));
7803 /* classTup is a copy, so OK to scribble on */
7804 classForm->relnamespace = newNspOid;
7806 simple_heap_update(classRel, &classTup->t_self, classTup);
7807 CatalogUpdateIndexes(classRel, classTup);
7809 /* Update dependency on schema if caller said so */
7810 if (hasDependEntry &&
7811 changeDependencyFor(RelationRelationId, relOid,
7812 NamespaceRelationId, oldNspOid, newNspOid) != 1)
7813 elog(ERROR, "failed to change schema dependency for relation \"%s\"",
7814 NameStr(classForm->relname));
7816 heap_freetuple(classTup);
7820 * Move all indexes for the specified relation to another namespace.
7822 * Note: we assume adequate permission checking was done by the caller,
7823 * and that the caller has a suitable lock on the owning relation.
7826 AlterIndexNamespaces(Relation classRel, Relation rel,
7827 Oid oldNspOid, Oid newNspOid)
7832 indexList = RelationGetIndexList(rel);
7834 foreach(l, indexList)
7836 Oid indexOid = lfirst_oid(l);
7839 * Note: currently, the index will not have its own dependency on the
7840 * namespace, so we don't need to do changeDependencyFor(). There's no
7841 * rowtype in pg_type, either.
7843 AlterRelationNamespaceInternal(classRel, indexOid,
7844 oldNspOid, newNspOid,
7848 list_free(indexList);
7852 * Move all SERIAL-column sequences of the specified relation to another
7855 * Note: we assume adequate permission checking was done by the caller,
7856 * and that the caller has a suitable lock on the owning relation.
7859 AlterSeqNamespaces(Relation classRel, Relation rel,
7860 Oid oldNspOid, Oid newNspOid, const char *newNspName)
7868 * SERIAL sequences are those having an auto dependency on one of the
7869 * table's columns (we don't care *which* column, exactly).
7871 depRel = heap_open(DependRelationId, AccessShareLock);
7873 ScanKeyInit(&key[0],
7874 Anum_pg_depend_refclassid,
7875 BTEqualStrategyNumber, F_OIDEQ,
7876 ObjectIdGetDatum(RelationRelationId));
7877 ScanKeyInit(&key[1],
7878 Anum_pg_depend_refobjid,
7879 BTEqualStrategyNumber, F_OIDEQ,
7880 ObjectIdGetDatum(RelationGetRelid(rel)));
7881 /* we leave refobjsubid unspecified */
7883 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
7884 SnapshotNow, 2, key);
7886 while (HeapTupleIsValid(tup = systable_getnext(scan)))
7888 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
7891 /* skip dependencies other than auto dependencies on columns */
7892 if (depForm->refobjsubid == 0 ||
7893 depForm->classid != RelationRelationId ||
7894 depForm->objsubid != 0 ||
7895 depForm->deptype != DEPENDENCY_AUTO)
7898 /* Use relation_open just in case it's an index */
7899 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
7901 /* skip non-sequence relations */
7902 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
7904 /* No need to keep the lock */
7905 relation_close(seqRel, AccessExclusiveLock);
7909 /* Fix the pg_class and pg_depend entries */
7910 AlterRelationNamespaceInternal(classRel, depForm->objid,
7911 oldNspOid, newNspOid,
7915 * Sequences have entries in pg_type. We need to be careful to move
7916 * them to the new namespace, too.
7918 AlterTypeNamespaceInternal(RelationGetForm(seqRel)->reltype,
7919 newNspOid, false, false);
7921 /* Now we can close it. Keep the lock till end of transaction. */
7922 relation_close(seqRel, NoLock);
7925 systable_endscan(scan);
7927 relation_close(depRel, AccessShareLock);
7932 * This code supports
7933 * CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
7935 * Because we only support this for TEMP tables, it's sufficient to remember
7936 * the state in a backend-local data structure.
7940 * Register a newly-created relation's ON COMMIT action.
7943 register_on_commit_action(Oid relid, OnCommitAction action)
7946 MemoryContext oldcxt;
7949 * We needn't bother registering the relation unless there is an ON COMMIT
7950 * action we need to take.
7952 if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
7955 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
7957 oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
7959 oc->oncommit = action;
7960 oc->creating_subid = GetCurrentSubTransactionId();
7961 oc->deleting_subid = InvalidSubTransactionId;
7963 on_commits = lcons(oc, on_commits);
7965 MemoryContextSwitchTo(oldcxt);
7969 * Unregister any ON COMMIT action when a relation is deleted.
7971 * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
7974 remove_on_commit_action(Oid relid)
7978 foreach(l, on_commits)
7980 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
7982 if (oc->relid == relid)
7984 oc->deleting_subid = GetCurrentSubTransactionId();
7991 * Perform ON COMMIT actions.
7993 * This is invoked just before actually committing, since it's possible
7994 * to encounter errors.
7997 PreCommit_on_commit_actions(void)
8000 List *oids_to_truncate = NIL;
8002 foreach(l, on_commits)
8004 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
8006 /* Ignore entry if already dropped in this xact */
8007 if (oc->deleting_subid != InvalidSubTransactionId)
8010 switch (oc->oncommit)
8013 case ONCOMMIT_PRESERVE_ROWS:
8014 /* Do nothing (there shouldn't be such entries, actually) */
8016 case ONCOMMIT_DELETE_ROWS:
8017 oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
8021 ObjectAddress object;
8023 object.classId = RelationRelationId;
8024 object.objectId = oc->relid;
8025 object.objectSubId = 0;
8026 performDeletion(&object, DROP_CASCADE);
8029 * Note that table deletion will call
8030 * remove_on_commit_action, so the entry should get marked
8033 Assert(oc->deleting_subid != InvalidSubTransactionId);
8038 if (oids_to_truncate != NIL)
8040 heap_truncate(oids_to_truncate);
8041 CommandCounterIncrement(); /* XXX needed? */
8046 * Post-commit or post-abort cleanup for ON COMMIT management.
8048 * All we do here is remove no-longer-needed OnCommitItem entries.
8050 * During commit, remove entries that were deleted during this transaction;
8051 * during abort, remove those created during this transaction.
8054 AtEOXact_on_commit_actions(bool isCommit)
8057 ListCell *prev_item;
8060 cur_item = list_head(on_commits);
8062 while (cur_item != NULL)
8064 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
8066 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
8067 oc->creating_subid != InvalidSubTransactionId)
8069 /* cur_item must be removed */
8070 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
8073 cur_item = lnext(prev_item);
8075 cur_item = list_head(on_commits);
8079 /* cur_item must be preserved */
8080 oc->creating_subid = InvalidSubTransactionId;
8081 oc->deleting_subid = InvalidSubTransactionId;
8082 prev_item = cur_item;
8083 cur_item = lnext(prev_item);
8089 * Post-subcommit or post-subabort cleanup for ON COMMIT management.
8091 * During subabort, we can immediately remove entries created during this
8092 * subtransaction. During subcommit, just relabel entries marked during
8093 * this subtransaction as being the parent's responsibility.
8096 AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
8097 SubTransactionId parentSubid)
8100 ListCell *prev_item;
8103 cur_item = list_head(on_commits);
8105 while (cur_item != NULL)
8107 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
8109 if (!isCommit && oc->creating_subid == mySubid)
8111 /* cur_item must be removed */
8112 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
8115 cur_item = lnext(prev_item);
8117 cur_item = list_head(on_commits);
8121 /* cur_item must be preserved */
8122 if (oc->creating_subid == mySubid)
8123 oc->creating_subid = parentSubid;
8124 if (oc->deleting_subid == mySubid)
8125 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
8126 prev_item = cur_item;
8127 cur_item = lnext(prev_item);