1 /*-------------------------------------------------------------------------
4 * Commands for creating and altering table structures and settings
6 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/commands/tablecmds.c,v 1.263 2008/08/25 22:42:32 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_namespace.h"
33 #include "catalog/pg_opclass.h"
34 #include "catalog/pg_tablespace.h"
35 #include "catalog/pg_trigger.h"
36 #include "catalog/pg_type.h"
37 #include "catalog/pg_type_fn.h"
38 #include "catalog/toasting.h"
39 #include "commands/cluster.h"
40 #include "commands/defrem.h"
41 #include "commands/sequence.h"
42 #include "commands/tablecmds.h"
43 #include "commands/tablespace.h"
44 #include "commands/trigger.h"
45 #include "commands/typecmds.h"
46 #include "executor/executor.h"
47 #include "miscadmin.h"
48 #include "nodes/makefuncs.h"
49 #include "nodes/nodeFuncs.h"
50 #include "nodes/parsenodes.h"
51 #include "optimizer/clauses.h"
52 #include "optimizer/plancat.h"
53 #include "optimizer/prep.h"
54 #include "parser/gramparse.h"
55 #include "parser/parse_clause.h"
56 #include "parser/parse_coerce.h"
57 #include "parser/parse_expr.h"
58 #include "parser/parse_oper.h"
59 #include "parser/parse_relation.h"
60 #include "parser/parse_type.h"
61 #include "parser/parse_utilcmd.h"
62 #include "parser/parser.h"
63 #include "rewrite/rewriteDefine.h"
64 #include "rewrite/rewriteHandler.h"
65 #include "storage/bufmgr.h"
66 #include "storage/lmgr.h"
67 #include "storage/smgr.h"
68 #include "utils/acl.h"
69 #include "utils/builtins.h"
70 #include "utils/fmgroids.h"
71 #include "utils/inval.h"
72 #include "utils/lsyscache.h"
73 #include "utils/memutils.h"
74 #include "utils/relcache.h"
75 #include "utils/snapmgr.h"
76 #include "utils/syscache.h"
77 #include "utils/tqual.h"
81 * ON COMMIT action list
83 typedef struct OnCommitItem
85 Oid relid; /* relid of relation */
86 OnCommitAction oncommit; /* what to do at end of xact */
89 * If this entry was created during the current transaction,
90 * creating_subid is the ID of the creating subxact; if created in a prior
91 * transaction, creating_subid is zero. If deleted during the current
92 * transaction, deleting_subid is the ID of the deleting subxact; if no
93 * deletion request is pending, deleting_subid is zero.
95 SubTransactionId creating_subid;
96 SubTransactionId deleting_subid;
99 static List *on_commits = NIL;
103 * State information for ALTER TABLE
105 * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
106 * structs, one for each table modified by the operation (the named table
107 * plus any child tables that are affected). We save lists of subcommands
108 * to apply to this table (possibly modified by parse transformation steps);
109 * these lists will be executed in Phase 2. If a Phase 3 step is needed,
110 * necessary information is stored in the constraints and newvals lists.
112 * Phase 2 is divided into multiple passes; subcommands are executed in
113 * a pass determined by subcommand type.
116 #define AT_PASS_DROP 0 /* DROP (all flavors) */
117 #define AT_PASS_ALTER_TYPE 1 /* ALTER COLUMN TYPE */
118 #define AT_PASS_OLD_INDEX 2 /* re-add existing indexes */
119 #define AT_PASS_OLD_CONSTR 3 /* re-add existing constraints */
120 #define AT_PASS_COL_ATTRS 4 /* set other column attributes */
121 /* We could support a RENAME COLUMN pass here, but not currently used */
122 #define AT_PASS_ADD_COL 5 /* ADD COLUMN */
123 #define AT_PASS_ADD_INDEX 6 /* ADD indexes */
124 #define AT_PASS_ADD_CONSTR 7 /* ADD constraints, defaults */
125 #define AT_PASS_MISC 8 /* other stuff */
126 #define AT_NUM_PASSES 9
128 typedef struct AlteredTableInfo
130 /* Information saved before any work commences: */
131 Oid relid; /* Relation to work on */
132 char relkind; /* Its relkind */
133 TupleDesc oldDesc; /* Pre-modification tuple descriptor */
134 /* Information saved by Phase 1 for Phase 2: */
135 List *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
136 /* Information saved by Phases 1/2 for Phase 3: */
137 List *constraints; /* List of NewConstraint */
138 List *newvals; /* List of NewColumnValue */
139 bool new_notnull; /* T if we added new NOT NULL constraints */
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 conid; /* OID of pg_constraint entry, if FOREIGN */
156 Node *qual; /* Check expr or FkConstraint struct */
157 List *qualstate; /* Execution state for CHECK */
161 * Struct describing one new column value that needs to be computed during
162 * Phase 3 copy (this could be either a new column with a non-null default, or
163 * a column that we're changing the type of). Columns without such an entry
164 * are just copied from the old table during ATRewriteTable. Note that the
165 * expr is an expression over *old* table values.
167 typedef struct NewColumnValue
169 AttrNumber attnum; /* which column */
170 Expr *expr; /* expression to compute */
171 ExprState *exprstate; /* execution state */
175 * Error-reporting support for RemoveRelations
177 struct dropmsgstrings
180 int nonexistent_code;
181 const char *nonexistent_msg;
182 const char *skipping_msg;
183 const char *nota_msg;
184 const char *drophint_msg;
187 static const struct dropmsgstrings dropmsgstringarray[] = {
189 ERRCODE_UNDEFINED_TABLE,
190 gettext_noop("table \"%s\" does not exist"),
191 gettext_noop("table \"%s\" does not exist, skipping"),
192 gettext_noop("\"%s\" is not a table"),
193 gettext_noop("Use DROP TABLE to remove a table.")},
195 ERRCODE_UNDEFINED_TABLE,
196 gettext_noop("sequence \"%s\" does not exist"),
197 gettext_noop("sequence \"%s\" does not exist, skipping"),
198 gettext_noop("\"%s\" is not a sequence"),
199 gettext_noop("Use DROP SEQUENCE to remove a sequence.")},
201 ERRCODE_UNDEFINED_TABLE,
202 gettext_noop("view \"%s\" does not exist"),
203 gettext_noop("view \"%s\" does not exist, skipping"),
204 gettext_noop("\"%s\" is not a view"),
205 gettext_noop("Use DROP VIEW to remove a view.")},
207 ERRCODE_UNDEFINED_OBJECT,
208 gettext_noop("index \"%s\" does not exist"),
209 gettext_noop("index \"%s\" does not exist, skipping"),
210 gettext_noop("\"%s\" is not an index"),
211 gettext_noop("Use DROP INDEX to remove an index.")},
212 {RELKIND_COMPOSITE_TYPE,
213 ERRCODE_UNDEFINED_OBJECT,
214 gettext_noop("type \"%s\" does not exist"),
215 gettext_noop("type \"%s\" does not exist, skipping"),
216 gettext_noop("\"%s\" is not a type"),
217 gettext_noop("Use DROP TYPE to remove a type.")},
218 {'\0', 0, NULL, NULL, NULL, NULL}
222 static void truncate_check_rel(Relation rel);
223 static List *MergeAttributes(List *schema, List *supers, bool istemp,
224 List **supOids, List **supconstr, int *supOidCount);
225 static bool MergeCheckConstraint(List *constraints, char *name, Node *expr);
226 static bool change_varattnos_walker(Node *node, const AttrNumber *newattno);
227 static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel);
228 static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
229 static void StoreCatalogInheritance(Oid relationId, List *supers);
230 static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
231 int16 seqNumber, Relation inhRelation);
232 static int findAttrByName(const char *attributeName, List *schema);
233 static void setRelhassubclassInRelation(Oid relationId, bool relhassubclass);
234 static void AlterIndexNamespaces(Relation classRel, Relation rel,
235 Oid oldNspOid, Oid newNspOid);
236 static void AlterSeqNamespaces(Relation classRel, Relation rel,
237 Oid oldNspOid, Oid newNspOid,
238 const char *newNspName);
239 static int transformColumnNameList(Oid relId, List *colList,
240 int16 *attnums, Oid *atttypids);
241 static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
243 int16 *attnums, Oid *atttypids,
245 static Oid transformFkeyCheckAttrs(Relation pkrel,
246 int numattrs, int16 *attnums,
248 static void validateForeignKeyConstraint(FkConstraint *fkconstraint,
249 Relation rel, Relation pkrel, Oid constraintOid);
250 static void createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
252 static void ATController(Relation rel, List *cmds, bool recurse);
253 static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
254 bool recurse, bool recursing);
255 static void ATRewriteCatalogs(List **wqueue);
256 static void ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
258 static void ATRewriteTables(List **wqueue);
259 static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap);
260 static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
261 static void ATSimplePermissions(Relation rel, bool allowView);
262 static void ATSimplePermissionsRelationOrIndex(Relation rel);
263 static void ATSimpleRecursion(List **wqueue, Relation rel,
264 AlterTableCmd *cmd, bool recurse);
265 static void ATOneLevelRecursion(List **wqueue, Relation rel,
267 static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
269 static void ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
271 static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
272 static void ATExecDropNotNull(Relation rel, const char *colName);
273 static void ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
274 const char *colName);
275 static void ATExecColumnDefault(Relation rel, const char *colName,
277 static void ATPrepSetStatistics(Relation rel, const char *colName,
279 static void ATExecSetStatistics(Relation rel, const char *colName,
281 static void ATExecSetStorage(Relation rel, const char *colName,
283 static void ATExecDropColumn(Relation rel, const char *colName,
284 DropBehavior behavior,
285 bool recurse, bool recursing);
286 static void ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
287 IndexStmt *stmt, bool is_rebuild);
288 static void ATExecAddConstraint(List **wqueue,
289 AlteredTableInfo *tab, Relation rel,
290 Node *newConstraint, bool recurse);
291 static void ATAddCheckConstraint(List **wqueue,
292 AlteredTableInfo *tab, Relation rel,
294 bool recurse, bool recursing);
295 static void ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
296 FkConstraint *fkconstraint);
297 static void ATExecDropConstraint(Relation rel, const char *constrName,
298 DropBehavior behavior,
299 bool recurse, bool recursing);
300 static void ATPrepAlterColumnType(List **wqueue,
301 AlteredTableInfo *tab, Relation rel,
302 bool recurse, bool recursing,
304 static void ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
305 const char *colName, TypeName *typename);
306 static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab);
307 static void ATPostAlterTypeParse(char *cmd, List **wqueue);
308 static void change_owner_recurse_to_sequences(Oid relationOid,
310 static void ATExecClusterOn(Relation rel, const char *indexName);
311 static void ATExecDropCluster(Relation rel);
312 static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
313 char *tablespacename);
314 static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace);
315 static void ATExecSetRelOptions(Relation rel, List *defList, bool isReset);
316 static void ATExecEnableDisableTrigger(Relation rel, char *trigname,
317 char fires_when, bool skip_system);
318 static void ATExecEnableDisableRule(Relation rel, char *rulename,
320 static void ATExecAddInherit(Relation rel, RangeVar *parent);
321 static void ATExecDropInherit(Relation rel, RangeVar *parent);
322 static void copy_relation_data(SMgrRelation rel, SMgrRelation dst,
323 ForkNumber forkNum, bool istemp);
326 /* ----------------------------------------------------------------
328 * Creates a new relation.
330 * If successful, returns the OID of the new relation.
331 * ----------------------------------------------------------------
334 DefineRelation(CreateStmt *stmt, char relkind)
336 char relname[NAMEDATALEN];
338 List *schema = stmt->tableElts;
342 TupleDesc descriptor;
344 List *old_constraints;
348 List *cookedDefaults;
354 * Truncate relname to appropriate length (probably a waste of time, as
355 * parser should have done this already).
357 StrNCpy(relname, stmt->relation->relname, NAMEDATALEN);
360 * Check consistency of arguments
362 if (stmt->oncommit != ONCOMMIT_NOOP && !stmt->relation->istemp)
364 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
365 errmsg("ON COMMIT can only be used on temporary tables")));
368 * Look up the namespace in which we are supposed to create the relation.
369 * Check we have permission to create there. Skip check if bootstrapping,
370 * since permissions machinery may not be working yet.
372 namespaceId = RangeVarGetCreationNamespace(stmt->relation);
374 if (!IsBootstrapProcessingMode())
378 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
380 if (aclresult != ACLCHECK_OK)
381 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
382 get_namespace_name(namespaceId));
386 * Select tablespace to use. If not specified, use default tablespace
387 * (which may in turn default to database's default).
389 if (stmt->tablespacename)
391 tablespaceId = get_tablespace_oid(stmt->tablespacename);
392 if (!OidIsValid(tablespaceId))
394 (errcode(ERRCODE_UNDEFINED_OBJECT),
395 errmsg("tablespace \"%s\" does not exist",
396 stmt->tablespacename)));
400 tablespaceId = GetDefaultTablespace(stmt->relation->istemp);
401 /* note InvalidOid is OK in this case */
404 /* Check permissions except when using database's default */
405 if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
409 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
411 if (aclresult != ACLCHECK_OK)
412 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
413 get_tablespace_name(tablespaceId));
417 * Parse and validate reloptions, if any.
419 reloptions = transformRelOptions((Datum) 0, stmt->options, true, false);
421 (void) heap_reloptions(relkind, reloptions, true);
424 * Look up inheritance ancestors and generate relation schema, including
425 * inherited attributes.
427 schema = MergeAttributes(schema, stmt->inhRelations,
428 stmt->relation->istemp,
429 &inheritOids, &old_constraints, &parentOidCount);
432 * Create a tuple descriptor from the relation schema. Note that this
433 * deals with column names, types, and NOT NULL constraints, but not
434 * default values or CHECK constraints; we handle those below.
436 descriptor = BuildDescForRelation(schema);
438 localHasOids = interpretOidsOption(stmt->options);
439 descriptor->tdhasoid = (localHasOids || parentOidCount > 0);
442 * Find columns with default values and prepare for insertion of the
443 * defaults. Pre-cooked (that is, inherited) defaults go into a list of
444 * CookedConstraint structs that we'll pass to heap_create_with_catalog,
445 * while raw defaults go into a list of RawColumnDefault structs that
446 * will be processed by AddRelationNewConstraints. (We can't deal with
447 * raw expressions until we can do transformExpr.)
449 * We can set the atthasdef flags now in the tuple descriptor; this just
450 * saves StoreAttrDefault from having to do an immediate update of the
454 cookedDefaults = NIL;
457 foreach(listptr, schema)
459 ColumnDef *colDef = lfirst(listptr);
463 if (colDef->raw_default != NULL)
465 RawColumnDefault *rawEnt;
467 Assert(colDef->cooked_default == NULL);
469 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
470 rawEnt->attnum = attnum;
471 rawEnt->raw_default = colDef->raw_default;
472 rawDefaults = lappend(rawDefaults, rawEnt);
473 descriptor->attrs[attnum - 1]->atthasdef = true;
475 else if (colDef->cooked_default != NULL)
477 CookedConstraint *cooked;
479 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
480 cooked->contype = CONSTR_DEFAULT;
482 cooked->attnum = attnum;
483 cooked->expr = stringToNode(colDef->cooked_default);
484 cooked->is_local = true; /* not used for defaults */
485 cooked->inhcount = 0; /* ditto */
486 cookedDefaults = lappend(cookedDefaults, cooked);
487 descriptor->attrs[attnum - 1]->atthasdef = true;
492 * Create the relation. Inherited defaults and constraints are passed
493 * in for immediate handling --- since they don't need parsing, they
494 * can be stored immediately.
496 relationId = heap_create_with_catalog(relname,
502 list_concat(cookedDefaults,
510 allowSystemTableMods);
512 StoreCatalogInheritance(relationId, inheritOids);
515 * We must bump the command counter to make the newly-created relation
516 * tuple visible for opening.
518 CommandCounterIncrement();
521 * Open the new relation and acquire exclusive lock on it. This isn't
522 * really necessary for locking out other backends (since they can't see
523 * the new rel anyway until we commit), but it keeps the lock manager from
524 * complaining about deadlock risks.
526 rel = relation_open(relationId, AccessExclusiveLock);
529 * Now add any newly specified column default values and CHECK constraints
530 * to the new relation. These are passed to us in the form of raw
531 * parsetrees; we need to transform them to executable expression trees
532 * before they can be added. The most convenient way to do that is to
533 * apply the parser's transformExpr routine, but transformExpr doesn't
534 * work unless we have a pre-existing relation. So, the transformation has
535 * to be postponed to this final step of CREATE TABLE.
537 if (rawDefaults || stmt->constraints)
538 AddRelationNewConstraints(rel, rawDefaults, stmt->constraints,
542 * Clean up. We keep lock on new relation (although it shouldn't be
543 * visible to anyone else anyway, until commit).
545 relation_close(rel, NoLock);
551 * Emit the right error or warning message for a "DROP" command issued on a
552 * non-existent relation
555 DropErrorMsgNonExistent(const char *relname, char rightkind, bool missing_ok)
557 const struct dropmsgstrings *rentry;
559 for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
561 if (rentry->kind == rightkind)
566 (errcode(rentry->nonexistent_code),
567 errmsg(rentry->nonexistent_msg, relname)));
571 ereport(NOTICE, (errmsg(rentry->skipping_msg, relname)));
577 Assert(rentry->kind != '\0'); /* Should be impossible */
581 * Emit the right error message for a "DROP" command issued on a
582 * relation of the wrong type
585 DropErrorMsgWrongType(const char *relname, char wrongkind, char rightkind)
587 const struct dropmsgstrings *rentry;
588 const struct dropmsgstrings *wentry;
590 for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
591 if (rentry->kind == rightkind)
593 Assert(rentry->kind != '\0');
595 for (wentry = dropmsgstringarray; wentry->kind != '\0'; wentry++)
596 if (wentry->kind == wrongkind)
598 /* wrongkind could be something we don't have in our table... */
601 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
602 errmsg(rentry->nota_msg, relname),
603 (wentry->kind != '\0') ? errhint(wentry->drophint_msg) : 0));
608 * Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW
611 RemoveRelations(DropStmt *drop)
613 ObjectAddresses *objects;
618 * First we identify all the relations, then we delete them in a single
619 * performMultipleDeletions() call. This is to avoid unwanted
620 * DROP RESTRICT errors if one of the relations depends on another.
623 /* Determine required relkind */
624 switch (drop->removeType)
627 relkind = RELKIND_RELATION;
631 relkind = RELKIND_INDEX;
634 case OBJECT_SEQUENCE:
635 relkind = RELKIND_SEQUENCE;
639 relkind = RELKIND_VIEW;
643 elog(ERROR, "unrecognized drop object type: %d",
644 (int) drop->removeType);
645 relkind = 0; /* keep compiler quiet */
649 /* Lock and validate each relation; build a list of object addresses */
650 objects = new_object_addresses();
652 foreach(cell, drop->objects)
654 RangeVar *rel = makeRangeVarFromNameList((List *) lfirst(cell));
657 Form_pg_class classform;
661 * These next few steps are a great deal like relation_openrv, but we
662 * don't bother building a relcache entry since we don't need it.
664 * Check for shared-cache-inval messages before trying to access the
665 * relation. This is needed to cover the case where the name
666 * identifies a rel that has been dropped and recreated since the
667 * start of our transaction: if we don't flush the old syscache entry,
668 * then we'll latch onto that entry and suffer an error later.
670 AcceptInvalidationMessages();
672 /* Look up the appropriate relation using namespace search */
673 relOid = RangeVarGetRelid(rel, true);
676 if (!OidIsValid(relOid))
678 DropErrorMsgNonExistent(rel->relname, relkind, drop->missing_ok);
683 * In DROP INDEX, attempt to acquire lock on the parent table before
684 * locking the index. index_drop() will need this anyway, and since
685 * regular queries lock tables before their indexes, we risk deadlock
686 * if we do it the other way around. No error if we don't find a
687 * pg_index entry, though --- that most likely means it isn't an
688 * index, and we'll fail below.
690 if (relkind == RELKIND_INDEX)
692 tuple = SearchSysCache(INDEXRELID,
693 ObjectIdGetDatum(relOid),
695 if (HeapTupleIsValid(tuple))
697 Form_pg_index index = (Form_pg_index) GETSTRUCT(tuple);
699 LockRelationOid(index->indrelid, AccessExclusiveLock);
700 ReleaseSysCache(tuple);
704 /* Get the lock before trying to fetch the syscache entry */
705 LockRelationOid(relOid, AccessExclusiveLock);
707 tuple = SearchSysCache(RELOID,
708 ObjectIdGetDatum(relOid),
710 if (!HeapTupleIsValid(tuple))
711 elog(ERROR, "cache lookup failed for relation %u", relOid);
712 classform = (Form_pg_class) GETSTRUCT(tuple);
714 if (classform->relkind != relkind)
715 DropErrorMsgWrongType(rel->relname, classform->relkind, relkind);
717 /* Allow DROP to either table owner or schema owner */
718 if (!pg_class_ownercheck(relOid, GetUserId()) &&
719 !pg_namespace_ownercheck(classform->relnamespace, GetUserId()))
720 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
723 if (!allowSystemTableMods && IsSystemClass(classform))
725 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
726 errmsg("permission denied: \"%s\" is a system catalog",
729 /* OK, we're ready to delete this one */
730 obj.classId = RelationRelationId;
731 obj.objectId = relOid;
734 add_exact_object_address(&obj, objects);
736 ReleaseSysCache(tuple);
739 performMultipleDeletions(objects, drop->behavior);
741 free_object_addresses(objects);
746 * Executes a TRUNCATE command.
748 * This is a multi-relation truncate. We first open and grab exclusive
749 * lock on all relations involved, checking permissions and otherwise
750 * verifying that the relation is OK for truncation. In CASCADE mode,
751 * relations having FK references to the targeted relations are automatically
752 * added to the group; in RESTRICT mode, we check that all FK references are
753 * internal to the group that's being truncated. Finally all the relations
754 * are truncated and reindexed.
757 ExecuteTruncate(TruncateStmt *stmt)
761 List *seq_relids = NIL;
763 ResultRelInfo *resultRelInfos;
764 ResultRelInfo *resultRelInfo;
768 * Open, exclusive-lock, and check all the explicitly-specified relations
770 foreach(cell, stmt->relations)
772 RangeVar *rv = lfirst(cell);
775 rel = heap_openrv(rv, AccessExclusiveLock);
776 /* don't throw error for "TRUNCATE foo, foo" */
777 if (list_member_oid(relids, RelationGetRelid(rel)))
779 heap_close(rel, AccessExclusiveLock);
782 truncate_check_rel(rel);
783 rels = lappend(rels, rel);
784 relids = lappend_oid(relids, RelationGetRelid(rel));
788 * In CASCADE mode, suck in all referencing relations as well. This
789 * requires multiple iterations to find indirectly-dependent relations. At
790 * each phase, we need to exclusive-lock new rels before looking for their
791 * dependencies, else we might miss something. Also, we check each rel as
792 * soon as we open it, to avoid a faux pas such as holding lock for a long
793 * time on a rel we have no permissions for.
795 if (stmt->behavior == DROP_CASCADE)
801 newrelids = heap_truncate_find_FKs(relids);
802 if (newrelids == NIL)
803 break; /* nothing else to add */
805 foreach(cell, newrelids)
807 Oid relid = lfirst_oid(cell);
810 rel = heap_open(relid, AccessExclusiveLock);
812 (errmsg("truncate cascades to table \"%s\"",
813 RelationGetRelationName(rel))));
814 truncate_check_rel(rel);
815 rels = lappend(rels, rel);
816 relids = lappend_oid(relids, relid);
822 * Check foreign key references. In CASCADE mode, this should be
823 * unnecessary since we just pulled in all the references; but as a
824 * cross-check, do it anyway if in an Assert-enabled build.
826 #ifdef USE_ASSERT_CHECKING
827 heap_truncate_check_FKs(rels, false);
829 if (stmt->behavior == DROP_RESTRICT)
830 heap_truncate_check_FKs(rels, false);
834 * If we are asked to restart sequences, find all the sequences,
835 * lock them (we only need AccessShareLock because that's all that
836 * ALTER SEQUENCE takes), and check permissions. We want to do this
837 * early since it's pointless to do all the truncation work only to fail
838 * on sequence permissions.
840 if (stmt->restart_seqs)
844 Relation rel = (Relation) lfirst(cell);
845 List *seqlist = getOwnedSequences(RelationGetRelid(rel));
848 foreach(seqcell, seqlist)
850 Oid seq_relid = lfirst_oid(seqcell);
853 seq_rel = relation_open(seq_relid, AccessShareLock);
855 /* This check must match AlterSequence! */
856 if (!pg_class_ownercheck(seq_relid, GetUserId()))
857 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
858 RelationGetRelationName(seq_rel));
860 seq_relids = lappend_oid(seq_relids, seq_relid);
862 relation_close(seq_rel, NoLock);
867 /* Prepare to catch AFTER triggers. */
868 AfterTriggerBeginQuery();
871 * To fire triggers, we'll need an EState as well as a ResultRelInfo
874 estate = CreateExecutorState();
875 resultRelInfos = (ResultRelInfo *)
876 palloc(list_length(rels) * sizeof(ResultRelInfo));
877 resultRelInfo = resultRelInfos;
880 Relation rel = (Relation) lfirst(cell);
882 InitResultRelInfo(resultRelInfo,
884 0, /* dummy rangetable index */
885 CMD_DELETE, /* don't need any index info */
889 estate->es_result_relations = resultRelInfos;
890 estate->es_num_result_relations = list_length(rels);
893 * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
894 * truncating (this is because one of them might throw an error).
895 * Also, if we were to allow them to prevent statement execution,
896 * that would need to be handled here.
898 resultRelInfo = resultRelInfos;
901 estate->es_result_relation_info = resultRelInfo;
902 ExecBSTruncateTriggers(estate, resultRelInfo);
907 * OK, truncate each table.
911 Relation rel = (Relation) lfirst(cell);
916 * Create a new empty storage file for the relation, and assign it as
917 * the relfilenode value. The old storage file is scheduled for
918 * deletion at commit.
920 setNewRelfilenode(rel, RecentXmin);
922 heap_relid = RelationGetRelid(rel);
923 toast_relid = rel->rd_rel->reltoastrelid;
926 * The same for the toast table, if any.
928 if (OidIsValid(toast_relid))
930 rel = relation_open(toast_relid, AccessExclusiveLock);
931 setNewRelfilenode(rel, RecentXmin);
932 heap_close(rel, NoLock);
936 * Reconstruct the indexes to match, and we're done.
938 reindex_relation(heap_relid, true);
942 * Process all AFTER STATEMENT TRUNCATE triggers.
944 resultRelInfo = resultRelInfos;
947 estate->es_result_relation_info = resultRelInfo;
948 ExecASTruncateTriggers(estate, resultRelInfo);
952 /* Handle queued AFTER triggers */
953 AfterTriggerEndQuery(estate);
955 /* We can clean up the EState now */
956 FreeExecutorState(estate);
958 /* And close the rels (can't do this while EState still holds refs) */
961 Relation rel = (Relation) lfirst(cell);
963 heap_close(rel, NoLock);
967 * Lastly, restart any owned sequences if we were asked to. This is done
968 * last because it's nontransactional: restarts will not roll back if
969 * we abort later. Hence it's important to postpone them as long as
970 * possible. (This is also a big reason why we locked and
971 * permission-checked the sequences beforehand.)
973 if (stmt->restart_seqs)
975 List *options = list_make1(makeDefElem("restart", NULL));
977 foreach(cell, seq_relids)
979 Oid seq_relid = lfirst_oid(cell);
981 AlterSequenceInternal(seq_relid, options);
987 * Check that a given rel is safe to truncate. Subroutine for ExecuteTruncate
990 truncate_check_rel(Relation rel)
992 /* Only allow truncate on regular tables */
993 if (rel->rd_rel->relkind != RELKIND_RELATION)
995 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
996 errmsg("\"%s\" is not a table",
997 RelationGetRelationName(rel))));
999 /* Permissions checks */
1000 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
1001 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1002 RelationGetRelationName(rel));
1004 if (!allowSystemTableMods && IsSystemRelation(rel))
1006 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1007 errmsg("permission denied: \"%s\" is a system catalog",
1008 RelationGetRelationName(rel))));
1011 * We can never allow truncation of shared or nailed-in-cache relations,
1012 * because we can't support changing their relfilenode values.
1014 if (rel->rd_rel->relisshared || rel->rd_isnailed)
1016 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1017 errmsg("cannot truncate system relation \"%s\"",
1018 RelationGetRelationName(rel))));
1021 * Don't allow truncate on temp tables of other backends ... their local
1022 * buffer manager is not going to cope.
1024 if (isOtherTempNamespace(RelationGetNamespace(rel)))
1026 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1027 errmsg("cannot truncate temporary tables of other sessions")));
1030 * Also check for active uses of the relation in the current transaction,
1031 * including open scans and pending AFTER trigger events.
1033 CheckTableNotInUse(rel, "TRUNCATE");
1038 * Returns new schema given initial schema and superclasses.
1041 * 'schema' is the column/attribute definition for the table. (It's a list
1042 * of ColumnDef's.) It is destructively changed.
1043 * 'supers' is a list of names (as RangeVar nodes) of parent relations.
1044 * 'istemp' is TRUE if we are creating a temp relation.
1047 * 'supOids' receives a list of the OIDs of the parent relations.
1048 * 'supconstr' receives a list of constraints belonging to the parents,
1049 * updated as necessary to be valid for the child.
1050 * 'supOidCount' is set to the number of parents that have OID columns.
1053 * Completed schema list.
1056 * The order in which the attributes are inherited is very important.
1057 * Intuitively, the inherited attributes should come first. If a table
1058 * inherits from multiple parents, the order of those attributes are
1059 * according to the order of the parents specified in CREATE TABLE.
1061 * Here's an example:
1063 * create table person (name text, age int4, location point);
1064 * create table emp (salary int4, manager text) inherits(person);
1065 * create table student (gpa float8) inherits (person);
1066 * create table stud_emp (percent int4) inherits (emp, student);
1068 * The order of the attributes of stud_emp is:
1070 * person {1:name, 2:age, 3:location}
1072 * {6:gpa} student emp {4:salary, 5:manager}
1074 * stud_emp {7:percent}
1076 * If the same attribute name appears multiple times, then it appears
1077 * in the result table in the proper location for its first appearance.
1079 * Constraints (including NOT NULL constraints) for the child table
1080 * are the union of all relevant constraints, from both the child schema
1081 * and parent tables.
1083 * The default value for a child column is defined as:
1084 * (1) If the child schema specifies a default, that value is used.
1085 * (2) If neither the child nor any parent specifies a default, then
1086 * the column will not have a default.
1087 * (3) If conflicting defaults are inherited from different parents
1088 * (and not overridden by the child), an error is raised.
1089 * (4) Otherwise the inherited default is used.
1090 * Rule (3) is new in Postgres 7.1; in earlier releases you got a
1091 * rather arbitrary choice of which parent default to use.
1095 MergeAttributes(List *schema, List *supers, bool istemp,
1096 List **supOids, List **supconstr, int *supOidCount)
1099 List *inhSchema = NIL;
1100 List *parentOids = NIL;
1101 List *constraints = NIL;
1102 int parentsWithOids = 0;
1103 bool have_bogus_defaults = false;
1104 char *bogus_marker = "Bogus!"; /* marks conflicting defaults */
1108 * Check for and reject tables with too many columns. We perform this
1109 * check relatively early for two reasons: (a) we don't run the risk of
1110 * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
1111 * okay if we're processing <= 1600 columns, but could take minutes to
1112 * execute if the user attempts to create a table with hundreds of
1113 * thousands of columns.
1115 * Note that we also need to check that any we do not exceed this figure
1116 * after including columns from inherited relations.
1118 if (list_length(schema) > MaxHeapAttributeNumber)
1120 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1121 errmsg("tables can have at most %d columns",
1122 MaxHeapAttributeNumber)));
1125 * Check for duplicate names in the explicit list of attributes.
1127 * Although we might consider merging such entries in the same way that we
1128 * handle name conflicts for inherited attributes, it seems to make more
1129 * sense to assume such conflicts are errors.
1131 foreach(entry, schema)
1133 ColumnDef *coldef = lfirst(entry);
1136 for_each_cell(rest, lnext(entry))
1138 ColumnDef *restdef = lfirst(rest);
1140 if (strcmp(coldef->colname, restdef->colname) == 0)
1142 (errcode(ERRCODE_DUPLICATE_COLUMN),
1143 errmsg("column \"%s\" specified more than once",
1149 * Scan the parents left-to-right, and merge their attributes to form a
1150 * list of inherited attributes (inhSchema). Also check to see if we need
1151 * to inherit an OID column.
1154 foreach(entry, supers)
1156 RangeVar *parent = (RangeVar *) lfirst(entry);
1158 TupleDesc tupleDesc;
1159 TupleConstr *constr;
1160 AttrNumber *newattno;
1161 AttrNumber parent_attno;
1163 relation = heap_openrv(parent, AccessShareLock);
1165 if (relation->rd_rel->relkind != RELKIND_RELATION)
1167 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1168 errmsg("inherited relation \"%s\" is not a table",
1170 /* Permanent rels cannot inherit from temporary ones */
1171 if (!istemp && isTempNamespace(RelationGetNamespace(relation)))
1173 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1174 errmsg("cannot inherit from temporary relation \"%s\"",
1178 * We should have an UNDER permission flag for this, but for now,
1179 * demand that creator of a child table own the parent.
1181 if (!pg_class_ownercheck(RelationGetRelid(relation), GetUserId()))
1182 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1183 RelationGetRelationName(relation));
1186 * Reject duplications in the list of parents.
1188 if (list_member_oid(parentOids, RelationGetRelid(relation)))
1190 (errcode(ERRCODE_DUPLICATE_TABLE),
1191 errmsg("relation \"%s\" would be inherited from more than once",
1194 parentOids = lappend_oid(parentOids, RelationGetRelid(relation));
1196 if (relation->rd_rel->relhasoids)
1199 tupleDesc = RelationGetDescr(relation);
1200 constr = tupleDesc->constr;
1203 * newattno[] will contain the child-table attribute numbers for the
1204 * attributes of this parent table. (They are not the same for
1205 * parents after the first one, nor if we have dropped columns.)
1207 newattno = (AttrNumber *)
1208 palloc(tupleDesc->natts * sizeof(AttrNumber));
1210 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1213 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
1214 char *attributeName = NameStr(attribute->attname);
1219 * Ignore dropped columns in the parent.
1221 if (attribute->attisdropped)
1224 * change_varattnos_of_a_node asserts that this is greater
1225 * than zero, so if anything tries to use it, we should find
1228 newattno[parent_attno - 1] = 0;
1233 * Does it conflict with some previously inherited column?
1235 exist_attno = findAttrByName(attributeName, inhSchema);
1236 if (exist_attno > 0)
1242 * Yes, try to merge the two column definitions. They must
1243 * have the same type and typmod.
1246 (errmsg("merging multiple inherited definitions of column \"%s\"",
1248 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1249 defTypeId = typenameTypeId(NULL, def->typename, &deftypmod);
1250 if (defTypeId != attribute->atttypid ||
1251 deftypmod != attribute->atttypmod)
1253 (errcode(ERRCODE_DATATYPE_MISMATCH),
1254 errmsg("inherited column \"%s\" has a type conflict",
1256 errdetail("%s versus %s",
1257 TypeNameToString(def->typename),
1258 format_type_be(attribute->atttypid))));
1260 /* Merge of NOT NULL constraints = OR 'em together */
1261 def->is_not_null |= attribute->attnotnull;
1262 /* Default and other constraints are handled below */
1263 newattno[parent_attno - 1] = exist_attno;
1268 * No, create a new inherited column
1270 def = makeNode(ColumnDef);
1271 def->colname = pstrdup(attributeName);
1272 def->typename = makeTypeNameFromOid(attribute->atttypid,
1273 attribute->atttypmod);
1275 def->is_local = false;
1276 def->is_not_null = attribute->attnotnull;
1277 def->raw_default = NULL;
1278 def->cooked_default = NULL;
1279 def->constraints = NIL;
1280 inhSchema = lappend(inhSchema, def);
1281 newattno[parent_attno - 1] = ++child_attno;
1285 * Copy default if any
1287 if (attribute->atthasdef)
1289 char *this_default = NULL;
1290 AttrDefault *attrdef;
1293 /* Find default in constraint structure */
1294 Assert(constr != NULL);
1295 attrdef = constr->defval;
1296 for (i = 0; i < constr->num_defval; i++)
1298 if (attrdef[i].adnum == parent_attno)
1300 this_default = attrdef[i].adbin;
1304 Assert(this_default != NULL);
1307 * If default expr could contain any vars, we'd need to fix
1308 * 'em, but it can't; so default is ready to apply to child.
1310 * If we already had a default from some prior parent, check
1311 * to see if they are the same. If so, no problem; if not,
1312 * mark the column as having a bogus default. Below, we will
1313 * complain if the bogus default isn't overridden by the child
1316 Assert(def->raw_default == NULL);
1317 if (def->cooked_default == NULL)
1318 def->cooked_default = pstrdup(this_default);
1319 else if (strcmp(def->cooked_default, this_default) != 0)
1321 def->cooked_default = bogus_marker;
1322 have_bogus_defaults = true;
1328 * Now copy the CHECK constraints of this parent, adjusting attnos
1329 * using the completed newattno[] map. Identically named constraints
1330 * are merged if possible, else we throw error.
1332 if (constr && constr->num_check > 0)
1334 ConstrCheck *check = constr->check;
1337 for (i = 0; i < constr->num_check; i++)
1339 char *name = check[i].ccname;
1342 /* adjust varattnos of ccbin here */
1343 expr = stringToNode(check[i].ccbin);
1344 change_varattnos_of_a_node(expr, newattno);
1346 /* check for duplicate */
1347 if (!MergeCheckConstraint(constraints, name, expr))
1349 /* nope, this is a new one */
1350 CookedConstraint *cooked;
1352 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1353 cooked->contype = CONSTR_CHECK;
1354 cooked->name = pstrdup(name);
1355 cooked->attnum = 0; /* not used for constraints */
1356 cooked->expr = expr;
1357 cooked->is_local = false;
1358 cooked->inhcount = 1;
1359 constraints = lappend(constraints, cooked);
1367 * Close the parent rel, but keep our AccessShareLock on it until xact
1368 * commit. That will prevent someone else from deleting or ALTERing
1369 * the parent before the child is committed.
1371 heap_close(relation, NoLock);
1375 * If we had no inherited attributes, the result schema is just the
1376 * explicitly declared columns. Otherwise, we need to merge the declared
1377 * columns into the inherited schema list.
1379 if (inhSchema != NIL)
1381 foreach(entry, schema)
1383 ColumnDef *newdef = lfirst(entry);
1384 char *attributeName = newdef->colname;
1388 * Does it conflict with some previously inherited column?
1390 exist_attno = findAttrByName(attributeName, inhSchema);
1391 if (exist_attno > 0)
1400 * Yes, try to merge the two column definitions. They must
1401 * have the same type and typmod.
1404 (errmsg("merging column \"%s\" with inherited definition",
1406 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1407 defTypeId = typenameTypeId(NULL, def->typename, &deftypmod);
1408 newTypeId = typenameTypeId(NULL, newdef->typename, &newtypmod);
1409 if (defTypeId != newTypeId || deftypmod != newtypmod)
1411 (errcode(ERRCODE_DATATYPE_MISMATCH),
1412 errmsg("column \"%s\" has a type conflict",
1414 errdetail("%s versus %s",
1415 TypeNameToString(def->typename),
1416 TypeNameToString(newdef->typename))));
1417 /* Mark the column as locally defined */
1418 def->is_local = true;
1419 /* Merge of NOT NULL constraints = OR 'em together */
1420 def->is_not_null |= newdef->is_not_null;
1421 /* If new def has a default, override previous default */
1422 if (newdef->raw_default != NULL)
1424 def->raw_default = newdef->raw_default;
1425 def->cooked_default = newdef->cooked_default;
1431 * No, attach new column to result schema
1433 inhSchema = lappend(inhSchema, newdef);
1440 * Check that we haven't exceeded the legal # of columns after merging
1441 * in inherited columns.
1443 if (list_length(schema) > MaxHeapAttributeNumber)
1445 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1446 errmsg("tables can have at most %d columns",
1447 MaxHeapAttributeNumber)));
1451 * If we found any conflicting parent default values, check to make sure
1452 * they were overridden by the child.
1454 if (have_bogus_defaults)
1456 foreach(entry, schema)
1458 ColumnDef *def = lfirst(entry);
1460 if (def->cooked_default == bogus_marker)
1462 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
1463 errmsg("column \"%s\" inherits conflicting default values",
1465 errhint("To resolve the conflict, specify a default explicitly.")));
1469 *supOids = parentOids;
1470 *supconstr = constraints;
1471 *supOidCount = parentsWithOids;
1477 * MergeCheckConstraint
1478 * Try to merge an inherited CHECK constraint with previous ones
1480 * If we inherit identically-named constraints from multiple parents, we must
1481 * merge them, or throw an error if they don't have identical definitions.
1483 * constraints is a list of CookedConstraint structs for previous constraints.
1485 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
1486 * got a so-far-unique name, or throws error if conflict.
1489 MergeCheckConstraint(List *constraints, char *name, Node *expr)
1493 foreach(lc, constraints)
1495 CookedConstraint *ccon = (CookedConstraint *) lfirst(lc);
1497 Assert(ccon->contype == CONSTR_CHECK);
1499 /* Non-matching names never conflict */
1500 if (strcmp(ccon->name, name) != 0)
1503 if (equal(expr, ccon->expr))
1511 (errcode(ERRCODE_DUPLICATE_OBJECT),
1512 errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
1521 * Replace varattno values in an expression tree according to the given
1522 * map array, that is, varattno N is replaced by newattno[N-1]. It is
1523 * caller's responsibility to ensure that the array is long enough to
1524 * define values for all user varattnos present in the tree. System column
1525 * attnos remain unchanged.
1527 * Note that the passed node tree is modified in-place!
1530 change_varattnos_of_a_node(Node *node, const AttrNumber *newattno)
1532 /* no setup needed, so away we go */
1533 (void) change_varattnos_walker(node, newattno);
1537 change_varattnos_walker(Node *node, const AttrNumber *newattno)
1543 Var *var = (Var *) node;
1545 if (var->varlevelsup == 0 && var->varno == 1 &&
1549 * ??? the following may be a problem when the node is multiply
1550 * referenced though stringToNode() doesn't create such a node
1553 Assert(newattno[var->varattno - 1] > 0);
1554 var->varattno = var->varoattno = newattno[var->varattno - 1];
1558 return expression_tree_walker(node, change_varattnos_walker,
1563 * Generate a map for change_varattnos_of_a_node from old and new TupleDesc's,
1564 * matching according to column name.
1567 varattnos_map(TupleDesc old, TupleDesc new)
1573 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * old->natts);
1574 for (i = 1; i <= old->natts; i++)
1576 if (old->attrs[i - 1]->attisdropped)
1577 continue; /* leave the entry as zero */
1579 for (j = 1; j <= new->natts; j++)
1581 if (strcmp(NameStr(old->attrs[i - 1]->attname),
1582 NameStr(new->attrs[j - 1]->attname)) == 0)
1593 * Generate a map for change_varattnos_of_a_node from a TupleDesc and a list
1597 varattnos_map_schema(TupleDesc old, List *schema)
1602 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * old->natts);
1603 for (i = 1; i <= old->natts; i++)
1605 if (old->attrs[i - 1]->attisdropped)
1606 continue; /* leave the entry as zero */
1608 attmap[i - 1] = findAttrByName(NameStr(old->attrs[i - 1]->attname),
1616 * StoreCatalogInheritance
1617 * Updates the system catalogs with proper inheritance information.
1619 * supers is a list of the OIDs of the new relation's direct ancestors.
1622 StoreCatalogInheritance(Oid relationId, List *supers)
1631 AssertArg(OidIsValid(relationId));
1637 * Store INHERITS information in pg_inherits using direct ancestors only.
1638 * Also enter dependencies on the direct ancestors, and make sure they are
1639 * marked with relhassubclass = true.
1641 * (Once upon a time, both direct and indirect ancestors were found here
1642 * and then entered into pg_ipl. Since that catalog doesn't exist
1643 * anymore, there's no need to look for indirect ancestors.)
1645 relation = heap_open(InheritsRelationId, RowExclusiveLock);
1648 foreach(entry, supers)
1650 Oid parentOid = lfirst_oid(entry);
1652 StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation);
1656 heap_close(relation, RowExclusiveLock);
1660 * Make catalog entries showing relationId as being an inheritance child
1661 * of parentOid. inhRelation is the already-opened pg_inherits catalog.
1664 StoreCatalogInheritance1(Oid relationId, Oid parentOid,
1665 int16 seqNumber, Relation inhRelation)
1667 TupleDesc desc = RelationGetDescr(inhRelation);
1668 Datum datum[Natts_pg_inherits];
1669 char nullarr[Natts_pg_inherits];
1670 ObjectAddress childobject,
1675 * Make the pg_inherits entry
1677 datum[0] = ObjectIdGetDatum(relationId); /* inhrelid */
1678 datum[1] = ObjectIdGetDatum(parentOid); /* inhparent */
1679 datum[2] = Int16GetDatum(seqNumber); /* inhseqno */
1685 tuple = heap_formtuple(desc, datum, nullarr);
1687 simple_heap_insert(inhRelation, tuple);
1689 CatalogUpdateIndexes(inhRelation, tuple);
1691 heap_freetuple(tuple);
1694 * Store a dependency too
1696 parentobject.classId = RelationRelationId;
1697 parentobject.objectId = parentOid;
1698 parentobject.objectSubId = 0;
1699 childobject.classId = RelationRelationId;
1700 childobject.objectId = relationId;
1701 childobject.objectSubId = 0;
1703 recordDependencyOn(&childobject, &parentobject, DEPENDENCY_NORMAL);
1706 * Mark the parent as having subclasses.
1708 setRelhassubclassInRelation(parentOid, true);
1712 * Look for an existing schema entry with the given name.
1714 * Returns the index (starting with 1) if attribute already exists in schema,
1718 findAttrByName(const char *attributeName, List *schema)
1725 ColumnDef *def = lfirst(s);
1727 if (strcmp(attributeName, def->colname) == 0)
1736 * Update a relation's pg_class.relhassubclass entry to the given value
1739 setRelhassubclassInRelation(Oid relationId, bool relhassubclass)
1741 Relation relationRelation;
1743 Form_pg_class classtuple;
1746 * Fetch a modifiable copy of the tuple, modify it, update pg_class.
1748 * If the tuple already has the right relhassubclass setting, we don't
1749 * need to update it, but we still need to issue an SI inval message.
1751 relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
1752 tuple = SearchSysCacheCopy(RELOID,
1753 ObjectIdGetDatum(relationId),
1755 if (!HeapTupleIsValid(tuple))
1756 elog(ERROR, "cache lookup failed for relation %u", relationId);
1757 classtuple = (Form_pg_class) GETSTRUCT(tuple);
1759 if (classtuple->relhassubclass != relhassubclass)
1761 classtuple->relhassubclass = relhassubclass;
1762 simple_heap_update(relationRelation, &tuple->t_self, tuple);
1764 /* keep the catalog indexes up to date */
1765 CatalogUpdateIndexes(relationRelation, tuple);
1769 /* no need to change tuple, but force relcache rebuild anyway */
1770 CacheInvalidateRelcacheByTuple(tuple);
1773 heap_freetuple(tuple);
1774 heap_close(relationRelation, RowExclusiveLock);
1779 * renameatt - changes the name of a attribute in a relation
1781 * Attname attribute is changed in attribute catalog.
1782 * No record of the previous attname is kept (correct?).
1784 * get proper relrelation from relation catalog (if not arg)
1785 * scan attribute catalog
1786 * for name conflict (within rel)
1787 * for original attribute (if not arg)
1788 * modify attname in attribute tuple
1789 * insert modified attribute in attribute catalog
1790 * delete original attribute from attribute catalog
1793 renameatt(Oid myrelid,
1794 const char *oldattname,
1795 const char *newattname,
1799 Relation targetrelation;
1800 Relation attrelation;
1802 Form_pg_attribute attform;
1805 ListCell *indexoidscan;
1808 * Grab an exclusive lock on the target table, which we will NOT release
1809 * until end of transaction.
1811 targetrelation = relation_open(myrelid, AccessExclusiveLock);
1814 * permissions checking. this would normally be done in utility.c, but
1815 * this particular routine is recursive.
1817 * normally, only the owner of a class can change its schema.
1819 if (!pg_class_ownercheck(myrelid, GetUserId()))
1820 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1821 RelationGetRelationName(targetrelation));
1822 if (!allowSystemTableMods && IsSystemRelation(targetrelation))
1824 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1825 errmsg("permission denied: \"%s\" is a system catalog",
1826 RelationGetRelationName(targetrelation))));
1829 * if the 'recurse' flag is set then we are supposed to rename this
1830 * attribute in all classes that inherit from 'relname' (as well as in
1833 * any permissions or problems with duplicate attributes will cause the
1834 * whole transaction to abort, which is what we want -- all or nothing.
1841 /* this routine is actually in the planner */
1842 children = find_all_inheritors(myrelid);
1845 * find_all_inheritors does the recursive search of the inheritance
1846 * hierarchy, so all we have to do is process all of the relids in the
1847 * list that it returns.
1849 foreach(child, children)
1851 Oid childrelid = lfirst_oid(child);
1853 if (childrelid == myrelid)
1855 /* note we need not recurse again */
1856 renameatt(childrelid, oldattname, newattname, false, true);
1862 * If we are told not to recurse, there had better not be any child
1863 * tables; else the rename would put them out of step.
1866 find_inheritance_children(myrelid) != NIL)
1868 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1869 errmsg("inherited column \"%s\" must be renamed in child tables too",
1873 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
1875 atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
1876 if (!HeapTupleIsValid(atttup))
1878 (errcode(ERRCODE_UNDEFINED_COLUMN),
1879 errmsg("column \"%s\" does not exist",
1881 attform = (Form_pg_attribute) GETSTRUCT(atttup);
1883 attnum = attform->attnum;
1886 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1887 errmsg("cannot rename system column \"%s\"",
1891 * if the attribute is inherited, forbid the renaming, unless we are
1892 * already inside a recursive rename.
1894 if (attform->attinhcount > 0 && !recursing)
1896 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1897 errmsg("cannot rename inherited column \"%s\"",
1900 /* should not already exist */
1901 /* this test is deliberately not attisdropped-aware */
1902 if (SearchSysCacheExists(ATTNAME,
1903 ObjectIdGetDatum(myrelid),
1904 PointerGetDatum(newattname),
1907 (errcode(ERRCODE_DUPLICATE_COLUMN),
1908 errmsg("column \"%s\" of relation \"%s\" already exists",
1909 newattname, RelationGetRelationName(targetrelation))));
1911 namestrcpy(&(attform->attname), newattname);
1913 simple_heap_update(attrelation, &atttup->t_self, atttup);
1915 /* keep system catalog indexes current */
1916 CatalogUpdateIndexes(attrelation, atttup);
1918 heap_freetuple(atttup);
1921 * Update column names of indexes that refer to the column being renamed.
1923 indexoidlist = RelationGetIndexList(targetrelation);
1925 foreach(indexoidscan, indexoidlist)
1927 Oid indexoid = lfirst_oid(indexoidscan);
1929 Form_pg_index indexform;
1933 * Scan through index columns to see if there's any simple index
1934 * entries for this attribute. We ignore expressional entries.
1936 indextup = SearchSysCache(INDEXRELID,
1937 ObjectIdGetDatum(indexoid),
1939 if (!HeapTupleIsValid(indextup))
1940 elog(ERROR, "cache lookup failed for index %u", indexoid);
1941 indexform = (Form_pg_index) GETSTRUCT(indextup);
1943 for (i = 0; i < indexform->indnatts; i++)
1945 if (attnum != indexform->indkey.values[i])
1949 * Found one, rename it.
1951 atttup = SearchSysCacheCopy(ATTNUM,
1952 ObjectIdGetDatum(indexoid),
1953 Int16GetDatum(i + 1),
1955 if (!HeapTupleIsValid(atttup))
1956 continue; /* should we raise an error? */
1959 * Update the (copied) attribute tuple.
1961 namestrcpy(&(((Form_pg_attribute) GETSTRUCT(atttup))->attname),
1964 simple_heap_update(attrelation, &atttup->t_self, atttup);
1966 /* keep system catalog indexes current */
1967 CatalogUpdateIndexes(attrelation, atttup);
1969 heap_freetuple(atttup);
1972 ReleaseSysCache(indextup);
1975 list_free(indexoidlist);
1977 heap_close(attrelation, RowExclusiveLock);
1979 relation_close(targetrelation, NoLock); /* close rel but keep lock */
1984 * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW RENAME
1986 * Caller has already done permissions checks.
1989 RenameRelation(Oid myrelid, const char *newrelname, ObjectType reltype)
1991 Relation targetrelation;
1996 * Grab an exclusive lock on the target table, index, sequence or view,
1997 * which we will NOT release until end of transaction.
1999 targetrelation = relation_open(myrelid, AccessExclusiveLock);
2001 namespaceId = RelationGetNamespace(targetrelation);
2002 relkind = targetrelation->rd_rel->relkind;
2005 * For compatibility with prior releases, we don't complain if ALTER TABLE
2006 * or ALTER INDEX is used to rename a sequence or view.
2008 if (reltype == OBJECT_SEQUENCE && relkind != RELKIND_SEQUENCE)
2010 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2011 errmsg("\"%s\" is not a sequence",
2012 RelationGetRelationName(targetrelation))));
2014 if (reltype == OBJECT_VIEW && relkind != RELKIND_VIEW)
2016 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2017 errmsg("\"%s\" is not a view",
2018 RelationGetRelationName(targetrelation))));
2021 * Don't allow ALTER TABLE on composite types.
2022 * We want people to use ALTER TYPE for that.
2024 if (relkind == RELKIND_COMPOSITE_TYPE)
2026 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2027 errmsg("\"%s\" is a composite type",
2028 RelationGetRelationName(targetrelation)),
2029 errhint("Use ALTER TYPE instead.")));
2032 RenameRelationInternal(myrelid, newrelname, namespaceId);
2035 * Close rel, but keep exclusive lock!
2037 relation_close(targetrelation, NoLock);
2041 * RenameRelationInternal - change the name of a relation
2043 * XXX - When renaming sequences, we don't bother to modify the
2044 * sequence name that is stored within the sequence itself
2045 * (this would cause problems with MVCC). In the future,
2046 * the sequence name should probably be removed from the
2047 * sequence, AFAIK there's no need for it to be there.
2050 RenameRelationInternal(Oid myrelid, const char *newrelname, Oid namespaceId)
2052 Relation targetrelation;
2053 Relation relrelation; /* for RELATION relation */
2055 Form_pg_class relform;
2058 * Grab an exclusive lock on the target table, index, sequence or
2059 * view, which we will NOT release until end of transaction.
2061 targetrelation = relation_open(myrelid, AccessExclusiveLock);
2064 * Find relation's pg_class tuple, and make sure newrelname isn't in use.
2066 relrelation = heap_open(RelationRelationId, RowExclusiveLock);
2068 reltup = SearchSysCacheCopy(RELOID,
2069 ObjectIdGetDatum(myrelid),
2071 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
2072 elog(ERROR, "cache lookup failed for relation %u", myrelid);
2073 relform = (Form_pg_class) GETSTRUCT(reltup);
2075 if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
2077 (errcode(ERRCODE_DUPLICATE_TABLE),
2078 errmsg("relation \"%s\" already exists",
2082 * Update pg_class tuple with new relname. (Scribbling on reltup is OK
2083 * because it's a copy...)
2085 namestrcpy(&(relform->relname), newrelname);
2087 simple_heap_update(relrelation, &reltup->t_self, reltup);
2089 /* keep the system catalog indexes current */
2090 CatalogUpdateIndexes(relrelation, reltup);
2092 heap_freetuple(reltup);
2093 heap_close(relrelation, RowExclusiveLock);
2096 * Also rename the associated type, if any.
2098 if (OidIsValid(targetrelation->rd_rel->reltype))
2099 RenameTypeInternal(targetrelation->rd_rel->reltype,
2100 newrelname, namespaceId);
2103 * Also rename the associated constraint, if any.
2105 if (targetrelation->rd_rel->relkind == RELKIND_INDEX)
2107 Oid constraintId = get_index_constraint(myrelid);
2109 if (OidIsValid(constraintId))
2110 RenameConstraintById(constraintId, newrelname);
2114 * Close rel, but keep exclusive lock!
2116 relation_close(targetrelation, NoLock);
2120 * Disallow ALTER TABLE (and similar commands) when the current backend has
2121 * any open reference to the target table besides the one just acquired by
2122 * the calling command; this implies there's an open cursor or active plan.
2123 * We need this check because our AccessExclusiveLock doesn't protect us
2124 * against stomping on our own foot, only other people's feet!
2126 * For ALTER TABLE, the only case known to cause serious trouble is ALTER
2127 * COLUMN TYPE, and some changes are obviously pretty benign, so this could
2128 * possibly be relaxed to only error out for certain types of alterations.
2129 * But the use-case for allowing any of these things is not obvious, so we
2130 * won't work hard at it for now.
2132 * We also reject these commands if there are any pending AFTER trigger events
2133 * for the rel. This is certainly necessary for the rewriting variants of
2134 * ALTER TABLE, because they don't preserve tuple TIDs and so the pending
2135 * events would try to fetch the wrong tuples. It might be overly cautious
2136 * in other cases, but again it seems better to err on the side of paranoia.
2138 * REINDEX calls this with "rel" referencing the index to be rebuilt; here
2139 * we are worried about active indexscans on the index. The trigger-event
2140 * check can be skipped, since we are doing no damage to the parent table.
2142 * The statement name (eg, "ALTER TABLE") is passed for use in error messages.
2145 CheckTableNotInUse(Relation rel, const char *stmt)
2147 int expected_refcnt;
2149 expected_refcnt = rel->rd_isnailed ? 2 : 1;
2150 if (rel->rd_refcnt != expected_refcnt)
2152 (errcode(ERRCODE_OBJECT_IN_USE),
2153 /* translator: first %s is a SQL command, eg ALTER TABLE */
2154 errmsg("cannot %s \"%s\" because "
2155 "it is being used by active queries in this session",
2156 stmt, RelationGetRelationName(rel))));
2158 if (rel->rd_rel->relkind != RELKIND_INDEX &&
2159 AfterTriggerPendingOnRel(RelationGetRelid(rel)))
2161 (errcode(ERRCODE_OBJECT_IN_USE),
2162 /* translator: first %s is a SQL command, eg ALTER TABLE */
2163 errmsg("cannot %s \"%s\" because "
2164 "it has pending trigger events",
2165 stmt, RelationGetRelationName(rel))));
2170 * Execute ALTER TABLE, which can be a list of subcommands
2172 * ALTER TABLE is performed in three phases:
2173 * 1. Examine subcommands and perform pre-transformation checking.
2174 * 2. Update system catalogs.
2175 * 3. Scan table(s) to check new constraints, and optionally recopy
2176 * the data into new table(s).
2177 * Phase 3 is not performed unless one or more of the subcommands requires
2178 * it. The intention of this design is to allow multiple independent
2179 * updates of the table schema to be performed with only one pass over the
2182 * ATPrepCmd performs phase 1. A "work queue" entry is created for
2183 * each table to be affected (there may be multiple affected tables if the
2184 * commands traverse a table inheritance hierarchy). Also we do preliminary
2185 * validation of the subcommands, including parse transformation of those
2186 * expressions that need to be evaluated with respect to the old table
2189 * ATRewriteCatalogs performs phase 2 for each affected table. (Note that
2190 * phases 2 and 3 normally do no explicit recursion, since phase 1 already
2191 * did it --- although some subcommands have to recurse in phase 2 instead.)
2192 * Certain subcommands need to be performed before others to avoid
2193 * unnecessary conflicts; for example, DROP COLUMN should come before
2194 * ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
2195 * lists, one for each logical "pass" of phase 2.
2197 * ATRewriteTables performs phase 3 for those tables that need it.
2199 * Thanks to the magic of MVCC, an error anywhere along the way rolls back
2200 * the whole operation; we don't have to do anything special to clean up.
2203 AlterTable(AlterTableStmt *stmt)
2205 Relation rel = relation_openrv(stmt->relation, AccessExclusiveLock);
2207 CheckTableNotInUse(rel, "ALTER TABLE");
2209 /* Check relation type against type specified in the ALTER command */
2210 switch (stmt->relkind)
2214 * For mostly-historical reasons, we allow ALTER TABLE to apply
2215 * to all relation types.
2220 if (rel->rd_rel->relkind != RELKIND_INDEX)
2222 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2223 errmsg("\"%s\" is not an index",
2224 RelationGetRelationName(rel))));
2227 case OBJECT_SEQUENCE:
2228 if (rel->rd_rel->relkind != RELKIND_SEQUENCE)
2230 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2231 errmsg("\"%s\" is not a sequence",
2232 RelationGetRelationName(rel))));
2236 if (rel->rd_rel->relkind != RELKIND_VIEW)
2238 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2239 errmsg("\"%s\" is not a view",
2240 RelationGetRelationName(rel))));
2244 elog(ERROR, "unrecognized object type: %d", (int) stmt->relkind);
2247 ATController(rel, stmt->cmds, interpretInhOption(stmt->relation->inhOpt));
2251 * AlterTableInternal
2253 * ALTER TABLE with target specified by OID
2255 * We do not reject if the relation is already open, because it's quite
2256 * likely that one or more layers of caller have it open. That means it
2257 * is unsafe to use this entry point for alterations that could break
2258 * existing query plans. On the assumption it's not used for such, we
2259 * don't have to reject pending AFTER triggers, either.
2262 AlterTableInternal(Oid relid, List *cmds, bool recurse)
2264 Relation rel = relation_open(relid, AccessExclusiveLock);
2266 ATController(rel, cmds, recurse);
2270 ATController(Relation rel, List *cmds, bool recurse)
2275 /* Phase 1: preliminary examination of commands, create work queue */
2278 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2280 ATPrepCmd(&wqueue, rel, cmd, recurse, false);
2283 /* Close the relation, but keep lock until commit */
2284 relation_close(rel, NoLock);
2286 /* Phase 2: update system catalogs */
2287 ATRewriteCatalogs(&wqueue);
2289 /* Phase 3: scan/rewrite tables as needed */
2290 ATRewriteTables(&wqueue);
2296 * Traffic cop for ALTER TABLE Phase 1 operations, including simple
2297 * recursion and permission checks.
2299 * Caller must have acquired AccessExclusiveLock on relation already.
2300 * This lock should be held until commit.
2303 ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
2304 bool recurse, bool recursing)
2306 AlteredTableInfo *tab;
2309 /* Find or create work queue entry for this table */
2310 tab = ATGetQueueEntry(wqueue, rel);
2313 * Copy the original subcommand for each table. This avoids conflicts
2314 * when different child tables need to make different parse
2315 * transformations (for example, the same column may have different column
2316 * numbers in different children).
2318 cmd = copyObject(cmd);
2321 * Do permissions checking, recursion to child tables if needed, and any
2322 * additional phase-1 processing needed.
2324 switch (cmd->subtype)
2326 case AT_AddColumn: /* ADD COLUMN */
2327 ATSimplePermissions(rel, false);
2328 /* Performs own recursion */
2329 ATPrepAddColumn(wqueue, rel, recurse, cmd);
2330 pass = AT_PASS_ADD_COL;
2332 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
2335 * We allow defaults on views so that INSERT into a view can have
2336 * default-ish behavior. This works because the rewriter
2337 * substitutes default values into INSERTs before it expands
2340 ATSimplePermissions(rel, true);
2341 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2342 /* No command-specific prep needed */
2343 pass = cmd->def ? AT_PASS_ADD_CONSTR : AT_PASS_DROP;
2345 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
2346 ATSimplePermissions(rel, false);
2347 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2348 /* No command-specific prep needed */
2349 pass = AT_PASS_DROP;
2351 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
2352 ATSimplePermissions(rel, false);
2353 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2354 /* No command-specific prep needed */
2355 pass = AT_PASS_ADD_CONSTR;
2357 case AT_SetStatistics: /* ALTER COLUMN STATISTICS */
2358 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2359 /* Performs own permission checks */
2360 ATPrepSetStatistics(rel, cmd->name, cmd->def);
2361 pass = AT_PASS_COL_ATTRS;
2363 case AT_SetStorage: /* ALTER COLUMN STORAGE */
2364 ATSimplePermissions(rel, false);
2365 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2366 /* No command-specific prep needed */
2367 pass = AT_PASS_COL_ATTRS;
2369 case AT_DropColumn: /* DROP COLUMN */
2370 ATSimplePermissions(rel, false);
2371 /* Recursion occurs during execution phase */
2372 /* No command-specific prep needed except saving recurse flag */
2374 cmd->subtype = AT_DropColumnRecurse;
2375 pass = AT_PASS_DROP;
2377 case AT_AddIndex: /* ADD INDEX */
2378 ATSimplePermissions(rel, false);
2379 /* This command never recurses */
2380 /* No command-specific prep needed */
2381 pass = AT_PASS_ADD_INDEX;
2383 case AT_AddConstraint: /* ADD CONSTRAINT */
2384 ATSimplePermissions(rel, false);
2385 /* Recursion occurs during execution phase */
2386 /* No command-specific prep needed except saving recurse flag */
2388 cmd->subtype = AT_AddConstraintRecurse;
2389 pass = AT_PASS_ADD_CONSTR;
2391 case AT_DropConstraint: /* DROP CONSTRAINT */
2392 ATSimplePermissions(rel, false);
2393 /* Recursion occurs during execution phase */
2394 /* No command-specific prep needed except saving recurse flag */
2396 cmd->subtype = AT_DropConstraintRecurse;
2397 pass = AT_PASS_DROP;
2399 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
2400 ATSimplePermissions(rel, false);
2401 /* Performs own recursion */
2402 ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd);
2403 pass = AT_PASS_ALTER_TYPE;
2405 case AT_ChangeOwner: /* ALTER OWNER */
2406 /* This command never recurses */
2407 /* No command-specific prep needed */
2408 pass = AT_PASS_MISC;
2410 case AT_ClusterOn: /* CLUSTER ON */
2411 case AT_DropCluster: /* SET WITHOUT CLUSTER */
2412 ATSimplePermissions(rel, false);
2413 /* These commands never recurse */
2414 /* No command-specific prep needed */
2415 pass = AT_PASS_MISC;
2417 case AT_DropOids: /* SET WITHOUT OIDS */
2418 ATSimplePermissions(rel, false);
2419 /* Performs own recursion */
2420 if (rel->rd_rel->relhasoids)
2422 AlterTableCmd *dropCmd = makeNode(AlterTableCmd);
2424 dropCmd->subtype = AT_DropColumn;
2425 dropCmd->name = pstrdup("oid");
2426 dropCmd->behavior = cmd->behavior;
2427 ATPrepCmd(wqueue, rel, dropCmd, recurse, false);
2429 pass = AT_PASS_DROP;
2431 case AT_SetTableSpace: /* SET TABLESPACE */
2432 ATSimplePermissionsRelationOrIndex(rel);
2433 /* This command never recurses */
2434 ATPrepSetTableSpace(tab, rel, cmd->name);
2435 pass = AT_PASS_MISC; /* doesn't actually matter */
2437 case AT_SetRelOptions: /* SET (...) */
2438 case AT_ResetRelOptions: /* RESET (...) */
2439 ATSimplePermissionsRelationOrIndex(rel);
2440 /* This command never recurses */
2441 /* No command-specific prep needed */
2442 pass = AT_PASS_MISC;
2444 case AT_EnableTrig: /* ENABLE TRIGGER variants */
2445 case AT_EnableAlwaysTrig:
2446 case AT_EnableReplicaTrig:
2447 case AT_EnableTrigAll:
2448 case AT_EnableTrigUser:
2449 case AT_DisableTrig: /* DISABLE TRIGGER variants */
2450 case AT_DisableTrigAll:
2451 case AT_DisableTrigUser:
2452 case AT_EnableRule: /* ENABLE/DISABLE RULE variants */
2453 case AT_EnableAlwaysRule:
2454 case AT_EnableReplicaRule:
2455 case AT_DisableRule:
2456 case AT_AddInherit: /* INHERIT / NO INHERIT */
2457 case AT_DropInherit:
2458 ATSimplePermissions(rel, false);
2459 /* These commands never recurse */
2460 /* No command-specific prep needed */
2461 pass = AT_PASS_MISC;
2464 elog(ERROR, "unrecognized alter table type: %d",
2465 (int) cmd->subtype);
2466 pass = 0; /* keep compiler quiet */
2470 /* Add the subcommand to the appropriate list for phase 2 */
2471 tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
2477 * Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
2478 * dispatched in a "safe" execution order (designed to avoid unnecessary
2482 ATRewriteCatalogs(List **wqueue)
2488 * We process all the tables "in parallel", one pass at a time. This is
2489 * needed because we may have to propagate work from one table to another
2490 * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
2491 * re-adding of the foreign key constraint to the other table). Work can
2492 * only be propagated into later passes, however.
2494 for (pass = 0; pass < AT_NUM_PASSES; pass++)
2496 /* Go through each table that needs to be processed */
2497 foreach(ltab, *wqueue)
2499 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2500 List *subcmds = tab->subcmds[pass];
2508 * Exclusive lock was obtained by phase 1, needn't get it again
2510 rel = relation_open(tab->relid, NoLock);
2512 foreach(lcmd, subcmds)
2513 ATExecCmd(wqueue, tab, rel, (AlterTableCmd *) lfirst(lcmd));
2516 * After the ALTER TYPE pass, do cleanup work (this is not done in
2517 * ATExecAlterColumnType since it should be done only once if
2518 * multiple columns of a table are altered).
2520 if (pass == AT_PASS_ALTER_TYPE)
2521 ATPostAlterTypeCleanup(wqueue, tab);
2523 relation_close(rel, NoLock);
2528 * Check to see if a toast table must be added, if we executed any
2529 * subcommands that might have added a column or changed column storage.
2531 foreach(ltab, *wqueue)
2533 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2535 if (tab->relkind == RELKIND_RELATION &&
2536 (tab->subcmds[AT_PASS_ADD_COL] ||
2537 tab->subcmds[AT_PASS_ALTER_TYPE] ||
2538 tab->subcmds[AT_PASS_COL_ATTRS]))
2539 AlterTableCreateToastTable(tab->relid);
2544 * ATExecCmd: dispatch a subcommand to appropriate execution routine
2547 ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
2550 switch (cmd->subtype)
2552 case AT_AddColumn: /* ADD COLUMN */
2553 ATExecAddColumn(tab, rel, (ColumnDef *) cmd->def);
2555 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
2556 ATExecColumnDefault(rel, cmd->name, cmd->def);
2558 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
2559 ATExecDropNotNull(rel, cmd->name);
2561 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
2562 ATExecSetNotNull(tab, rel, cmd->name);
2564 case AT_SetStatistics: /* ALTER COLUMN STATISTICS */
2565 ATExecSetStatistics(rel, cmd->name, cmd->def);
2567 case AT_SetStorage: /* ALTER COLUMN STORAGE */
2568 ATExecSetStorage(rel, cmd->name, cmd->def);
2570 case AT_DropColumn: /* DROP COLUMN */
2571 ATExecDropColumn(rel, cmd->name, cmd->behavior, false, false);
2573 case AT_DropColumnRecurse: /* DROP COLUMN with recursion */
2574 ATExecDropColumn(rel, cmd->name, cmd->behavior, true, false);
2576 case AT_AddIndex: /* ADD INDEX */
2577 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false);
2579 case AT_ReAddIndex: /* ADD INDEX */
2580 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true);
2582 case AT_AddConstraint: /* ADD CONSTRAINT */
2583 ATExecAddConstraint(wqueue, tab, rel, cmd->def, false);
2585 case AT_AddConstraintRecurse: /* ADD CONSTRAINT with recursion */
2586 ATExecAddConstraint(wqueue, tab, rel, cmd->def, true);
2588 case AT_DropConstraint: /* DROP CONSTRAINT */
2589 ATExecDropConstraint(rel, cmd->name, cmd->behavior, false, false);
2591 case AT_DropConstraintRecurse: /* DROP CONSTRAINT with recursion */
2592 ATExecDropConstraint(rel, cmd->name, cmd->behavior, true, false);
2594 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
2595 ATExecAlterColumnType(tab, rel, cmd->name, (TypeName *) cmd->def);
2597 case AT_ChangeOwner: /* ALTER OWNER */
2598 ATExecChangeOwner(RelationGetRelid(rel),
2599 get_roleid_checked(cmd->name),
2602 case AT_ClusterOn: /* CLUSTER ON */
2603 ATExecClusterOn(rel, cmd->name);
2605 case AT_DropCluster: /* SET WITHOUT CLUSTER */
2606 ATExecDropCluster(rel);
2608 case AT_DropOids: /* SET WITHOUT OIDS */
2611 * Nothing to do here; we'll have generated a DropColumn
2612 * subcommand to do the real work
2615 case AT_SetTableSpace: /* SET TABLESPACE */
2618 * Nothing to do here; Phase 3 does the work
2621 case AT_SetRelOptions: /* SET (...) */
2622 ATExecSetRelOptions(rel, (List *) cmd->def, false);
2624 case AT_ResetRelOptions: /* RESET (...) */
2625 ATExecSetRelOptions(rel, (List *) cmd->def, true);
2628 case AT_EnableTrig: /* ENABLE TRIGGER name */
2629 ATExecEnableDisableTrigger(rel, cmd->name,
2630 TRIGGER_FIRES_ON_ORIGIN, false);
2632 case AT_EnableAlwaysTrig: /* ENABLE ALWAYS TRIGGER name */
2633 ATExecEnableDisableTrigger(rel, cmd->name,
2634 TRIGGER_FIRES_ALWAYS, false);
2636 case AT_EnableReplicaTrig: /* ENABLE REPLICA TRIGGER name */
2637 ATExecEnableDisableTrigger(rel, cmd->name,
2638 TRIGGER_FIRES_ON_REPLICA, false);
2640 case AT_DisableTrig: /* DISABLE TRIGGER name */
2641 ATExecEnableDisableTrigger(rel, cmd->name,
2642 TRIGGER_DISABLED, false);
2644 case AT_EnableTrigAll: /* ENABLE TRIGGER ALL */
2645 ATExecEnableDisableTrigger(rel, NULL,
2646 TRIGGER_FIRES_ON_ORIGIN, false);
2648 case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
2649 ATExecEnableDisableTrigger(rel, NULL,
2650 TRIGGER_DISABLED, false);
2652 case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
2653 ATExecEnableDisableTrigger(rel, NULL,
2654 TRIGGER_FIRES_ON_ORIGIN, true);
2656 case AT_DisableTrigUser: /* DISABLE TRIGGER USER */
2657 ATExecEnableDisableTrigger(rel, NULL,
2658 TRIGGER_DISABLED, true);
2661 case AT_EnableRule: /* ENABLE RULE name */
2662 ATExecEnableDisableRule(rel, cmd->name,
2663 RULE_FIRES_ON_ORIGIN);
2665 case AT_EnableAlwaysRule: /* ENABLE ALWAYS RULE name */
2666 ATExecEnableDisableRule(rel, cmd->name,
2669 case AT_EnableReplicaRule: /* ENABLE REPLICA RULE name */
2670 ATExecEnableDisableRule(rel, cmd->name,
2671 RULE_FIRES_ON_REPLICA);
2673 case AT_DisableRule: /* DISABLE RULE name */
2674 ATExecEnableDisableRule(rel, cmd->name,
2679 ATExecAddInherit(rel, (RangeVar *) cmd->def);
2681 case AT_DropInherit:
2682 ATExecDropInherit(rel, (RangeVar *) cmd->def);
2685 elog(ERROR, "unrecognized alter table type: %d",
2686 (int) cmd->subtype);
2691 * Bump the command counter to ensure the next subcommand in the sequence
2692 * can see the changes so far
2694 CommandCounterIncrement();
2698 * ATRewriteTables: ALTER TABLE phase 3
2701 ATRewriteTables(List **wqueue)
2705 /* Go through each table that needs to be checked or rewritten */
2706 foreach(ltab, *wqueue)
2708 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2711 * We only need to rewrite the table if at least one column needs to
2714 if (tab->newvals != NIL)
2716 /* Build a temporary relation and copy data */
2718 char NewHeapName[NAMEDATALEN];
2721 ObjectAddress object;
2723 OldHeap = heap_open(tab->relid, NoLock);
2726 * We can never allow rewriting of shared or nailed-in-cache
2727 * relations, because we can't support changing their relfilenode
2730 if (OldHeap->rd_rel->relisshared || OldHeap->rd_isnailed)
2732 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2733 errmsg("cannot rewrite system relation \"%s\"",
2734 RelationGetRelationName(OldHeap))));
2737 * Don't allow rewrite on temp tables of other backends ... their
2738 * local buffer manager is not going to cope.
2740 if (isOtherTempNamespace(RelationGetNamespace(OldHeap)))
2742 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2743 errmsg("cannot rewrite temporary tables of other sessions")));
2746 * Select destination tablespace (same as original unless user
2747 * requested a change)
2749 if (tab->newTableSpace)
2750 NewTableSpace = tab->newTableSpace;
2752 NewTableSpace = OldHeap->rd_rel->reltablespace;
2754 heap_close(OldHeap, NoLock);
2757 * Create the new heap, using a temporary name in the same
2758 * namespace as the existing table. NOTE: there is some risk of
2759 * collision with user relnames. Working around this seems more
2760 * trouble than it's worth; in particular, we can't create the new
2761 * heap in a different namespace from the old, or we will have
2762 * problems with the TEMP status of temp tables.
2764 snprintf(NewHeapName, sizeof(NewHeapName),
2765 "pg_temp_%u", tab->relid);
2767 OIDNewHeap = make_new_heap(tab->relid, NewHeapName, NewTableSpace);
2770 * Copy the heap data into the new table with the desired
2771 * modifications, and test the current data within the table
2772 * against new constraints generated by ALTER TABLE commands.
2774 ATRewriteTable(tab, OIDNewHeap);
2777 * Swap the physical files of the old and new heaps. Since we are
2778 * generating a new heap, we can use RecentXmin for the table's
2779 * new relfrozenxid because we rewrote all the tuples on
2780 * ATRewriteTable, so no older Xid remains on the table.
2782 swap_relation_files(tab->relid, OIDNewHeap, RecentXmin);
2784 CommandCounterIncrement();
2786 /* Destroy new heap with old filenode */
2787 object.classId = RelationRelationId;
2788 object.objectId = OIDNewHeap;
2789 object.objectSubId = 0;
2792 * The new relation is local to our transaction and we know
2793 * nothing depends on it, so DROP_RESTRICT should be OK.
2795 performDeletion(&object, DROP_RESTRICT);
2796 /* performDeletion does CommandCounterIncrement at end */
2799 * Rebuild each index on the relation (but not the toast table,
2800 * which is all-new anyway). We do not need
2801 * CommandCounterIncrement() because reindex_relation does it.
2803 reindex_relation(tab->relid, false);
2808 * Test the current data within the table against new constraints
2809 * generated by ALTER TABLE commands, but don't rebuild data.
2811 if (tab->constraints != NIL || tab->new_notnull)
2812 ATRewriteTable(tab, InvalidOid);
2815 * If we had SET TABLESPACE but no reason to reconstruct tuples,
2816 * just do a block-by-block copy.
2818 if (tab->newTableSpace)
2819 ATExecSetTableSpace(tab->relid, tab->newTableSpace);
2824 * Foreign key constraints are checked in a final pass, since (a) it's
2825 * generally best to examine each one separately, and (b) it's at least
2826 * theoretically possible that we have changed both relations of the
2827 * foreign key, and we'd better have finished both rewrites before we try
2828 * to read the tables.
2830 foreach(ltab, *wqueue)
2832 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2833 Relation rel = NULL;
2836 foreach(lcon, tab->constraints)
2838 NewConstraint *con = lfirst(lcon);
2840 if (con->contype == CONSTR_FOREIGN)
2842 FkConstraint *fkconstraint = (FkConstraint *) con->qual;
2847 /* Long since locked, no need for another */
2848 rel = heap_open(tab->relid, NoLock);
2851 refrel = heap_open(con->refrelid, RowShareLock);
2853 validateForeignKeyConstraint(fkconstraint, rel, refrel,
2856 heap_close(refrel, NoLock);
2861 heap_close(rel, NoLock);
2866 * ATRewriteTable: scan or rewrite one table
2868 * OIDNewHeap is InvalidOid if we don't need to rewrite
2871 ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap)
2875 TupleDesc oldTupDesc;
2876 TupleDesc newTupDesc;
2877 bool needscan = false;
2878 List *notnull_attrs;
2884 * Open the relation(s). We have surely already locked the existing
2887 oldrel = heap_open(tab->relid, NoLock);
2888 oldTupDesc = tab->oldDesc;
2889 newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
2891 if (OidIsValid(OIDNewHeap))
2892 newrel = heap_open(OIDNewHeap, AccessExclusiveLock);
2897 * If we need to rewrite the table, the operation has to be propagated to
2898 * tables that use this table's rowtype as a column type.
2900 * (Eventually this will probably become true for scans as well, but at
2901 * the moment a composite type does not enforce any constraints, so it's
2902 * not necessary/appropriate to enforce them just during ALTER.)
2905 find_composite_type_dependencies(oldrel->rd_rel->reltype,
2906 RelationGetRelationName(oldrel),
2910 * Generate the constraint and default execution states
2913 estate = CreateExecutorState();
2915 /* Build the needed expression execution states */
2916 foreach(l, tab->constraints)
2918 NewConstraint *con = lfirst(l);
2920 switch (con->contype)
2924 con->qualstate = (List *)
2925 ExecPrepareExpr((Expr *) con->qual, estate);
2927 case CONSTR_FOREIGN:
2928 /* Nothing to do here */
2931 elog(ERROR, "unrecognized constraint type: %d",
2932 (int) con->contype);
2936 foreach(l, tab->newvals)
2938 NewColumnValue *ex = lfirst(l);
2942 ex->exprstate = ExecPrepareExpr((Expr *) ex->expr, estate);
2945 notnull_attrs = NIL;
2946 if (newrel || tab->new_notnull)
2949 * If we are rebuilding the tuples OR if we added any new NOT NULL
2950 * constraints, check all not-null constraints. This is a bit of
2951 * overkill but it minimizes risk of bugs, and heap_attisnull is a
2952 * pretty cheap test anyway.
2954 for (i = 0; i < newTupDesc->natts; i++)
2956 if (newTupDesc->attrs[i]->attnotnull &&
2957 !newTupDesc->attrs[i]->attisdropped)
2958 notnull_attrs = lappend_int(notnull_attrs, i);
2966 ExprContext *econtext;
2969 TupleTableSlot *oldslot;
2970 TupleTableSlot *newslot;
2973 MemoryContext oldCxt;
2974 List *dropped_attrs = NIL;
2977 econtext = GetPerTupleExprContext(estate);
2980 * Make tuple slots for old and new tuples. Note that even when the
2981 * tuples are the same, the tupDescs might not be (consider ADD COLUMN
2982 * without a default).
2984 oldslot = MakeSingleTupleTableSlot(oldTupDesc);
2985 newslot = MakeSingleTupleTableSlot(newTupDesc);
2987 /* Preallocate values/isnull arrays */
2988 i = Max(newTupDesc->natts, oldTupDesc->natts);
2989 values = (Datum *) palloc(i * sizeof(Datum));
2990 isnull = (bool *) palloc(i * sizeof(bool));
2991 memset(values, 0, i * sizeof(Datum));
2992 memset(isnull, true, i * sizeof(bool));
2995 * Any attributes that are dropped according to the new tuple
2996 * descriptor can be set to NULL. We precompute the list of dropped
2997 * attributes to avoid needing to do so in the per-tuple loop.
2999 for (i = 0; i < newTupDesc->natts; i++)
3001 if (newTupDesc->attrs[i]->attisdropped)
3002 dropped_attrs = lappend_int(dropped_attrs, i);
3006 * Scan through the rows, generating a new row if needed and then
3007 * checking all the constraints.
3009 scan = heap_beginscan(oldrel, SnapshotNow, 0, NULL);
3012 * Switch to per-tuple memory context and reset it for each tuple
3013 * produced, so we don't leak memory.
3015 oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
3017 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
3021 Oid tupOid = InvalidOid;
3023 /* Extract data from old tuple */
3024 heap_deform_tuple(tuple, oldTupDesc, values, isnull);
3025 if (oldTupDesc->tdhasoid)
3026 tupOid = HeapTupleGetOid(tuple);
3028 /* Set dropped attributes to null in new tuple */
3029 foreach(lc, dropped_attrs)
3030 isnull[lfirst_int(lc)] = true;
3033 * Process supplied expressions to replace selected columns.
3034 * Expression inputs come from the old tuple.
3036 ExecStoreTuple(tuple, oldslot, InvalidBuffer, false);
3037 econtext->ecxt_scantuple = oldslot;
3039 foreach(l, tab->newvals)
3041 NewColumnValue *ex = lfirst(l);
3043 values[ex->attnum - 1] = ExecEvalExpr(ex->exprstate,
3045 &isnull[ex->attnum - 1],
3050 * Form the new tuple. Note that we don't explicitly pfree it,
3051 * since the per-tuple memory context will be reset shortly.
3053 tuple = heap_form_tuple(newTupDesc, values, isnull);
3055 /* Preserve OID, if any */
3056 if (newTupDesc->tdhasoid)
3057 HeapTupleSetOid(tuple, tupOid);
3060 /* Now check any constraints on the possibly-changed tuple */
3061 ExecStoreTuple(tuple, newslot, InvalidBuffer, false);
3062 econtext->ecxt_scantuple = newslot;
3064 foreach(l, notnull_attrs)
3066 int attn = lfirst_int(l);
3068 if (heap_attisnull(tuple, attn + 1))
3070 (errcode(ERRCODE_NOT_NULL_VIOLATION),
3071 errmsg("column \"%s\" contains null values",
3072 NameStr(newTupDesc->attrs[attn]->attname))));
3075 foreach(l, tab->constraints)
3077 NewConstraint *con = lfirst(l);
3079 switch (con->contype)
3082 if (!ExecQual(con->qualstate, econtext, true))
3084 (errcode(ERRCODE_CHECK_VIOLATION),
3085 errmsg("check constraint \"%s\" is violated by some row",
3088 case CONSTR_FOREIGN:
3089 /* Nothing to do here */
3092 elog(ERROR, "unrecognized constraint type: %d",
3093 (int) con->contype);
3097 /* Write the tuple out to the new relation */
3099 simple_heap_insert(newrel, tuple);
3101 ResetExprContext(econtext);
3103 CHECK_FOR_INTERRUPTS();
3106 MemoryContextSwitchTo(oldCxt);
3109 ExecDropSingleTupleTableSlot(oldslot);
3110 ExecDropSingleTupleTableSlot(newslot);
3113 FreeExecutorState(estate);
3115 heap_close(oldrel, NoLock);
3117 heap_close(newrel, NoLock);
3121 * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
3123 static AlteredTableInfo *
3124 ATGetQueueEntry(List **wqueue, Relation rel)
3126 Oid relid = RelationGetRelid(rel);
3127 AlteredTableInfo *tab;
3130 foreach(ltab, *wqueue)
3132 tab = (AlteredTableInfo *) lfirst(ltab);
3133 if (tab->relid == relid)
3138 * Not there, so add it. Note that we make a copy of the relation's
3139 * existing descriptor before anything interesting can happen to it.
3141 tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
3143 tab->relkind = rel->rd_rel->relkind;
3144 tab->oldDesc = CreateTupleDescCopy(RelationGetDescr(rel));
3146 *wqueue = lappend(*wqueue, tab);
3152 * ATSimplePermissions
3154 * - Ensure that it is a relation (or possibly a view)
3155 * - Ensure this user is the owner
3156 * - Ensure that it is not a system table
3159 ATSimplePermissions(Relation rel, bool allowView)
3161 if (rel->rd_rel->relkind != RELKIND_RELATION)
3165 if (rel->rd_rel->relkind != RELKIND_VIEW)
3167 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3168 errmsg("\"%s\" is not a table or view",
3169 RelationGetRelationName(rel))));
3173 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3174 errmsg("\"%s\" is not a table",
3175 RelationGetRelationName(rel))));
3178 /* Permissions checks */
3179 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3180 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3181 RelationGetRelationName(rel));
3183 if (!allowSystemTableMods && IsSystemRelation(rel))
3185 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3186 errmsg("permission denied: \"%s\" is a system catalog",
3187 RelationGetRelationName(rel))));
3191 * ATSimplePermissionsRelationOrIndex
3193 * - Ensure that it is a relation or an index
3194 * - Ensure this user is the owner
3195 * - Ensure that it is not a system table
3198 ATSimplePermissionsRelationOrIndex(Relation rel)
3200 if (rel->rd_rel->relkind != RELKIND_RELATION &&
3201 rel->rd_rel->relkind != RELKIND_INDEX)
3203 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3204 errmsg("\"%s\" is not a table or index",
3205 RelationGetRelationName(rel))));
3207 /* Permissions checks */
3208 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3209 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3210 RelationGetRelationName(rel));
3212 if (!allowSystemTableMods && IsSystemRelation(rel))
3214 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3215 errmsg("permission denied: \"%s\" is a system catalog",
3216 RelationGetRelationName(rel))));
3222 * Simple table recursion sufficient for most ALTER TABLE operations.
3223 * All direct and indirect children are processed in an unspecified order.
3224 * Note that if a child inherits from the original table via multiple
3225 * inheritance paths, it will be visited just once.
3228 ATSimpleRecursion(List **wqueue, Relation rel,
3229 AlterTableCmd *cmd, bool recurse)
3232 * Propagate to children if desired. Non-table relations never have
3233 * children, so no need to search in that case.
3235 if (recurse && rel->rd_rel->relkind == RELKIND_RELATION)
3237 Oid relid = RelationGetRelid(rel);
3241 /* this routine is actually in the planner */
3242 children = find_all_inheritors(relid);
3245 * find_all_inheritors does the recursive search of the inheritance
3246 * hierarchy, so all we have to do is process all of the relids in the
3247 * list that it returns.
3249 foreach(child, children)
3251 Oid childrelid = lfirst_oid(child);
3254 if (childrelid == relid)
3256 childrel = relation_open(childrelid, AccessExclusiveLock);
3257 CheckTableNotInUse(childrel, "ALTER TABLE");
3258 ATPrepCmd(wqueue, childrel, cmd, false, true);
3259 relation_close(childrel, NoLock);
3265 * ATOneLevelRecursion
3267 * Here, we visit only direct inheritance children. It is expected that
3268 * the command's prep routine will recurse again to find indirect children.
3269 * When using this technique, a multiply-inheriting child will be visited
3273 ATOneLevelRecursion(List **wqueue, Relation rel,
3276 Oid relid = RelationGetRelid(rel);
3280 /* this routine is actually in the planner */
3281 children = find_inheritance_children(relid);
3283 foreach(child, children)
3285 Oid childrelid = lfirst_oid(child);
3288 childrel = relation_open(childrelid, AccessExclusiveLock);
3289 CheckTableNotInUse(childrel, "ALTER TABLE");
3290 ATPrepCmd(wqueue, childrel, cmd, true, true);
3291 relation_close(childrel, NoLock);
3297 * find_composite_type_dependencies
3299 * Check to see if a composite type is being used as a column in some
3300 * other table (possibly nested several levels deep in composite types!).
3301 * Eventually, we'd like to propagate the check or rewrite operation
3302 * into other such tables, but for now, just error out if we find any.
3304 * Caller should provide either a table name or a type name (not both) to
3305 * report in the error message, if any.
3307 * We assume that functions and views depending on the type are not reasons
3308 * to reject the ALTER. (How safe is this really?)
3311 find_composite_type_dependencies(Oid typeOid,
3312 const char *origTblName,
3313 const char *origTypeName)
3317 SysScanDesc depScan;
3322 * We scan pg_depend to find those things that depend on the rowtype. (We
3323 * assume we can ignore refobjsubid for a rowtype.)
3325 depRel = heap_open(DependRelationId, AccessShareLock);
3327 ScanKeyInit(&key[0],
3328 Anum_pg_depend_refclassid,
3329 BTEqualStrategyNumber, F_OIDEQ,
3330 ObjectIdGetDatum(TypeRelationId));
3331 ScanKeyInit(&key[1],
3332 Anum_pg_depend_refobjid,
3333 BTEqualStrategyNumber, F_OIDEQ,
3334 ObjectIdGetDatum(typeOid));
3336 depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
3337 SnapshotNow, 2, key);
3339 while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
3341 Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
3343 Form_pg_attribute att;
3345 /* Ignore dependees that aren't user columns of relations */
3346 /* (we assume system columns are never of rowtypes) */
3347 if (pg_depend->classid != RelationRelationId ||
3348 pg_depend->objsubid <= 0)
3351 rel = relation_open(pg_depend->objid, AccessShareLock);
3352 att = rel->rd_att->attrs[pg_depend->objsubid - 1];
3354 if (rel->rd_rel->relkind == RELKIND_RELATION)
3358 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3359 errmsg("cannot alter table \"%s\" because column \"%s\".\"%s\" uses its rowtype",
3361 RelationGetRelationName(rel),
3362 NameStr(att->attname))));
3365 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3366 errmsg("cannot alter type \"%s\" because column \"%s\".\"%s\" uses it",
3368 RelationGetRelationName(rel),
3369 NameStr(att->attname))));
3371 else if (OidIsValid(rel->rd_rel->reltype))
3374 * A view or composite type itself isn't a problem, but we must
3375 * recursively check for indirect dependencies via its rowtype.
3377 find_composite_type_dependencies(rel->rd_rel->reltype,
3378 origTblName, origTypeName);
3381 relation_close(rel, AccessShareLock);
3384 systable_endscan(depScan);
3386 relation_close(depRel, AccessShareLock);
3389 * If there's an array type for the rowtype, must check for uses of it,
3392 arrayOid = get_array_type(typeOid);
3393 if (OidIsValid(arrayOid))
3394 find_composite_type_dependencies(arrayOid, origTblName, origTypeName);
3399 * ALTER TABLE ADD COLUMN
3401 * Adds an additional attribute to a relation making the assumption that
3402 * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
3403 * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
3407 ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
3411 * Recurse to add the column to child classes, if requested.
3413 * We must recurse one level at a time, so that multiply-inheriting
3414 * children are visited the right number of times and end up with the
3415 * right attinhcount.
3419 AlterTableCmd *childCmd = copyObject(cmd);
3420 ColumnDef *colDefChild = (ColumnDef *) childCmd->def;
3422 /* Child should see column as singly inherited */
3423 colDefChild->inhcount = 1;
3424 colDefChild->is_local = false;
3426 ATOneLevelRecursion(wqueue, rel, childCmd);
3431 * If we are told not to recurse, there had better not be any child
3432 * tables; else the addition would put them out of step.
3434 if (find_inheritance_children(RelationGetRelid(rel)) != NIL)
3436 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3437 errmsg("column must be added to child tables too")));
3442 ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
3445 Oid myrelid = RelationGetRelid(rel);
3449 HeapTuple attributeTuple;
3450 Form_pg_attribute attribute;
3451 FormData_pg_attribute attributeD;
3455 HeapTuple typeTuple;
3461 attrdesc = heap_open(AttributeRelationId, RowExclusiveLock);
3464 * Are we adding the column to a recursion child? If so, check whether to
3465 * merge with an existing definition for the column.
3467 if (colDef->inhcount > 0)
3471 /* Does child already have a column by this name? */
3472 tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
3473 if (HeapTupleIsValid(tuple))
3475 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
3479 /* Okay if child matches by type */
3480 ctypeId = typenameTypeId(NULL, colDef->typename, &ctypmod);
3481 if (ctypeId != childatt->atttypid ||
3482 ctypmod != childatt->atttypmod)
3484 (errcode(ERRCODE_DATATYPE_MISMATCH),
3485 errmsg("child table \"%s\" has different type for column \"%s\"",
3486 RelationGetRelationName(rel), colDef->colname)));
3488 /* Bump the existing child att's inhcount */
3489 childatt->attinhcount++;
3490 simple_heap_update(attrdesc, &tuple->t_self, tuple);
3491 CatalogUpdateIndexes(attrdesc, tuple);
3493 heap_freetuple(tuple);
3495 /* Inform the user about the merge */
3497 (errmsg("merging definition of column \"%s\" for child \"%s\"",
3498 colDef->colname, RelationGetRelationName(rel))));
3500 heap_close(attrdesc, RowExclusiveLock);
3505 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
3507 reltup = SearchSysCacheCopy(RELOID,
3508 ObjectIdGetDatum(myrelid),
3510 if (!HeapTupleIsValid(reltup))
3511 elog(ERROR, "cache lookup failed for relation %u", myrelid);
3514 * this test is deliberately not attisdropped-aware, since if one tries to
3515 * add a column matching a dropped column name, it's gonna fail anyway.
3517 if (SearchSysCacheExists(ATTNAME,
3518 ObjectIdGetDatum(myrelid),
3519 PointerGetDatum(colDef->colname),
3522 (errcode(ERRCODE_DUPLICATE_COLUMN),
3523 errmsg("column \"%s\" of relation \"%s\" already exists",
3524 colDef->colname, RelationGetRelationName(rel))));
3526 minattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts;
3527 maxatts = minattnum + 1;
3528 if (maxatts > MaxHeapAttributeNumber)
3530 (errcode(ERRCODE_TOO_MANY_COLUMNS),
3531 errmsg("tables can have at most %d columns",
3532 MaxHeapAttributeNumber)));
3535 typeTuple = typenameType(NULL, colDef->typename, &typmod);
3536 tform = (Form_pg_type) GETSTRUCT(typeTuple);
3537 typeOid = HeapTupleGetOid(typeTuple);
3539 /* make sure datatype is legal for a column */
3540 CheckAttributeType(colDef->colname, typeOid);
3542 attributeTuple = heap_addheader(Natts_pg_attribute,
3544 ATTRIBUTE_TUPLE_SIZE,
3545 (void *) &attributeD);
3547 attribute = (Form_pg_attribute) GETSTRUCT(attributeTuple);
3549 attribute->attrelid = myrelid;
3550 namestrcpy(&(attribute->attname), colDef->colname);
3551 attribute->atttypid = typeOid;
3552 attribute->attstattarget = -1;
3553 attribute->attlen = tform->typlen;
3554 attribute->attcacheoff = -1;
3555 attribute->atttypmod = typmod;
3556 attribute->attnum = i;
3557 attribute->attbyval = tform->typbyval;
3558 attribute->attndims = list_length(colDef->typename->arrayBounds);
3559 attribute->attstorage = tform->typstorage;
3560 attribute->attalign = tform->typalign;
3561 attribute->attnotnull = colDef->is_not_null;
3562 attribute->atthasdef = false;
3563 attribute->attisdropped = false;
3564 attribute->attislocal = colDef->is_local;
3565 attribute->attinhcount = colDef->inhcount;
3567 ReleaseSysCache(typeTuple);
3569 simple_heap_insert(attrdesc, attributeTuple);
3571 /* Update indexes on pg_attribute */
3572 CatalogUpdateIndexes(attrdesc, attributeTuple);
3574 heap_close(attrdesc, RowExclusiveLock);
3577 * Update number of attributes in pg_class tuple
3579 ((Form_pg_class) GETSTRUCT(reltup))->relnatts = maxatts;
3581 simple_heap_update(pgclass, &reltup->t_self, reltup);
3583 /* keep catalog indexes current */
3584 CatalogUpdateIndexes(pgclass, reltup);
3586 heap_freetuple(reltup);
3588 heap_close(pgclass, RowExclusiveLock);
3590 /* Make the attribute's catalog entry visible */
3591 CommandCounterIncrement();
3594 * Store the DEFAULT, if any, in the catalogs
3596 if (colDef->raw_default)
3598 RawColumnDefault *rawEnt;
3600 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3601 rawEnt->attnum = attribute->attnum;
3602 rawEnt->raw_default = copyObject(colDef->raw_default);
3605 * This function is intended for CREATE TABLE, so it processes a
3606 * _list_ of defaults, but we just do one.
3608 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL, false, true);
3610 /* Make the additional catalog changes visible */
3611 CommandCounterIncrement();
3615 * Tell Phase 3 to fill in the default expression, if there is one.
3617 * If there is no default, Phase 3 doesn't have to do anything, because
3618 * that effectively means that the default is NULL. The heap tuple access
3619 * routines always check for attnum > # of attributes in tuple, and return
3620 * NULL if so, so without any modification of the tuple data we will get
3621 * the effect of NULL values in the new column.
3623 * An exception occurs when the new column is of a domain type: the domain
3624 * might have a NOT NULL constraint, or a check constraint that indirectly
3625 * rejects nulls. If there are any domain constraints then we construct
3626 * an explicit NULL default value that will be passed through
3627 * CoerceToDomain processing. (This is a tad inefficient, since it causes
3628 * rewriting the table which we really don't have to do, but the present
3629 * design of domain processing doesn't offer any simple way of checking
3630 * the constraints more directly.)
3632 * Note: we use build_column_default, and not just the cooked default
3633 * returned by AddRelationNewConstraints, so that the right thing happens
3634 * when a datatype's default applies.
3636 defval = (Expr *) build_column_default(rel, attribute->attnum);
3638 if (!defval && GetDomainConstraints(typeOid) != NIL)
3643 baseTypeMod = typmod;
3644 baseTypeId = getBaseTypeAndTypmod(typeOid, &baseTypeMod);
3645 defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod);
3646 defval = (Expr *) coerce_to_target_type(NULL,
3651 COERCION_ASSIGNMENT,
3652 COERCE_IMPLICIT_CAST);
3653 if (defval == NULL) /* should not happen */
3654 elog(ERROR, "failed to coerce base type to domain");
3659 NewColumnValue *newval;
3661 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
3662 newval->attnum = attribute->attnum;
3663 newval->expr = defval;
3665 tab->newvals = lappend(tab->newvals, newval);
3669 * If the new column is NOT NULL, tell Phase 3 it needs to test that.
3671 tab->new_notnull |= colDef->is_not_null;
3674 * Add needed dependency entries for the new column.
3676 add_column_datatype_dependency(myrelid, i, attribute->atttypid);
3680 * Install a column's dependency on its datatype.
3683 add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
3685 ObjectAddress myself,
3688 myself.classId = RelationRelationId;
3689 myself.objectId = relid;
3690 myself.objectSubId = attnum;
3691 referenced.classId = TypeRelationId;
3692 referenced.objectId = typid;
3693 referenced.objectSubId = 0;
3694 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
3698 * ALTER TABLE ALTER COLUMN DROP NOT NULL
3701 ATExecDropNotNull(Relation rel, const char *colName)
3707 ListCell *indexoidscan;
3710 * lookup the attribute
3712 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3714 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3716 if (!HeapTupleIsValid(tuple))
3718 (errcode(ERRCODE_UNDEFINED_COLUMN),
3719 errmsg("column \"%s\" of relation \"%s\" does not exist",
3720 colName, RelationGetRelationName(rel))));
3722 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3724 /* Prevent them from altering a system attribute */
3727 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3728 errmsg("cannot alter system column \"%s\"",
3732 * Check that the attribute is not in a primary key
3735 /* Loop over all indexes on the relation */
3736 indexoidlist = RelationGetIndexList(rel);
3738 foreach(indexoidscan, indexoidlist)
3740 Oid indexoid = lfirst_oid(indexoidscan);
3741 HeapTuple indexTuple;
3742 Form_pg_index indexStruct;
3745 indexTuple = SearchSysCache(INDEXRELID,
3746 ObjectIdGetDatum(indexoid),
3748 if (!HeapTupleIsValid(indexTuple))
3749 elog(ERROR, "cache lookup failed for index %u", indexoid);
3750 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
3752 /* If the index is not a primary key, skip the check */
3753 if (indexStruct->indisprimary)
3756 * Loop over each attribute in the primary key and see if it
3757 * matches the to-be-altered attribute
3759 for (i = 0; i < indexStruct->indnatts; i++)
3761 if (indexStruct->indkey.values[i] == attnum)
3763 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3764 errmsg("column \"%s\" is in a primary key",
3769 ReleaseSysCache(indexTuple);
3772 list_free(indexoidlist);
3775 * Okay, actually perform the catalog change ... if needed
3777 if (((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3779 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = FALSE;
3781 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3783 /* keep the system catalog indexes current */
3784 CatalogUpdateIndexes(attr_rel, tuple);
3787 heap_close(attr_rel, RowExclusiveLock);
3791 * ALTER TABLE ALTER COLUMN SET NOT NULL
3794 ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
3795 const char *colName)
3802 * lookup the attribute
3804 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3806 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3808 if (!HeapTupleIsValid(tuple))
3810 (errcode(ERRCODE_UNDEFINED_COLUMN),
3811 errmsg("column \"%s\" of relation \"%s\" does not exist",
3812 colName, RelationGetRelationName(rel))));
3814 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3816 /* Prevent them from altering a system attribute */
3819 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3820 errmsg("cannot alter system column \"%s\"",
3824 * Okay, actually perform the catalog change ... if needed
3826 if (!((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3828 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = TRUE;
3830 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3832 /* keep the system catalog indexes current */
3833 CatalogUpdateIndexes(attr_rel, tuple);
3835 /* Tell Phase 3 it needs to test the constraint */
3836 tab->new_notnull = true;
3839 heap_close(attr_rel, RowExclusiveLock);
3843 * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
3846 ATExecColumnDefault(Relation rel, const char *colName,
3852 * get the number of the attribute
3854 attnum = get_attnum(RelationGetRelid(rel), colName);
3855 if (attnum == InvalidAttrNumber)
3857 (errcode(ERRCODE_UNDEFINED_COLUMN),
3858 errmsg("column \"%s\" of relation \"%s\" does not exist",
3859 colName, RelationGetRelationName(rel))));
3861 /* Prevent them from altering a system attribute */
3864 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3865 errmsg("cannot alter system column \"%s\"",
3869 * Remove any old default for the column. We use RESTRICT here for
3870 * safety, but at present we do not expect anything to depend on the
3873 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false);
3878 RawColumnDefault *rawEnt;
3880 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3881 rawEnt->attnum = attnum;
3882 rawEnt->raw_default = newDefault;
3885 * This function is intended for CREATE TABLE, so it processes a
3886 * _list_ of defaults, but we just do one.
3888 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL, false, true);
3893 * ALTER TABLE ALTER COLUMN SET STATISTICS
3896 ATPrepSetStatistics(Relation rel, const char *colName, Node *flagValue)
3899 * We do our own permission checking because (a) we want to allow SET
3900 * STATISTICS on indexes (for expressional index columns), and (b) we want
3901 * to allow SET STATISTICS on system catalogs without requiring
3902 * allowSystemTableMods to be turned on.
3904 if (rel->rd_rel->relkind != RELKIND_RELATION &&
3905 rel->rd_rel->relkind != RELKIND_INDEX)
3907 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3908 errmsg("\"%s\" is not a table or index",
3909 RelationGetRelationName(rel))));
3911 /* Permissions checks */
3912 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3913 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3914 RelationGetRelationName(rel));
3918 ATExecSetStatistics(Relation rel, const char *colName, Node *newValue)
3921 Relation attrelation;
3923 Form_pg_attribute attrtuple;
3925 Assert(IsA(newValue, Integer));
3926 newtarget = intVal(newValue);
3929 * Limit target to a sane range
3934 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3935 errmsg("statistics target %d is too low",
3938 else if (newtarget > 1000)
3942 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3943 errmsg("lowering statistics target to %d",
3947 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
3949 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3951 if (!HeapTupleIsValid(tuple))
3953 (errcode(ERRCODE_UNDEFINED_COLUMN),
3954 errmsg("column \"%s\" of relation \"%s\" does not exist",
3955 colName, RelationGetRelationName(rel))));
3956 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
3958 if (attrtuple->attnum <= 0)
3960 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3961 errmsg("cannot alter system column \"%s\"",
3964 attrtuple->attstattarget = newtarget;
3966 simple_heap_update(attrelation, &tuple->t_self, tuple);
3968 /* keep system catalog indexes current */
3969 CatalogUpdateIndexes(attrelation, tuple);
3971 heap_freetuple(tuple);
3973 heap_close(attrelation, RowExclusiveLock);
3977 * ALTER TABLE ALTER COLUMN SET STORAGE
3980 ATExecSetStorage(Relation rel, const char *colName, Node *newValue)
3984 Relation attrelation;
3986 Form_pg_attribute attrtuple;
3988 Assert(IsA(newValue, String));
3989 storagemode = strVal(newValue);
3991 if (pg_strcasecmp(storagemode, "plain") == 0)
3993 else if (pg_strcasecmp(storagemode, "external") == 0)
3995 else if (pg_strcasecmp(storagemode, "extended") == 0)
3997 else if (pg_strcasecmp(storagemode, "main") == 0)
4002 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4003 errmsg("invalid storage type \"%s\"",
4005 newstorage = 0; /* keep compiler quiet */
4008 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
4010 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4012 if (!HeapTupleIsValid(tuple))
4014 (errcode(ERRCODE_UNDEFINED_COLUMN),
4015 errmsg("column \"%s\" of relation \"%s\" does not exist",
4016 colName, RelationGetRelationName(rel))));
4017 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
4019 if (attrtuple->attnum <= 0)
4021 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4022 errmsg("cannot alter system column \"%s\"",
4026 * safety check: do not allow toasted storage modes unless column datatype
4029 if (newstorage == 'p' || TypeIsToastable(attrtuple->atttypid))
4030 attrtuple->attstorage = newstorage;
4033 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4034 errmsg("column data type %s can only have storage PLAIN",
4035 format_type_be(attrtuple->atttypid))));
4037 simple_heap_update(attrelation, &tuple->t_self, tuple);
4039 /* keep system catalog indexes current */
4040 CatalogUpdateIndexes(attrelation, tuple);
4042 heap_freetuple(tuple);
4044 heap_close(attrelation, RowExclusiveLock);
4049 * ALTER TABLE DROP COLUMN
4051 * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
4052 * because we have to decide at runtime whether to recurse or not depending
4053 * on whether attinhcount goes to zero or not. (We can't check this in a
4054 * static pre-pass because it won't handle multiple inheritance situations
4055 * correctly.) Since DROP COLUMN doesn't need to create any work queue
4056 * entries for Phase 3, it's okay to recurse internally in this routine
4057 * without considering the work queue.
4060 ATExecDropColumn(Relation rel, const char *colName,
4061 DropBehavior behavior,
4062 bool recurse, bool recursing)
4065 Form_pg_attribute targetatt;
4068 ObjectAddress object;
4070 /* At top level, permission check was done in ATPrepCmd, else do it */
4072 ATSimplePermissions(rel, false);
4075 * get the number of the attribute
4077 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
4078 if (!HeapTupleIsValid(tuple))
4080 (errcode(ERRCODE_UNDEFINED_COLUMN),
4081 errmsg("column \"%s\" of relation \"%s\" does not exist",
4082 colName, RelationGetRelationName(rel))));
4083 targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
4085 attnum = targetatt->attnum;
4087 /* Can't drop a system attribute, except OID */
4088 if (attnum <= 0 && attnum != ObjectIdAttributeNumber)
4090 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4091 errmsg("cannot drop system column \"%s\"",
4094 /* Don't drop inherited columns */
4095 if (targetatt->attinhcount > 0 && !recursing)
4097 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4098 errmsg("cannot drop inherited column \"%s\"",
4101 ReleaseSysCache(tuple);
4104 * Propagate to children as appropriate. Unlike most other ALTER
4105 * routines, we have to do this one level of recursion at a time; we can't
4106 * use find_all_inheritors to do it in one pass.
4108 children = find_inheritance_children(RelationGetRelid(rel));
4115 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
4116 foreach(child, children)
4118 Oid childrelid = lfirst_oid(child);
4120 Form_pg_attribute childatt;
4122 childrel = heap_open(childrelid, AccessExclusiveLock);
4123 CheckTableNotInUse(childrel, "ALTER TABLE");
4125 tuple = SearchSysCacheCopyAttName(childrelid, colName);
4126 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
4127 elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
4128 colName, childrelid);
4129 childatt = (Form_pg_attribute) GETSTRUCT(tuple);
4131 if (childatt->attinhcount <= 0) /* shouldn't happen */
4132 elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
4133 childrelid, colName);
4138 * If the child column has other definition sources, just
4139 * decrement its inheritance count; if not, recurse to delete
4142 if (childatt->attinhcount == 1 && !childatt->attislocal)
4144 /* Time to delete this child column, too */
4145 ATExecDropColumn(childrel, colName, behavior, true, true);
4149 /* Child column must survive my deletion */
4150 childatt->attinhcount--;
4152 simple_heap_update(attr_rel, &tuple->t_self, tuple);
4154 /* keep the system catalog indexes current */
4155 CatalogUpdateIndexes(attr_rel, tuple);
4157 /* Make update visible */
4158 CommandCounterIncrement();
4164 * If we were told to drop ONLY in this table (no recursion),
4165 * we need to mark the inheritors' attributes as locally
4166 * defined rather than inherited.
4168 childatt->attinhcount--;
4169 childatt->attislocal = true;
4171 simple_heap_update(attr_rel, &tuple->t_self, tuple);
4173 /* keep the system catalog indexes current */
4174 CatalogUpdateIndexes(attr_rel, tuple);
4176 /* Make update visible */
4177 CommandCounterIncrement();
4180 heap_freetuple(tuple);
4182 heap_close(childrel, NoLock);
4184 heap_close(attr_rel, RowExclusiveLock);
4188 * Perform the actual column deletion
4190 object.classId = RelationRelationId;
4191 object.objectId = RelationGetRelid(rel);
4192 object.objectSubId = attnum;
4194 performDeletion(&object, behavior);
4197 * If we dropped the OID column, must adjust pg_class.relhasoids
4199 if (attnum == ObjectIdAttributeNumber)
4202 Form_pg_class tuple_class;
4204 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
4206 tuple = SearchSysCacheCopy(RELOID,
4207 ObjectIdGetDatum(RelationGetRelid(rel)),
4209 if (!HeapTupleIsValid(tuple))
4210 elog(ERROR, "cache lookup failed for relation %u",
4211 RelationGetRelid(rel));
4212 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
4214 tuple_class->relhasoids = false;
4215 simple_heap_update(class_rel, &tuple->t_self, tuple);
4217 /* Keep the catalog indexes up to date */
4218 CatalogUpdateIndexes(class_rel, tuple);
4220 heap_close(class_rel, RowExclusiveLock);
4225 * ALTER TABLE ADD INDEX
4227 * There is no such command in the grammar, but parse_utilcmd.c converts
4228 * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands. This lets
4229 * us schedule creation of the index at the appropriate time during ALTER.
4232 ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
4233 IndexStmt *stmt, bool is_rebuild)
4239 Assert(IsA(stmt, IndexStmt));
4241 /* suppress schema rights check when rebuilding existing index */
4242 check_rights = !is_rebuild;
4243 /* skip index build if phase 3 will have to rewrite table anyway */
4244 skip_build = (tab->newvals != NIL);
4245 /* suppress notices when rebuilding existing index */
4248 /* The IndexStmt has already been through transformIndexStmt */
4250 DefineIndex(stmt->relation, /* relation */
4251 stmt->idxname, /* index name */
4252 InvalidOid, /* no predefined OID */
4253 stmt->accessMethod, /* am name */
4255 stmt->indexParams, /* parameters */
4256 (Expr *) stmt->whereClause,
4261 true, /* is_alter_table */
4269 * ALTER TABLE ADD CONSTRAINT
4272 ATExecAddConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
4273 Node *newConstraint, bool recurse)
4275 switch (nodeTag(newConstraint))
4279 Constraint *constr = (Constraint *) newConstraint;
4282 * Currently, we only expect to see CONSTR_CHECK nodes
4283 * arriving here (see the preprocessing done in
4284 * parse_utilcmd.c). Use a switch anyway to make it easier to
4285 * add more code later.
4287 switch (constr->contype)
4290 ATAddCheckConstraint(wqueue, tab, rel,
4291 constr, recurse, false);
4294 elog(ERROR, "unrecognized constraint type: %d",
4295 (int) constr->contype);
4299 case T_FkConstraint:
4301 FkConstraint *fkconstraint = (FkConstraint *) newConstraint;
4304 * Note that we currently never recurse for FK constraints,
4305 * so the "recurse" flag is silently ignored.
4307 * Assign or validate constraint name
4309 if (fkconstraint->constr_name)
4311 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
4312 RelationGetRelid(rel),
4313 RelationGetNamespace(rel),
4314 fkconstraint->constr_name))
4316 (errcode(ERRCODE_DUPLICATE_OBJECT),
4317 errmsg("constraint \"%s\" for relation \"%s\" already exists",
4318 fkconstraint->constr_name,
4319 RelationGetRelationName(rel))));
4322 fkconstraint->constr_name =
4323 ChooseConstraintName(RelationGetRelationName(rel),
4324 strVal(linitial(fkconstraint->fk_attrs)),
4326 RelationGetNamespace(rel),
4329 ATAddForeignKeyConstraint(tab, rel, fkconstraint);
4334 elog(ERROR, "unrecognized node type: %d",
4335 (int) nodeTag(newConstraint));
4340 * Add a check constraint to a single table and its children
4342 * Subroutine for ATExecAddConstraint.
4344 * We must recurse to child tables during execution, rather than using
4345 * ALTER TABLE's normal prep-time recursion. The reason is that all the
4346 * constraints *must* be given the same name, else they won't be seen as
4347 * related later. If the user didn't explicitly specify a name, then
4348 * AddRelationNewConstraints would normally assign different names to the
4349 * child constraints. To fix that, we must capture the name assigned at
4350 * the parent table and pass that down.
4353 ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
4354 Constraint *constr, bool recurse, bool recursing)
4361 /* At top level, permission check was done in ATPrepCmd, else do it */
4363 ATSimplePermissions(rel, false);
4366 * Call AddRelationNewConstraints to do the work, making sure it works on
4367 * a copy of the Constraint so transformExpr can't modify the original.
4368 * It returns a list of cooked constraints.
4370 * If the constraint ends up getting merged with a pre-existing one, it's
4371 * omitted from the returned list, which is what we want: we do not need
4372 * to do any validation work. That can only happen at child tables,
4373 * though, since we disallow merging at the top level.
4375 newcons = AddRelationNewConstraints(rel, NIL,
4376 list_make1(copyObject(constr)),
4377 recursing, !recursing);
4379 /* Add each constraint to Phase 3's queue */
4380 foreach(lcon, newcons)
4382 CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
4383 NewConstraint *newcon;
4385 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
4386 newcon->name = ccon->name;
4387 newcon->contype = ccon->contype;
4388 /* ExecQual wants implicit-AND format */
4389 newcon->qual = (Node *) make_ands_implicit((Expr *) ccon->expr);
4391 tab->constraints = lappend(tab->constraints, newcon);
4393 /* Save the actually assigned name if it was defaulted */
4394 if (constr->name == NULL)
4395 constr->name = ccon->name;
4398 /* At this point we must have a locked-down name to use */
4399 Assert(constr->name != NULL);
4401 /* Advance command counter in case same table is visited multiple times */
4402 CommandCounterIncrement();
4405 * Propagate to children as appropriate. Unlike most other ALTER
4406 * routines, we have to do this one level of recursion at a time; we can't
4407 * use find_all_inheritors to do it in one pass.
4409 children = find_inheritance_children(RelationGetRelid(rel));
4412 * If we are told not to recurse, there had better not be any child
4413 * tables; else the addition would put them out of step.
4415 if (children && !recurse)
4417 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4418 errmsg("constraint must be added to child tables too")));
4420 foreach(child, children)
4422 Oid childrelid = lfirst_oid(child);
4424 AlteredTableInfo *childtab;
4426 childrel = heap_open(childrelid, AccessExclusiveLock);
4427 CheckTableNotInUse(childrel, "ALTER TABLE");
4429 /* Find or create work queue entry for this table */
4430 childtab = ATGetQueueEntry(wqueue, childrel);
4432 /* Recurse to child */
4433 ATAddCheckConstraint(wqueue, childtab, childrel,
4434 constr, recurse, true);
4436 heap_close(childrel, NoLock);
4441 * Add a foreign-key constraint to a single table
4443 * Subroutine for ATExecAddConstraint. Must already hold exclusive
4444 * lock on the rel, and have done appropriate validity/permissions checks
4448 ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
4449 FkConstraint *fkconstraint)
4452 AclResult aclresult;
4453 int16 pkattnum[INDEX_MAX_KEYS];
4454 int16 fkattnum[INDEX_MAX_KEYS];
4455 Oid pktypoid[INDEX_MAX_KEYS];
4456 Oid fktypoid[INDEX_MAX_KEYS];
4457 Oid opclasses[INDEX_MAX_KEYS];
4458 Oid pfeqoperators[INDEX_MAX_KEYS];
4459 Oid ppeqoperators[INDEX_MAX_KEYS];
4460 Oid ffeqoperators[INDEX_MAX_KEYS];
4468 * Grab an exclusive lock on the pk table, so that someone doesn't delete
4469 * rows out from under us. (Although a lesser lock would do for that
4470 * purpose, we'll need exclusive lock anyway to add triggers to the pk
4471 * table; trying to start with a lesser lock will just create a risk of
4474 pkrel = heap_openrv(fkconstraint->pktable, AccessExclusiveLock);
4477 * Validity and permissions checks
4479 * Note: REFERENCES permissions checks are redundant with CREATE TRIGGER,
4480 * but we may as well error out sooner instead of later.
4482 if (pkrel->rd_rel->relkind != RELKIND_RELATION)
4484 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4485 errmsg("referenced relation \"%s\" is not a table",
4486 RelationGetRelationName(pkrel))));
4488 aclresult = pg_class_aclcheck(RelationGetRelid(pkrel), GetUserId(),
4490 if (aclresult != ACLCHECK_OK)
4491 aclcheck_error(aclresult, ACL_KIND_CLASS,
4492 RelationGetRelationName(pkrel));
4494 if (!allowSystemTableMods && IsSystemRelation(pkrel))
4496 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4497 errmsg("permission denied: \"%s\" is a system catalog",
4498 RelationGetRelationName(pkrel))));
4500 aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
4502 if (aclresult != ACLCHECK_OK)
4503 aclcheck_error(aclresult, ACL_KIND_CLASS,
4504 RelationGetRelationName(rel));
4507 * Disallow reference from permanent table to temp table or vice versa.
4508 * (The ban on perm->temp is for fairly obvious reasons. The ban on
4509 * temp->perm is because other backends might need to run the RI triggers
4510 * on the perm table, but they can't reliably see tuples the owning
4511 * backend has created in the temp table, because non-shared buffers are
4512 * used for temp tables.)
4514 if (isTempNamespace(RelationGetNamespace(pkrel)))
4516 if (!isTempNamespace(RelationGetNamespace(rel)))
4518 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4519 errmsg("cannot reference temporary table from permanent table constraint")));
4523 if (isTempNamespace(RelationGetNamespace(rel)))
4525 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4526 errmsg("cannot reference permanent table from temporary table constraint")));
4530 * Look up the referencing attributes to make sure they exist, and record
4531 * their attnums and type OIDs.
4533 MemSet(pkattnum, 0, sizeof(pkattnum));
4534 MemSet(fkattnum, 0, sizeof(fkattnum));
4535 MemSet(pktypoid, 0, sizeof(pktypoid));
4536 MemSet(fktypoid, 0, sizeof(fktypoid));
4537 MemSet(opclasses, 0, sizeof(opclasses));
4538 MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
4539 MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
4540 MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
4542 numfks = transformColumnNameList(RelationGetRelid(rel),
4543 fkconstraint->fk_attrs,
4544 fkattnum, fktypoid);
4547 * If the attribute list for the referenced table was omitted, lookup the
4548 * definition of the primary key and use it. Otherwise, validate the
4549 * supplied attribute list. In either case, discover the index OID and
4550 * index opclasses, and the attnums and type OIDs of the attributes.
4552 if (fkconstraint->pk_attrs == NIL)
4554 numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
4555 &fkconstraint->pk_attrs,
4561 numpks = transformColumnNameList(RelationGetRelid(pkrel),
4562 fkconstraint->pk_attrs,
4563 pkattnum, pktypoid);
4564 /* Look for an index matching the column list */
4565 indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
4570 * Look up the equality operators to use in the constraint.
4572 * Note that we have to be careful about the difference between the actual
4573 * PK column type and the opclass' declared input type, which might be
4574 * only binary-compatible with it. The declared opcintype is the right
4575 * thing to probe pg_amop with.
4577 if (numfks != numpks)
4579 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4580 errmsg("number of referencing and referenced columns for foreign key disagree")));
4582 for (i = 0; i < numpks; i++)
4584 Oid pktype = pktypoid[i];
4585 Oid fktype = fktypoid[i];
4588 Form_pg_opclass cla_tup;
4597 /* We need several fields out of the pg_opclass entry */
4598 cla_ht = SearchSysCache(CLAOID,
4599 ObjectIdGetDatum(opclasses[i]),
4601 if (!HeapTupleIsValid(cla_ht))
4602 elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
4603 cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
4604 amid = cla_tup->opcmethod;
4605 opfamily = cla_tup->opcfamily;
4606 opcintype = cla_tup->opcintype;
4607 ReleaseSysCache(cla_ht);
4610 * Check it's a btree; currently this can never fail since no other
4611 * index AMs support unique indexes. If we ever did have other types
4612 * of unique indexes, we'd need a way to determine which operator
4613 * strategy number is equality. (Is it reasonable to insist that
4614 * every such index AM use btree's number for equality?)
4616 if (amid != BTREE_AM_OID)
4617 elog(ERROR, "only b-tree indexes are supported for foreign keys");
4618 eqstrategy = BTEqualStrategyNumber;
4621 * There had better be a primary equality operator for the index.
4622 * We'll use it for PK = PK comparisons.
4624 ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
4627 if (!OidIsValid(ppeqop))
4628 elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
4629 eqstrategy, opcintype, opcintype, opfamily);
4632 * Are there equality operators that take exactly the FK type? Assume
4633 * we should look through any domain here.
4635 fktyped = getBaseType(fktype);
4637 pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
4639 if (OidIsValid(pfeqop))
4640 ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
4643 ffeqop = InvalidOid; /* keep compiler quiet */
4645 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4648 * Otherwise, look for an implicit cast from the FK type to the
4649 * opcintype, and if found, use the primary equality operator.
4650 * This is a bit tricky because opcintype might be a polymorphic
4651 * type such as ANYARRAY or ANYENUM; so what we have to test is
4652 * whether the two actual column types can be concurrently cast to
4653 * that type. (Otherwise, we'd fail to reject combinations such
4654 * as int[] and point[].)
4656 Oid input_typeids[2];
4657 Oid target_typeids[2];
4659 input_typeids[0] = pktype;
4660 input_typeids[1] = fktype;
4661 target_typeids[0] = opcintype;
4662 target_typeids[1] = opcintype;
4663 if (can_coerce_type(2, input_typeids, target_typeids,
4665 pfeqop = ffeqop = ppeqop;
4668 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4670 (errcode(ERRCODE_DATATYPE_MISMATCH),
4671 errmsg("foreign key constraint \"%s\" "
4672 "cannot be implemented",
4673 fkconstraint->constr_name),
4674 errdetail("Key columns \"%s\" and \"%s\" "
4675 "are of incompatible types: %s and %s.",
4676 strVal(list_nth(fkconstraint->fk_attrs, i)),
4677 strVal(list_nth(fkconstraint->pk_attrs, i)),
4678 format_type_be(fktype),
4679 format_type_be(pktype))));
4681 pfeqoperators[i] = pfeqop;
4682 ppeqoperators[i] = ppeqop;
4683 ffeqoperators[i] = ffeqop;
4687 * Record the FK constraint in pg_constraint.
4689 constrOid = CreateConstraintEntry(fkconstraint->constr_name,
4690 RelationGetNamespace(rel),
4692 fkconstraint->deferrable,
4693 fkconstraint->initdeferred,
4694 RelationGetRelid(rel),
4697 InvalidOid, /* not a domain
4699 RelationGetRelid(pkrel),
4705 fkconstraint->fk_upd_action,
4706 fkconstraint->fk_del_action,
4707 fkconstraint->fk_matchtype,
4709 NULL, /* no check constraint */
4716 * Create the triggers that will enforce the constraint.
4718 createForeignKeyTriggers(rel, fkconstraint, constrOid);
4721 * Tell Phase 3 to check that the constraint is satisfied by existing rows
4722 * (we can skip this during table creation).
4724 if (!fkconstraint->skip_validation)
4726 NewConstraint *newcon;
4728 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
4729 newcon->name = fkconstraint->constr_name;
4730 newcon->contype = CONSTR_FOREIGN;
4731 newcon->refrelid = RelationGetRelid(pkrel);
4732 newcon->conid = constrOid;
4733 newcon->qual = (Node *) fkconstraint;
4735 tab->constraints = lappend(tab->constraints, newcon);
4739 * Close pk table, but keep lock until we've committed.
4741 heap_close(pkrel, NoLock);
4746 * transformColumnNameList - transform list of column names
4748 * Lookup each name and return its attnum and type OID
4751 transformColumnNameList(Oid relId, List *colList,
4752 int16 *attnums, Oid *atttypids)
4760 char *attname = strVal(lfirst(l));
4763 atttuple = SearchSysCacheAttName(relId, attname);
4764 if (!HeapTupleIsValid(atttuple))
4766 (errcode(ERRCODE_UNDEFINED_COLUMN),
4767 errmsg("column \"%s\" referenced in foreign key constraint does not exist",
4769 if (attnum >= INDEX_MAX_KEYS)
4771 (errcode(ERRCODE_TOO_MANY_COLUMNS),
4772 errmsg("cannot have more than %d keys in a foreign key",
4774 attnums[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->attnum;
4775 atttypids[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->atttypid;
4776 ReleaseSysCache(atttuple);
4784 * transformFkeyGetPrimaryKey -
4786 * Look up the names, attnums, and types of the primary key attributes
4787 * for the pkrel. Also return the index OID and index opclasses of the
4788 * index supporting the primary key.
4790 * All parameters except pkrel are output parameters. Also, the function
4791 * return value is the number of attributes in the primary key.
4793 * Used when the column list in the REFERENCES specification is omitted.
4796 transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
4798 int16 *attnums, Oid *atttypids,
4802 ListCell *indexoidscan;
4803 HeapTuple indexTuple = NULL;
4804 Form_pg_index indexStruct = NULL;
4805 Datum indclassDatum;
4807 oidvector *indclass;
4811 * Get the list of index OIDs for the table from the relcache, and look up
4812 * each one in the pg_index syscache until we find one marked primary key
4813 * (hopefully there isn't more than one such).
4815 *indexOid = InvalidOid;
4817 indexoidlist = RelationGetIndexList(pkrel);
4819 foreach(indexoidscan, indexoidlist)
4821 Oid indexoid = lfirst_oid(indexoidscan);
4823 indexTuple = SearchSysCache(INDEXRELID,
4824 ObjectIdGetDatum(indexoid),
4826 if (!HeapTupleIsValid(indexTuple))
4827 elog(ERROR, "cache lookup failed for index %u", indexoid);
4828 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4829 if (indexStruct->indisprimary)
4831 *indexOid = indexoid;
4834 ReleaseSysCache(indexTuple);
4837 list_free(indexoidlist);
4840 * Check that we found it
4842 if (!OidIsValid(*indexOid))
4844 (errcode(ERRCODE_UNDEFINED_OBJECT),
4845 errmsg("there is no primary key for referenced table \"%s\"",
4846 RelationGetRelationName(pkrel))));
4848 /* Must get indclass the hard way */
4849 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4850 Anum_pg_index_indclass, &isnull);
4852 indclass = (oidvector *) DatumGetPointer(indclassDatum);
4855 * Now build the list of PK attributes from the indkey definition (we
4856 * assume a primary key cannot have expressional elements)
4859 for (i = 0; i < indexStruct->indnatts; i++)
4861 int pkattno = indexStruct->indkey.values[i];
4863 attnums[i] = pkattno;
4864 atttypids[i] = attnumTypeId(pkrel, pkattno);
4865 opclasses[i] = indclass->values[i];
4866 *attnamelist = lappend(*attnamelist,
4867 makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
4870 ReleaseSysCache(indexTuple);
4876 * transformFkeyCheckAttrs -
4878 * Make sure that the attributes of a referenced table belong to a unique
4879 * (or primary key) constraint. Return the OID of the index supporting
4880 * the constraint, as well as the opclasses associated with the index
4884 transformFkeyCheckAttrs(Relation pkrel,
4885 int numattrs, int16 *attnums,
4886 Oid *opclasses) /* output parameter */
4888 Oid indexoid = InvalidOid;
4891 ListCell *indexoidscan;
4894 * Get the list of index OIDs for the table from the relcache, and look up
4895 * each one in the pg_index syscache, and match unique indexes to the list
4896 * of attnums we are given.
4898 indexoidlist = RelationGetIndexList(pkrel);
4900 foreach(indexoidscan, indexoidlist)
4902 HeapTuple indexTuple;
4903 Form_pg_index indexStruct;
4907 indexoid = lfirst_oid(indexoidscan);
4908 indexTuple = SearchSysCache(INDEXRELID,
4909 ObjectIdGetDatum(indexoid),
4911 if (!HeapTupleIsValid(indexTuple))
4912 elog(ERROR, "cache lookup failed for index %u", indexoid);
4913 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4916 * Must have the right number of columns; must be unique and not a
4917 * partial index; forget it if there are any expressions, too
4919 if (indexStruct->indnatts == numattrs &&
4920 indexStruct->indisunique &&
4921 heap_attisnull(indexTuple, Anum_pg_index_indpred) &&
4922 heap_attisnull(indexTuple, Anum_pg_index_indexprs))
4924 /* Must get indclass the hard way */
4925 Datum indclassDatum;
4927 oidvector *indclass;
4929 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4930 Anum_pg_index_indclass, &isnull);
4932 indclass = (oidvector *) DatumGetPointer(indclassDatum);
4935 * The given attnum list may match the index columns in any order.
4936 * Check that each list is a subset of the other.
4938 for (i = 0; i < numattrs; i++)
4941 for (j = 0; j < numattrs; j++)
4943 if (attnums[i] == indexStruct->indkey.values[j])
4954 for (i = 0; i < numattrs; i++)
4957 for (j = 0; j < numattrs; j++)
4959 if (attnums[j] == indexStruct->indkey.values[i])
4961 opclasses[j] = indclass->values[i];
4971 ReleaseSysCache(indexTuple);
4978 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4979 errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
4980 RelationGetRelationName(pkrel))));
4982 list_free(indexoidlist);
4988 * Scan the existing rows in a table to verify they meet a proposed FK
4991 * Caller must have opened and locked both relations.
4994 validateForeignKeyConstraint(FkConstraint *fkconstraint,
5004 * Build a trigger call structure; we'll need it either way.
5006 MemSet(&trig, 0, sizeof(trig));
5007 trig.tgoid = InvalidOid;
5008 trig.tgname = fkconstraint->constr_name;
5009 trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
5010 trig.tgisconstraint = TRUE;
5011 trig.tgconstrrelid = RelationGetRelid(pkrel);
5012 trig.tgconstraint = constraintOid;
5013 trig.tgdeferrable = FALSE;
5014 trig.tginitdeferred = FALSE;
5015 /* we needn't fill in tgargs */
5018 * See if we can do it with a single LEFT JOIN query. A FALSE result
5019 * indicates we must proceed with the fire-the-trigger method.
5021 if (RI_Initial_Check(&trig, rel, pkrel))
5025 * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
5026 * if that tuple had just been inserted. If any of those fail, it should
5027 * ereport(ERROR) and that's that.
5029 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
5031 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
5033 FunctionCallInfoData fcinfo;
5034 TriggerData trigdata;
5037 * Make a call to the trigger function
5039 * No parameters are passed, but we do set a context
5041 MemSet(&fcinfo, 0, sizeof(fcinfo));
5044 * We assume RI_FKey_check_ins won't look at flinfo...
5046 trigdata.type = T_TriggerData;
5047 trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
5048 trigdata.tg_relation = rel;
5049 trigdata.tg_trigtuple = tuple;
5050 trigdata.tg_newtuple = NULL;
5051 trigdata.tg_trigger = &trig;
5052 trigdata.tg_trigtuplebuf = scan->rs_cbuf;
5053 trigdata.tg_newtuplebuf = InvalidBuffer;
5055 fcinfo.context = (Node *) &trigdata;
5057 RI_FKey_check_ins(&fcinfo);
5064 CreateFKCheckTrigger(RangeVar *myRel, FkConstraint *fkconstraint,
5065 Oid constraintOid, bool on_insert)
5067 CreateTrigStmt *fk_trigger;
5069 fk_trigger = makeNode(CreateTrigStmt);
5070 fk_trigger->trigname = fkconstraint->constr_name;
5071 fk_trigger->relation = myRel;
5072 fk_trigger->before = false;
5073 fk_trigger->row = true;
5075 /* Either ON INSERT or ON UPDATE */
5078 fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
5079 fk_trigger->actions[0] = 'i';
5083 fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
5084 fk_trigger->actions[0] = 'u';
5086 fk_trigger->actions[1] = '\0';
5088 fk_trigger->isconstraint = true;
5089 fk_trigger->deferrable = fkconstraint->deferrable;
5090 fk_trigger->initdeferred = fkconstraint->initdeferred;
5091 fk_trigger->constrrel = fkconstraint->pktable;
5092 fk_trigger->args = NIL;
5094 (void) CreateTrigger(fk_trigger, constraintOid);
5096 /* Make changes-so-far visible */
5097 CommandCounterIncrement();
5101 * Create the triggers that implement an FK constraint.
5104 createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
5108 CreateTrigStmt *fk_trigger;
5111 * Reconstruct a RangeVar for my relation (not passed in, unfortunately).
5113 myRel = makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
5114 pstrdup(RelationGetRelationName(rel)));
5116 /* Make changes-so-far visible */
5117 CommandCounterIncrement();
5120 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the CHECK
5121 * action for both INSERTs and UPDATEs on the referencing table.
5123 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, true);
5124 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, false);
5127 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
5128 * DELETE action on the referenced table.
5130 fk_trigger = makeNode(CreateTrigStmt);
5131 fk_trigger->trigname = fkconstraint->constr_name;
5132 fk_trigger->relation = fkconstraint->pktable;
5133 fk_trigger->before = false;
5134 fk_trigger->row = true;
5135 fk_trigger->actions[0] = 'd';
5136 fk_trigger->actions[1] = '\0';
5138 fk_trigger->isconstraint = true;
5139 fk_trigger->constrrel = myRel;
5140 switch (fkconstraint->fk_del_action)
5142 case FKCONSTR_ACTION_NOACTION:
5143 fk_trigger->deferrable = fkconstraint->deferrable;
5144 fk_trigger->initdeferred = fkconstraint->initdeferred;
5145 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
5147 case FKCONSTR_ACTION_RESTRICT:
5148 fk_trigger->deferrable = false;
5149 fk_trigger->initdeferred = false;
5150 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
5152 case FKCONSTR_ACTION_CASCADE:
5153 fk_trigger->deferrable = false;
5154 fk_trigger->initdeferred = false;
5155 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
5157 case FKCONSTR_ACTION_SETNULL:
5158 fk_trigger->deferrable = false;
5159 fk_trigger->initdeferred = false;
5160 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
5162 case FKCONSTR_ACTION_SETDEFAULT:
5163 fk_trigger->deferrable = false;
5164 fk_trigger->initdeferred = false;
5165 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
5168 elog(ERROR, "unrecognized FK action type: %d",
5169 (int) fkconstraint->fk_del_action);
5172 fk_trigger->args = NIL;
5174 (void) CreateTrigger(fk_trigger, constraintOid);
5176 /* Make changes-so-far visible */
5177 CommandCounterIncrement();
5180 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
5181 * UPDATE action on the referenced table.
5183 fk_trigger = makeNode(CreateTrigStmt);
5184 fk_trigger->trigname = fkconstraint->constr_name;
5185 fk_trigger->relation = fkconstraint->pktable;
5186 fk_trigger->before = false;
5187 fk_trigger->row = true;
5188 fk_trigger->actions[0] = 'u';
5189 fk_trigger->actions[1] = '\0';
5190 fk_trigger->isconstraint = true;
5191 fk_trigger->constrrel = myRel;
5192 switch (fkconstraint->fk_upd_action)
5194 case FKCONSTR_ACTION_NOACTION:
5195 fk_trigger->deferrable = fkconstraint->deferrable;
5196 fk_trigger->initdeferred = fkconstraint->initdeferred;
5197 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
5199 case FKCONSTR_ACTION_RESTRICT:
5200 fk_trigger->deferrable = false;
5201 fk_trigger->initdeferred = false;
5202 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
5204 case FKCONSTR_ACTION_CASCADE:
5205 fk_trigger->deferrable = false;
5206 fk_trigger->initdeferred = false;
5207 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
5209 case FKCONSTR_ACTION_SETNULL:
5210 fk_trigger->deferrable = false;
5211 fk_trigger->initdeferred = false;
5212 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
5214 case FKCONSTR_ACTION_SETDEFAULT:
5215 fk_trigger->deferrable = false;
5216 fk_trigger->initdeferred = false;
5217 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
5220 elog(ERROR, "unrecognized FK action type: %d",
5221 (int) fkconstraint->fk_upd_action);
5224 fk_trigger->args = NIL;
5226 (void) CreateTrigger(fk_trigger, constraintOid);
5230 * ALTER TABLE DROP CONSTRAINT
5232 * Like DROP COLUMN, we can't use the normal ALTER TABLE recursion mechanism.
5235 ATExecDropConstraint(Relation rel, const char *constrName,
5236 DropBehavior behavior,
5237 bool recurse, bool recursing)
5242 Form_pg_constraint con;
5247 bool is_check_constraint = false;
5249 /* At top level, permission check was done in ATPrepCmd, else do it */
5251 ATSimplePermissions(rel, false);
5253 conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
5256 * Find and drop the target constraint
5259 Anum_pg_constraint_conrelid,
5260 BTEqualStrategyNumber, F_OIDEQ,
5261 ObjectIdGetDatum(RelationGetRelid(rel)));
5262 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
5263 true, SnapshotNow, 1, &key);
5265 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
5267 ObjectAddress conobj;
5269 con = (Form_pg_constraint) GETSTRUCT(tuple);
5271 if (strcmp(NameStr(con->conname), constrName) != 0)
5274 /* Don't drop inherited constraints */
5275 if (con->coninhcount > 0 && !recursing)
5277 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5278 errmsg("cannot drop inherited constraint \"%s\" of relation \"%s\"",
5279 constrName, RelationGetRelationName(rel))));
5281 /* Right now only CHECK constraints can be inherited */
5282 if (con->contype == CONSTRAINT_CHECK)
5283 is_check_constraint = true;
5286 * Perform the actual constraint deletion
5288 conobj.classId = ConstraintRelationId;
5289 conobj.objectId = HeapTupleGetOid(tuple);
5290 conobj.objectSubId = 0;
5292 performDeletion(&conobj, behavior);
5297 systable_endscan(scan);
5301 (errcode(ERRCODE_UNDEFINED_OBJECT),
5302 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
5303 constrName, RelationGetRelationName(rel))));
5306 * Propagate to children as appropriate. Unlike most other ALTER
5307 * routines, we have to do this one level of recursion at a time; we can't
5308 * use find_all_inheritors to do it in one pass.
5310 if (is_check_constraint)
5311 children = find_inheritance_children(RelationGetRelid(rel));
5315 foreach(child, children)
5317 Oid childrelid = lfirst_oid(child);
5320 childrel = heap_open(childrelid, AccessExclusiveLock);
5321 CheckTableNotInUse(childrel, "ALTER TABLE");
5324 Anum_pg_constraint_conrelid,
5325 BTEqualStrategyNumber, F_OIDEQ,
5326 ObjectIdGetDatum(childrelid));
5327 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
5328 true, SnapshotNow, 1, &key);
5332 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
5334 HeapTuple copy_tuple;
5336 con = (Form_pg_constraint) GETSTRUCT(tuple);
5338 /* Right now only CHECK constraints can be inherited */
5339 if (con->contype != CONSTRAINT_CHECK)
5342 if (strcmp(NameStr(con->conname), constrName) != 0)
5347 if (con->coninhcount <= 0) /* shouldn't happen */
5348 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
5349 childrelid, constrName);
5351 copy_tuple = heap_copytuple(tuple);
5352 con = (Form_pg_constraint) GETSTRUCT(copy_tuple);
5357 * If the child constraint has other definition sources,
5358 * just decrement its inheritance count; if not, recurse
5361 if (con->coninhcount == 1 && !con->conislocal)
5363 /* Time to delete this child constraint, too */
5364 ATExecDropConstraint(childrel, constrName, behavior,
5369 /* Child constraint must survive my deletion */
5371 simple_heap_update(conrel, ©_tuple->t_self, copy_tuple);
5372 CatalogUpdateIndexes(conrel, copy_tuple);
5374 /* Make update visible */
5375 CommandCounterIncrement();
5381 * If we were told to drop ONLY in this table (no
5382 * recursion), we need to mark the inheritors' constraints
5383 * as locally defined rather than inherited.
5386 con->conislocal = true;
5388 simple_heap_update(conrel, ©_tuple->t_self, copy_tuple);
5389 CatalogUpdateIndexes(conrel, copy_tuple);
5391 /* Make update visible */
5392 CommandCounterIncrement();
5395 heap_freetuple(copy_tuple);
5398 systable_endscan(scan);
5402 (errcode(ERRCODE_UNDEFINED_OBJECT),
5403 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
5405 RelationGetRelationName(childrel))));
5407 heap_close(childrel, NoLock);
5410 heap_close(conrel, RowExclusiveLock);
5417 ATPrepAlterColumnType(List **wqueue,
5418 AlteredTableInfo *tab, Relation rel,
5419 bool recurse, bool recursing,
5422 char *colName = cmd->name;
5423 TypeName *typename = (TypeName *) cmd->def;
5425 Form_pg_attribute attTup;
5430 NewColumnValue *newval;
5431 ParseState *pstate = make_parsestate(NULL);
5433 /* lookup the attribute so we can check inheritance status */
5434 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
5435 if (!HeapTupleIsValid(tuple))
5437 (errcode(ERRCODE_UNDEFINED_COLUMN),
5438 errmsg("column \"%s\" of relation \"%s\" does not exist",
5439 colName, RelationGetRelationName(rel))));
5440 attTup = (Form_pg_attribute) GETSTRUCT(tuple);
5441 attnum = attTup->attnum;
5443 /* Can't alter a system attribute */
5446 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5447 errmsg("cannot alter system column \"%s\"",
5450 /* Don't alter inherited columns */
5451 if (attTup->attinhcount > 0 && !recursing)
5453 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5454 errmsg("cannot alter inherited column \"%s\"",
5457 /* Look up the target type */
5458 targettype = typenameTypeId(NULL, typename, &targettypmod);
5460 /* make sure datatype is legal for a column */
5461 CheckAttributeType(colName, targettype);
5464 * Set up an expression to transform the old data value to the new type.
5465 * If a USING option was given, transform and use that expression, else
5466 * just take the old value and try to coerce it. We do this first so that
5467 * type incompatibility can be detected before we waste effort, and
5468 * because we need the expression to be parsed against the original table
5475 /* Expression must be able to access vars of old table */
5476 rte = addRangeTableEntryForRelation(pstate,
5481 addRTEtoQuery(pstate, rte, false, true, true);
5483 transform = transformExpr(pstate, cmd->transform);
5485 /* It can't return a set */
5486 if (expression_returns_set(transform))
5488 (errcode(ERRCODE_DATATYPE_MISMATCH),
5489 errmsg("transform expression must not return a set")));
5491 /* No subplans or aggregates, either... */
5492 if (pstate->p_hasSubLinks)
5494 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5495 errmsg("cannot use subquery in transform expression")));
5496 if (pstate->p_hasAggs)
5498 (errcode(ERRCODE_GROUPING_ERROR),
5499 errmsg("cannot use aggregate function in transform expression")));
5503 transform = (Node *) makeVar(1, attnum,
5504 attTup->atttypid, attTup->atttypmod,
5508 transform = coerce_to_target_type(pstate,
5509 transform, exprType(transform),
5510 targettype, targettypmod,
5511 COERCION_ASSIGNMENT,
5512 COERCE_IMPLICIT_CAST);
5513 if (transform == NULL)
5515 (errcode(ERRCODE_DATATYPE_MISMATCH),
5516 errmsg("column \"%s\" cannot be cast to type \"%s\"",
5517 colName, TypeNameToString(typename))));
5520 * Add a work queue item to make ATRewriteTable update the column
5523 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
5524 newval->attnum = attnum;
5525 newval->expr = (Expr *) transform;
5527 tab->newvals = lappend(tab->newvals, newval);
5529 ReleaseSysCache(tuple);
5532 * The recursion case is handled by ATSimpleRecursion. However, if we are
5533 * told not to recurse, there had better not be any child tables; else the
5534 * alter would put them out of step.
5537 ATSimpleRecursion(wqueue, rel, cmd, recurse);
5538 else if (!recursing &&
5539 find_inheritance_children(RelationGetRelid(rel)) != NIL)
5541 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5542 errmsg("type of inherited column \"%s\" must be changed in child tables too",
5547 ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
5548 const char *colName, TypeName *typename)
5551 Form_pg_attribute attTup;
5553 HeapTuple typeTuple;
5558 Relation attrelation;
5564 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
5566 /* Look up the target column */
5567 heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5568 if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
5570 (errcode(ERRCODE_UNDEFINED_COLUMN),
5571 errmsg("column \"%s\" of relation \"%s\" does not exist",
5572 colName, RelationGetRelationName(rel))));
5573 attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
5574 attnum = attTup->attnum;
5576 /* Check for multiple ALTER TYPE on same column --- can't cope */
5577 if (attTup->atttypid != tab->oldDesc->attrs[attnum - 1]->atttypid ||
5578 attTup->atttypmod != tab->oldDesc->attrs[attnum - 1]->atttypmod)
5580 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5581 errmsg("cannot alter type of column \"%s\" twice",
5584 /* Look up the target type (should not fail, since prep found it) */
5585 typeTuple = typenameType(NULL, typename, &targettypmod);
5586 tform = (Form_pg_type) GETSTRUCT(typeTuple);
5587 targettype = HeapTupleGetOid(typeTuple);
5590 * If there is a default expression for the column, get it and ensure we
5591 * can coerce it to the new datatype. (We must do this before changing
5592 * the column type, because build_column_default itself will try to
5593 * coerce, and will not issue the error message we want if it fails.)
5595 * We remove any implicit coercion steps at the top level of the old
5596 * default expression; this has been agreed to satisfy the principle of
5597 * least surprise. (The conversion to the new column type should act like
5598 * it started from what the user sees as the stored expression, and the
5599 * implicit coercions aren't going to be shown.)
5601 if (attTup->atthasdef)
5603 defaultexpr = build_column_default(rel, attnum);
5604 Assert(defaultexpr);
5605 defaultexpr = strip_implicit_coercions(defaultexpr);
5606 defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
5607 defaultexpr, exprType(defaultexpr),
5608 targettype, targettypmod,
5609 COERCION_ASSIGNMENT,
5610 COERCE_IMPLICIT_CAST);
5611 if (defaultexpr == NULL)
5613 (errcode(ERRCODE_DATATYPE_MISMATCH),
5614 errmsg("default for column \"%s\" cannot be cast to type \"%s\"",
5615 colName, TypeNameToString(typename))));
5621 * Find everything that depends on the column (constraints, indexes, etc),
5622 * and record enough information to let us recreate the objects.
5624 * The actual recreation does not happen here, but only after we have
5625 * performed all the individual ALTER TYPE operations. We have to save
5626 * the info before executing ALTER TYPE, though, else the deparser will
5629 * There could be multiple entries for the same object, so we must check
5630 * to ensure we process each one only once. Note: we assume that an index
5631 * that implements a constraint will not show a direct dependency on the
5634 depRel = heap_open(DependRelationId, RowExclusiveLock);
5636 ScanKeyInit(&key[0],
5637 Anum_pg_depend_refclassid,
5638 BTEqualStrategyNumber, F_OIDEQ,
5639 ObjectIdGetDatum(RelationRelationId));
5640 ScanKeyInit(&key[1],
5641 Anum_pg_depend_refobjid,
5642 BTEqualStrategyNumber, F_OIDEQ,
5643 ObjectIdGetDatum(RelationGetRelid(rel)));
5644 ScanKeyInit(&key[2],
5645 Anum_pg_depend_refobjsubid,
5646 BTEqualStrategyNumber, F_INT4EQ,
5647 Int32GetDatum((int32) attnum));
5649 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
5650 SnapshotNow, 3, key);
5652 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5654 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5655 ObjectAddress foundObject;
5657 /* We don't expect any PIN dependencies on columns */
5658 if (foundDep->deptype == DEPENDENCY_PIN)
5659 elog(ERROR, "cannot alter type of a pinned column");
5661 foundObject.classId = foundDep->classid;
5662 foundObject.objectId = foundDep->objid;
5663 foundObject.objectSubId = foundDep->objsubid;
5665 switch (getObjectClass(&foundObject))
5669 char relKind = get_rel_relkind(foundObject.objectId);
5671 if (relKind == RELKIND_INDEX)
5673 Assert(foundObject.objectSubId == 0);
5674 if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
5676 tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
5677 foundObject.objectId);
5678 tab->changedIndexDefs = lappend(tab->changedIndexDefs,
5679 pg_get_indexdef_string(foundObject.objectId));
5682 else if (relKind == RELKIND_SEQUENCE)
5685 * This must be a SERIAL column's sequence. We need
5686 * not do anything to it.
5688 Assert(foundObject.objectSubId == 0);
5692 /* Not expecting any other direct dependencies... */
5693 elog(ERROR, "unexpected object depending on column: %s",
5694 getObjectDescription(&foundObject));
5699 case OCLASS_CONSTRAINT:
5700 Assert(foundObject.objectSubId == 0);
5701 if (!list_member_oid(tab->changedConstraintOids,
5702 foundObject.objectId))
5704 char *defstring = pg_get_constraintdef_string(foundObject.objectId);
5707 * Put NORMAL dependencies at the front of the list and
5708 * AUTO dependencies at the back. This makes sure that
5709 * foreign-key constraints depending on this column will
5710 * be dropped before unique or primary-key constraints of
5711 * the column; which we must have because the FK
5712 * constraints depend on the indexes belonging to the
5713 * unique constraints.
5715 if (foundDep->deptype == DEPENDENCY_NORMAL)
5717 tab->changedConstraintOids =
5718 lcons_oid(foundObject.objectId,
5719 tab->changedConstraintOids);
5720 tab->changedConstraintDefs =
5722 tab->changedConstraintDefs);
5726 tab->changedConstraintOids =
5727 lappend_oid(tab->changedConstraintOids,
5728 foundObject.objectId);
5729 tab->changedConstraintDefs =
5730 lappend(tab->changedConstraintDefs,
5736 case OCLASS_REWRITE:
5737 /* XXX someday see if we can cope with revising views */
5739 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5740 errmsg("cannot alter type of a column used by a view or rule"),
5741 errdetail("%s depends on column \"%s\"",
5742 getObjectDescription(&foundObject),
5746 case OCLASS_DEFAULT:
5749 * Ignore the column's default expression, since we will fix
5752 Assert(defaultexpr);
5758 case OCLASS_CONVERSION:
5759 case OCLASS_LANGUAGE:
5760 case OCLASS_OPERATOR:
5761 case OCLASS_OPCLASS:
5762 case OCLASS_OPFAMILY:
5763 case OCLASS_TRIGGER:
5765 case OCLASS_TSPARSER:
5767 case OCLASS_TSTEMPLATE:
5768 case OCLASS_TSCONFIG:
5771 * We don't expect any of these sorts of objects to depend on
5774 elog(ERROR, "unexpected object depending on column: %s",
5775 getObjectDescription(&foundObject));
5779 elog(ERROR, "unrecognized object class: %u",
5780 foundObject.classId);
5784 systable_endscan(scan);
5787 * Now scan for dependencies of this column on other things. The only
5788 * thing we should find is the dependency on the column datatype, which we
5791 ScanKeyInit(&key[0],
5792 Anum_pg_depend_classid,
5793 BTEqualStrategyNumber, F_OIDEQ,
5794 ObjectIdGetDatum(RelationRelationId));
5795 ScanKeyInit(&key[1],
5796 Anum_pg_depend_objid,
5797 BTEqualStrategyNumber, F_OIDEQ,
5798 ObjectIdGetDatum(RelationGetRelid(rel)));
5799 ScanKeyInit(&key[2],
5800 Anum_pg_depend_objsubid,
5801 BTEqualStrategyNumber, F_INT4EQ,
5802 Int32GetDatum((int32) attnum));
5804 scan = systable_beginscan(depRel, DependDependerIndexId, true,
5805 SnapshotNow, 3, key);
5807 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5809 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5811 if (foundDep->deptype != DEPENDENCY_NORMAL)
5812 elog(ERROR, "found unexpected dependency type '%c'",
5814 if (foundDep->refclassid != TypeRelationId ||
5815 foundDep->refobjid != attTup->atttypid)
5816 elog(ERROR, "found unexpected dependency for column");
5818 simple_heap_delete(depRel, &depTup->t_self);
5821 systable_endscan(scan);
5823 heap_close(depRel, RowExclusiveLock);
5826 * Here we go --- change the recorded column type. (Note heapTup is a
5827 * copy of the syscache entry, so okay to scribble on.)
5829 attTup->atttypid = targettype;
5830 attTup->atttypmod = targettypmod;
5831 attTup->attndims = list_length(typename->arrayBounds);
5832 attTup->attlen = tform->typlen;
5833 attTup->attbyval = tform->typbyval;
5834 attTup->attalign = tform->typalign;
5835 attTup->attstorage = tform->typstorage;
5837 ReleaseSysCache(typeTuple);
5839 simple_heap_update(attrelation, &heapTup->t_self, heapTup);
5841 /* keep system catalog indexes current */
5842 CatalogUpdateIndexes(attrelation, heapTup);
5844 heap_close(attrelation, RowExclusiveLock);
5846 /* Install dependency on new datatype */
5847 add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
5850 * Drop any pg_statistic entry for the column, since it's now wrong type
5852 RemoveStatistics(RelationGetRelid(rel), attnum);
5855 * Update the default, if present, by brute force --- remove and re-add
5856 * the default. Probably unsafe to take shortcuts, since the new version
5857 * may well have additional dependencies. (It's okay to do this now,
5858 * rather than after other ALTER TYPE commands, since the default won't
5859 * depend on other column types.)
5863 /* Must make new row visible since it will be updated again */
5864 CommandCounterIncrement();
5867 * We use RESTRICT here for safety, but at present we do not expect
5868 * anything to depend on the default.
5870 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true);
5872 StoreAttrDefault(rel, attnum, defaultexpr);
5876 heap_freetuple(heapTup);
5880 * Cleanup after we've finished all the ALTER TYPE operations for a
5881 * particular relation. We have to drop and recreate all the indexes
5882 * and constraints that depend on the altered columns.
5885 ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab)
5891 * Re-parse the index and constraint definitions, and attach them to the
5892 * appropriate work queue entries. We do this before dropping because in
5893 * the case of a FOREIGN KEY constraint, we might not yet have exclusive
5894 * lock on the table the constraint is attached to, and we need to get
5895 * that before dropping. It's safe because the parser won't actually look
5896 * at the catalogs to detect the existing entry.
5898 foreach(l, tab->changedIndexDefs)
5899 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
5900 foreach(l, tab->changedConstraintDefs)
5901 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
5904 * Now we can drop the existing constraints and indexes --- constraints
5905 * first, since some of them might depend on the indexes. In fact, we
5906 * have to delete FOREIGN KEY constraints before UNIQUE constraints, but
5907 * we already ordered the constraint list to ensure that would happen. It
5908 * should be okay to use DROP_RESTRICT here, since nothing else should be
5909 * depending on these objects.
5911 foreach(l, tab->changedConstraintOids)
5913 obj.classId = ConstraintRelationId;
5914 obj.objectId = lfirst_oid(l);
5915 obj.objectSubId = 0;
5916 performDeletion(&obj, DROP_RESTRICT);
5919 foreach(l, tab->changedIndexOids)
5921 obj.classId = RelationRelationId;
5922 obj.objectId = lfirst_oid(l);
5923 obj.objectSubId = 0;
5924 performDeletion(&obj, DROP_RESTRICT);
5928 * The objects will get recreated during subsequent passes over the work
5934 ATPostAlterTypeParse(char *cmd, List **wqueue)
5936 List *raw_parsetree_list;
5937 List *querytree_list;
5938 ListCell *list_item;
5941 * We expect that we will get only ALTER TABLE and CREATE INDEX
5942 * statements. Hence, there is no need to pass them through
5943 * parse_analyze() or the rewriter, but instead we need to pass them
5944 * through parse_utilcmd.c to make them ready for execution.
5946 raw_parsetree_list = raw_parser(cmd);
5947 querytree_list = NIL;
5948 foreach(list_item, raw_parsetree_list)
5950 Node *stmt = (Node *) lfirst(list_item);
5952 if (IsA(stmt, IndexStmt))
5953 querytree_list = lappend(querytree_list,
5954 transformIndexStmt((IndexStmt *) stmt,
5956 else if (IsA(stmt, AlterTableStmt))
5957 querytree_list = list_concat(querytree_list,
5958 transformAlterTableStmt((AlterTableStmt *) stmt,
5961 querytree_list = lappend(querytree_list, stmt);
5965 * Attach each generated command to the proper place in the work queue.
5966 * Note this could result in creation of entirely new work-queue entries.
5968 foreach(list_item, querytree_list)
5970 Node *stm = (Node *) lfirst(list_item);
5972 AlteredTableInfo *tab;
5974 switch (nodeTag(stm))
5978 IndexStmt *stmt = (IndexStmt *) stm;
5979 AlterTableCmd *newcmd;
5981 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
5982 tab = ATGetQueueEntry(wqueue, rel);
5983 newcmd = makeNode(AlterTableCmd);
5984 newcmd->subtype = AT_ReAddIndex;
5985 newcmd->def = (Node *) stmt;
5986 tab->subcmds[AT_PASS_OLD_INDEX] =
5987 lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
5988 relation_close(rel, NoLock);
5991 case T_AlterTableStmt:
5993 AlterTableStmt *stmt = (AlterTableStmt *) stm;
5996 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
5997 tab = ATGetQueueEntry(wqueue, rel);
5998 foreach(lcmd, stmt->cmds)
6000 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
6002 switch (cmd->subtype)
6005 cmd->subtype = AT_ReAddIndex;
6006 tab->subcmds[AT_PASS_OLD_INDEX] =
6007 lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
6009 case AT_AddConstraint:
6010 tab->subcmds[AT_PASS_OLD_CONSTR] =
6011 lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
6014 elog(ERROR, "unexpected statement type: %d",
6015 (int) cmd->subtype);
6018 relation_close(rel, NoLock);
6022 elog(ERROR, "unexpected statement type: %d",
6023 (int) nodeTag(stm));
6032 * recursing is true if we are recursing from a table to its indexes,
6033 * sequences, or toast table. We don't allow the ownership of those things to
6034 * be changed separately from the parent table. Also, we can skip permission
6035 * checks (this is necessary not just an optimization, else we'd fail to
6036 * handle toast tables properly).
6038 * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
6039 * free-standing composite type.
6042 ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing)
6044 Relation target_rel;
6047 Form_pg_class tuple_class;
6050 * Get exclusive lock till end of transaction on the target table. Use
6051 * relation_open so that we can work on indexes and sequences.
6053 target_rel = relation_open(relationOid, AccessExclusiveLock);
6055 /* Get its pg_class tuple, too */
6056 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
6058 tuple = SearchSysCache(RELOID,
6059 ObjectIdGetDatum(relationOid),
6061 if (!HeapTupleIsValid(tuple))
6062 elog(ERROR, "cache lookup failed for relation %u", relationOid);
6063 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
6065 /* Can we change the ownership of this tuple? */
6066 switch (tuple_class->relkind)
6068 case RELKIND_RELATION:
6070 /* ok to change owner */
6076 * Because ALTER INDEX OWNER used to be allowed, and in fact
6077 * is generated by old versions of pg_dump, we give a warning
6078 * and do nothing rather than erroring out. Also, to avoid
6079 * unnecessary chatter while restoring those old dumps, say
6080 * nothing at all if the command would be a no-op anyway.
6082 if (tuple_class->relowner != newOwnerId)
6084 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6085 errmsg("cannot change owner of index \"%s\"",
6086 NameStr(tuple_class->relname)),
6087 errhint("Change the ownership of the index's table, instead.")));
6088 /* quick hack to exit via the no-op path */
6089 newOwnerId = tuple_class->relowner;
6092 case RELKIND_SEQUENCE:
6094 tuple_class->relowner != newOwnerId)
6096 /* if it's an owned sequence, disallow changing it by itself */
6100 if (sequenceIsOwned(relationOid, &tableId, &colId))
6102 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6103 errmsg("cannot change owner of sequence \"%s\"",
6104 NameStr(tuple_class->relname)),
6105 errdetail("Sequence \"%s\" is linked to table \"%s\".",
6106 NameStr(tuple_class->relname),
6107 get_rel_name(tableId))));
6110 case RELKIND_COMPOSITE_TYPE:
6114 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6115 errmsg("\"%s\" is a composite type",
6116 NameStr(tuple_class->relname)),
6117 errhint("Use ALTER TYPE instead.")));
6119 case RELKIND_TOASTVALUE:
6125 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6126 errmsg("\"%s\" is not a table, view, or sequence",
6127 NameStr(tuple_class->relname))));
6131 * If the new owner is the same as the existing owner, consider the
6132 * command to have succeeded. This is for dump restoration purposes.
6134 if (tuple_class->relowner != newOwnerId)
6136 Datum repl_val[Natts_pg_class];
6137 char repl_null[Natts_pg_class];
6138 char repl_repl[Natts_pg_class];
6144 /* skip permission checks when recursing to index or toast table */
6147 /* Superusers can always do it */
6150 Oid namespaceOid = tuple_class->relnamespace;
6151 AclResult aclresult;
6153 /* Otherwise, must be owner of the existing object */
6154 if (!pg_class_ownercheck(relationOid, GetUserId()))
6155 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
6156 RelationGetRelationName(target_rel));
6158 /* Must be able to become new owner */
6159 check_is_member_of_role(GetUserId(), newOwnerId);
6161 /* New owner must have CREATE privilege on namespace */
6162 aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
6164 if (aclresult != ACLCHECK_OK)
6165 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
6166 get_namespace_name(namespaceOid));
6170 memset(repl_null, ' ', sizeof(repl_null));
6171 memset(repl_repl, ' ', sizeof(repl_repl));
6173 repl_repl[Anum_pg_class_relowner - 1] = 'r';
6174 repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
6177 * Determine the modified ACL for the new owner. This is only
6178 * necessary when the ACL is non-null.
6180 aclDatum = SysCacheGetAttr(RELOID, tuple,
6181 Anum_pg_class_relacl,
6185 newAcl = aclnewowner(DatumGetAclP(aclDatum),
6186 tuple_class->relowner, newOwnerId);
6187 repl_repl[Anum_pg_class_relacl - 1] = 'r';
6188 repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
6191 newtuple = heap_modifytuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
6193 simple_heap_update(class_rel, &newtuple->t_self, newtuple);
6194 CatalogUpdateIndexes(class_rel, newtuple);
6196 heap_freetuple(newtuple);
6199 * Update owner dependency reference, if any. A composite type has
6200 * none, because it's tracked for the pg_type entry instead of here;
6201 * indexes and TOAST tables don't have their own entries either.
6203 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
6204 tuple_class->relkind != RELKIND_INDEX &&
6205 tuple_class->relkind != RELKIND_TOASTVALUE)
6206 changeDependencyOnOwner(RelationRelationId, relationOid,
6210 * Also change the ownership of the table's rowtype, if it has one
6212 if (tuple_class->relkind != RELKIND_INDEX)
6213 AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId,
6214 tuple_class->relkind == RELKIND_COMPOSITE_TYPE);
6217 * If we are operating on a table, also change the ownership of any
6218 * indexes and sequences that belong to the table, as well as the
6219 * table's toast table (if it has one)
6221 if (tuple_class->relkind == RELKIND_RELATION ||
6222 tuple_class->relkind == RELKIND_TOASTVALUE)
6224 List *index_oid_list;
6227 /* Find all the indexes belonging to this relation */
6228 index_oid_list = RelationGetIndexList(target_rel);
6230 /* For each index, recursively change its ownership */
6231 foreach(i, index_oid_list)
6232 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true);
6234 list_free(index_oid_list);
6237 if (tuple_class->relkind == RELKIND_RELATION)
6239 /* If it has a toast table, recurse to change its ownership */
6240 if (tuple_class->reltoastrelid != InvalidOid)
6241 ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
6244 /* If it has dependent sequences, recurse to change them too */
6245 change_owner_recurse_to_sequences(relationOid, newOwnerId);
6249 ReleaseSysCache(tuple);
6250 heap_close(class_rel, RowExclusiveLock);
6251 relation_close(target_rel, NoLock);
6255 * change_owner_recurse_to_sequences
6257 * Helper function for ATExecChangeOwner. Examines pg_depend searching
6258 * for sequences that are dependent on serial columns, and changes their
6262 change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId)
6270 * SERIAL sequences are those having an auto dependency on one of the
6271 * table's columns (we don't care *which* column, exactly).
6273 depRel = heap_open(DependRelationId, AccessShareLock);
6275 ScanKeyInit(&key[0],
6276 Anum_pg_depend_refclassid,
6277 BTEqualStrategyNumber, F_OIDEQ,
6278 ObjectIdGetDatum(RelationRelationId));
6279 ScanKeyInit(&key[1],
6280 Anum_pg_depend_refobjid,
6281 BTEqualStrategyNumber, F_OIDEQ,
6282 ObjectIdGetDatum(relationOid));
6283 /* we leave refobjsubid unspecified */
6285 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
6286 SnapshotNow, 2, key);
6288 while (HeapTupleIsValid(tup = systable_getnext(scan)))
6290 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
6293 /* skip dependencies other than auto dependencies on columns */
6294 if (depForm->refobjsubid == 0 ||
6295 depForm->classid != RelationRelationId ||
6296 depForm->objsubid != 0 ||
6297 depForm->deptype != DEPENDENCY_AUTO)
6300 /* Use relation_open just in case it's an index */
6301 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
6303 /* skip non-sequence relations */
6304 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
6306 /* No need to keep the lock */
6307 relation_close(seqRel, AccessExclusiveLock);
6311 /* We don't need to close the sequence while we alter it. */
6312 ATExecChangeOwner(depForm->objid, newOwnerId, true);
6314 /* Now we can close it. Keep the lock till end of transaction. */
6315 relation_close(seqRel, NoLock);
6318 systable_endscan(scan);
6320 relation_close(depRel, AccessShareLock);
6324 * ALTER TABLE CLUSTER ON
6326 * The only thing we have to do is to change the indisclustered bits.
6329 ATExecClusterOn(Relation rel, const char *indexName)
6333 indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
6335 if (!OidIsValid(indexOid))
6337 (errcode(ERRCODE_UNDEFINED_OBJECT),
6338 errmsg("index \"%s\" for table \"%s\" does not exist",
6339 indexName, RelationGetRelationName(rel))));
6341 /* Check index is valid to cluster on */
6342 check_index_is_clusterable(rel, indexOid, false);
6344 /* And do the work */
6345 mark_index_clustered(rel, indexOid);
6349 * ALTER TABLE SET WITHOUT CLUSTER
6351 * We have to find any indexes on the table that have indisclustered bit
6352 * set and turn it off.
6355 ATExecDropCluster(Relation rel)
6357 mark_index_clustered(rel, InvalidOid);
6361 * ALTER TABLE SET TABLESPACE
6364 ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, char *tablespacename)
6367 AclResult aclresult;
6369 /* Check that the tablespace exists */
6370 tablespaceId = get_tablespace_oid(tablespacename);
6371 if (!OidIsValid(tablespaceId))
6373 (errcode(ERRCODE_UNDEFINED_OBJECT),
6374 errmsg("tablespace \"%s\" does not exist", tablespacename)));
6376 /* Check its permissions */
6377 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(), ACL_CREATE);
6378 if (aclresult != ACLCHECK_OK)
6379 aclcheck_error(aclresult, ACL_KIND_TABLESPACE, tablespacename);
6381 /* Save info for Phase 3 to do the real work */
6382 if (OidIsValid(tab->newTableSpace))
6384 (errcode(ERRCODE_SYNTAX_ERROR),
6385 errmsg("cannot have multiple SET TABLESPACE subcommands")));
6386 tab->newTableSpace = tablespaceId;
6390 * ALTER TABLE/INDEX SET (...) or RESET (...)
6393 ATExecSetRelOptions(Relation rel, List *defList, bool isReset)
6402 Datum repl_val[Natts_pg_class];
6403 char repl_null[Natts_pg_class];
6404 char repl_repl[Natts_pg_class];
6407 return; /* nothing to do */
6409 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
6411 /* Get the old reloptions */
6412 relid = RelationGetRelid(rel);
6413 tuple = SearchSysCache(RELOID,
6414 ObjectIdGetDatum(relid),
6416 if (!HeapTupleIsValid(tuple))
6417 elog(ERROR, "cache lookup failed for relation %u", relid);
6419 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions, &isnull);
6421 /* Generate new proposed reloptions (text array) */
6422 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
6423 defList, false, isReset);
6426 switch (rel->rd_rel->relkind)
6428 case RELKIND_RELATION:
6429 case RELKIND_TOASTVALUE:
6430 (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
6433 (void) index_reloptions(rel->rd_am->amoptions, newOptions, true);
6437 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6438 errmsg("\"%s\" is not a table, index, or TOAST table",
6439 RelationGetRelationName(rel))));
6444 * All we need do here is update the pg_class row; the new options will be
6445 * propagated into relcaches during post-commit cache inval.
6447 memset(repl_val, 0, sizeof(repl_val));
6448 memset(repl_null, ' ', sizeof(repl_null));
6449 memset(repl_repl, ' ', sizeof(repl_repl));
6451 if (newOptions != (Datum) 0)
6452 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
6454 repl_null[Anum_pg_class_reloptions - 1] = 'n';
6456 repl_repl[Anum_pg_class_reloptions - 1] = 'r';
6458 newtuple = heap_modifytuple(tuple, RelationGetDescr(pgclass),
6459 repl_val, repl_null, repl_repl);
6461 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
6463 CatalogUpdateIndexes(pgclass, newtuple);
6465 heap_freetuple(newtuple);
6467 ReleaseSysCache(tuple);
6469 heap_close(pgclass, RowExclusiveLock);
6473 * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
6474 * rewriting to be done, so we just want to copy the data as fast as possible.
6477 ATExecSetTableSpace(Oid tableOid, Oid newTableSpace)
6483 RelFileNode newrnode;
6484 SMgrRelation dstrel;
6487 Form_pg_class rd_rel;
6491 * Need lock here in case we are recursing to toast table or index
6493 rel = relation_open(tableOid, AccessExclusiveLock);
6496 * We can never allow moving of shared or nailed-in-cache relations,
6497 * because we can't support changing their reltablespace values.
6499 if (rel->rd_rel->relisshared || rel->rd_isnailed)
6501 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6502 errmsg("cannot move system relation \"%s\"",
6503 RelationGetRelationName(rel))));
6505 /* Can't move a non-shared relation into pg_global */
6506 if (newTableSpace == GLOBALTABLESPACE_OID)
6508 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6509 errmsg("only shared relations can be placed in pg_global tablespace")));
6512 * Don't allow moving temp tables of other backends ... their local buffer
6513 * manager is not going to cope.
6515 if (isOtherTempNamespace(RelationGetNamespace(rel)))
6517 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6518 errmsg("cannot move temporary tables of other sessions")));
6521 * No work if no change in tablespace.
6523 oldTableSpace = rel->rd_rel->reltablespace;
6524 if (newTableSpace == oldTableSpace ||
6525 (newTableSpace == MyDatabaseTableSpace && oldTableSpace == 0))
6527 relation_close(rel, NoLock);
6531 reltoastrelid = rel->rd_rel->reltoastrelid;
6532 reltoastidxid = rel->rd_rel->reltoastidxid;
6534 /* Get a modifiable copy of the relation's pg_class row */
6535 pg_class = heap_open(RelationRelationId, RowExclusiveLock);
6537 tuple = SearchSysCacheCopy(RELOID,
6538 ObjectIdGetDatum(tableOid),
6540 if (!HeapTupleIsValid(tuple))
6541 elog(ERROR, "cache lookup failed for relation %u", tableOid);
6542 rd_rel = (Form_pg_class) GETSTRUCT(tuple);
6545 * Since we copy the file directly without looking at the shared buffers,
6546 * we'd better first flush out any pages of the source relation that are
6547 * in shared buffers. We assume no new changes will be made while we are
6548 * holding exclusive lock on the rel.
6550 FlushRelationBuffers(rel);
6552 /* Open old and new relation */
6553 newrnode = rel->rd_node;
6554 newrnode.spcNode = newTableSpace;
6555 dstrel = smgropen(newrnode);
6557 RelationOpenSmgr(rel);
6560 * Create and copy all forks of the relation, and schedule unlinking
6561 * of old physical files.
6563 * NOTE: any conflict in relfilenode value will be caught in
6564 * smgrcreate() below.
6566 for (forkNum = 0; forkNum <= MAX_FORKNUM; forkNum++)
6568 if (smgrexists(rel->rd_smgr, forkNum))
6570 smgrcreate(dstrel, forkNum, rel->rd_istemp, false);
6571 copy_relation_data(rel->rd_smgr, dstrel, forkNum, rel->rd_istemp);
6573 smgrscheduleunlink(rel->rd_smgr, forkNum, rel->rd_istemp);
6577 /* Close old and new relation */
6579 RelationCloseSmgr(rel);
6581 /* update the pg_class row */
6582 rd_rel->reltablespace = (newTableSpace == MyDatabaseTableSpace) ? InvalidOid : newTableSpace;
6583 simple_heap_update(pg_class, &tuple->t_self, tuple);
6584 CatalogUpdateIndexes(pg_class, tuple);
6586 heap_freetuple(tuple);
6588 heap_close(pg_class, RowExclusiveLock);
6590 relation_close(rel, NoLock);
6592 /* Make sure the reltablespace change is visible */
6593 CommandCounterIncrement();
6595 /* Move associated toast relation and/or index, too */
6596 if (OidIsValid(reltoastrelid))
6597 ATExecSetTableSpace(reltoastrelid, newTableSpace);
6598 if (OidIsValid(reltoastidxid))
6599 ATExecSetTableSpace(reltoastidxid, newTableSpace);
6603 * Copy data, block by block
6606 copy_relation_data(SMgrRelation src, SMgrRelation dst,
6607 ForkNumber forkNum, bool istemp)
6610 BlockNumber nblocks;
6613 Page page = (Page) buf;
6616 * We need to log the copied data in WAL iff WAL archiving is enabled AND
6617 * it's not a temp rel.
6619 use_wal = XLogArchivingActive() && !istemp;
6621 nblocks = smgrnblocks(src, forkNum);
6623 for (blkno = 0; blkno < nblocks; blkno++)
6625 smgrread(src, forkNum, blkno, buf);
6629 log_newpage(&dst->smgr_rnode, forkNum, blkno, page);
6632 * Now write the page. We say isTemp = true even if it's not a temp
6633 * rel, because there's no need for smgr to schedule an fsync for this
6634 * write; we'll do it ourselves below.
6636 smgrextend(dst, forkNum, blkno, buf, true);
6640 * If the rel isn't temp, we must fsync it down to disk before it's safe
6641 * to commit the transaction. (For a temp rel we don't care since the rel
6642 * will be uninteresting after a crash anyway.)
6644 * It's obvious that we must do this when not WAL-logging the copy. It's
6645 * less obvious that we have to do it even if we did WAL-log the copied
6646 * pages. The reason is that since we're copying outside shared buffers, a
6647 * CHECKPOINT occurring during the copy has no way to flush the previously
6648 * written data to disk (indeed it won't know the new rel even exists). A
6649 * crash later on would replay WAL from the checkpoint, therefore it
6650 * wouldn't replay our earlier WAL entries. If we do not fsync those pages
6651 * here, they might still not be on disk when the crash occurs.
6654 smgrimmedsync(dst, forkNum);
6658 * ALTER TABLE ENABLE/DISABLE TRIGGER
6660 * We just pass this off to trigger.c.
6663 ATExecEnableDisableTrigger(Relation rel, char *trigname,
6664 char fires_when, bool skip_system)
6666 EnableDisableTrigger(rel, trigname, fires_when, skip_system);
6670 * ALTER TABLE ENABLE/DISABLE RULE
6672 * We just pass this off to rewriteDefine.c.
6675 ATExecEnableDisableRule(Relation rel, char *trigname,
6678 EnableDisableRule(rel, trigname, fires_when);
6682 * ALTER TABLE INHERIT
6684 * Add a parent to the child's parents. This verifies that all the columns and
6685 * check constraints of the parent appear in the child and that they have the
6686 * same data types and expressions.
6689 ATExecAddInherit(Relation child_rel, RangeVar *parent)
6691 Relation parent_rel,
6695 HeapTuple inheritsTuple;
6700 * AccessShareLock on the parent is what's obtained during normal CREATE
6701 * TABLE ... INHERITS ..., so should be enough here.
6703 parent_rel = heap_openrv(parent, AccessShareLock);
6706 * Must be owner of both parent and child -- child was checked by
6707 * ATSimplePermissions call in ATPrepCmd
6709 ATSimplePermissions(parent_rel, false);
6711 /* Permanent rels cannot inherit from temporary ones */
6712 if (!isTempNamespace(RelationGetNamespace(child_rel)) &&
6713 isTempNamespace(RelationGetNamespace(parent_rel)))
6715 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6716 errmsg("cannot inherit from temporary relation \"%s\"",
6717 RelationGetRelationName(parent_rel))));
6720 * Check for duplicates in the list of parents, and determine the highest
6721 * inhseqno already present; we'll use the next one for the new parent.
6722 * (Note: get RowExclusiveLock because we will write pg_inherits below.)
6724 * Note: we do not reject the case where the child already inherits from
6725 * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
6727 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
6729 Anum_pg_inherits_inhrelid,
6730 BTEqualStrategyNumber, F_OIDEQ,
6731 ObjectIdGetDatum(RelationGetRelid(child_rel)));
6732 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
6733 true, SnapshotNow, 1, &key);
6735 /* inhseqno sequences start at 1 */
6737 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
6739 Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
6741 if (inh->inhparent == RelationGetRelid(parent_rel))
6743 (errcode(ERRCODE_DUPLICATE_TABLE),
6744 errmsg("relation \"%s\" would be inherited from more than once",
6745 RelationGetRelationName(parent_rel))));
6746 if (inh->inhseqno > inhseqno)
6747 inhseqno = inh->inhseqno;
6749 systable_endscan(scan);
6752 * Prevent circularity by seeing if proposed parent inherits from child.
6753 * (In particular, this disallows making a rel inherit from itself.)
6755 * This is not completely bulletproof because of race conditions: in
6756 * multi-level inheritance trees, someone else could concurrently be
6757 * making another inheritance link that closes the loop but does not join
6758 * either of the rels we have locked. Preventing that seems to require
6759 * exclusive locks on the entire inheritance tree, which is a cure worse
6760 * than the disease. find_all_inheritors() will cope with circularity
6761 * anyway, so don't sweat it too much.
6763 children = find_all_inheritors(RelationGetRelid(child_rel));
6765 if (list_member_oid(children, RelationGetRelid(parent_rel)))
6767 (errcode(ERRCODE_DUPLICATE_TABLE),
6768 errmsg("circular inheritance not allowed"),
6769 errdetail("\"%s\" is already a child of \"%s\".",
6771 RelationGetRelationName(child_rel))));
6773 /* If parent has OIDs then child must have OIDs */
6774 if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
6776 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6777 errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
6778 RelationGetRelationName(child_rel),
6779 RelationGetRelationName(parent_rel))));
6781 /* Match up the columns and bump attinhcount as needed */
6782 MergeAttributesIntoExisting(child_rel, parent_rel);
6784 /* Match up the constraints and bump coninhcount as needed */
6785 MergeConstraintsIntoExisting(child_rel, parent_rel);
6788 * OK, it looks valid. Make the catalog entries that show inheritance.
6790 StoreCatalogInheritance1(RelationGetRelid(child_rel),
6791 RelationGetRelid(parent_rel),
6795 /* Now we're done with pg_inherits */
6796 heap_close(catalogRelation, RowExclusiveLock);
6798 /* keep our lock on the parent relation until commit */
6799 heap_close(parent_rel, NoLock);
6803 * Obtain the source-text form of the constraint expression for a check
6804 * constraint, given its pg_constraint tuple
6807 decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
6809 Form_pg_constraint con;
6814 con = (Form_pg_constraint) GETSTRUCT(contup);
6815 attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
6817 elog(ERROR, "null conbin for constraint %u", HeapTupleGetOid(contup));
6819 expr = DirectFunctionCall2(pg_get_expr, attr,
6820 ObjectIdGetDatum(con->conrelid));
6821 return TextDatumGetCString(expr);
6825 * Determine whether two check constraints are functionally equivalent
6827 * The test we apply is to see whether they reverse-compile to the same
6828 * source string. This insulates us from issues like whether attributes
6829 * have the same physical column numbers in parent and child relations.
6832 constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
6834 Form_pg_constraint acon = (Form_pg_constraint) GETSTRUCT(a);
6835 Form_pg_constraint bcon = (Form_pg_constraint) GETSTRUCT(b);
6837 if (acon->condeferrable != bcon->condeferrable ||
6838 acon->condeferred != bcon->condeferred ||
6839 strcmp(decompile_conbin(a, tupleDesc),
6840 decompile_conbin(b, tupleDesc)) != 0)
6847 * Check columns in child table match up with columns in parent, and increment
6848 * their attinhcount.
6850 * Called by ATExecAddInherit
6852 * Currently all parent columns must be found in child. Missing columns are an
6853 * error. One day we might consider creating new columns like CREATE TABLE
6854 * does. However, that is widely unpopular --- in the common use case of
6855 * partitioned tables it's a foot-gun.
6857 * The data type must match exactly. If the parent column is NOT NULL then
6858 * the child must be as well. Defaults are not compared, however.
6861 MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel)
6864 AttrNumber parent_attno;
6866 TupleDesc tupleDesc;
6867 TupleConstr *constr;
6870 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
6872 tupleDesc = RelationGetDescr(parent_rel);
6873 parent_natts = tupleDesc->natts;
6874 constr = tupleDesc->constr;
6876 for (parent_attno = 1; parent_attno <= parent_natts; parent_attno++)
6878 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
6879 char *attributeName = NameStr(attribute->attname);
6881 /* Ignore dropped columns in the parent. */
6882 if (attribute->attisdropped)
6885 /* Find same column in child (matching on column name). */
6886 tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel),
6888 if (HeapTupleIsValid(tuple))
6890 /* Check they are same type and typmod */
6891 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
6893 if (attribute->atttypid != childatt->atttypid ||
6894 attribute->atttypmod != childatt->atttypmod)
6896 (errcode(ERRCODE_DATATYPE_MISMATCH),
6897 errmsg("child table \"%s\" has different type for column \"%s\"",
6898 RelationGetRelationName(child_rel),
6901 if (attribute->attnotnull && !childatt->attnotnull)
6903 (errcode(ERRCODE_DATATYPE_MISMATCH),
6904 errmsg("column \"%s\" in child table must be marked NOT NULL",
6908 * OK, bump the child column's inheritance count. (If we fail
6909 * later on, this change will just roll back.)
6911 childatt->attinhcount++;
6912 simple_heap_update(attrrel, &tuple->t_self, tuple);
6913 CatalogUpdateIndexes(attrrel, tuple);
6914 heap_freetuple(tuple);
6919 (errcode(ERRCODE_DATATYPE_MISMATCH),
6920 errmsg("child table is missing column \"%s\"",
6925 heap_close(attrrel, RowExclusiveLock);
6929 * Check constraints in child table match up with constraints in parent,
6930 * and increment their coninhcount.
6932 * Called by ATExecAddInherit
6934 * Currently all constraints in parent must be present in the child. One day we
6935 * may consider adding new constraints like CREATE TABLE does. We may also want
6936 * to allow an optional flag on parent table constraints indicating they are
6937 * intended to ONLY apply to the master table, not to the children. That would
6938 * make it possible to ensure no records are mistakenly inserted into the
6939 * master in partitioned tables rather than the appropriate child.
6941 * XXX This is O(N^2) which may be an issue with tables with hundreds of
6942 * constraints. As long as tables have more like 10 constraints it shouldn't be
6943 * a problem though. Even 100 constraints ought not be the end of the world.
6946 MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
6948 Relation catalog_relation;
6949 TupleDesc tuple_desc;
6950 SysScanDesc parent_scan;
6951 ScanKeyData parent_key;
6952 HeapTuple parent_tuple;
6954 catalog_relation = heap_open(ConstraintRelationId, RowExclusiveLock);
6955 tuple_desc = RelationGetDescr(catalog_relation);
6957 /* Outer loop scans through the parent's constraint definitions */
6958 ScanKeyInit(&parent_key,
6959 Anum_pg_constraint_conrelid,
6960 BTEqualStrategyNumber, F_OIDEQ,
6961 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
6962 parent_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
6963 true, SnapshotNow, 1, &parent_key);
6965 while (HeapTupleIsValid(parent_tuple = systable_getnext(parent_scan)))
6967 Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(parent_tuple);
6968 SysScanDesc child_scan;
6969 ScanKeyData child_key;
6970 HeapTuple child_tuple;
6973 if (parent_con->contype != CONSTRAINT_CHECK)
6976 /* Search for a child constraint matching this one */
6977 ScanKeyInit(&child_key,
6978 Anum_pg_constraint_conrelid,
6979 BTEqualStrategyNumber, F_OIDEQ,
6980 ObjectIdGetDatum(RelationGetRelid(child_rel)));
6981 child_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
6982 true, SnapshotNow, 1, &child_key);
6984 while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
6986 Form_pg_constraint child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
6987 HeapTuple child_copy;
6989 if (child_con->contype != CONSTRAINT_CHECK)
6992 if (strcmp(NameStr(parent_con->conname),
6993 NameStr(child_con->conname)) != 0)
6996 if (!constraints_equivalent(parent_tuple, child_tuple, tuple_desc))
6998 (errcode(ERRCODE_DATATYPE_MISMATCH),
6999 errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
7000 RelationGetRelationName(child_rel),
7001 NameStr(parent_con->conname))));
7004 * OK, bump the child constraint's inheritance count. (If we fail
7005 * later on, this change will just roll back.)
7007 child_copy = heap_copytuple(child_tuple);
7008 child_con = (Form_pg_constraint) GETSTRUCT(child_copy);
7009 child_con->coninhcount++;
7010 simple_heap_update(catalog_relation, &child_copy->t_self, child_copy);
7011 CatalogUpdateIndexes(catalog_relation, child_copy);
7012 heap_freetuple(child_copy);
7018 systable_endscan(child_scan);
7022 (errcode(ERRCODE_DATATYPE_MISMATCH),
7023 errmsg("child table is missing constraint \"%s\"",
7024 NameStr(parent_con->conname))));
7027 systable_endscan(parent_scan);
7028 heap_close(catalog_relation, RowExclusiveLock);
7032 * ALTER TABLE NO INHERIT
7034 * Drop a parent from the child's parents. This just adjusts the attinhcount
7035 * and attislocal of the columns and removes the pg_inherit and pg_depend
7038 * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
7039 * up attislocal stays true, which means if a child is ever removed from a
7040 * parent then its columns will never be automatically dropped which may
7041 * surprise. But at least we'll never surprise by dropping columns someone
7042 * isn't expecting to be dropped which would actually mean data loss.
7044 * coninhcount and conislocal for inherited constraints are adjusted in
7045 * exactly the same way.
7048 ATExecDropInherit(Relation rel, RangeVar *parent)
7050 Relation parent_rel;
7051 Relation catalogRelation;
7054 HeapTuple inheritsTuple,
7062 * AccessShareLock on the parent is probably enough, seeing that DROP
7063 * TABLE doesn't lock parent tables at all. We need some lock since we'll
7064 * be inspecting the parent's schema.
7066 parent_rel = heap_openrv(parent, AccessShareLock);
7069 * We don't bother to check ownership of the parent table --- ownership of
7070 * the child is presumed enough rights.
7074 * Find and destroy the pg_inherits entry linking the two, or error out if
7077 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
7078 ScanKeyInit(&key[0],
7079 Anum_pg_inherits_inhrelid,
7080 BTEqualStrategyNumber, F_OIDEQ,
7081 ObjectIdGetDatum(RelationGetRelid(rel)));
7082 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
7083 true, SnapshotNow, 1, key);
7085 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
7089 inhparent = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
7090 if (inhparent == RelationGetRelid(parent_rel))
7092 simple_heap_delete(catalogRelation, &inheritsTuple->t_self);
7098 systable_endscan(scan);
7099 heap_close(catalogRelation, RowExclusiveLock);
7103 (errcode(ERRCODE_UNDEFINED_TABLE),
7104 errmsg("relation \"%s\" is not a parent of relation \"%s\"",
7105 RelationGetRelationName(parent_rel),
7106 RelationGetRelationName(rel))));
7109 * Search through child columns looking for ones matching parent rel
7111 catalogRelation = heap_open(AttributeRelationId, RowExclusiveLock);
7112 ScanKeyInit(&key[0],
7113 Anum_pg_attribute_attrelid,
7114 BTEqualStrategyNumber, F_OIDEQ,
7115 ObjectIdGetDatum(RelationGetRelid(rel)));
7116 scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
7117 true, SnapshotNow, 1, key);
7118 while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
7120 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
7122 /* Ignore if dropped or not inherited */
7123 if (att->attisdropped)
7125 if (att->attinhcount <= 0)
7128 if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
7129 NameStr(att->attname)))
7131 /* Decrement inhcount and possibly set islocal to true */
7132 HeapTuple copyTuple = heap_copytuple(attributeTuple);
7133 Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
7135 copy_att->attinhcount--;
7136 if (copy_att->attinhcount == 0)
7137 copy_att->attislocal = true;
7139 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
7140 CatalogUpdateIndexes(catalogRelation, copyTuple);
7141 heap_freetuple(copyTuple);
7144 systable_endscan(scan);
7145 heap_close(catalogRelation, RowExclusiveLock);
7148 * Likewise, find inherited check constraints and disinherit them.
7149 * To do this, we first need a list of the names of the parent's check
7150 * constraints. (We cheat a bit by only checking for name matches,
7151 * assuming that the expressions will match.)
7153 catalogRelation = heap_open(ConstraintRelationId, RowExclusiveLock);
7154 ScanKeyInit(&key[0],
7155 Anum_pg_constraint_conrelid,
7156 BTEqualStrategyNumber, F_OIDEQ,
7157 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
7158 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
7159 true, SnapshotNow, 1, key);
7163 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
7165 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
7167 if (con->contype == CONSTRAINT_CHECK)
7168 connames = lappend(connames, pstrdup(NameStr(con->conname)));
7171 systable_endscan(scan);
7173 /* Now scan the child's constraints */
7174 ScanKeyInit(&key[0],
7175 Anum_pg_constraint_conrelid,
7176 BTEqualStrategyNumber, F_OIDEQ,
7177 ObjectIdGetDatum(RelationGetRelid(rel)));
7178 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
7179 true, SnapshotNow, 1, key);
7181 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
7183 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
7187 if (con->contype != CONSTRAINT_CHECK)
7191 foreach (lc, connames)
7193 if (strcmp(NameStr(con->conname), (char *) lfirst(lc)) == 0)
7202 /* Decrement inhcount and possibly set islocal to true */
7203 HeapTuple copyTuple = heap_copytuple(constraintTuple);
7204 Form_pg_constraint copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
7205 if (copy_con->coninhcount <= 0) /* shouldn't happen */
7206 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
7207 RelationGetRelid(rel), NameStr(copy_con->conname));
7209 copy_con->coninhcount--;
7210 if (copy_con->coninhcount == 0)
7211 copy_con->conislocal = true;
7213 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
7214 CatalogUpdateIndexes(catalogRelation, copyTuple);
7215 heap_freetuple(copyTuple);
7219 systable_endscan(scan);
7220 heap_close(catalogRelation, RowExclusiveLock);
7223 * Drop the dependency
7225 * There's no convenient way to do this, so go trawling through pg_depend
7227 catalogRelation = heap_open(DependRelationId, RowExclusiveLock);
7229 ScanKeyInit(&key[0],
7230 Anum_pg_depend_classid,
7231 BTEqualStrategyNumber, F_OIDEQ,
7232 ObjectIdGetDatum(RelationRelationId));
7233 ScanKeyInit(&key[1],
7234 Anum_pg_depend_objid,
7235 BTEqualStrategyNumber, F_OIDEQ,
7236 ObjectIdGetDatum(RelationGetRelid(rel)));
7237 ScanKeyInit(&key[2],
7238 Anum_pg_depend_objsubid,
7239 BTEqualStrategyNumber, F_INT4EQ,
7242 scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
7243 SnapshotNow, 3, key);
7245 while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
7247 Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
7249 if (dep->refclassid == RelationRelationId &&
7250 dep->refobjid == RelationGetRelid(parent_rel) &&
7251 dep->refobjsubid == 0 &&
7252 dep->deptype == DEPENDENCY_NORMAL)
7253 simple_heap_delete(catalogRelation, &depTuple->t_self);
7256 systable_endscan(scan);
7257 heap_close(catalogRelation, RowExclusiveLock);
7259 /* keep our lock on the parent relation until commit */
7260 heap_close(parent_rel, NoLock);
7265 * Execute ALTER TABLE SET SCHEMA
7267 * Note: caller must have checked ownership of the relation already
7270 AlterTableNamespace(RangeVar *relation, const char *newschema,
7271 ObjectType stmttype)
7279 rel = relation_openrv(relation, AccessExclusiveLock);
7281 relid = RelationGetRelid(rel);
7282 oldNspOid = RelationGetNamespace(rel);
7284 /* Check relation type against type specified in the ALTER command */
7289 * For mostly-historical reasons, we allow ALTER TABLE to apply
7290 * to all relation types.
7294 case OBJECT_SEQUENCE:
7295 if (rel->rd_rel->relkind != RELKIND_SEQUENCE)
7297 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7298 errmsg("\"%s\" is not a sequence",
7299 RelationGetRelationName(rel))));
7303 if (rel->rd_rel->relkind != RELKIND_VIEW)
7305 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7306 errmsg("\"%s\" is not a view",
7307 RelationGetRelationName(rel))));
7311 elog(ERROR, "unrecognized object type: %d", (int) stmttype);
7314 /* Can we change the schema of this tuple? */
7315 switch (rel->rd_rel->relkind)
7317 case RELKIND_RELATION:
7319 /* ok to change schema */
7321 case RELKIND_SEQUENCE:
7323 /* if it's an owned sequence, disallow moving it by itself */
7327 if (sequenceIsOwned(relid, &tableId, &colId))
7329 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7330 errmsg("cannot move an owned sequence into another schema"),
7331 errdetail("Sequence \"%s\" is linked to table \"%s\".",
7332 RelationGetRelationName(rel),
7333 get_rel_name(tableId))));
7336 case RELKIND_COMPOSITE_TYPE:
7338 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7339 errmsg("\"%s\" is a composite type",
7340 RelationGetRelationName(rel)),
7341 errhint("Use ALTER TYPE instead.")));
7344 case RELKIND_TOASTVALUE:
7348 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7349 errmsg("\"%s\" is not a table, view, or sequence",
7350 RelationGetRelationName(rel))));
7353 /* get schema OID and check its permissions */
7354 nspOid = LookupCreationNamespace(newschema);
7356 if (oldNspOid == nspOid)
7358 (errcode(ERRCODE_DUPLICATE_TABLE),
7359 errmsg("relation \"%s\" is already in schema \"%s\"",
7360 RelationGetRelationName(rel),
7363 /* disallow renaming into or out of temp schemas */
7364 if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
7366 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7367 errmsg("cannot move objects into or out of temporary schemas")));
7369 /* same for TOAST schema */
7370 if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
7372 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7373 errmsg("cannot move objects into or out of TOAST schema")));
7375 /* OK, modify the pg_class row and pg_depend entry */
7376 classRel = heap_open(RelationRelationId, RowExclusiveLock);
7378 AlterRelationNamespaceInternal(classRel, relid, oldNspOid, nspOid, true);
7380 /* Fix the table's rowtype too */
7381 AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid, false, false);
7383 /* Fix other dependent stuff */
7384 if (rel->rd_rel->relkind == RELKIND_RELATION)
7386 AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid);
7387 AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid, newschema);
7388 AlterConstraintNamespaces(relid, oldNspOid, nspOid, false);
7391 heap_close(classRel, RowExclusiveLock);
7393 /* close rel, but keep lock until commit */
7394 relation_close(rel, NoLock);
7398 * The guts of relocating a relation to another namespace: fix the pg_class
7399 * entry, and the pg_depend entry if any. Caller must already have
7400 * opened and write-locked pg_class.
7403 AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
7404 Oid oldNspOid, Oid newNspOid,
7405 bool hasDependEntry)
7408 Form_pg_class classForm;
7410 classTup = SearchSysCacheCopy(RELOID,
7411 ObjectIdGetDatum(relOid),
7413 if (!HeapTupleIsValid(classTup))
7414 elog(ERROR, "cache lookup failed for relation %u", relOid);
7415 classForm = (Form_pg_class) GETSTRUCT(classTup);
7417 Assert(classForm->relnamespace == oldNspOid);
7419 /* check for duplicate name (more friendly than unique-index failure) */
7420 if (get_relname_relid(NameStr(classForm->relname),
7421 newNspOid) != InvalidOid)
7423 (errcode(ERRCODE_DUPLICATE_TABLE),
7424 errmsg("relation \"%s\" already exists in schema \"%s\"",
7425 NameStr(classForm->relname),
7426 get_namespace_name(newNspOid))));
7428 /* classTup is a copy, so OK to scribble on */
7429 classForm->relnamespace = newNspOid;
7431 simple_heap_update(classRel, &classTup->t_self, classTup);
7432 CatalogUpdateIndexes(classRel, classTup);
7434 /* Update dependency on schema if caller said so */
7435 if (hasDependEntry &&
7436 changeDependencyFor(RelationRelationId, relOid,
7437 NamespaceRelationId, oldNspOid, newNspOid) != 1)
7438 elog(ERROR, "failed to change schema dependency for relation \"%s\"",
7439 NameStr(classForm->relname));
7441 heap_freetuple(classTup);
7445 * Move all indexes for the specified relation to another namespace.
7447 * Note: we assume adequate permission checking was done by the caller,
7448 * and that the caller has a suitable lock on the owning relation.
7451 AlterIndexNamespaces(Relation classRel, Relation rel,
7452 Oid oldNspOid, Oid newNspOid)
7457 indexList = RelationGetIndexList(rel);
7459 foreach(l, indexList)
7461 Oid indexOid = lfirst_oid(l);
7464 * Note: currently, the index will not have its own dependency on the
7465 * namespace, so we don't need to do changeDependencyFor(). There's no
7466 * rowtype in pg_type, either.
7468 AlterRelationNamespaceInternal(classRel, indexOid,
7469 oldNspOid, newNspOid,
7473 list_free(indexList);
7477 * Move all SERIAL-column sequences of the specified relation to another
7480 * Note: we assume adequate permission checking was done by the caller,
7481 * and that the caller has a suitable lock on the owning relation.
7484 AlterSeqNamespaces(Relation classRel, Relation rel,
7485 Oid oldNspOid, Oid newNspOid, const char *newNspName)
7493 * SERIAL sequences are those having an auto dependency on one of the
7494 * table's columns (we don't care *which* column, exactly).
7496 depRel = heap_open(DependRelationId, AccessShareLock);
7498 ScanKeyInit(&key[0],
7499 Anum_pg_depend_refclassid,
7500 BTEqualStrategyNumber, F_OIDEQ,
7501 ObjectIdGetDatum(RelationRelationId));
7502 ScanKeyInit(&key[1],
7503 Anum_pg_depend_refobjid,
7504 BTEqualStrategyNumber, F_OIDEQ,
7505 ObjectIdGetDatum(RelationGetRelid(rel)));
7506 /* we leave refobjsubid unspecified */
7508 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
7509 SnapshotNow, 2, key);
7511 while (HeapTupleIsValid(tup = systable_getnext(scan)))
7513 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
7516 /* skip dependencies other than auto dependencies on columns */
7517 if (depForm->refobjsubid == 0 ||
7518 depForm->classid != RelationRelationId ||
7519 depForm->objsubid != 0 ||
7520 depForm->deptype != DEPENDENCY_AUTO)
7523 /* Use relation_open just in case it's an index */
7524 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
7526 /* skip non-sequence relations */
7527 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
7529 /* No need to keep the lock */
7530 relation_close(seqRel, AccessExclusiveLock);
7534 /* Fix the pg_class and pg_depend entries */
7535 AlterRelationNamespaceInternal(classRel, depForm->objid,
7536 oldNspOid, newNspOid,
7540 * Sequences have entries in pg_type. We need to be careful to move
7541 * them to the new namespace, too.
7543 AlterTypeNamespaceInternal(RelationGetForm(seqRel)->reltype,
7544 newNspOid, false, false);
7546 /* Now we can close it. Keep the lock till end of transaction. */
7547 relation_close(seqRel, NoLock);
7550 systable_endscan(scan);
7552 relation_close(depRel, AccessShareLock);
7557 * This code supports
7558 * CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
7560 * Because we only support this for TEMP tables, it's sufficient to remember
7561 * the state in a backend-local data structure.
7565 * Register a newly-created relation's ON COMMIT action.
7568 register_on_commit_action(Oid relid, OnCommitAction action)
7571 MemoryContext oldcxt;
7574 * We needn't bother registering the relation unless there is an ON COMMIT
7575 * action we need to take.
7577 if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
7580 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
7582 oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
7584 oc->oncommit = action;
7585 oc->creating_subid = GetCurrentSubTransactionId();
7586 oc->deleting_subid = InvalidSubTransactionId;
7588 on_commits = lcons(oc, on_commits);
7590 MemoryContextSwitchTo(oldcxt);
7594 * Unregister any ON COMMIT action when a relation is deleted.
7596 * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
7599 remove_on_commit_action(Oid relid)
7603 foreach(l, on_commits)
7605 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
7607 if (oc->relid == relid)
7609 oc->deleting_subid = GetCurrentSubTransactionId();
7616 * Perform ON COMMIT actions.
7618 * This is invoked just before actually committing, since it's possible
7619 * to encounter errors.
7622 PreCommit_on_commit_actions(void)
7625 List *oids_to_truncate = NIL;
7627 foreach(l, on_commits)
7629 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
7631 /* Ignore entry if already dropped in this xact */
7632 if (oc->deleting_subid != InvalidSubTransactionId)
7635 switch (oc->oncommit)
7638 case ONCOMMIT_PRESERVE_ROWS:
7639 /* Do nothing (there shouldn't be such entries, actually) */
7641 case ONCOMMIT_DELETE_ROWS:
7642 oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
7646 ObjectAddress object;
7648 object.classId = RelationRelationId;
7649 object.objectId = oc->relid;
7650 object.objectSubId = 0;
7651 performDeletion(&object, DROP_CASCADE);
7654 * Note that table deletion will call
7655 * remove_on_commit_action, so the entry should get marked
7658 Assert(oc->deleting_subid != InvalidSubTransactionId);
7663 if (oids_to_truncate != NIL)
7665 heap_truncate(oids_to_truncate);
7666 CommandCounterIncrement(); /* XXX needed? */
7671 * Post-commit or post-abort cleanup for ON COMMIT management.
7673 * All we do here is remove no-longer-needed OnCommitItem entries.
7675 * During commit, remove entries that were deleted during this transaction;
7676 * during abort, remove those created during this transaction.
7679 AtEOXact_on_commit_actions(bool isCommit)
7682 ListCell *prev_item;
7685 cur_item = list_head(on_commits);
7687 while (cur_item != NULL)
7689 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
7691 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
7692 oc->creating_subid != InvalidSubTransactionId)
7694 /* cur_item must be removed */
7695 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
7698 cur_item = lnext(prev_item);
7700 cur_item = list_head(on_commits);
7704 /* cur_item must be preserved */
7705 oc->creating_subid = InvalidSubTransactionId;
7706 oc->deleting_subid = InvalidSubTransactionId;
7707 prev_item = cur_item;
7708 cur_item = lnext(prev_item);
7714 * Post-subcommit or post-subabort cleanup for ON COMMIT management.
7716 * During subabort, we can immediately remove entries created during this
7717 * subtransaction. During subcommit, just relabel entries marked during
7718 * this subtransaction as being the parent's responsibility.
7721 AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
7722 SubTransactionId parentSubid)
7725 ListCell *prev_item;
7728 cur_item = list_head(on_commits);
7730 while (cur_item != NULL)
7732 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
7734 if (!isCommit && oc->creating_subid == mySubid)
7736 /* cur_item must be removed */
7737 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
7740 cur_item = lnext(prev_item);
7742 cur_item = list_head(on_commits);
7746 /* cur_item must be preserved */
7747 if (oc->creating_subid == mySubid)
7748 oc->creating_subid = parentSubid;
7749 if (oc->deleting_subid == mySubid)
7750 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
7751 prev_item = cur_item;
7752 cur_item = lnext(prev_item);