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.262 2008/08/11 11:05:11 heikki 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/parsenodes.h"
50 #include "optimizer/clauses.h"
51 #include "optimizer/plancat.h"
52 #include "optimizer/prep.h"
53 #include "parser/gramparse.h"
54 #include "parser/parse_clause.h"
55 #include "parser/parse_coerce.h"
56 #include "parser/parse_expr.h"
57 #include "parser/parse_oper.h"
58 #include "parser/parse_relation.h"
59 #include "parser/parse_type.h"
60 #include "parser/parse_utilcmd.h"
61 #include "parser/parser.h"
62 #include "rewrite/rewriteDefine.h"
63 #include "rewrite/rewriteHandler.h"
64 #include "storage/bufmgr.h"
65 #include "storage/lmgr.h"
66 #include "storage/smgr.h"
67 #include "utils/acl.h"
68 #include "utils/builtins.h"
69 #include "utils/fmgroids.h"
70 #include "utils/inval.h"
71 #include "utils/lsyscache.h"
72 #include "utils/memutils.h"
73 #include "utils/relcache.h"
74 #include "utils/snapmgr.h"
75 #include "utils/syscache.h"
76 #include "utils/tqual.h"
80 * ON COMMIT action list
82 typedef struct OnCommitItem
84 Oid relid; /* relid of relation */
85 OnCommitAction oncommit; /* what to do at end of xact */
88 * If this entry was created during the current transaction,
89 * creating_subid is the ID of the creating subxact; if created in a prior
90 * transaction, creating_subid is zero. If deleted during the current
91 * transaction, deleting_subid is the ID of the deleting subxact; if no
92 * deletion request is pending, deleting_subid is zero.
94 SubTransactionId creating_subid;
95 SubTransactionId deleting_subid;
98 static List *on_commits = NIL;
102 * State information for ALTER TABLE
104 * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
105 * structs, one for each table modified by the operation (the named table
106 * plus any child tables that are affected). We save lists of subcommands
107 * to apply to this table (possibly modified by parse transformation steps);
108 * these lists will be executed in Phase 2. If a Phase 3 step is needed,
109 * necessary information is stored in the constraints and newvals lists.
111 * Phase 2 is divided into multiple passes; subcommands are executed in
112 * a pass determined by subcommand type.
115 #define AT_PASS_DROP 0 /* DROP (all flavors) */
116 #define AT_PASS_ALTER_TYPE 1 /* ALTER COLUMN TYPE */
117 #define AT_PASS_OLD_INDEX 2 /* re-add existing indexes */
118 #define AT_PASS_OLD_CONSTR 3 /* re-add existing constraints */
119 #define AT_PASS_COL_ATTRS 4 /* set other column attributes */
120 /* We could support a RENAME COLUMN pass here, but not currently used */
121 #define AT_PASS_ADD_COL 5 /* ADD COLUMN */
122 #define AT_PASS_ADD_INDEX 6 /* ADD indexes */
123 #define AT_PASS_ADD_CONSTR 7 /* ADD constraints, defaults */
124 #define AT_PASS_MISC 8 /* other stuff */
125 #define AT_NUM_PASSES 9
127 typedef struct AlteredTableInfo
129 /* Information saved before any work commences: */
130 Oid relid; /* Relation to work on */
131 char relkind; /* Its relkind */
132 TupleDesc oldDesc; /* Pre-modification tuple descriptor */
133 /* Information saved by Phase 1 for Phase 2: */
134 List *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
135 /* Information saved by Phases 1/2 for Phase 3: */
136 List *constraints; /* List of NewConstraint */
137 List *newvals; /* List of NewColumnValue */
138 bool new_notnull; /* T if we added new NOT NULL constraints */
139 Oid newTableSpace; /* new tablespace; 0 means no change */
140 /* Objects to rebuild after completing ALTER TYPE operations */
141 List *changedConstraintOids; /* OIDs of constraints to rebuild */
142 List *changedConstraintDefs; /* string definitions of same */
143 List *changedIndexOids; /* OIDs of indexes to rebuild */
144 List *changedIndexDefs; /* string definitions of same */
147 /* Struct describing one new constraint to check in Phase 3 scan */
148 /* Note: new NOT NULL constraints are handled elsewhere */
149 typedef struct NewConstraint
151 char *name; /* Constraint name, or NULL if none */
152 ConstrType contype; /* CHECK or FOREIGN */
153 Oid refrelid; /* PK rel, if FOREIGN */
154 Oid conid; /* OID of pg_constraint entry, if FOREIGN */
155 Node *qual; /* Check expr or FkConstraint struct */
156 List *qualstate; /* Execution state for CHECK */
160 * Struct describing one new column value that needs to be computed during
161 * Phase 3 copy (this could be either a new column with a non-null default, or
162 * a column that we're changing the type of). Columns without such an entry
163 * are just copied from the old table during ATRewriteTable. Note that the
164 * expr is an expression over *old* table values.
166 typedef struct NewColumnValue
168 AttrNumber attnum; /* which column */
169 Expr *expr; /* expression to compute */
170 ExprState *exprstate; /* execution state */
174 * Error-reporting support for RemoveRelations
176 struct dropmsgstrings
179 int nonexistent_code;
180 const char *nonexistent_msg;
181 const char *skipping_msg;
182 const char *nota_msg;
183 const char *drophint_msg;
186 static const struct dropmsgstrings dropmsgstringarray[] = {
188 ERRCODE_UNDEFINED_TABLE,
189 gettext_noop("table \"%s\" does not exist"),
190 gettext_noop("table \"%s\" does not exist, skipping"),
191 gettext_noop("\"%s\" is not a table"),
192 gettext_noop("Use DROP TABLE to remove a table.")},
194 ERRCODE_UNDEFINED_TABLE,
195 gettext_noop("sequence \"%s\" does not exist"),
196 gettext_noop("sequence \"%s\" does not exist, skipping"),
197 gettext_noop("\"%s\" is not a sequence"),
198 gettext_noop("Use DROP SEQUENCE to remove a sequence.")},
200 ERRCODE_UNDEFINED_TABLE,
201 gettext_noop("view \"%s\" does not exist"),
202 gettext_noop("view \"%s\" does not exist, skipping"),
203 gettext_noop("\"%s\" is not a view"),
204 gettext_noop("Use DROP VIEW to remove a view.")},
206 ERRCODE_UNDEFINED_OBJECT,
207 gettext_noop("index \"%s\" does not exist"),
208 gettext_noop("index \"%s\" does not exist, skipping"),
209 gettext_noop("\"%s\" is not an index"),
210 gettext_noop("Use DROP INDEX to remove an index.")},
211 {RELKIND_COMPOSITE_TYPE,
212 ERRCODE_UNDEFINED_OBJECT,
213 gettext_noop("type \"%s\" does not exist"),
214 gettext_noop("type \"%s\" does not exist, skipping"),
215 gettext_noop("\"%s\" is not a type"),
216 gettext_noop("Use DROP TYPE to remove a type.")},
217 {'\0', 0, NULL, NULL, NULL, NULL}
221 static void truncate_check_rel(Relation rel);
222 static List *MergeAttributes(List *schema, List *supers, bool istemp,
223 List **supOids, List **supconstr, int *supOidCount);
224 static bool MergeCheckConstraint(List *constraints, char *name, Node *expr);
225 static bool change_varattnos_walker(Node *node, const AttrNumber *newattno);
226 static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel);
227 static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
228 static void StoreCatalogInheritance(Oid relationId, List *supers);
229 static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
230 int16 seqNumber, Relation inhRelation);
231 static int findAttrByName(const char *attributeName, List *schema);
232 static void setRelhassubclassInRelation(Oid relationId, bool relhassubclass);
233 static void AlterIndexNamespaces(Relation classRel, Relation rel,
234 Oid oldNspOid, Oid newNspOid);
235 static void AlterSeqNamespaces(Relation classRel, Relation rel,
236 Oid oldNspOid, Oid newNspOid,
237 const char *newNspName);
238 static int transformColumnNameList(Oid relId, List *colList,
239 int16 *attnums, Oid *atttypids);
240 static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
242 int16 *attnums, Oid *atttypids,
244 static Oid transformFkeyCheckAttrs(Relation pkrel,
245 int numattrs, int16 *attnums,
247 static void validateForeignKeyConstraint(FkConstraint *fkconstraint,
248 Relation rel, Relation pkrel, Oid constraintOid);
249 static void createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
251 static void ATController(Relation rel, List *cmds, bool recurse);
252 static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
253 bool recurse, bool recursing);
254 static void ATRewriteCatalogs(List **wqueue);
255 static void ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
257 static void ATRewriteTables(List **wqueue);
258 static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap);
259 static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
260 static void ATSimplePermissions(Relation rel, bool allowView);
261 static void ATSimplePermissionsRelationOrIndex(Relation rel);
262 static void ATSimpleRecursion(List **wqueue, Relation rel,
263 AlterTableCmd *cmd, bool recurse);
264 static void ATOneLevelRecursion(List **wqueue, Relation rel,
266 static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
268 static void ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
270 static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
271 static void ATExecDropNotNull(Relation rel, const char *colName);
272 static void ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
273 const char *colName);
274 static void ATExecColumnDefault(Relation rel, const char *colName,
276 static void ATPrepSetStatistics(Relation rel, const char *colName,
278 static void ATExecSetStatistics(Relation rel, const char *colName,
280 static void ATExecSetStorage(Relation rel, const char *colName,
282 static void ATExecDropColumn(Relation rel, const char *colName,
283 DropBehavior behavior,
284 bool recurse, bool recursing);
285 static void ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
286 IndexStmt *stmt, bool is_rebuild);
287 static void ATExecAddConstraint(List **wqueue,
288 AlteredTableInfo *tab, Relation rel,
289 Node *newConstraint, bool recurse);
290 static void ATAddCheckConstraint(List **wqueue,
291 AlteredTableInfo *tab, Relation rel,
293 bool recurse, bool recursing);
294 static void ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
295 FkConstraint *fkconstraint);
296 static void ATExecDropConstraint(Relation rel, const char *constrName,
297 DropBehavior behavior,
298 bool recurse, bool recursing);
299 static void ATPrepAlterColumnType(List **wqueue,
300 AlteredTableInfo *tab, Relation rel,
301 bool recurse, bool recursing,
303 static void ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
304 const char *colName, TypeName *typename);
305 static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab);
306 static void ATPostAlterTypeParse(char *cmd, List **wqueue);
307 static void change_owner_recurse_to_sequences(Oid relationOid,
309 static void ATExecClusterOn(Relation rel, const char *indexName);
310 static void ATExecDropCluster(Relation rel);
311 static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
312 char *tablespacename);
313 static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace);
314 static void ATExecSetRelOptions(Relation rel, List *defList, bool isReset);
315 static void ATExecEnableDisableTrigger(Relation rel, char *trigname,
316 char fires_when, bool skip_system);
317 static void ATExecEnableDisableRule(Relation rel, char *rulename,
319 static void ATExecAddInherit(Relation rel, RangeVar *parent);
320 static void ATExecDropInherit(Relation rel, RangeVar *parent);
321 static void copy_relation_data(SMgrRelation rel, SMgrRelation dst,
322 ForkNumber forkNum, bool istemp);
325 /* ----------------------------------------------------------------
327 * Creates a new relation.
329 * If successful, returns the OID of the new relation.
330 * ----------------------------------------------------------------
333 DefineRelation(CreateStmt *stmt, char relkind)
335 char relname[NAMEDATALEN];
337 List *schema = stmt->tableElts;
341 TupleDesc descriptor;
343 List *old_constraints;
347 List *cookedDefaults;
353 * Truncate relname to appropriate length (probably a waste of time, as
354 * parser should have done this already).
356 StrNCpy(relname, stmt->relation->relname, NAMEDATALEN);
359 * Check consistency of arguments
361 if (stmt->oncommit != ONCOMMIT_NOOP && !stmt->relation->istemp)
363 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
364 errmsg("ON COMMIT can only be used on temporary tables")));
367 * Look up the namespace in which we are supposed to create the relation.
368 * Check we have permission to create there. Skip check if bootstrapping,
369 * since permissions machinery may not be working yet.
371 namespaceId = RangeVarGetCreationNamespace(stmt->relation);
373 if (!IsBootstrapProcessingMode())
377 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
379 if (aclresult != ACLCHECK_OK)
380 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
381 get_namespace_name(namespaceId));
385 * Select tablespace to use. If not specified, use default tablespace
386 * (which may in turn default to database's default).
388 if (stmt->tablespacename)
390 tablespaceId = get_tablespace_oid(stmt->tablespacename);
391 if (!OidIsValid(tablespaceId))
393 (errcode(ERRCODE_UNDEFINED_OBJECT),
394 errmsg("tablespace \"%s\" does not exist",
395 stmt->tablespacename)));
399 tablespaceId = GetDefaultTablespace(stmt->relation->istemp);
400 /* note InvalidOid is OK in this case */
403 /* Check permissions except when using database's default */
404 if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
408 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
410 if (aclresult != ACLCHECK_OK)
411 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
412 get_tablespace_name(tablespaceId));
416 * Parse and validate reloptions, if any.
418 reloptions = transformRelOptions((Datum) 0, stmt->options, true, false);
420 (void) heap_reloptions(relkind, reloptions, true);
423 * Look up inheritance ancestors and generate relation schema, including
424 * inherited attributes.
426 schema = MergeAttributes(schema, stmt->inhRelations,
427 stmt->relation->istemp,
428 &inheritOids, &old_constraints, &parentOidCount);
431 * Create a tuple descriptor from the relation schema. Note that this
432 * deals with column names, types, and NOT NULL constraints, but not
433 * default values or CHECK constraints; we handle those below.
435 descriptor = BuildDescForRelation(schema);
437 localHasOids = interpretOidsOption(stmt->options);
438 descriptor->tdhasoid = (localHasOids || parentOidCount > 0);
441 * Find columns with default values and prepare for insertion of the
442 * defaults. Pre-cooked (that is, inherited) defaults go into a list of
443 * CookedConstraint structs that we'll pass to heap_create_with_catalog,
444 * while raw defaults go into a list of RawColumnDefault structs that
445 * will be processed by AddRelationNewConstraints. (We can't deal with
446 * raw expressions until we can do transformExpr.)
448 * We can set the atthasdef flags now in the tuple descriptor; this just
449 * saves StoreAttrDefault from having to do an immediate update of the
453 cookedDefaults = NIL;
456 foreach(listptr, schema)
458 ColumnDef *colDef = lfirst(listptr);
462 if (colDef->raw_default != NULL)
464 RawColumnDefault *rawEnt;
466 Assert(colDef->cooked_default == NULL);
468 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
469 rawEnt->attnum = attnum;
470 rawEnt->raw_default = colDef->raw_default;
471 rawDefaults = lappend(rawDefaults, rawEnt);
472 descriptor->attrs[attnum - 1]->atthasdef = true;
474 else if (colDef->cooked_default != NULL)
476 CookedConstraint *cooked;
478 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
479 cooked->contype = CONSTR_DEFAULT;
481 cooked->attnum = attnum;
482 cooked->expr = stringToNode(colDef->cooked_default);
483 cooked->is_local = true; /* not used for defaults */
484 cooked->inhcount = 0; /* ditto */
485 cookedDefaults = lappend(cookedDefaults, cooked);
486 descriptor->attrs[attnum - 1]->atthasdef = true;
491 * Create the relation. Inherited defaults and constraints are passed
492 * in for immediate handling --- since they don't need parsing, they
493 * can be stored immediately.
495 relationId = heap_create_with_catalog(relname,
501 list_concat(cookedDefaults,
509 allowSystemTableMods);
511 StoreCatalogInheritance(relationId, inheritOids);
514 * We must bump the command counter to make the newly-created relation
515 * tuple visible for opening.
517 CommandCounterIncrement();
520 * Open the new relation and acquire exclusive lock on it. This isn't
521 * really necessary for locking out other backends (since they can't see
522 * the new rel anyway until we commit), but it keeps the lock manager from
523 * complaining about deadlock risks.
525 rel = relation_open(relationId, AccessExclusiveLock);
528 * Now add any newly specified column default values and CHECK constraints
529 * to the new relation. These are passed to us in the form of raw
530 * parsetrees; we need to transform them to executable expression trees
531 * before they can be added. The most convenient way to do that is to
532 * apply the parser's transformExpr routine, but transformExpr doesn't
533 * work unless we have a pre-existing relation. So, the transformation has
534 * to be postponed to this final step of CREATE TABLE.
536 if (rawDefaults || stmt->constraints)
537 AddRelationNewConstraints(rel, rawDefaults, stmt->constraints,
541 * Clean up. We keep lock on new relation (although it shouldn't be
542 * visible to anyone else anyway, until commit).
544 relation_close(rel, NoLock);
550 * Emit the right error or warning message for a "DROP" command issued on a
551 * non-existent relation
554 DropErrorMsgNonExistent(const char *relname, char rightkind, bool missing_ok)
556 const struct dropmsgstrings *rentry;
558 for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
560 if (rentry->kind == rightkind)
565 (errcode(rentry->nonexistent_code),
566 errmsg(rentry->nonexistent_msg, relname)));
570 ereport(NOTICE, (errmsg(rentry->skipping_msg, relname)));
576 Assert(rentry->kind != '\0'); /* Should be impossible */
580 * Emit the right error message for a "DROP" command issued on a
581 * relation of the wrong type
584 DropErrorMsgWrongType(const char *relname, char wrongkind, char rightkind)
586 const struct dropmsgstrings *rentry;
587 const struct dropmsgstrings *wentry;
589 for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
590 if (rentry->kind == rightkind)
592 Assert(rentry->kind != '\0');
594 for (wentry = dropmsgstringarray; wentry->kind != '\0'; wentry++)
595 if (wentry->kind == wrongkind)
597 /* wrongkind could be something we don't have in our table... */
600 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
601 errmsg(rentry->nota_msg, relname),
602 (wentry->kind != '\0') ? errhint(wentry->drophint_msg) : 0));
607 * Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW
610 RemoveRelations(DropStmt *drop)
612 ObjectAddresses *objects;
617 * First we identify all the relations, then we delete them in a single
618 * performMultipleDeletions() call. This is to avoid unwanted
619 * DROP RESTRICT errors if one of the relations depends on another.
622 /* Determine required relkind */
623 switch (drop->removeType)
626 relkind = RELKIND_RELATION;
630 relkind = RELKIND_INDEX;
633 case OBJECT_SEQUENCE:
634 relkind = RELKIND_SEQUENCE;
638 relkind = RELKIND_VIEW;
642 elog(ERROR, "unrecognized drop object type: %d",
643 (int) drop->removeType);
644 relkind = 0; /* keep compiler quiet */
648 /* Lock and validate each relation; build a list of object addresses */
649 objects = new_object_addresses();
651 foreach(cell, drop->objects)
653 RangeVar *rel = makeRangeVarFromNameList((List *) lfirst(cell));
656 Form_pg_class classform;
660 * These next few steps are a great deal like relation_openrv, but we
661 * don't bother building a relcache entry since we don't need it.
663 * Check for shared-cache-inval messages before trying to access the
664 * relation. This is needed to cover the case where the name
665 * identifies a rel that has been dropped and recreated since the
666 * start of our transaction: if we don't flush the old syscache entry,
667 * then we'll latch onto that entry and suffer an error later.
669 AcceptInvalidationMessages();
671 /* Look up the appropriate relation using namespace search */
672 relOid = RangeVarGetRelid(rel, true);
675 if (!OidIsValid(relOid))
677 DropErrorMsgNonExistent(rel->relname, relkind, drop->missing_ok);
682 * In DROP INDEX, attempt to acquire lock on the parent table before
683 * locking the index. index_drop() will need this anyway, and since
684 * regular queries lock tables before their indexes, we risk deadlock
685 * if we do it the other way around. No error if we don't find a
686 * pg_index entry, though --- that most likely means it isn't an
687 * index, and we'll fail below.
689 if (relkind == RELKIND_INDEX)
691 tuple = SearchSysCache(INDEXRELID,
692 ObjectIdGetDatum(relOid),
694 if (HeapTupleIsValid(tuple))
696 Form_pg_index index = (Form_pg_index) GETSTRUCT(tuple);
698 LockRelationOid(index->indrelid, AccessExclusiveLock);
699 ReleaseSysCache(tuple);
703 /* Get the lock before trying to fetch the syscache entry */
704 LockRelationOid(relOid, AccessExclusiveLock);
706 tuple = SearchSysCache(RELOID,
707 ObjectIdGetDatum(relOid),
709 if (!HeapTupleIsValid(tuple))
710 elog(ERROR, "cache lookup failed for relation %u", relOid);
711 classform = (Form_pg_class) GETSTRUCT(tuple);
713 if (classform->relkind != relkind)
714 DropErrorMsgWrongType(rel->relname, classform->relkind, relkind);
716 /* Allow DROP to either table owner or schema owner */
717 if (!pg_class_ownercheck(relOid, GetUserId()) &&
718 !pg_namespace_ownercheck(classform->relnamespace, GetUserId()))
719 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
722 if (!allowSystemTableMods && IsSystemClass(classform))
724 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
725 errmsg("permission denied: \"%s\" is a system catalog",
728 /* OK, we're ready to delete this one */
729 obj.classId = RelationRelationId;
730 obj.objectId = relOid;
733 add_exact_object_address(&obj, objects);
735 ReleaseSysCache(tuple);
738 performMultipleDeletions(objects, drop->behavior);
740 free_object_addresses(objects);
745 * Executes a TRUNCATE command.
747 * This is a multi-relation truncate. We first open and grab exclusive
748 * lock on all relations involved, checking permissions and otherwise
749 * verifying that the relation is OK for truncation. In CASCADE mode,
750 * relations having FK references to the targeted relations are automatically
751 * added to the group; in RESTRICT mode, we check that all FK references are
752 * internal to the group that's being truncated. Finally all the relations
753 * are truncated and reindexed.
756 ExecuteTruncate(TruncateStmt *stmt)
760 List *seq_relids = NIL;
762 ResultRelInfo *resultRelInfos;
763 ResultRelInfo *resultRelInfo;
767 * Open, exclusive-lock, and check all the explicitly-specified relations
769 foreach(cell, stmt->relations)
771 RangeVar *rv = lfirst(cell);
774 rel = heap_openrv(rv, AccessExclusiveLock);
775 /* don't throw error for "TRUNCATE foo, foo" */
776 if (list_member_oid(relids, RelationGetRelid(rel)))
778 heap_close(rel, AccessExclusiveLock);
781 truncate_check_rel(rel);
782 rels = lappend(rels, rel);
783 relids = lappend_oid(relids, RelationGetRelid(rel));
787 * In CASCADE mode, suck in all referencing relations as well. This
788 * requires multiple iterations to find indirectly-dependent relations. At
789 * each phase, we need to exclusive-lock new rels before looking for their
790 * dependencies, else we might miss something. Also, we check each rel as
791 * soon as we open it, to avoid a faux pas such as holding lock for a long
792 * time on a rel we have no permissions for.
794 if (stmt->behavior == DROP_CASCADE)
800 newrelids = heap_truncate_find_FKs(relids);
801 if (newrelids == NIL)
802 break; /* nothing else to add */
804 foreach(cell, newrelids)
806 Oid relid = lfirst_oid(cell);
809 rel = heap_open(relid, AccessExclusiveLock);
811 (errmsg("truncate cascades to table \"%s\"",
812 RelationGetRelationName(rel))));
813 truncate_check_rel(rel);
814 rels = lappend(rels, rel);
815 relids = lappend_oid(relids, relid);
821 * Check foreign key references. In CASCADE mode, this should be
822 * unnecessary since we just pulled in all the references; but as a
823 * cross-check, do it anyway if in an Assert-enabled build.
825 #ifdef USE_ASSERT_CHECKING
826 heap_truncate_check_FKs(rels, false);
828 if (stmt->behavior == DROP_RESTRICT)
829 heap_truncate_check_FKs(rels, false);
833 * If we are asked to restart sequences, find all the sequences,
834 * lock them (we only need AccessShareLock because that's all that
835 * ALTER SEQUENCE takes), and check permissions. We want to do this
836 * early since it's pointless to do all the truncation work only to fail
837 * on sequence permissions.
839 if (stmt->restart_seqs)
843 Relation rel = (Relation) lfirst(cell);
844 List *seqlist = getOwnedSequences(RelationGetRelid(rel));
847 foreach(seqcell, seqlist)
849 Oid seq_relid = lfirst_oid(seqcell);
852 seq_rel = relation_open(seq_relid, AccessShareLock);
854 /* This check must match AlterSequence! */
855 if (!pg_class_ownercheck(seq_relid, GetUserId()))
856 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
857 RelationGetRelationName(seq_rel));
859 seq_relids = lappend_oid(seq_relids, seq_relid);
861 relation_close(seq_rel, NoLock);
866 /* Prepare to catch AFTER triggers. */
867 AfterTriggerBeginQuery();
870 * To fire triggers, we'll need an EState as well as a ResultRelInfo
873 estate = CreateExecutorState();
874 resultRelInfos = (ResultRelInfo *)
875 palloc(list_length(rels) * sizeof(ResultRelInfo));
876 resultRelInfo = resultRelInfos;
879 Relation rel = (Relation) lfirst(cell);
881 InitResultRelInfo(resultRelInfo,
883 0, /* dummy rangetable index */
884 CMD_DELETE, /* don't need any index info */
888 estate->es_result_relations = resultRelInfos;
889 estate->es_num_result_relations = list_length(rels);
892 * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
893 * truncating (this is because one of them might throw an error).
894 * Also, if we were to allow them to prevent statement execution,
895 * that would need to be handled here.
897 resultRelInfo = resultRelInfos;
900 estate->es_result_relation_info = resultRelInfo;
901 ExecBSTruncateTriggers(estate, resultRelInfo);
906 * OK, truncate each table.
910 Relation rel = (Relation) lfirst(cell);
915 * Create a new empty storage file for the relation, and assign it as
916 * the relfilenode value. The old storage file is scheduled for
917 * deletion at commit.
919 setNewRelfilenode(rel, RecentXmin);
921 heap_relid = RelationGetRelid(rel);
922 toast_relid = rel->rd_rel->reltoastrelid;
925 * The same for the toast table, if any.
927 if (OidIsValid(toast_relid))
929 rel = relation_open(toast_relid, AccessExclusiveLock);
930 setNewRelfilenode(rel, RecentXmin);
931 heap_close(rel, NoLock);
935 * Reconstruct the indexes to match, and we're done.
937 reindex_relation(heap_relid, true);
941 * Process all AFTER STATEMENT TRUNCATE triggers.
943 resultRelInfo = resultRelInfos;
946 estate->es_result_relation_info = resultRelInfo;
947 ExecASTruncateTriggers(estate, resultRelInfo);
951 /* Handle queued AFTER triggers */
952 AfterTriggerEndQuery(estate);
954 /* We can clean up the EState now */
955 FreeExecutorState(estate);
957 /* And close the rels (can't do this while EState still holds refs) */
960 Relation rel = (Relation) lfirst(cell);
962 heap_close(rel, NoLock);
966 * Lastly, restart any owned sequences if we were asked to. This is done
967 * last because it's nontransactional: restarts will not roll back if
968 * we abort later. Hence it's important to postpone them as long as
969 * possible. (This is also a big reason why we locked and
970 * permission-checked the sequences beforehand.)
972 if (stmt->restart_seqs)
974 List *options = list_make1(makeDefElem("restart", NULL));
976 foreach(cell, seq_relids)
978 Oid seq_relid = lfirst_oid(cell);
980 AlterSequenceInternal(seq_relid, options);
986 * Check that a given rel is safe to truncate. Subroutine for ExecuteTruncate
989 truncate_check_rel(Relation rel)
991 /* Only allow truncate on regular tables */
992 if (rel->rd_rel->relkind != RELKIND_RELATION)
994 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
995 errmsg("\"%s\" is not a table",
996 RelationGetRelationName(rel))));
998 /* Permissions checks */
999 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
1000 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1001 RelationGetRelationName(rel));
1003 if (!allowSystemTableMods && IsSystemRelation(rel))
1005 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1006 errmsg("permission denied: \"%s\" is a system catalog",
1007 RelationGetRelationName(rel))));
1010 * We can never allow truncation of shared or nailed-in-cache relations,
1011 * because we can't support changing their relfilenode values.
1013 if (rel->rd_rel->relisshared || rel->rd_isnailed)
1015 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1016 errmsg("cannot truncate system relation \"%s\"",
1017 RelationGetRelationName(rel))));
1020 * Don't allow truncate on temp tables of other backends ... their local
1021 * buffer manager is not going to cope.
1023 if (isOtherTempNamespace(RelationGetNamespace(rel)))
1025 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1026 errmsg("cannot truncate temporary tables of other sessions")));
1029 * Also check for active uses of the relation in the current transaction,
1030 * including open scans and pending AFTER trigger events.
1032 CheckTableNotInUse(rel, "TRUNCATE");
1037 * Returns new schema given initial schema and superclasses.
1040 * 'schema' is the column/attribute definition for the table. (It's a list
1041 * of ColumnDef's.) It is destructively changed.
1042 * 'supers' is a list of names (as RangeVar nodes) of parent relations.
1043 * 'istemp' is TRUE if we are creating a temp relation.
1046 * 'supOids' receives a list of the OIDs of the parent relations.
1047 * 'supconstr' receives a list of constraints belonging to the parents,
1048 * updated as necessary to be valid for the child.
1049 * 'supOidCount' is set to the number of parents that have OID columns.
1052 * Completed schema list.
1055 * The order in which the attributes are inherited is very important.
1056 * Intuitively, the inherited attributes should come first. If a table
1057 * inherits from multiple parents, the order of those attributes are
1058 * according to the order of the parents specified in CREATE TABLE.
1060 * Here's an example:
1062 * create table person (name text, age int4, location point);
1063 * create table emp (salary int4, manager text) inherits(person);
1064 * create table student (gpa float8) inherits (person);
1065 * create table stud_emp (percent int4) inherits (emp, student);
1067 * The order of the attributes of stud_emp is:
1069 * person {1:name, 2:age, 3:location}
1071 * {6:gpa} student emp {4:salary, 5:manager}
1073 * stud_emp {7:percent}
1075 * If the same attribute name appears multiple times, then it appears
1076 * in the result table in the proper location for its first appearance.
1078 * Constraints (including NOT NULL constraints) for the child table
1079 * are the union of all relevant constraints, from both the child schema
1080 * and parent tables.
1082 * The default value for a child column is defined as:
1083 * (1) If the child schema specifies a default, that value is used.
1084 * (2) If neither the child nor any parent specifies a default, then
1085 * the column will not have a default.
1086 * (3) If conflicting defaults are inherited from different parents
1087 * (and not overridden by the child), an error is raised.
1088 * (4) Otherwise the inherited default is used.
1089 * Rule (3) is new in Postgres 7.1; in earlier releases you got a
1090 * rather arbitrary choice of which parent default to use.
1094 MergeAttributes(List *schema, List *supers, bool istemp,
1095 List **supOids, List **supconstr, int *supOidCount)
1098 List *inhSchema = NIL;
1099 List *parentOids = NIL;
1100 List *constraints = NIL;
1101 int parentsWithOids = 0;
1102 bool have_bogus_defaults = false;
1103 char *bogus_marker = "Bogus!"; /* marks conflicting defaults */
1107 * Check for and reject tables with too many columns. We perform this
1108 * check relatively early for two reasons: (a) we don't run the risk of
1109 * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
1110 * okay if we're processing <= 1600 columns, but could take minutes to
1111 * execute if the user attempts to create a table with hundreds of
1112 * thousands of columns.
1114 * Note that we also need to check that any we do not exceed this figure
1115 * after including columns from inherited relations.
1117 if (list_length(schema) > MaxHeapAttributeNumber)
1119 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1120 errmsg("tables can have at most %d columns",
1121 MaxHeapAttributeNumber)));
1124 * Check for duplicate names in the explicit list of attributes.
1126 * Although we might consider merging such entries in the same way that we
1127 * handle name conflicts for inherited attributes, it seems to make more
1128 * sense to assume such conflicts are errors.
1130 foreach(entry, schema)
1132 ColumnDef *coldef = lfirst(entry);
1135 for_each_cell(rest, lnext(entry))
1137 ColumnDef *restdef = lfirst(rest);
1139 if (strcmp(coldef->colname, restdef->colname) == 0)
1141 (errcode(ERRCODE_DUPLICATE_COLUMN),
1142 errmsg("column \"%s\" specified more than once",
1148 * Scan the parents left-to-right, and merge their attributes to form a
1149 * list of inherited attributes (inhSchema). Also check to see if we need
1150 * to inherit an OID column.
1153 foreach(entry, supers)
1155 RangeVar *parent = (RangeVar *) lfirst(entry);
1157 TupleDesc tupleDesc;
1158 TupleConstr *constr;
1159 AttrNumber *newattno;
1160 AttrNumber parent_attno;
1162 relation = heap_openrv(parent, AccessShareLock);
1164 if (relation->rd_rel->relkind != RELKIND_RELATION)
1166 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1167 errmsg("inherited relation \"%s\" is not a table",
1169 /* Permanent rels cannot inherit from temporary ones */
1170 if (!istemp && isTempNamespace(RelationGetNamespace(relation)))
1172 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1173 errmsg("cannot inherit from temporary relation \"%s\"",
1177 * We should have an UNDER permission flag for this, but for now,
1178 * demand that creator of a child table own the parent.
1180 if (!pg_class_ownercheck(RelationGetRelid(relation), GetUserId()))
1181 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1182 RelationGetRelationName(relation));
1185 * Reject duplications in the list of parents.
1187 if (list_member_oid(parentOids, RelationGetRelid(relation)))
1189 (errcode(ERRCODE_DUPLICATE_TABLE),
1190 errmsg("relation \"%s\" would be inherited from more than once",
1193 parentOids = lappend_oid(parentOids, RelationGetRelid(relation));
1195 if (relation->rd_rel->relhasoids)
1198 tupleDesc = RelationGetDescr(relation);
1199 constr = tupleDesc->constr;
1202 * newattno[] will contain the child-table attribute numbers for the
1203 * attributes of this parent table. (They are not the same for
1204 * parents after the first one, nor if we have dropped columns.)
1206 newattno = (AttrNumber *)
1207 palloc(tupleDesc->natts * sizeof(AttrNumber));
1209 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1212 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
1213 char *attributeName = NameStr(attribute->attname);
1218 * Ignore dropped columns in the parent.
1220 if (attribute->attisdropped)
1223 * change_varattnos_of_a_node asserts that this is greater
1224 * than zero, so if anything tries to use it, we should find
1227 newattno[parent_attno - 1] = 0;
1232 * Does it conflict with some previously inherited column?
1234 exist_attno = findAttrByName(attributeName, inhSchema);
1235 if (exist_attno > 0)
1241 * Yes, try to merge the two column definitions. They must
1242 * have the same type and typmod.
1245 (errmsg("merging multiple inherited definitions of column \"%s\"",
1247 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1248 defTypeId = typenameTypeId(NULL, def->typename, &deftypmod);
1249 if (defTypeId != attribute->atttypid ||
1250 deftypmod != attribute->atttypmod)
1252 (errcode(ERRCODE_DATATYPE_MISMATCH),
1253 errmsg("inherited column \"%s\" has a type conflict",
1255 errdetail("%s versus %s",
1256 TypeNameToString(def->typename),
1257 format_type_be(attribute->atttypid))));
1259 /* Merge of NOT NULL constraints = OR 'em together */
1260 def->is_not_null |= attribute->attnotnull;
1261 /* Default and other constraints are handled below */
1262 newattno[parent_attno - 1] = exist_attno;
1267 * No, create a new inherited column
1269 def = makeNode(ColumnDef);
1270 def->colname = pstrdup(attributeName);
1271 def->typename = makeTypeNameFromOid(attribute->atttypid,
1272 attribute->atttypmod);
1274 def->is_local = false;
1275 def->is_not_null = attribute->attnotnull;
1276 def->raw_default = NULL;
1277 def->cooked_default = NULL;
1278 def->constraints = NIL;
1279 inhSchema = lappend(inhSchema, def);
1280 newattno[parent_attno - 1] = ++child_attno;
1284 * Copy default if any
1286 if (attribute->atthasdef)
1288 char *this_default = NULL;
1289 AttrDefault *attrdef;
1292 /* Find default in constraint structure */
1293 Assert(constr != NULL);
1294 attrdef = constr->defval;
1295 for (i = 0; i < constr->num_defval; i++)
1297 if (attrdef[i].adnum == parent_attno)
1299 this_default = attrdef[i].adbin;
1303 Assert(this_default != NULL);
1306 * If default expr could contain any vars, we'd need to fix
1307 * 'em, but it can't; so default is ready to apply to child.
1309 * If we already had a default from some prior parent, check
1310 * to see if they are the same. If so, no problem; if not,
1311 * mark the column as having a bogus default. Below, we will
1312 * complain if the bogus default isn't overridden by the child
1315 Assert(def->raw_default == NULL);
1316 if (def->cooked_default == NULL)
1317 def->cooked_default = pstrdup(this_default);
1318 else if (strcmp(def->cooked_default, this_default) != 0)
1320 def->cooked_default = bogus_marker;
1321 have_bogus_defaults = true;
1327 * Now copy the CHECK constraints of this parent, adjusting attnos
1328 * using the completed newattno[] map. Identically named constraints
1329 * are merged if possible, else we throw error.
1331 if (constr && constr->num_check > 0)
1333 ConstrCheck *check = constr->check;
1336 for (i = 0; i < constr->num_check; i++)
1338 char *name = check[i].ccname;
1341 /* adjust varattnos of ccbin here */
1342 expr = stringToNode(check[i].ccbin);
1343 change_varattnos_of_a_node(expr, newattno);
1345 /* check for duplicate */
1346 if (!MergeCheckConstraint(constraints, name, expr))
1348 /* nope, this is a new one */
1349 CookedConstraint *cooked;
1351 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1352 cooked->contype = CONSTR_CHECK;
1353 cooked->name = pstrdup(name);
1354 cooked->attnum = 0; /* not used for constraints */
1355 cooked->expr = expr;
1356 cooked->is_local = false;
1357 cooked->inhcount = 1;
1358 constraints = lappend(constraints, cooked);
1366 * Close the parent rel, but keep our AccessShareLock on it until xact
1367 * commit. That will prevent someone else from deleting or ALTERing
1368 * the parent before the child is committed.
1370 heap_close(relation, NoLock);
1374 * If we had no inherited attributes, the result schema is just the
1375 * explicitly declared columns. Otherwise, we need to merge the declared
1376 * columns into the inherited schema list.
1378 if (inhSchema != NIL)
1380 foreach(entry, schema)
1382 ColumnDef *newdef = lfirst(entry);
1383 char *attributeName = newdef->colname;
1387 * Does it conflict with some previously inherited column?
1389 exist_attno = findAttrByName(attributeName, inhSchema);
1390 if (exist_attno > 0)
1399 * Yes, try to merge the two column definitions. They must
1400 * have the same type and typmod.
1403 (errmsg("merging column \"%s\" with inherited definition",
1405 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1406 defTypeId = typenameTypeId(NULL, def->typename, &deftypmod);
1407 newTypeId = typenameTypeId(NULL, newdef->typename, &newtypmod);
1408 if (defTypeId != newTypeId || deftypmod != newtypmod)
1410 (errcode(ERRCODE_DATATYPE_MISMATCH),
1411 errmsg("column \"%s\" has a type conflict",
1413 errdetail("%s versus %s",
1414 TypeNameToString(def->typename),
1415 TypeNameToString(newdef->typename))));
1416 /* Mark the column as locally defined */
1417 def->is_local = true;
1418 /* Merge of NOT NULL constraints = OR 'em together */
1419 def->is_not_null |= newdef->is_not_null;
1420 /* If new def has a default, override previous default */
1421 if (newdef->raw_default != NULL)
1423 def->raw_default = newdef->raw_default;
1424 def->cooked_default = newdef->cooked_default;
1430 * No, attach new column to result schema
1432 inhSchema = lappend(inhSchema, newdef);
1439 * Check that we haven't exceeded the legal # of columns after merging
1440 * in inherited columns.
1442 if (list_length(schema) > MaxHeapAttributeNumber)
1444 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1445 errmsg("tables can have at most %d columns",
1446 MaxHeapAttributeNumber)));
1450 * If we found any conflicting parent default values, check to make sure
1451 * they were overridden by the child.
1453 if (have_bogus_defaults)
1455 foreach(entry, schema)
1457 ColumnDef *def = lfirst(entry);
1459 if (def->cooked_default == bogus_marker)
1461 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
1462 errmsg("column \"%s\" inherits conflicting default values",
1464 errhint("To resolve the conflict, specify a default explicitly.")));
1468 *supOids = parentOids;
1469 *supconstr = constraints;
1470 *supOidCount = parentsWithOids;
1476 * MergeCheckConstraint
1477 * Try to merge an inherited CHECK constraint with previous ones
1479 * If we inherit identically-named constraints from multiple parents, we must
1480 * merge them, or throw an error if they don't have identical definitions.
1482 * constraints is a list of CookedConstraint structs for previous constraints.
1484 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
1485 * got a so-far-unique name, or throws error if conflict.
1488 MergeCheckConstraint(List *constraints, char *name, Node *expr)
1492 foreach(lc, constraints)
1494 CookedConstraint *ccon = (CookedConstraint *) lfirst(lc);
1496 Assert(ccon->contype == CONSTR_CHECK);
1498 /* Non-matching names never conflict */
1499 if (strcmp(ccon->name, name) != 0)
1502 if (equal(expr, ccon->expr))
1510 (errcode(ERRCODE_DUPLICATE_OBJECT),
1511 errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
1520 * Replace varattno values in an expression tree according to the given
1521 * map array, that is, varattno N is replaced by newattno[N-1]. It is
1522 * caller's responsibility to ensure that the array is long enough to
1523 * define values for all user varattnos present in the tree. System column
1524 * attnos remain unchanged.
1526 * Note that the passed node tree is modified in-place!
1529 change_varattnos_of_a_node(Node *node, const AttrNumber *newattno)
1531 /* no setup needed, so away we go */
1532 (void) change_varattnos_walker(node, newattno);
1536 change_varattnos_walker(Node *node, const AttrNumber *newattno)
1542 Var *var = (Var *) node;
1544 if (var->varlevelsup == 0 && var->varno == 1 &&
1548 * ??? the following may be a problem when the node is multiply
1549 * referenced though stringToNode() doesn't create such a node
1552 Assert(newattno[var->varattno - 1] > 0);
1553 var->varattno = var->varoattno = newattno[var->varattno - 1];
1557 return expression_tree_walker(node, change_varattnos_walker,
1562 * Generate a map for change_varattnos_of_a_node from old and new TupleDesc's,
1563 * matching according to column name.
1566 varattnos_map(TupleDesc old, TupleDesc new)
1572 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * old->natts);
1573 for (i = 1; i <= old->natts; i++)
1575 if (old->attrs[i - 1]->attisdropped)
1576 continue; /* leave the entry as zero */
1578 for (j = 1; j <= new->natts; j++)
1580 if (strcmp(NameStr(old->attrs[i - 1]->attname),
1581 NameStr(new->attrs[j - 1]->attname)) == 0)
1592 * Generate a map for change_varattnos_of_a_node from a TupleDesc and a list
1596 varattnos_map_schema(TupleDesc old, List *schema)
1601 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * old->natts);
1602 for (i = 1; i <= old->natts; i++)
1604 if (old->attrs[i - 1]->attisdropped)
1605 continue; /* leave the entry as zero */
1607 attmap[i - 1] = findAttrByName(NameStr(old->attrs[i - 1]->attname),
1615 * StoreCatalogInheritance
1616 * Updates the system catalogs with proper inheritance information.
1618 * supers is a list of the OIDs of the new relation's direct ancestors.
1621 StoreCatalogInheritance(Oid relationId, List *supers)
1630 AssertArg(OidIsValid(relationId));
1636 * Store INHERITS information in pg_inherits using direct ancestors only.
1637 * Also enter dependencies on the direct ancestors, and make sure they are
1638 * marked with relhassubclass = true.
1640 * (Once upon a time, both direct and indirect ancestors were found here
1641 * and then entered into pg_ipl. Since that catalog doesn't exist
1642 * anymore, there's no need to look for indirect ancestors.)
1644 relation = heap_open(InheritsRelationId, RowExclusiveLock);
1647 foreach(entry, supers)
1649 Oid parentOid = lfirst_oid(entry);
1651 StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation);
1655 heap_close(relation, RowExclusiveLock);
1659 * Make catalog entries showing relationId as being an inheritance child
1660 * of parentOid. inhRelation is the already-opened pg_inherits catalog.
1663 StoreCatalogInheritance1(Oid relationId, Oid parentOid,
1664 int16 seqNumber, Relation inhRelation)
1666 TupleDesc desc = RelationGetDescr(inhRelation);
1667 Datum datum[Natts_pg_inherits];
1668 char nullarr[Natts_pg_inherits];
1669 ObjectAddress childobject,
1674 * Make the pg_inherits entry
1676 datum[0] = ObjectIdGetDatum(relationId); /* inhrelid */
1677 datum[1] = ObjectIdGetDatum(parentOid); /* inhparent */
1678 datum[2] = Int16GetDatum(seqNumber); /* inhseqno */
1684 tuple = heap_formtuple(desc, datum, nullarr);
1686 simple_heap_insert(inhRelation, tuple);
1688 CatalogUpdateIndexes(inhRelation, tuple);
1690 heap_freetuple(tuple);
1693 * Store a dependency too
1695 parentobject.classId = RelationRelationId;
1696 parentobject.objectId = parentOid;
1697 parentobject.objectSubId = 0;
1698 childobject.classId = RelationRelationId;
1699 childobject.objectId = relationId;
1700 childobject.objectSubId = 0;
1702 recordDependencyOn(&childobject, &parentobject, DEPENDENCY_NORMAL);
1705 * Mark the parent as having subclasses.
1707 setRelhassubclassInRelation(parentOid, true);
1711 * Look for an existing schema entry with the given name.
1713 * Returns the index (starting with 1) if attribute already exists in schema,
1717 findAttrByName(const char *attributeName, List *schema)
1724 ColumnDef *def = lfirst(s);
1726 if (strcmp(attributeName, def->colname) == 0)
1735 * Update a relation's pg_class.relhassubclass entry to the given value
1738 setRelhassubclassInRelation(Oid relationId, bool relhassubclass)
1740 Relation relationRelation;
1742 Form_pg_class classtuple;
1745 * Fetch a modifiable copy of the tuple, modify it, update pg_class.
1747 * If the tuple already has the right relhassubclass setting, we don't
1748 * need to update it, but we still need to issue an SI inval message.
1750 relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
1751 tuple = SearchSysCacheCopy(RELOID,
1752 ObjectIdGetDatum(relationId),
1754 if (!HeapTupleIsValid(tuple))
1755 elog(ERROR, "cache lookup failed for relation %u", relationId);
1756 classtuple = (Form_pg_class) GETSTRUCT(tuple);
1758 if (classtuple->relhassubclass != relhassubclass)
1760 classtuple->relhassubclass = relhassubclass;
1761 simple_heap_update(relationRelation, &tuple->t_self, tuple);
1763 /* keep the catalog indexes up to date */
1764 CatalogUpdateIndexes(relationRelation, tuple);
1768 /* no need to change tuple, but force relcache rebuild anyway */
1769 CacheInvalidateRelcacheByTuple(tuple);
1772 heap_freetuple(tuple);
1773 heap_close(relationRelation, RowExclusiveLock);
1778 * renameatt - changes the name of a attribute in a relation
1780 * Attname attribute is changed in attribute catalog.
1781 * No record of the previous attname is kept (correct?).
1783 * get proper relrelation from relation catalog (if not arg)
1784 * scan attribute catalog
1785 * for name conflict (within rel)
1786 * for original attribute (if not arg)
1787 * modify attname in attribute tuple
1788 * insert modified attribute in attribute catalog
1789 * delete original attribute from attribute catalog
1792 renameatt(Oid myrelid,
1793 const char *oldattname,
1794 const char *newattname,
1798 Relation targetrelation;
1799 Relation attrelation;
1801 Form_pg_attribute attform;
1804 ListCell *indexoidscan;
1807 * Grab an exclusive lock on the target table, which we will NOT release
1808 * until end of transaction.
1810 targetrelation = relation_open(myrelid, AccessExclusiveLock);
1813 * permissions checking. this would normally be done in utility.c, but
1814 * this particular routine is recursive.
1816 * normally, only the owner of a class can change its schema.
1818 if (!pg_class_ownercheck(myrelid, GetUserId()))
1819 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1820 RelationGetRelationName(targetrelation));
1821 if (!allowSystemTableMods && IsSystemRelation(targetrelation))
1823 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1824 errmsg("permission denied: \"%s\" is a system catalog",
1825 RelationGetRelationName(targetrelation))));
1828 * if the 'recurse' flag is set then we are supposed to rename this
1829 * attribute in all classes that inherit from 'relname' (as well as in
1832 * any permissions or problems with duplicate attributes will cause the
1833 * whole transaction to abort, which is what we want -- all or nothing.
1840 /* this routine is actually in the planner */
1841 children = find_all_inheritors(myrelid);
1844 * find_all_inheritors does the recursive search of the inheritance
1845 * hierarchy, so all we have to do is process all of the relids in the
1846 * list that it returns.
1848 foreach(child, children)
1850 Oid childrelid = lfirst_oid(child);
1852 if (childrelid == myrelid)
1854 /* note we need not recurse again */
1855 renameatt(childrelid, oldattname, newattname, false, true);
1861 * If we are told not to recurse, there had better not be any child
1862 * tables; else the rename would put them out of step.
1865 find_inheritance_children(myrelid) != NIL)
1867 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1868 errmsg("inherited column \"%s\" must be renamed in child tables too",
1872 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
1874 atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
1875 if (!HeapTupleIsValid(atttup))
1877 (errcode(ERRCODE_UNDEFINED_COLUMN),
1878 errmsg("column \"%s\" does not exist",
1880 attform = (Form_pg_attribute) GETSTRUCT(atttup);
1882 attnum = attform->attnum;
1885 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1886 errmsg("cannot rename system column \"%s\"",
1890 * if the attribute is inherited, forbid the renaming, unless we are
1891 * already inside a recursive rename.
1893 if (attform->attinhcount > 0 && !recursing)
1895 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1896 errmsg("cannot rename inherited column \"%s\"",
1899 /* should not already exist */
1900 /* this test is deliberately not attisdropped-aware */
1901 if (SearchSysCacheExists(ATTNAME,
1902 ObjectIdGetDatum(myrelid),
1903 PointerGetDatum(newattname),
1906 (errcode(ERRCODE_DUPLICATE_COLUMN),
1907 errmsg("column \"%s\" of relation \"%s\" already exists",
1908 newattname, RelationGetRelationName(targetrelation))));
1910 namestrcpy(&(attform->attname), newattname);
1912 simple_heap_update(attrelation, &atttup->t_self, atttup);
1914 /* keep system catalog indexes current */
1915 CatalogUpdateIndexes(attrelation, atttup);
1917 heap_freetuple(atttup);
1920 * Update column names of indexes that refer to the column being renamed.
1922 indexoidlist = RelationGetIndexList(targetrelation);
1924 foreach(indexoidscan, indexoidlist)
1926 Oid indexoid = lfirst_oid(indexoidscan);
1928 Form_pg_index indexform;
1932 * Scan through index columns to see if there's any simple index
1933 * entries for this attribute. We ignore expressional entries.
1935 indextup = SearchSysCache(INDEXRELID,
1936 ObjectIdGetDatum(indexoid),
1938 if (!HeapTupleIsValid(indextup))
1939 elog(ERROR, "cache lookup failed for index %u", indexoid);
1940 indexform = (Form_pg_index) GETSTRUCT(indextup);
1942 for (i = 0; i < indexform->indnatts; i++)
1944 if (attnum != indexform->indkey.values[i])
1948 * Found one, rename it.
1950 atttup = SearchSysCacheCopy(ATTNUM,
1951 ObjectIdGetDatum(indexoid),
1952 Int16GetDatum(i + 1),
1954 if (!HeapTupleIsValid(atttup))
1955 continue; /* should we raise an error? */
1958 * Update the (copied) attribute tuple.
1960 namestrcpy(&(((Form_pg_attribute) GETSTRUCT(atttup))->attname),
1963 simple_heap_update(attrelation, &atttup->t_self, atttup);
1965 /* keep system catalog indexes current */
1966 CatalogUpdateIndexes(attrelation, atttup);
1968 heap_freetuple(atttup);
1971 ReleaseSysCache(indextup);
1974 list_free(indexoidlist);
1976 heap_close(attrelation, RowExclusiveLock);
1978 relation_close(targetrelation, NoLock); /* close rel but keep lock */
1983 * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW RENAME
1985 * Caller has already done permissions checks.
1988 RenameRelation(Oid myrelid, const char *newrelname, ObjectType reltype)
1990 Relation targetrelation;
1995 * Grab an exclusive lock on the target table, index, sequence or view,
1996 * which we will NOT release until end of transaction.
1998 targetrelation = relation_open(myrelid, AccessExclusiveLock);
2000 namespaceId = RelationGetNamespace(targetrelation);
2001 relkind = targetrelation->rd_rel->relkind;
2004 * For compatibility with prior releases, we don't complain if ALTER TABLE
2005 * or ALTER INDEX is used to rename a sequence or view.
2007 if (reltype == OBJECT_SEQUENCE && relkind != RELKIND_SEQUENCE)
2009 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2010 errmsg("\"%s\" is not a sequence",
2011 RelationGetRelationName(targetrelation))));
2013 if (reltype == OBJECT_VIEW && relkind != RELKIND_VIEW)
2015 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2016 errmsg("\"%s\" is not a view",
2017 RelationGetRelationName(targetrelation))));
2020 * Don't allow ALTER TABLE on composite types.
2021 * We want people to use ALTER TYPE for that.
2023 if (relkind == RELKIND_COMPOSITE_TYPE)
2025 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2026 errmsg("\"%s\" is a composite type",
2027 RelationGetRelationName(targetrelation)),
2028 errhint("Use ALTER TYPE instead.")));
2031 RenameRelationInternal(myrelid, newrelname, namespaceId);
2034 * Close rel, but keep exclusive lock!
2036 relation_close(targetrelation, NoLock);
2040 * RenameRelationInternal - change the name of a relation
2042 * XXX - When renaming sequences, we don't bother to modify the
2043 * sequence name that is stored within the sequence itself
2044 * (this would cause problems with MVCC). In the future,
2045 * the sequence name should probably be removed from the
2046 * sequence, AFAIK there's no need for it to be there.
2049 RenameRelationInternal(Oid myrelid, const char *newrelname, Oid namespaceId)
2051 Relation targetrelation;
2052 Relation relrelation; /* for RELATION relation */
2054 Form_pg_class relform;
2057 * Grab an exclusive lock on the target table, index, sequence or
2058 * view, which we will NOT release until end of transaction.
2060 targetrelation = relation_open(myrelid, AccessExclusiveLock);
2063 * Find relation's pg_class tuple, and make sure newrelname isn't in use.
2065 relrelation = heap_open(RelationRelationId, RowExclusiveLock);
2067 reltup = SearchSysCacheCopy(RELOID,
2068 ObjectIdGetDatum(myrelid),
2070 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
2071 elog(ERROR, "cache lookup failed for relation %u", myrelid);
2072 relform = (Form_pg_class) GETSTRUCT(reltup);
2074 if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
2076 (errcode(ERRCODE_DUPLICATE_TABLE),
2077 errmsg("relation \"%s\" already exists",
2081 * Update pg_class tuple with new relname. (Scribbling on reltup is OK
2082 * because it's a copy...)
2084 namestrcpy(&(relform->relname), newrelname);
2086 simple_heap_update(relrelation, &reltup->t_self, reltup);
2088 /* keep the system catalog indexes current */
2089 CatalogUpdateIndexes(relrelation, reltup);
2091 heap_freetuple(reltup);
2092 heap_close(relrelation, RowExclusiveLock);
2095 * Also rename the associated type, if any.
2097 if (OidIsValid(targetrelation->rd_rel->reltype))
2098 RenameTypeInternal(targetrelation->rd_rel->reltype,
2099 newrelname, namespaceId);
2102 * Also rename the associated constraint, if any.
2104 if (targetrelation->rd_rel->relkind == RELKIND_INDEX)
2106 Oid constraintId = get_index_constraint(myrelid);
2108 if (OidIsValid(constraintId))
2109 RenameConstraintById(constraintId, newrelname);
2113 * Close rel, but keep exclusive lock!
2115 relation_close(targetrelation, NoLock);
2119 * Disallow ALTER TABLE (and similar commands) when the current backend has
2120 * any open reference to the target table besides the one just acquired by
2121 * the calling command; this implies there's an open cursor or active plan.
2122 * We need this check because our AccessExclusiveLock doesn't protect us
2123 * against stomping on our own foot, only other people's feet!
2125 * For ALTER TABLE, the only case known to cause serious trouble is ALTER
2126 * COLUMN TYPE, and some changes are obviously pretty benign, so this could
2127 * possibly be relaxed to only error out for certain types of alterations.
2128 * But the use-case for allowing any of these things is not obvious, so we
2129 * won't work hard at it for now.
2131 * We also reject these commands if there are any pending AFTER trigger events
2132 * for the rel. This is certainly necessary for the rewriting variants of
2133 * ALTER TABLE, because they don't preserve tuple TIDs and so the pending
2134 * events would try to fetch the wrong tuples. It might be overly cautious
2135 * in other cases, but again it seems better to err on the side of paranoia.
2137 * REINDEX calls this with "rel" referencing the index to be rebuilt; here
2138 * we are worried about active indexscans on the index. The trigger-event
2139 * check can be skipped, since we are doing no damage to the parent table.
2141 * The statement name (eg, "ALTER TABLE") is passed for use in error messages.
2144 CheckTableNotInUse(Relation rel, const char *stmt)
2146 int expected_refcnt;
2148 expected_refcnt = rel->rd_isnailed ? 2 : 1;
2149 if (rel->rd_refcnt != expected_refcnt)
2151 (errcode(ERRCODE_OBJECT_IN_USE),
2152 /* translator: first %s is a SQL command, eg ALTER TABLE */
2153 errmsg("cannot %s \"%s\" because "
2154 "it is being used by active queries in this session",
2155 stmt, RelationGetRelationName(rel))));
2157 if (rel->rd_rel->relkind != RELKIND_INDEX &&
2158 AfterTriggerPendingOnRel(RelationGetRelid(rel)))
2160 (errcode(ERRCODE_OBJECT_IN_USE),
2161 /* translator: first %s is a SQL command, eg ALTER TABLE */
2162 errmsg("cannot %s \"%s\" because "
2163 "it has pending trigger events",
2164 stmt, RelationGetRelationName(rel))));
2169 * Execute ALTER TABLE, which can be a list of subcommands
2171 * ALTER TABLE is performed in three phases:
2172 * 1. Examine subcommands and perform pre-transformation checking.
2173 * 2. Update system catalogs.
2174 * 3. Scan table(s) to check new constraints, and optionally recopy
2175 * the data into new table(s).
2176 * Phase 3 is not performed unless one or more of the subcommands requires
2177 * it. The intention of this design is to allow multiple independent
2178 * updates of the table schema to be performed with only one pass over the
2181 * ATPrepCmd performs phase 1. A "work queue" entry is created for
2182 * each table to be affected (there may be multiple affected tables if the
2183 * commands traverse a table inheritance hierarchy). Also we do preliminary
2184 * validation of the subcommands, including parse transformation of those
2185 * expressions that need to be evaluated with respect to the old table
2188 * ATRewriteCatalogs performs phase 2 for each affected table. (Note that
2189 * phases 2 and 3 normally do no explicit recursion, since phase 1 already
2190 * did it --- although some subcommands have to recurse in phase 2 instead.)
2191 * Certain subcommands need to be performed before others to avoid
2192 * unnecessary conflicts; for example, DROP COLUMN should come before
2193 * ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
2194 * lists, one for each logical "pass" of phase 2.
2196 * ATRewriteTables performs phase 3 for those tables that need it.
2198 * Thanks to the magic of MVCC, an error anywhere along the way rolls back
2199 * the whole operation; we don't have to do anything special to clean up.
2202 AlterTable(AlterTableStmt *stmt)
2204 Relation rel = relation_openrv(stmt->relation, AccessExclusiveLock);
2206 CheckTableNotInUse(rel, "ALTER TABLE");
2208 /* Check relation type against type specified in the ALTER command */
2209 switch (stmt->relkind)
2213 * For mostly-historical reasons, we allow ALTER TABLE to apply
2214 * to all relation types.
2219 if (rel->rd_rel->relkind != RELKIND_INDEX)
2221 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2222 errmsg("\"%s\" is not an index",
2223 RelationGetRelationName(rel))));
2226 case OBJECT_SEQUENCE:
2227 if (rel->rd_rel->relkind != RELKIND_SEQUENCE)
2229 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2230 errmsg("\"%s\" is not a sequence",
2231 RelationGetRelationName(rel))));
2235 if (rel->rd_rel->relkind != RELKIND_VIEW)
2237 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2238 errmsg("\"%s\" is not a view",
2239 RelationGetRelationName(rel))));
2243 elog(ERROR, "unrecognized object type: %d", (int) stmt->relkind);
2246 ATController(rel, stmt->cmds, interpretInhOption(stmt->relation->inhOpt));
2250 * AlterTableInternal
2252 * ALTER TABLE with target specified by OID
2254 * We do not reject if the relation is already open, because it's quite
2255 * likely that one or more layers of caller have it open. That means it
2256 * is unsafe to use this entry point for alterations that could break
2257 * existing query plans. On the assumption it's not used for such, we
2258 * don't have to reject pending AFTER triggers, either.
2261 AlterTableInternal(Oid relid, List *cmds, bool recurse)
2263 Relation rel = relation_open(relid, AccessExclusiveLock);
2265 ATController(rel, cmds, recurse);
2269 ATController(Relation rel, List *cmds, bool recurse)
2274 /* Phase 1: preliminary examination of commands, create work queue */
2277 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2279 ATPrepCmd(&wqueue, rel, cmd, recurse, false);
2282 /* Close the relation, but keep lock until commit */
2283 relation_close(rel, NoLock);
2285 /* Phase 2: update system catalogs */
2286 ATRewriteCatalogs(&wqueue);
2288 /* Phase 3: scan/rewrite tables as needed */
2289 ATRewriteTables(&wqueue);
2295 * Traffic cop for ALTER TABLE Phase 1 operations, including simple
2296 * recursion and permission checks.
2298 * Caller must have acquired AccessExclusiveLock on relation already.
2299 * This lock should be held until commit.
2302 ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
2303 bool recurse, bool recursing)
2305 AlteredTableInfo *tab;
2308 /* Find or create work queue entry for this table */
2309 tab = ATGetQueueEntry(wqueue, rel);
2312 * Copy the original subcommand for each table. This avoids conflicts
2313 * when different child tables need to make different parse
2314 * transformations (for example, the same column may have different column
2315 * numbers in different children).
2317 cmd = copyObject(cmd);
2320 * Do permissions checking, recursion to child tables if needed, and any
2321 * additional phase-1 processing needed.
2323 switch (cmd->subtype)
2325 case AT_AddColumn: /* ADD COLUMN */
2326 ATSimplePermissions(rel, false);
2327 /* Performs own recursion */
2328 ATPrepAddColumn(wqueue, rel, recurse, cmd);
2329 pass = AT_PASS_ADD_COL;
2331 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
2334 * We allow defaults on views so that INSERT into a view can have
2335 * default-ish behavior. This works because the rewriter
2336 * substitutes default values into INSERTs before it expands
2339 ATSimplePermissions(rel, true);
2340 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2341 /* No command-specific prep needed */
2342 pass = cmd->def ? AT_PASS_ADD_CONSTR : AT_PASS_DROP;
2344 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
2345 ATSimplePermissions(rel, false);
2346 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2347 /* No command-specific prep needed */
2348 pass = AT_PASS_DROP;
2350 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
2351 ATSimplePermissions(rel, false);
2352 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2353 /* No command-specific prep needed */
2354 pass = AT_PASS_ADD_CONSTR;
2356 case AT_SetStatistics: /* ALTER COLUMN STATISTICS */
2357 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2358 /* Performs own permission checks */
2359 ATPrepSetStatistics(rel, cmd->name, cmd->def);
2360 pass = AT_PASS_COL_ATTRS;
2362 case AT_SetStorage: /* ALTER COLUMN STORAGE */
2363 ATSimplePermissions(rel, false);
2364 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2365 /* No command-specific prep needed */
2366 pass = AT_PASS_COL_ATTRS;
2368 case AT_DropColumn: /* DROP COLUMN */
2369 ATSimplePermissions(rel, false);
2370 /* Recursion occurs during execution phase */
2371 /* No command-specific prep needed except saving recurse flag */
2373 cmd->subtype = AT_DropColumnRecurse;
2374 pass = AT_PASS_DROP;
2376 case AT_AddIndex: /* ADD INDEX */
2377 ATSimplePermissions(rel, false);
2378 /* This command never recurses */
2379 /* No command-specific prep needed */
2380 pass = AT_PASS_ADD_INDEX;
2382 case AT_AddConstraint: /* ADD CONSTRAINT */
2383 ATSimplePermissions(rel, false);
2384 /* Recursion occurs during execution phase */
2385 /* No command-specific prep needed except saving recurse flag */
2387 cmd->subtype = AT_AddConstraintRecurse;
2388 pass = AT_PASS_ADD_CONSTR;
2390 case AT_DropConstraint: /* DROP CONSTRAINT */
2391 ATSimplePermissions(rel, false);
2392 /* Recursion occurs during execution phase */
2393 /* No command-specific prep needed except saving recurse flag */
2395 cmd->subtype = AT_DropConstraintRecurse;
2396 pass = AT_PASS_DROP;
2398 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
2399 ATSimplePermissions(rel, false);
2400 /* Performs own recursion */
2401 ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd);
2402 pass = AT_PASS_ALTER_TYPE;
2404 case AT_ChangeOwner: /* ALTER OWNER */
2405 /* This command never recurses */
2406 /* No command-specific prep needed */
2407 pass = AT_PASS_MISC;
2409 case AT_ClusterOn: /* CLUSTER ON */
2410 case AT_DropCluster: /* SET WITHOUT CLUSTER */
2411 ATSimplePermissions(rel, false);
2412 /* These commands never recurse */
2413 /* No command-specific prep needed */
2414 pass = AT_PASS_MISC;
2416 case AT_DropOids: /* SET WITHOUT OIDS */
2417 ATSimplePermissions(rel, false);
2418 /* Performs own recursion */
2419 if (rel->rd_rel->relhasoids)
2421 AlterTableCmd *dropCmd = makeNode(AlterTableCmd);
2423 dropCmd->subtype = AT_DropColumn;
2424 dropCmd->name = pstrdup("oid");
2425 dropCmd->behavior = cmd->behavior;
2426 ATPrepCmd(wqueue, rel, dropCmd, recurse, false);
2428 pass = AT_PASS_DROP;
2430 case AT_SetTableSpace: /* SET TABLESPACE */
2431 ATSimplePermissionsRelationOrIndex(rel);
2432 /* This command never recurses */
2433 ATPrepSetTableSpace(tab, rel, cmd->name);
2434 pass = AT_PASS_MISC; /* doesn't actually matter */
2436 case AT_SetRelOptions: /* SET (...) */
2437 case AT_ResetRelOptions: /* RESET (...) */
2438 ATSimplePermissionsRelationOrIndex(rel);
2439 /* This command never recurses */
2440 /* No command-specific prep needed */
2441 pass = AT_PASS_MISC;
2443 case AT_EnableTrig: /* ENABLE TRIGGER variants */
2444 case AT_EnableAlwaysTrig:
2445 case AT_EnableReplicaTrig:
2446 case AT_EnableTrigAll:
2447 case AT_EnableTrigUser:
2448 case AT_DisableTrig: /* DISABLE TRIGGER variants */
2449 case AT_DisableTrigAll:
2450 case AT_DisableTrigUser:
2451 case AT_EnableRule: /* ENABLE/DISABLE RULE variants */
2452 case AT_EnableAlwaysRule:
2453 case AT_EnableReplicaRule:
2454 case AT_DisableRule:
2455 case AT_AddInherit: /* INHERIT / NO INHERIT */
2456 case AT_DropInherit:
2457 ATSimplePermissions(rel, false);
2458 /* These commands never recurse */
2459 /* No command-specific prep needed */
2460 pass = AT_PASS_MISC;
2463 elog(ERROR, "unrecognized alter table type: %d",
2464 (int) cmd->subtype);
2465 pass = 0; /* keep compiler quiet */
2469 /* Add the subcommand to the appropriate list for phase 2 */
2470 tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
2476 * Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
2477 * dispatched in a "safe" execution order (designed to avoid unnecessary
2481 ATRewriteCatalogs(List **wqueue)
2487 * We process all the tables "in parallel", one pass at a time. This is
2488 * needed because we may have to propagate work from one table to another
2489 * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
2490 * re-adding of the foreign key constraint to the other table). Work can
2491 * only be propagated into later passes, however.
2493 for (pass = 0; pass < AT_NUM_PASSES; pass++)
2495 /* Go through each table that needs to be processed */
2496 foreach(ltab, *wqueue)
2498 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2499 List *subcmds = tab->subcmds[pass];
2507 * Exclusive lock was obtained by phase 1, needn't get it again
2509 rel = relation_open(tab->relid, NoLock);
2511 foreach(lcmd, subcmds)
2512 ATExecCmd(wqueue, tab, rel, (AlterTableCmd *) lfirst(lcmd));
2515 * After the ALTER TYPE pass, do cleanup work (this is not done in
2516 * ATExecAlterColumnType since it should be done only once if
2517 * multiple columns of a table are altered).
2519 if (pass == AT_PASS_ALTER_TYPE)
2520 ATPostAlterTypeCleanup(wqueue, tab);
2522 relation_close(rel, NoLock);
2527 * Check to see if a toast table must be added, if we executed any
2528 * subcommands that might have added a column or changed column storage.
2530 foreach(ltab, *wqueue)
2532 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2534 if (tab->relkind == RELKIND_RELATION &&
2535 (tab->subcmds[AT_PASS_ADD_COL] ||
2536 tab->subcmds[AT_PASS_ALTER_TYPE] ||
2537 tab->subcmds[AT_PASS_COL_ATTRS]))
2538 AlterTableCreateToastTable(tab->relid);
2543 * ATExecCmd: dispatch a subcommand to appropriate execution routine
2546 ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
2549 switch (cmd->subtype)
2551 case AT_AddColumn: /* ADD COLUMN */
2552 ATExecAddColumn(tab, rel, (ColumnDef *) cmd->def);
2554 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
2555 ATExecColumnDefault(rel, cmd->name, cmd->def);
2557 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
2558 ATExecDropNotNull(rel, cmd->name);
2560 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
2561 ATExecSetNotNull(tab, rel, cmd->name);
2563 case AT_SetStatistics: /* ALTER COLUMN STATISTICS */
2564 ATExecSetStatistics(rel, cmd->name, cmd->def);
2566 case AT_SetStorage: /* ALTER COLUMN STORAGE */
2567 ATExecSetStorage(rel, cmd->name, cmd->def);
2569 case AT_DropColumn: /* DROP COLUMN */
2570 ATExecDropColumn(rel, cmd->name, cmd->behavior, false, false);
2572 case AT_DropColumnRecurse: /* DROP COLUMN with recursion */
2573 ATExecDropColumn(rel, cmd->name, cmd->behavior, true, false);
2575 case AT_AddIndex: /* ADD INDEX */
2576 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false);
2578 case AT_ReAddIndex: /* ADD INDEX */
2579 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true);
2581 case AT_AddConstraint: /* ADD CONSTRAINT */
2582 ATExecAddConstraint(wqueue, tab, rel, cmd->def, false);
2584 case AT_AddConstraintRecurse: /* ADD CONSTRAINT with recursion */
2585 ATExecAddConstraint(wqueue, tab, rel, cmd->def, true);
2587 case AT_DropConstraint: /* DROP CONSTRAINT */
2588 ATExecDropConstraint(rel, cmd->name, cmd->behavior, false, false);
2590 case AT_DropConstraintRecurse: /* DROP CONSTRAINT with recursion */
2591 ATExecDropConstraint(rel, cmd->name, cmd->behavior, true, false);
2593 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
2594 ATExecAlterColumnType(tab, rel, cmd->name, (TypeName *) cmd->def);
2596 case AT_ChangeOwner: /* ALTER OWNER */
2597 ATExecChangeOwner(RelationGetRelid(rel),
2598 get_roleid_checked(cmd->name),
2601 case AT_ClusterOn: /* CLUSTER ON */
2602 ATExecClusterOn(rel, cmd->name);
2604 case AT_DropCluster: /* SET WITHOUT CLUSTER */
2605 ATExecDropCluster(rel);
2607 case AT_DropOids: /* SET WITHOUT OIDS */
2610 * Nothing to do here; we'll have generated a DropColumn
2611 * subcommand to do the real work
2614 case AT_SetTableSpace: /* SET TABLESPACE */
2617 * Nothing to do here; Phase 3 does the work
2620 case AT_SetRelOptions: /* SET (...) */
2621 ATExecSetRelOptions(rel, (List *) cmd->def, false);
2623 case AT_ResetRelOptions: /* RESET (...) */
2624 ATExecSetRelOptions(rel, (List *) cmd->def, true);
2627 case AT_EnableTrig: /* ENABLE TRIGGER name */
2628 ATExecEnableDisableTrigger(rel, cmd->name,
2629 TRIGGER_FIRES_ON_ORIGIN, false);
2631 case AT_EnableAlwaysTrig: /* ENABLE ALWAYS TRIGGER name */
2632 ATExecEnableDisableTrigger(rel, cmd->name,
2633 TRIGGER_FIRES_ALWAYS, false);
2635 case AT_EnableReplicaTrig: /* ENABLE REPLICA TRIGGER name */
2636 ATExecEnableDisableTrigger(rel, cmd->name,
2637 TRIGGER_FIRES_ON_REPLICA, false);
2639 case AT_DisableTrig: /* DISABLE TRIGGER name */
2640 ATExecEnableDisableTrigger(rel, cmd->name,
2641 TRIGGER_DISABLED, false);
2643 case AT_EnableTrigAll: /* ENABLE TRIGGER ALL */
2644 ATExecEnableDisableTrigger(rel, NULL,
2645 TRIGGER_FIRES_ON_ORIGIN, false);
2647 case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
2648 ATExecEnableDisableTrigger(rel, NULL,
2649 TRIGGER_DISABLED, false);
2651 case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
2652 ATExecEnableDisableTrigger(rel, NULL,
2653 TRIGGER_FIRES_ON_ORIGIN, true);
2655 case AT_DisableTrigUser: /* DISABLE TRIGGER USER */
2656 ATExecEnableDisableTrigger(rel, NULL,
2657 TRIGGER_DISABLED, true);
2660 case AT_EnableRule: /* ENABLE RULE name */
2661 ATExecEnableDisableRule(rel, cmd->name,
2662 RULE_FIRES_ON_ORIGIN);
2664 case AT_EnableAlwaysRule: /* ENABLE ALWAYS RULE name */
2665 ATExecEnableDisableRule(rel, cmd->name,
2668 case AT_EnableReplicaRule: /* ENABLE REPLICA RULE name */
2669 ATExecEnableDisableRule(rel, cmd->name,
2670 RULE_FIRES_ON_REPLICA);
2672 case AT_DisableRule: /* DISABLE RULE name */
2673 ATExecEnableDisableRule(rel, cmd->name,
2678 ATExecAddInherit(rel, (RangeVar *) cmd->def);
2680 case AT_DropInherit:
2681 ATExecDropInherit(rel, (RangeVar *) cmd->def);
2684 elog(ERROR, "unrecognized alter table type: %d",
2685 (int) cmd->subtype);
2690 * Bump the command counter to ensure the next subcommand in the sequence
2691 * can see the changes so far
2693 CommandCounterIncrement();
2697 * ATRewriteTables: ALTER TABLE phase 3
2700 ATRewriteTables(List **wqueue)
2704 /* Go through each table that needs to be checked or rewritten */
2705 foreach(ltab, *wqueue)
2707 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2710 * We only need to rewrite the table if at least one column needs to
2713 if (tab->newvals != NIL)
2715 /* Build a temporary relation and copy data */
2717 char NewHeapName[NAMEDATALEN];
2720 ObjectAddress object;
2722 OldHeap = heap_open(tab->relid, NoLock);
2725 * We can never allow rewriting of shared or nailed-in-cache
2726 * relations, because we can't support changing their relfilenode
2729 if (OldHeap->rd_rel->relisshared || OldHeap->rd_isnailed)
2731 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2732 errmsg("cannot rewrite system relation \"%s\"",
2733 RelationGetRelationName(OldHeap))));
2736 * Don't allow rewrite on temp tables of other backends ... their
2737 * local buffer manager is not going to cope.
2739 if (isOtherTempNamespace(RelationGetNamespace(OldHeap)))
2741 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2742 errmsg("cannot rewrite temporary tables of other sessions")));
2745 * Select destination tablespace (same as original unless user
2746 * requested a change)
2748 if (tab->newTableSpace)
2749 NewTableSpace = tab->newTableSpace;
2751 NewTableSpace = OldHeap->rd_rel->reltablespace;
2753 heap_close(OldHeap, NoLock);
2756 * Create the new heap, using a temporary name in the same
2757 * namespace as the existing table. NOTE: there is some risk of
2758 * collision with user relnames. Working around this seems more
2759 * trouble than it's worth; in particular, we can't create the new
2760 * heap in a different namespace from the old, or we will have
2761 * problems with the TEMP status of temp tables.
2763 snprintf(NewHeapName, sizeof(NewHeapName),
2764 "pg_temp_%u", tab->relid);
2766 OIDNewHeap = make_new_heap(tab->relid, NewHeapName, NewTableSpace);
2769 * Copy the heap data into the new table with the desired
2770 * modifications, and test the current data within the table
2771 * against new constraints generated by ALTER TABLE commands.
2773 ATRewriteTable(tab, OIDNewHeap);
2776 * Swap the physical files of the old and new heaps. Since we are
2777 * generating a new heap, we can use RecentXmin for the table's
2778 * new relfrozenxid because we rewrote all the tuples on
2779 * ATRewriteTable, so no older Xid remains on the table.
2781 swap_relation_files(tab->relid, OIDNewHeap, RecentXmin);
2783 CommandCounterIncrement();
2785 /* Destroy new heap with old filenode */
2786 object.classId = RelationRelationId;
2787 object.objectId = OIDNewHeap;
2788 object.objectSubId = 0;
2791 * The new relation is local to our transaction and we know
2792 * nothing depends on it, so DROP_RESTRICT should be OK.
2794 performDeletion(&object, DROP_RESTRICT);
2795 /* performDeletion does CommandCounterIncrement at end */
2798 * Rebuild each index on the relation (but not the toast table,
2799 * which is all-new anyway). We do not need
2800 * CommandCounterIncrement() because reindex_relation does it.
2802 reindex_relation(tab->relid, false);
2807 * Test the current data within the table against new constraints
2808 * generated by ALTER TABLE commands, but don't rebuild data.
2810 if (tab->constraints != NIL || tab->new_notnull)
2811 ATRewriteTable(tab, InvalidOid);
2814 * If we had SET TABLESPACE but no reason to reconstruct tuples,
2815 * just do a block-by-block copy.
2817 if (tab->newTableSpace)
2818 ATExecSetTableSpace(tab->relid, tab->newTableSpace);
2823 * Foreign key constraints are checked in a final pass, since (a) it's
2824 * generally best to examine each one separately, and (b) it's at least
2825 * theoretically possible that we have changed both relations of the
2826 * foreign key, and we'd better have finished both rewrites before we try
2827 * to read the tables.
2829 foreach(ltab, *wqueue)
2831 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2832 Relation rel = NULL;
2835 foreach(lcon, tab->constraints)
2837 NewConstraint *con = lfirst(lcon);
2839 if (con->contype == CONSTR_FOREIGN)
2841 FkConstraint *fkconstraint = (FkConstraint *) con->qual;
2846 /* Long since locked, no need for another */
2847 rel = heap_open(tab->relid, NoLock);
2850 refrel = heap_open(con->refrelid, RowShareLock);
2852 validateForeignKeyConstraint(fkconstraint, rel, refrel,
2855 heap_close(refrel, NoLock);
2860 heap_close(rel, NoLock);
2865 * ATRewriteTable: scan or rewrite one table
2867 * OIDNewHeap is InvalidOid if we don't need to rewrite
2870 ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap)
2874 TupleDesc oldTupDesc;
2875 TupleDesc newTupDesc;
2876 bool needscan = false;
2877 List *notnull_attrs;
2883 * Open the relation(s). We have surely already locked the existing
2886 oldrel = heap_open(tab->relid, NoLock);
2887 oldTupDesc = tab->oldDesc;
2888 newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
2890 if (OidIsValid(OIDNewHeap))
2891 newrel = heap_open(OIDNewHeap, AccessExclusiveLock);
2896 * If we need to rewrite the table, the operation has to be propagated to
2897 * tables that use this table's rowtype as a column type.
2899 * (Eventually this will probably become true for scans as well, but at
2900 * the moment a composite type does not enforce any constraints, so it's
2901 * not necessary/appropriate to enforce them just during ALTER.)
2904 find_composite_type_dependencies(oldrel->rd_rel->reltype,
2905 RelationGetRelationName(oldrel),
2909 * Generate the constraint and default execution states
2912 estate = CreateExecutorState();
2914 /* Build the needed expression execution states */
2915 foreach(l, tab->constraints)
2917 NewConstraint *con = lfirst(l);
2919 switch (con->contype)
2923 con->qualstate = (List *)
2924 ExecPrepareExpr((Expr *) con->qual, estate);
2926 case CONSTR_FOREIGN:
2927 /* Nothing to do here */
2930 elog(ERROR, "unrecognized constraint type: %d",
2931 (int) con->contype);
2935 foreach(l, tab->newvals)
2937 NewColumnValue *ex = lfirst(l);
2941 ex->exprstate = ExecPrepareExpr((Expr *) ex->expr, estate);
2944 notnull_attrs = NIL;
2945 if (newrel || tab->new_notnull)
2948 * If we are rebuilding the tuples OR if we added any new NOT NULL
2949 * constraints, check all not-null constraints. This is a bit of
2950 * overkill but it minimizes risk of bugs, and heap_attisnull is a
2951 * pretty cheap test anyway.
2953 for (i = 0; i < newTupDesc->natts; i++)
2955 if (newTupDesc->attrs[i]->attnotnull &&
2956 !newTupDesc->attrs[i]->attisdropped)
2957 notnull_attrs = lappend_int(notnull_attrs, i);
2965 ExprContext *econtext;
2968 TupleTableSlot *oldslot;
2969 TupleTableSlot *newslot;
2972 MemoryContext oldCxt;
2973 List *dropped_attrs = NIL;
2976 econtext = GetPerTupleExprContext(estate);
2979 * Make tuple slots for old and new tuples. Note that even when the
2980 * tuples are the same, the tupDescs might not be (consider ADD COLUMN
2981 * without a default).
2983 oldslot = MakeSingleTupleTableSlot(oldTupDesc);
2984 newslot = MakeSingleTupleTableSlot(newTupDesc);
2986 /* Preallocate values/isnull arrays */
2987 i = Max(newTupDesc->natts, oldTupDesc->natts);
2988 values = (Datum *) palloc(i * sizeof(Datum));
2989 isnull = (bool *) palloc(i * sizeof(bool));
2990 memset(values, 0, i * sizeof(Datum));
2991 memset(isnull, true, i * sizeof(bool));
2994 * Any attributes that are dropped according to the new tuple
2995 * descriptor can be set to NULL. We precompute the list of dropped
2996 * attributes to avoid needing to do so in the per-tuple loop.
2998 for (i = 0; i < newTupDesc->natts; i++)
3000 if (newTupDesc->attrs[i]->attisdropped)
3001 dropped_attrs = lappend_int(dropped_attrs, i);
3005 * Scan through the rows, generating a new row if needed and then
3006 * checking all the constraints.
3008 scan = heap_beginscan(oldrel, SnapshotNow, 0, NULL);
3011 * Switch to per-tuple memory context and reset it for each tuple
3012 * produced, so we don't leak memory.
3014 oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
3016 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
3020 Oid tupOid = InvalidOid;
3022 /* Extract data from old tuple */
3023 heap_deform_tuple(tuple, oldTupDesc, values, isnull);
3024 if (oldTupDesc->tdhasoid)
3025 tupOid = HeapTupleGetOid(tuple);
3027 /* Set dropped attributes to null in new tuple */
3028 foreach(lc, dropped_attrs)
3029 isnull[lfirst_int(lc)] = true;
3032 * Process supplied expressions to replace selected columns.
3033 * Expression inputs come from the old tuple.
3035 ExecStoreTuple(tuple, oldslot, InvalidBuffer, false);
3036 econtext->ecxt_scantuple = oldslot;
3038 foreach(l, tab->newvals)
3040 NewColumnValue *ex = lfirst(l);
3042 values[ex->attnum - 1] = ExecEvalExpr(ex->exprstate,
3044 &isnull[ex->attnum - 1],
3049 * Form the new tuple. Note that we don't explicitly pfree it,
3050 * since the per-tuple memory context will be reset shortly.
3052 tuple = heap_form_tuple(newTupDesc, values, isnull);
3054 /* Preserve OID, if any */
3055 if (newTupDesc->tdhasoid)
3056 HeapTupleSetOid(tuple, tupOid);
3059 /* Now check any constraints on the possibly-changed tuple */
3060 ExecStoreTuple(tuple, newslot, InvalidBuffer, false);
3061 econtext->ecxt_scantuple = newslot;
3063 foreach(l, notnull_attrs)
3065 int attn = lfirst_int(l);
3067 if (heap_attisnull(tuple, attn + 1))
3069 (errcode(ERRCODE_NOT_NULL_VIOLATION),
3070 errmsg("column \"%s\" contains null values",
3071 NameStr(newTupDesc->attrs[attn]->attname))));
3074 foreach(l, tab->constraints)
3076 NewConstraint *con = lfirst(l);
3078 switch (con->contype)
3081 if (!ExecQual(con->qualstate, econtext, true))
3083 (errcode(ERRCODE_CHECK_VIOLATION),
3084 errmsg("check constraint \"%s\" is violated by some row",
3087 case CONSTR_FOREIGN:
3088 /* Nothing to do here */
3091 elog(ERROR, "unrecognized constraint type: %d",
3092 (int) con->contype);
3096 /* Write the tuple out to the new relation */
3098 simple_heap_insert(newrel, tuple);
3100 ResetExprContext(econtext);
3102 CHECK_FOR_INTERRUPTS();
3105 MemoryContextSwitchTo(oldCxt);
3108 ExecDropSingleTupleTableSlot(oldslot);
3109 ExecDropSingleTupleTableSlot(newslot);
3112 FreeExecutorState(estate);
3114 heap_close(oldrel, NoLock);
3116 heap_close(newrel, NoLock);
3120 * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
3122 static AlteredTableInfo *
3123 ATGetQueueEntry(List **wqueue, Relation rel)
3125 Oid relid = RelationGetRelid(rel);
3126 AlteredTableInfo *tab;
3129 foreach(ltab, *wqueue)
3131 tab = (AlteredTableInfo *) lfirst(ltab);
3132 if (tab->relid == relid)
3137 * Not there, so add it. Note that we make a copy of the relation's
3138 * existing descriptor before anything interesting can happen to it.
3140 tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
3142 tab->relkind = rel->rd_rel->relkind;
3143 tab->oldDesc = CreateTupleDescCopy(RelationGetDescr(rel));
3145 *wqueue = lappend(*wqueue, tab);
3151 * ATSimplePermissions
3153 * - Ensure that it is a relation (or possibly a view)
3154 * - Ensure this user is the owner
3155 * - Ensure that it is not a system table
3158 ATSimplePermissions(Relation rel, bool allowView)
3160 if (rel->rd_rel->relkind != RELKIND_RELATION)
3164 if (rel->rd_rel->relkind != RELKIND_VIEW)
3166 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3167 errmsg("\"%s\" is not a table or view",
3168 RelationGetRelationName(rel))));
3172 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3173 errmsg("\"%s\" is not a table",
3174 RelationGetRelationName(rel))));
3177 /* Permissions checks */
3178 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3179 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3180 RelationGetRelationName(rel));
3182 if (!allowSystemTableMods && IsSystemRelation(rel))
3184 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3185 errmsg("permission denied: \"%s\" is a system catalog",
3186 RelationGetRelationName(rel))));
3190 * ATSimplePermissionsRelationOrIndex
3192 * - Ensure that it is a relation or an index
3193 * - Ensure this user is the owner
3194 * - Ensure that it is not a system table
3197 ATSimplePermissionsRelationOrIndex(Relation rel)
3199 if (rel->rd_rel->relkind != RELKIND_RELATION &&
3200 rel->rd_rel->relkind != RELKIND_INDEX)
3202 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3203 errmsg("\"%s\" is not a table or index",
3204 RelationGetRelationName(rel))));
3206 /* Permissions checks */
3207 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3208 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3209 RelationGetRelationName(rel));
3211 if (!allowSystemTableMods && IsSystemRelation(rel))
3213 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3214 errmsg("permission denied: \"%s\" is a system catalog",
3215 RelationGetRelationName(rel))));
3221 * Simple table recursion sufficient for most ALTER TABLE operations.
3222 * All direct and indirect children are processed in an unspecified order.
3223 * Note that if a child inherits from the original table via multiple
3224 * inheritance paths, it will be visited just once.
3227 ATSimpleRecursion(List **wqueue, Relation rel,
3228 AlterTableCmd *cmd, bool recurse)
3231 * Propagate to children if desired. Non-table relations never have
3232 * children, so no need to search in that case.
3234 if (recurse && rel->rd_rel->relkind == RELKIND_RELATION)
3236 Oid relid = RelationGetRelid(rel);
3240 /* this routine is actually in the planner */
3241 children = find_all_inheritors(relid);
3244 * find_all_inheritors does the recursive search of the inheritance
3245 * hierarchy, so all we have to do is process all of the relids in the
3246 * list that it returns.
3248 foreach(child, children)
3250 Oid childrelid = lfirst_oid(child);
3253 if (childrelid == relid)
3255 childrel = relation_open(childrelid, AccessExclusiveLock);
3256 CheckTableNotInUse(childrel, "ALTER TABLE");
3257 ATPrepCmd(wqueue, childrel, cmd, false, true);
3258 relation_close(childrel, NoLock);
3264 * ATOneLevelRecursion
3266 * Here, we visit only direct inheritance children. It is expected that
3267 * the command's prep routine will recurse again to find indirect children.
3268 * When using this technique, a multiply-inheriting child will be visited
3272 ATOneLevelRecursion(List **wqueue, Relation rel,
3275 Oid relid = RelationGetRelid(rel);
3279 /* this routine is actually in the planner */
3280 children = find_inheritance_children(relid);
3282 foreach(child, children)
3284 Oid childrelid = lfirst_oid(child);
3287 childrel = relation_open(childrelid, AccessExclusiveLock);
3288 CheckTableNotInUse(childrel, "ALTER TABLE");
3289 ATPrepCmd(wqueue, childrel, cmd, true, true);
3290 relation_close(childrel, NoLock);
3296 * find_composite_type_dependencies
3298 * Check to see if a composite type is being used as a column in some
3299 * other table (possibly nested several levels deep in composite types!).
3300 * Eventually, we'd like to propagate the check or rewrite operation
3301 * into other such tables, but for now, just error out if we find any.
3303 * Caller should provide either a table name or a type name (not both) to
3304 * report in the error message, if any.
3306 * We assume that functions and views depending on the type are not reasons
3307 * to reject the ALTER. (How safe is this really?)
3310 find_composite_type_dependencies(Oid typeOid,
3311 const char *origTblName,
3312 const char *origTypeName)
3316 SysScanDesc depScan;
3321 * We scan pg_depend to find those things that depend on the rowtype. (We
3322 * assume we can ignore refobjsubid for a rowtype.)
3324 depRel = heap_open(DependRelationId, AccessShareLock);
3326 ScanKeyInit(&key[0],
3327 Anum_pg_depend_refclassid,
3328 BTEqualStrategyNumber, F_OIDEQ,
3329 ObjectIdGetDatum(TypeRelationId));
3330 ScanKeyInit(&key[1],
3331 Anum_pg_depend_refobjid,
3332 BTEqualStrategyNumber, F_OIDEQ,
3333 ObjectIdGetDatum(typeOid));
3335 depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
3336 SnapshotNow, 2, key);
3338 while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
3340 Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
3342 Form_pg_attribute att;
3344 /* Ignore dependees that aren't user columns of relations */
3345 /* (we assume system columns are never of rowtypes) */
3346 if (pg_depend->classid != RelationRelationId ||
3347 pg_depend->objsubid <= 0)
3350 rel = relation_open(pg_depend->objid, AccessShareLock);
3351 att = rel->rd_att->attrs[pg_depend->objsubid - 1];
3353 if (rel->rd_rel->relkind == RELKIND_RELATION)
3357 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3358 errmsg("cannot alter table \"%s\" because column \"%s\".\"%s\" uses its rowtype",
3360 RelationGetRelationName(rel),
3361 NameStr(att->attname))));
3364 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3365 errmsg("cannot alter type \"%s\" because column \"%s\".\"%s\" uses it",
3367 RelationGetRelationName(rel),
3368 NameStr(att->attname))));
3370 else if (OidIsValid(rel->rd_rel->reltype))
3373 * A view or composite type itself isn't a problem, but we must
3374 * recursively check for indirect dependencies via its rowtype.
3376 find_composite_type_dependencies(rel->rd_rel->reltype,
3377 origTblName, origTypeName);
3380 relation_close(rel, AccessShareLock);
3383 systable_endscan(depScan);
3385 relation_close(depRel, AccessShareLock);
3388 * If there's an array type for the rowtype, must check for uses of it,
3391 arrayOid = get_array_type(typeOid);
3392 if (OidIsValid(arrayOid))
3393 find_composite_type_dependencies(arrayOid, origTblName, origTypeName);
3398 * ALTER TABLE ADD COLUMN
3400 * Adds an additional attribute to a relation making the assumption that
3401 * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
3402 * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
3406 ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
3410 * Recurse to add the column to child classes, if requested.
3412 * We must recurse one level at a time, so that multiply-inheriting
3413 * children are visited the right number of times and end up with the
3414 * right attinhcount.
3418 AlterTableCmd *childCmd = copyObject(cmd);
3419 ColumnDef *colDefChild = (ColumnDef *) childCmd->def;
3421 /* Child should see column as singly inherited */
3422 colDefChild->inhcount = 1;
3423 colDefChild->is_local = false;
3425 ATOneLevelRecursion(wqueue, rel, childCmd);
3430 * If we are told not to recurse, there had better not be any child
3431 * tables; else the addition would put them out of step.
3433 if (find_inheritance_children(RelationGetRelid(rel)) != NIL)
3435 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3436 errmsg("column must be added to child tables too")));
3441 ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
3444 Oid myrelid = RelationGetRelid(rel);
3448 HeapTuple attributeTuple;
3449 Form_pg_attribute attribute;
3450 FormData_pg_attribute attributeD;
3454 HeapTuple typeTuple;
3460 attrdesc = heap_open(AttributeRelationId, RowExclusiveLock);
3463 * Are we adding the column to a recursion child? If so, check whether to
3464 * merge with an existing definition for the column.
3466 if (colDef->inhcount > 0)
3470 /* Does child already have a column by this name? */
3471 tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
3472 if (HeapTupleIsValid(tuple))
3474 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
3478 /* Okay if child matches by type */
3479 ctypeId = typenameTypeId(NULL, colDef->typename, &ctypmod);
3480 if (ctypeId != childatt->atttypid ||
3481 ctypmod != childatt->atttypmod)
3483 (errcode(ERRCODE_DATATYPE_MISMATCH),
3484 errmsg("child table \"%s\" has different type for column \"%s\"",
3485 RelationGetRelationName(rel), colDef->colname)));
3487 /* Bump the existing child att's inhcount */
3488 childatt->attinhcount++;
3489 simple_heap_update(attrdesc, &tuple->t_self, tuple);
3490 CatalogUpdateIndexes(attrdesc, tuple);
3492 heap_freetuple(tuple);
3494 /* Inform the user about the merge */
3496 (errmsg("merging definition of column \"%s\" for child \"%s\"",
3497 colDef->colname, RelationGetRelationName(rel))));
3499 heap_close(attrdesc, RowExclusiveLock);
3504 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
3506 reltup = SearchSysCacheCopy(RELOID,
3507 ObjectIdGetDatum(myrelid),
3509 if (!HeapTupleIsValid(reltup))
3510 elog(ERROR, "cache lookup failed for relation %u", myrelid);
3513 * this test is deliberately not attisdropped-aware, since if one tries to
3514 * add a column matching a dropped column name, it's gonna fail anyway.
3516 if (SearchSysCacheExists(ATTNAME,
3517 ObjectIdGetDatum(myrelid),
3518 PointerGetDatum(colDef->colname),
3521 (errcode(ERRCODE_DUPLICATE_COLUMN),
3522 errmsg("column \"%s\" of relation \"%s\" already exists",
3523 colDef->colname, RelationGetRelationName(rel))));
3525 minattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts;
3526 maxatts = minattnum + 1;
3527 if (maxatts > MaxHeapAttributeNumber)
3529 (errcode(ERRCODE_TOO_MANY_COLUMNS),
3530 errmsg("tables can have at most %d columns",
3531 MaxHeapAttributeNumber)));
3534 typeTuple = typenameType(NULL, colDef->typename, &typmod);
3535 tform = (Form_pg_type) GETSTRUCT(typeTuple);
3536 typeOid = HeapTupleGetOid(typeTuple);
3538 /* make sure datatype is legal for a column */
3539 CheckAttributeType(colDef->colname, typeOid);
3541 attributeTuple = heap_addheader(Natts_pg_attribute,
3543 ATTRIBUTE_TUPLE_SIZE,
3544 (void *) &attributeD);
3546 attribute = (Form_pg_attribute) GETSTRUCT(attributeTuple);
3548 attribute->attrelid = myrelid;
3549 namestrcpy(&(attribute->attname), colDef->colname);
3550 attribute->atttypid = typeOid;
3551 attribute->attstattarget = -1;
3552 attribute->attlen = tform->typlen;
3553 attribute->attcacheoff = -1;
3554 attribute->atttypmod = typmod;
3555 attribute->attnum = i;
3556 attribute->attbyval = tform->typbyval;
3557 attribute->attndims = list_length(colDef->typename->arrayBounds);
3558 attribute->attstorage = tform->typstorage;
3559 attribute->attalign = tform->typalign;
3560 attribute->attnotnull = colDef->is_not_null;
3561 attribute->atthasdef = false;
3562 attribute->attisdropped = false;
3563 attribute->attislocal = colDef->is_local;
3564 attribute->attinhcount = colDef->inhcount;
3566 ReleaseSysCache(typeTuple);
3568 simple_heap_insert(attrdesc, attributeTuple);
3570 /* Update indexes on pg_attribute */
3571 CatalogUpdateIndexes(attrdesc, attributeTuple);
3573 heap_close(attrdesc, RowExclusiveLock);
3576 * Update number of attributes in pg_class tuple
3578 ((Form_pg_class) GETSTRUCT(reltup))->relnatts = maxatts;
3580 simple_heap_update(pgclass, &reltup->t_self, reltup);
3582 /* keep catalog indexes current */
3583 CatalogUpdateIndexes(pgclass, reltup);
3585 heap_freetuple(reltup);
3587 heap_close(pgclass, RowExclusiveLock);
3589 /* Make the attribute's catalog entry visible */
3590 CommandCounterIncrement();
3593 * Store the DEFAULT, if any, in the catalogs
3595 if (colDef->raw_default)
3597 RawColumnDefault *rawEnt;
3599 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3600 rawEnt->attnum = attribute->attnum;
3601 rawEnt->raw_default = copyObject(colDef->raw_default);
3604 * This function is intended for CREATE TABLE, so it processes a
3605 * _list_ of defaults, but we just do one.
3607 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL, false, true);
3609 /* Make the additional catalog changes visible */
3610 CommandCounterIncrement();
3614 * Tell Phase 3 to fill in the default expression, if there is one.
3616 * If there is no default, Phase 3 doesn't have to do anything, because
3617 * that effectively means that the default is NULL. The heap tuple access
3618 * routines always check for attnum > # of attributes in tuple, and return
3619 * NULL if so, so without any modification of the tuple data we will get
3620 * the effect of NULL values in the new column.
3622 * An exception occurs when the new column is of a domain type: the domain
3623 * might have a NOT NULL constraint, or a check constraint that indirectly
3624 * rejects nulls. If there are any domain constraints then we construct
3625 * an explicit NULL default value that will be passed through
3626 * CoerceToDomain processing. (This is a tad inefficient, since it causes
3627 * rewriting the table which we really don't have to do, but the present
3628 * design of domain processing doesn't offer any simple way of checking
3629 * the constraints more directly.)
3631 * Note: we use build_column_default, and not just the cooked default
3632 * returned by AddRelationNewConstraints, so that the right thing happens
3633 * when a datatype's default applies.
3635 defval = (Expr *) build_column_default(rel, attribute->attnum);
3637 if (!defval && GetDomainConstraints(typeOid) != NIL)
3642 baseTypeMod = typmod;
3643 baseTypeId = getBaseTypeAndTypmod(typeOid, &baseTypeMod);
3644 defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod);
3645 defval = (Expr *) coerce_to_target_type(NULL,
3650 COERCION_ASSIGNMENT,
3651 COERCE_IMPLICIT_CAST);
3652 if (defval == NULL) /* should not happen */
3653 elog(ERROR, "failed to coerce base type to domain");
3658 NewColumnValue *newval;
3660 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
3661 newval->attnum = attribute->attnum;
3662 newval->expr = defval;
3664 tab->newvals = lappend(tab->newvals, newval);
3668 * If the new column is NOT NULL, tell Phase 3 it needs to test that.
3670 tab->new_notnull |= colDef->is_not_null;
3673 * Add needed dependency entries for the new column.
3675 add_column_datatype_dependency(myrelid, i, attribute->atttypid);
3679 * Install a column's dependency on its datatype.
3682 add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
3684 ObjectAddress myself,
3687 myself.classId = RelationRelationId;
3688 myself.objectId = relid;
3689 myself.objectSubId = attnum;
3690 referenced.classId = TypeRelationId;
3691 referenced.objectId = typid;
3692 referenced.objectSubId = 0;
3693 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
3697 * ALTER TABLE ALTER COLUMN DROP NOT NULL
3700 ATExecDropNotNull(Relation rel, const char *colName)
3706 ListCell *indexoidscan;
3709 * lookup the attribute
3711 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3713 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3715 if (!HeapTupleIsValid(tuple))
3717 (errcode(ERRCODE_UNDEFINED_COLUMN),
3718 errmsg("column \"%s\" of relation \"%s\" does not exist",
3719 colName, RelationGetRelationName(rel))));
3721 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3723 /* Prevent them from altering a system attribute */
3726 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3727 errmsg("cannot alter system column \"%s\"",
3731 * Check that the attribute is not in a primary key
3734 /* Loop over all indexes on the relation */
3735 indexoidlist = RelationGetIndexList(rel);
3737 foreach(indexoidscan, indexoidlist)
3739 Oid indexoid = lfirst_oid(indexoidscan);
3740 HeapTuple indexTuple;
3741 Form_pg_index indexStruct;
3744 indexTuple = SearchSysCache(INDEXRELID,
3745 ObjectIdGetDatum(indexoid),
3747 if (!HeapTupleIsValid(indexTuple))
3748 elog(ERROR, "cache lookup failed for index %u", indexoid);
3749 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
3751 /* If the index is not a primary key, skip the check */
3752 if (indexStruct->indisprimary)
3755 * Loop over each attribute in the primary key and see if it
3756 * matches the to-be-altered attribute
3758 for (i = 0; i < indexStruct->indnatts; i++)
3760 if (indexStruct->indkey.values[i] == attnum)
3762 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3763 errmsg("column \"%s\" is in a primary key",
3768 ReleaseSysCache(indexTuple);
3771 list_free(indexoidlist);
3774 * Okay, actually perform the catalog change ... if needed
3776 if (((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3778 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = FALSE;
3780 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3782 /* keep the system catalog indexes current */
3783 CatalogUpdateIndexes(attr_rel, tuple);
3786 heap_close(attr_rel, RowExclusiveLock);
3790 * ALTER TABLE ALTER COLUMN SET NOT NULL
3793 ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
3794 const char *colName)
3801 * lookup the attribute
3803 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3805 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3807 if (!HeapTupleIsValid(tuple))
3809 (errcode(ERRCODE_UNDEFINED_COLUMN),
3810 errmsg("column \"%s\" of relation \"%s\" does not exist",
3811 colName, RelationGetRelationName(rel))));
3813 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3815 /* Prevent them from altering a system attribute */
3818 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3819 errmsg("cannot alter system column \"%s\"",
3823 * Okay, actually perform the catalog change ... if needed
3825 if (!((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3827 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = TRUE;
3829 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3831 /* keep the system catalog indexes current */
3832 CatalogUpdateIndexes(attr_rel, tuple);
3834 /* Tell Phase 3 it needs to test the constraint */
3835 tab->new_notnull = true;
3838 heap_close(attr_rel, RowExclusiveLock);
3842 * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
3845 ATExecColumnDefault(Relation rel, const char *colName,
3851 * get the number of the attribute
3853 attnum = get_attnum(RelationGetRelid(rel), colName);
3854 if (attnum == InvalidAttrNumber)
3856 (errcode(ERRCODE_UNDEFINED_COLUMN),
3857 errmsg("column \"%s\" of relation \"%s\" does not exist",
3858 colName, RelationGetRelationName(rel))));
3860 /* Prevent them from altering a system attribute */
3863 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3864 errmsg("cannot alter system column \"%s\"",
3868 * Remove any old default for the column. We use RESTRICT here for
3869 * safety, but at present we do not expect anything to depend on the
3872 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false);
3877 RawColumnDefault *rawEnt;
3879 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3880 rawEnt->attnum = attnum;
3881 rawEnt->raw_default = newDefault;
3884 * This function is intended for CREATE TABLE, so it processes a
3885 * _list_ of defaults, but we just do one.
3887 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL, false, true);
3892 * ALTER TABLE ALTER COLUMN SET STATISTICS
3895 ATPrepSetStatistics(Relation rel, const char *colName, Node *flagValue)
3898 * We do our own permission checking because (a) we want to allow SET
3899 * STATISTICS on indexes (for expressional index columns), and (b) we want
3900 * to allow SET STATISTICS on system catalogs without requiring
3901 * allowSystemTableMods to be turned on.
3903 if (rel->rd_rel->relkind != RELKIND_RELATION &&
3904 rel->rd_rel->relkind != RELKIND_INDEX)
3906 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3907 errmsg("\"%s\" is not a table or index",
3908 RelationGetRelationName(rel))));
3910 /* Permissions checks */
3911 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3912 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3913 RelationGetRelationName(rel));
3917 ATExecSetStatistics(Relation rel, const char *colName, Node *newValue)
3920 Relation attrelation;
3922 Form_pg_attribute attrtuple;
3924 Assert(IsA(newValue, Integer));
3925 newtarget = intVal(newValue);
3928 * Limit target to a sane range
3933 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3934 errmsg("statistics target %d is too low",
3937 else if (newtarget > 1000)
3941 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3942 errmsg("lowering statistics target to %d",
3946 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
3948 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3950 if (!HeapTupleIsValid(tuple))
3952 (errcode(ERRCODE_UNDEFINED_COLUMN),
3953 errmsg("column \"%s\" of relation \"%s\" does not exist",
3954 colName, RelationGetRelationName(rel))));
3955 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
3957 if (attrtuple->attnum <= 0)
3959 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3960 errmsg("cannot alter system column \"%s\"",
3963 attrtuple->attstattarget = newtarget;
3965 simple_heap_update(attrelation, &tuple->t_self, tuple);
3967 /* keep system catalog indexes current */
3968 CatalogUpdateIndexes(attrelation, tuple);
3970 heap_freetuple(tuple);
3972 heap_close(attrelation, RowExclusiveLock);
3976 * ALTER TABLE ALTER COLUMN SET STORAGE
3979 ATExecSetStorage(Relation rel, const char *colName, Node *newValue)
3983 Relation attrelation;
3985 Form_pg_attribute attrtuple;
3987 Assert(IsA(newValue, String));
3988 storagemode = strVal(newValue);
3990 if (pg_strcasecmp(storagemode, "plain") == 0)
3992 else if (pg_strcasecmp(storagemode, "external") == 0)
3994 else if (pg_strcasecmp(storagemode, "extended") == 0)
3996 else if (pg_strcasecmp(storagemode, "main") == 0)
4001 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4002 errmsg("invalid storage type \"%s\"",
4004 newstorage = 0; /* keep compiler quiet */
4007 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
4009 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4011 if (!HeapTupleIsValid(tuple))
4013 (errcode(ERRCODE_UNDEFINED_COLUMN),
4014 errmsg("column \"%s\" of relation \"%s\" does not exist",
4015 colName, RelationGetRelationName(rel))));
4016 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
4018 if (attrtuple->attnum <= 0)
4020 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4021 errmsg("cannot alter system column \"%s\"",
4025 * safety check: do not allow toasted storage modes unless column datatype
4028 if (newstorage == 'p' || TypeIsToastable(attrtuple->atttypid))
4029 attrtuple->attstorage = newstorage;
4032 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4033 errmsg("column data type %s can only have storage PLAIN",
4034 format_type_be(attrtuple->atttypid))));
4036 simple_heap_update(attrelation, &tuple->t_self, tuple);
4038 /* keep system catalog indexes current */
4039 CatalogUpdateIndexes(attrelation, tuple);
4041 heap_freetuple(tuple);
4043 heap_close(attrelation, RowExclusiveLock);
4048 * ALTER TABLE DROP COLUMN
4050 * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
4051 * because we have to decide at runtime whether to recurse or not depending
4052 * on whether attinhcount goes to zero or not. (We can't check this in a
4053 * static pre-pass because it won't handle multiple inheritance situations
4054 * correctly.) Since DROP COLUMN doesn't need to create any work queue
4055 * entries for Phase 3, it's okay to recurse internally in this routine
4056 * without considering the work queue.
4059 ATExecDropColumn(Relation rel, const char *colName,
4060 DropBehavior behavior,
4061 bool recurse, bool recursing)
4064 Form_pg_attribute targetatt;
4067 ObjectAddress object;
4069 /* At top level, permission check was done in ATPrepCmd, else do it */
4071 ATSimplePermissions(rel, false);
4074 * get the number of the attribute
4076 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
4077 if (!HeapTupleIsValid(tuple))
4079 (errcode(ERRCODE_UNDEFINED_COLUMN),
4080 errmsg("column \"%s\" of relation \"%s\" does not exist",
4081 colName, RelationGetRelationName(rel))));
4082 targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
4084 attnum = targetatt->attnum;
4086 /* Can't drop a system attribute, except OID */
4087 if (attnum <= 0 && attnum != ObjectIdAttributeNumber)
4089 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4090 errmsg("cannot drop system column \"%s\"",
4093 /* Don't drop inherited columns */
4094 if (targetatt->attinhcount > 0 && !recursing)
4096 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4097 errmsg("cannot drop inherited column \"%s\"",
4100 ReleaseSysCache(tuple);
4103 * Propagate to children as appropriate. Unlike most other ALTER
4104 * routines, we have to do this one level of recursion at a time; we can't
4105 * use find_all_inheritors to do it in one pass.
4107 children = find_inheritance_children(RelationGetRelid(rel));
4114 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
4115 foreach(child, children)
4117 Oid childrelid = lfirst_oid(child);
4119 Form_pg_attribute childatt;
4121 childrel = heap_open(childrelid, AccessExclusiveLock);
4122 CheckTableNotInUse(childrel, "ALTER TABLE");
4124 tuple = SearchSysCacheCopyAttName(childrelid, colName);
4125 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
4126 elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
4127 colName, childrelid);
4128 childatt = (Form_pg_attribute) GETSTRUCT(tuple);
4130 if (childatt->attinhcount <= 0) /* shouldn't happen */
4131 elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
4132 childrelid, colName);
4137 * If the child column has other definition sources, just
4138 * decrement its inheritance count; if not, recurse to delete
4141 if (childatt->attinhcount == 1 && !childatt->attislocal)
4143 /* Time to delete this child column, too */
4144 ATExecDropColumn(childrel, colName, behavior, true, true);
4148 /* Child column must survive my deletion */
4149 childatt->attinhcount--;
4151 simple_heap_update(attr_rel, &tuple->t_self, tuple);
4153 /* keep the system catalog indexes current */
4154 CatalogUpdateIndexes(attr_rel, tuple);
4156 /* Make update visible */
4157 CommandCounterIncrement();
4163 * If we were told to drop ONLY in this table (no recursion),
4164 * we need to mark the inheritors' attributes as locally
4165 * defined rather than inherited.
4167 childatt->attinhcount--;
4168 childatt->attislocal = true;
4170 simple_heap_update(attr_rel, &tuple->t_self, tuple);
4172 /* keep the system catalog indexes current */
4173 CatalogUpdateIndexes(attr_rel, tuple);
4175 /* Make update visible */
4176 CommandCounterIncrement();
4179 heap_freetuple(tuple);
4181 heap_close(childrel, NoLock);
4183 heap_close(attr_rel, RowExclusiveLock);
4187 * Perform the actual column deletion
4189 object.classId = RelationRelationId;
4190 object.objectId = RelationGetRelid(rel);
4191 object.objectSubId = attnum;
4193 performDeletion(&object, behavior);
4196 * If we dropped the OID column, must adjust pg_class.relhasoids
4198 if (attnum == ObjectIdAttributeNumber)
4201 Form_pg_class tuple_class;
4203 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
4205 tuple = SearchSysCacheCopy(RELOID,
4206 ObjectIdGetDatum(RelationGetRelid(rel)),
4208 if (!HeapTupleIsValid(tuple))
4209 elog(ERROR, "cache lookup failed for relation %u",
4210 RelationGetRelid(rel));
4211 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
4213 tuple_class->relhasoids = false;
4214 simple_heap_update(class_rel, &tuple->t_self, tuple);
4216 /* Keep the catalog indexes up to date */
4217 CatalogUpdateIndexes(class_rel, tuple);
4219 heap_close(class_rel, RowExclusiveLock);
4224 * ALTER TABLE ADD INDEX
4226 * There is no such command in the grammar, but parse_utilcmd.c converts
4227 * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands. This lets
4228 * us schedule creation of the index at the appropriate time during ALTER.
4231 ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
4232 IndexStmt *stmt, bool is_rebuild)
4238 Assert(IsA(stmt, IndexStmt));
4240 /* suppress schema rights check when rebuilding existing index */
4241 check_rights = !is_rebuild;
4242 /* skip index build if phase 3 will have to rewrite table anyway */
4243 skip_build = (tab->newvals != NIL);
4244 /* suppress notices when rebuilding existing index */
4247 /* The IndexStmt has already been through transformIndexStmt */
4249 DefineIndex(stmt->relation, /* relation */
4250 stmt->idxname, /* index name */
4251 InvalidOid, /* no predefined OID */
4252 stmt->accessMethod, /* am name */
4254 stmt->indexParams, /* parameters */
4255 (Expr *) stmt->whereClause,
4260 true, /* is_alter_table */
4268 * ALTER TABLE ADD CONSTRAINT
4271 ATExecAddConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
4272 Node *newConstraint, bool recurse)
4274 switch (nodeTag(newConstraint))
4278 Constraint *constr = (Constraint *) newConstraint;
4281 * Currently, we only expect to see CONSTR_CHECK nodes
4282 * arriving here (see the preprocessing done in
4283 * parse_utilcmd.c). Use a switch anyway to make it easier to
4284 * add more code later.
4286 switch (constr->contype)
4289 ATAddCheckConstraint(wqueue, tab, rel,
4290 constr, recurse, false);
4293 elog(ERROR, "unrecognized constraint type: %d",
4294 (int) constr->contype);
4298 case T_FkConstraint:
4300 FkConstraint *fkconstraint = (FkConstraint *) newConstraint;
4303 * Note that we currently never recurse for FK constraints,
4304 * so the "recurse" flag is silently ignored.
4306 * Assign or validate constraint name
4308 if (fkconstraint->constr_name)
4310 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
4311 RelationGetRelid(rel),
4312 RelationGetNamespace(rel),
4313 fkconstraint->constr_name))
4315 (errcode(ERRCODE_DUPLICATE_OBJECT),
4316 errmsg("constraint \"%s\" for relation \"%s\" already exists",
4317 fkconstraint->constr_name,
4318 RelationGetRelationName(rel))));
4321 fkconstraint->constr_name =
4322 ChooseConstraintName(RelationGetRelationName(rel),
4323 strVal(linitial(fkconstraint->fk_attrs)),
4325 RelationGetNamespace(rel),
4328 ATAddForeignKeyConstraint(tab, rel, fkconstraint);
4333 elog(ERROR, "unrecognized node type: %d",
4334 (int) nodeTag(newConstraint));
4339 * Add a check constraint to a single table and its children
4341 * Subroutine for ATExecAddConstraint.
4343 * We must recurse to child tables during execution, rather than using
4344 * ALTER TABLE's normal prep-time recursion. The reason is that all the
4345 * constraints *must* be given the same name, else they won't be seen as
4346 * related later. If the user didn't explicitly specify a name, then
4347 * AddRelationNewConstraints would normally assign different names to the
4348 * child constraints. To fix that, we must capture the name assigned at
4349 * the parent table and pass that down.
4352 ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
4353 Constraint *constr, bool recurse, bool recursing)
4360 /* At top level, permission check was done in ATPrepCmd, else do it */
4362 ATSimplePermissions(rel, false);
4365 * Call AddRelationNewConstraints to do the work, making sure it works on
4366 * a copy of the Constraint so transformExpr can't modify the original.
4367 * It returns a list of cooked constraints.
4369 * If the constraint ends up getting merged with a pre-existing one, it's
4370 * omitted from the returned list, which is what we want: we do not need
4371 * to do any validation work. That can only happen at child tables,
4372 * though, since we disallow merging at the top level.
4374 newcons = AddRelationNewConstraints(rel, NIL,
4375 list_make1(copyObject(constr)),
4376 recursing, !recursing);
4378 /* Add each constraint to Phase 3's queue */
4379 foreach(lcon, newcons)
4381 CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
4382 NewConstraint *newcon;
4384 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
4385 newcon->name = ccon->name;
4386 newcon->contype = ccon->contype;
4387 /* ExecQual wants implicit-AND format */
4388 newcon->qual = (Node *) make_ands_implicit((Expr *) ccon->expr);
4390 tab->constraints = lappend(tab->constraints, newcon);
4392 /* Save the actually assigned name if it was defaulted */
4393 if (constr->name == NULL)
4394 constr->name = ccon->name;
4397 /* At this point we must have a locked-down name to use */
4398 Assert(constr->name != NULL);
4400 /* Advance command counter in case same table is visited multiple times */
4401 CommandCounterIncrement();
4404 * Propagate to children as appropriate. Unlike most other ALTER
4405 * routines, we have to do this one level of recursion at a time; we can't
4406 * use find_all_inheritors to do it in one pass.
4408 children = find_inheritance_children(RelationGetRelid(rel));
4411 * If we are told not to recurse, there had better not be any child
4412 * tables; else the addition would put them out of step.
4414 if (children && !recurse)
4416 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4417 errmsg("constraint must be added to child tables too")));
4419 foreach(child, children)
4421 Oid childrelid = lfirst_oid(child);
4423 AlteredTableInfo *childtab;
4425 childrel = heap_open(childrelid, AccessExclusiveLock);
4426 CheckTableNotInUse(childrel, "ALTER TABLE");
4428 /* Find or create work queue entry for this table */
4429 childtab = ATGetQueueEntry(wqueue, childrel);
4431 /* Recurse to child */
4432 ATAddCheckConstraint(wqueue, childtab, childrel,
4433 constr, recurse, true);
4435 heap_close(childrel, NoLock);
4440 * Add a foreign-key constraint to a single table
4442 * Subroutine for ATExecAddConstraint. Must already hold exclusive
4443 * lock on the rel, and have done appropriate validity/permissions checks
4447 ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
4448 FkConstraint *fkconstraint)
4451 AclResult aclresult;
4452 int16 pkattnum[INDEX_MAX_KEYS];
4453 int16 fkattnum[INDEX_MAX_KEYS];
4454 Oid pktypoid[INDEX_MAX_KEYS];
4455 Oid fktypoid[INDEX_MAX_KEYS];
4456 Oid opclasses[INDEX_MAX_KEYS];
4457 Oid pfeqoperators[INDEX_MAX_KEYS];
4458 Oid ppeqoperators[INDEX_MAX_KEYS];
4459 Oid ffeqoperators[INDEX_MAX_KEYS];
4467 * Grab an exclusive lock on the pk table, so that someone doesn't delete
4468 * rows out from under us. (Although a lesser lock would do for that
4469 * purpose, we'll need exclusive lock anyway to add triggers to the pk
4470 * table; trying to start with a lesser lock will just create a risk of
4473 pkrel = heap_openrv(fkconstraint->pktable, AccessExclusiveLock);
4476 * Validity and permissions checks
4478 * Note: REFERENCES permissions checks are redundant with CREATE TRIGGER,
4479 * but we may as well error out sooner instead of later.
4481 if (pkrel->rd_rel->relkind != RELKIND_RELATION)
4483 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4484 errmsg("referenced relation \"%s\" is not a table",
4485 RelationGetRelationName(pkrel))));
4487 aclresult = pg_class_aclcheck(RelationGetRelid(pkrel), GetUserId(),
4489 if (aclresult != ACLCHECK_OK)
4490 aclcheck_error(aclresult, ACL_KIND_CLASS,
4491 RelationGetRelationName(pkrel));
4493 if (!allowSystemTableMods && IsSystemRelation(pkrel))
4495 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4496 errmsg("permission denied: \"%s\" is a system catalog",
4497 RelationGetRelationName(pkrel))));
4499 aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
4501 if (aclresult != ACLCHECK_OK)
4502 aclcheck_error(aclresult, ACL_KIND_CLASS,
4503 RelationGetRelationName(rel));
4506 * Disallow reference from permanent table to temp table or vice versa.
4507 * (The ban on perm->temp is for fairly obvious reasons. The ban on
4508 * temp->perm is because other backends might need to run the RI triggers
4509 * on the perm table, but they can't reliably see tuples the owning
4510 * backend has created in the temp table, because non-shared buffers are
4511 * used for temp tables.)
4513 if (isTempNamespace(RelationGetNamespace(pkrel)))
4515 if (!isTempNamespace(RelationGetNamespace(rel)))
4517 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4518 errmsg("cannot reference temporary table from permanent table constraint")));
4522 if (isTempNamespace(RelationGetNamespace(rel)))
4524 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4525 errmsg("cannot reference permanent table from temporary table constraint")));
4529 * Look up the referencing attributes to make sure they exist, and record
4530 * their attnums and type OIDs.
4532 MemSet(pkattnum, 0, sizeof(pkattnum));
4533 MemSet(fkattnum, 0, sizeof(fkattnum));
4534 MemSet(pktypoid, 0, sizeof(pktypoid));
4535 MemSet(fktypoid, 0, sizeof(fktypoid));
4536 MemSet(opclasses, 0, sizeof(opclasses));
4537 MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
4538 MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
4539 MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
4541 numfks = transformColumnNameList(RelationGetRelid(rel),
4542 fkconstraint->fk_attrs,
4543 fkattnum, fktypoid);
4546 * If the attribute list for the referenced table was omitted, lookup the
4547 * definition of the primary key and use it. Otherwise, validate the
4548 * supplied attribute list. In either case, discover the index OID and
4549 * index opclasses, and the attnums and type OIDs of the attributes.
4551 if (fkconstraint->pk_attrs == NIL)
4553 numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
4554 &fkconstraint->pk_attrs,
4560 numpks = transformColumnNameList(RelationGetRelid(pkrel),
4561 fkconstraint->pk_attrs,
4562 pkattnum, pktypoid);
4563 /* Look for an index matching the column list */
4564 indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
4569 * Look up the equality operators to use in the constraint.
4571 * Note that we have to be careful about the difference between the actual
4572 * PK column type and the opclass' declared input type, which might be
4573 * only binary-compatible with it. The declared opcintype is the right
4574 * thing to probe pg_amop with.
4576 if (numfks != numpks)
4578 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4579 errmsg("number of referencing and referenced columns for foreign key disagree")));
4581 for (i = 0; i < numpks; i++)
4583 Oid pktype = pktypoid[i];
4584 Oid fktype = fktypoid[i];
4587 Form_pg_opclass cla_tup;
4596 /* We need several fields out of the pg_opclass entry */
4597 cla_ht = SearchSysCache(CLAOID,
4598 ObjectIdGetDatum(opclasses[i]),
4600 if (!HeapTupleIsValid(cla_ht))
4601 elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
4602 cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
4603 amid = cla_tup->opcmethod;
4604 opfamily = cla_tup->opcfamily;
4605 opcintype = cla_tup->opcintype;
4606 ReleaseSysCache(cla_ht);
4609 * Check it's a btree; currently this can never fail since no other
4610 * index AMs support unique indexes. If we ever did have other types
4611 * of unique indexes, we'd need a way to determine which operator
4612 * strategy number is equality. (Is it reasonable to insist that
4613 * every such index AM use btree's number for equality?)
4615 if (amid != BTREE_AM_OID)
4616 elog(ERROR, "only b-tree indexes are supported for foreign keys");
4617 eqstrategy = BTEqualStrategyNumber;
4620 * There had better be a primary equality operator for the index.
4621 * We'll use it for PK = PK comparisons.
4623 ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
4626 if (!OidIsValid(ppeqop))
4627 elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
4628 eqstrategy, opcintype, opcintype, opfamily);
4631 * Are there equality operators that take exactly the FK type? Assume
4632 * we should look through any domain here.
4634 fktyped = getBaseType(fktype);
4636 pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
4638 if (OidIsValid(pfeqop))
4639 ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
4642 ffeqop = InvalidOid; /* keep compiler quiet */
4644 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4647 * Otherwise, look for an implicit cast from the FK type to the
4648 * opcintype, and if found, use the primary equality operator.
4649 * This is a bit tricky because opcintype might be a polymorphic
4650 * type such as ANYARRAY or ANYENUM; so what we have to test is
4651 * whether the two actual column types can be concurrently cast to
4652 * that type. (Otherwise, we'd fail to reject combinations such
4653 * as int[] and point[].)
4655 Oid input_typeids[2];
4656 Oid target_typeids[2];
4658 input_typeids[0] = pktype;
4659 input_typeids[1] = fktype;
4660 target_typeids[0] = opcintype;
4661 target_typeids[1] = opcintype;
4662 if (can_coerce_type(2, input_typeids, target_typeids,
4664 pfeqop = ffeqop = ppeqop;
4667 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4669 (errcode(ERRCODE_DATATYPE_MISMATCH),
4670 errmsg("foreign key constraint \"%s\" "
4671 "cannot be implemented",
4672 fkconstraint->constr_name),
4673 errdetail("Key columns \"%s\" and \"%s\" "
4674 "are of incompatible types: %s and %s.",
4675 strVal(list_nth(fkconstraint->fk_attrs, i)),
4676 strVal(list_nth(fkconstraint->pk_attrs, i)),
4677 format_type_be(fktype),
4678 format_type_be(pktype))));
4680 pfeqoperators[i] = pfeqop;
4681 ppeqoperators[i] = ppeqop;
4682 ffeqoperators[i] = ffeqop;
4686 * Record the FK constraint in pg_constraint.
4688 constrOid = CreateConstraintEntry(fkconstraint->constr_name,
4689 RelationGetNamespace(rel),
4691 fkconstraint->deferrable,
4692 fkconstraint->initdeferred,
4693 RelationGetRelid(rel),
4696 InvalidOid, /* not a domain
4698 RelationGetRelid(pkrel),
4704 fkconstraint->fk_upd_action,
4705 fkconstraint->fk_del_action,
4706 fkconstraint->fk_matchtype,
4708 NULL, /* no check constraint */
4715 * Create the triggers that will enforce the constraint.
4717 createForeignKeyTriggers(rel, fkconstraint, constrOid);
4720 * Tell Phase 3 to check that the constraint is satisfied by existing rows
4721 * (we can skip this during table creation).
4723 if (!fkconstraint->skip_validation)
4725 NewConstraint *newcon;
4727 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
4728 newcon->name = fkconstraint->constr_name;
4729 newcon->contype = CONSTR_FOREIGN;
4730 newcon->refrelid = RelationGetRelid(pkrel);
4731 newcon->conid = constrOid;
4732 newcon->qual = (Node *) fkconstraint;
4734 tab->constraints = lappend(tab->constraints, newcon);
4738 * Close pk table, but keep lock until we've committed.
4740 heap_close(pkrel, NoLock);
4745 * transformColumnNameList - transform list of column names
4747 * Lookup each name and return its attnum and type OID
4750 transformColumnNameList(Oid relId, List *colList,
4751 int16 *attnums, Oid *atttypids)
4759 char *attname = strVal(lfirst(l));
4762 atttuple = SearchSysCacheAttName(relId, attname);
4763 if (!HeapTupleIsValid(atttuple))
4765 (errcode(ERRCODE_UNDEFINED_COLUMN),
4766 errmsg("column \"%s\" referenced in foreign key constraint does not exist",
4768 if (attnum >= INDEX_MAX_KEYS)
4770 (errcode(ERRCODE_TOO_MANY_COLUMNS),
4771 errmsg("cannot have more than %d keys in a foreign key",
4773 attnums[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->attnum;
4774 atttypids[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->atttypid;
4775 ReleaseSysCache(atttuple);
4783 * transformFkeyGetPrimaryKey -
4785 * Look up the names, attnums, and types of the primary key attributes
4786 * for the pkrel. Also return the index OID and index opclasses of the
4787 * index supporting the primary key.
4789 * All parameters except pkrel are output parameters. Also, the function
4790 * return value is the number of attributes in the primary key.
4792 * Used when the column list in the REFERENCES specification is omitted.
4795 transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
4797 int16 *attnums, Oid *atttypids,
4801 ListCell *indexoidscan;
4802 HeapTuple indexTuple = NULL;
4803 Form_pg_index indexStruct = NULL;
4804 Datum indclassDatum;
4806 oidvector *indclass;
4810 * Get the list of index OIDs for the table from the relcache, and look up
4811 * each one in the pg_index syscache until we find one marked primary key
4812 * (hopefully there isn't more than one such).
4814 *indexOid = InvalidOid;
4816 indexoidlist = RelationGetIndexList(pkrel);
4818 foreach(indexoidscan, indexoidlist)
4820 Oid indexoid = lfirst_oid(indexoidscan);
4822 indexTuple = SearchSysCache(INDEXRELID,
4823 ObjectIdGetDatum(indexoid),
4825 if (!HeapTupleIsValid(indexTuple))
4826 elog(ERROR, "cache lookup failed for index %u", indexoid);
4827 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4828 if (indexStruct->indisprimary)
4830 *indexOid = indexoid;
4833 ReleaseSysCache(indexTuple);
4836 list_free(indexoidlist);
4839 * Check that we found it
4841 if (!OidIsValid(*indexOid))
4843 (errcode(ERRCODE_UNDEFINED_OBJECT),
4844 errmsg("there is no primary key for referenced table \"%s\"",
4845 RelationGetRelationName(pkrel))));
4847 /* Must get indclass the hard way */
4848 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4849 Anum_pg_index_indclass, &isnull);
4851 indclass = (oidvector *) DatumGetPointer(indclassDatum);
4854 * Now build the list of PK attributes from the indkey definition (we
4855 * assume a primary key cannot have expressional elements)
4858 for (i = 0; i < indexStruct->indnatts; i++)
4860 int pkattno = indexStruct->indkey.values[i];
4862 attnums[i] = pkattno;
4863 atttypids[i] = attnumTypeId(pkrel, pkattno);
4864 opclasses[i] = indclass->values[i];
4865 *attnamelist = lappend(*attnamelist,
4866 makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
4869 ReleaseSysCache(indexTuple);
4875 * transformFkeyCheckAttrs -
4877 * Make sure that the attributes of a referenced table belong to a unique
4878 * (or primary key) constraint. Return the OID of the index supporting
4879 * the constraint, as well as the opclasses associated with the index
4883 transformFkeyCheckAttrs(Relation pkrel,
4884 int numattrs, int16 *attnums,
4885 Oid *opclasses) /* output parameter */
4887 Oid indexoid = InvalidOid;
4890 ListCell *indexoidscan;
4893 * Get the list of index OIDs for the table from the relcache, and look up
4894 * each one in the pg_index syscache, and match unique indexes to the list
4895 * of attnums we are given.
4897 indexoidlist = RelationGetIndexList(pkrel);
4899 foreach(indexoidscan, indexoidlist)
4901 HeapTuple indexTuple;
4902 Form_pg_index indexStruct;
4906 indexoid = lfirst_oid(indexoidscan);
4907 indexTuple = SearchSysCache(INDEXRELID,
4908 ObjectIdGetDatum(indexoid),
4910 if (!HeapTupleIsValid(indexTuple))
4911 elog(ERROR, "cache lookup failed for index %u", indexoid);
4912 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4915 * Must have the right number of columns; must be unique and not a
4916 * partial index; forget it if there are any expressions, too
4918 if (indexStruct->indnatts == numattrs &&
4919 indexStruct->indisunique &&
4920 heap_attisnull(indexTuple, Anum_pg_index_indpred) &&
4921 heap_attisnull(indexTuple, Anum_pg_index_indexprs))
4923 /* Must get indclass the hard way */
4924 Datum indclassDatum;
4926 oidvector *indclass;
4928 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4929 Anum_pg_index_indclass, &isnull);
4931 indclass = (oidvector *) DatumGetPointer(indclassDatum);
4934 * The given attnum list may match the index columns in any order.
4935 * Check that each list is a subset of the other.
4937 for (i = 0; i < numattrs; i++)
4940 for (j = 0; j < numattrs; j++)
4942 if (attnums[i] == indexStruct->indkey.values[j])
4953 for (i = 0; i < numattrs; i++)
4956 for (j = 0; j < numattrs; j++)
4958 if (attnums[j] == indexStruct->indkey.values[i])
4960 opclasses[j] = indclass->values[i];
4970 ReleaseSysCache(indexTuple);
4977 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4978 errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
4979 RelationGetRelationName(pkrel))));
4981 list_free(indexoidlist);
4987 * Scan the existing rows in a table to verify they meet a proposed FK
4990 * Caller must have opened and locked both relations.
4993 validateForeignKeyConstraint(FkConstraint *fkconstraint,
5003 * Build a trigger call structure; we'll need it either way.
5005 MemSet(&trig, 0, sizeof(trig));
5006 trig.tgoid = InvalidOid;
5007 trig.tgname = fkconstraint->constr_name;
5008 trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
5009 trig.tgisconstraint = TRUE;
5010 trig.tgconstrrelid = RelationGetRelid(pkrel);
5011 trig.tgconstraint = constraintOid;
5012 trig.tgdeferrable = FALSE;
5013 trig.tginitdeferred = FALSE;
5014 /* we needn't fill in tgargs */
5017 * See if we can do it with a single LEFT JOIN query. A FALSE result
5018 * indicates we must proceed with the fire-the-trigger method.
5020 if (RI_Initial_Check(&trig, rel, pkrel))
5024 * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
5025 * if that tuple had just been inserted. If any of those fail, it should
5026 * ereport(ERROR) and that's that.
5028 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
5030 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
5032 FunctionCallInfoData fcinfo;
5033 TriggerData trigdata;
5036 * Make a call to the trigger function
5038 * No parameters are passed, but we do set a context
5040 MemSet(&fcinfo, 0, sizeof(fcinfo));
5043 * We assume RI_FKey_check_ins won't look at flinfo...
5045 trigdata.type = T_TriggerData;
5046 trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
5047 trigdata.tg_relation = rel;
5048 trigdata.tg_trigtuple = tuple;
5049 trigdata.tg_newtuple = NULL;
5050 trigdata.tg_trigger = &trig;
5051 trigdata.tg_trigtuplebuf = scan->rs_cbuf;
5052 trigdata.tg_newtuplebuf = InvalidBuffer;
5054 fcinfo.context = (Node *) &trigdata;
5056 RI_FKey_check_ins(&fcinfo);
5063 CreateFKCheckTrigger(RangeVar *myRel, FkConstraint *fkconstraint,
5064 Oid constraintOid, bool on_insert)
5066 CreateTrigStmt *fk_trigger;
5068 fk_trigger = makeNode(CreateTrigStmt);
5069 fk_trigger->trigname = fkconstraint->constr_name;
5070 fk_trigger->relation = myRel;
5071 fk_trigger->before = false;
5072 fk_trigger->row = true;
5074 /* Either ON INSERT or ON UPDATE */
5077 fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
5078 fk_trigger->actions[0] = 'i';
5082 fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
5083 fk_trigger->actions[0] = 'u';
5085 fk_trigger->actions[1] = '\0';
5087 fk_trigger->isconstraint = true;
5088 fk_trigger->deferrable = fkconstraint->deferrable;
5089 fk_trigger->initdeferred = fkconstraint->initdeferred;
5090 fk_trigger->constrrel = fkconstraint->pktable;
5091 fk_trigger->args = NIL;
5093 (void) CreateTrigger(fk_trigger, constraintOid);
5095 /* Make changes-so-far visible */
5096 CommandCounterIncrement();
5100 * Create the triggers that implement an FK constraint.
5103 createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
5107 CreateTrigStmt *fk_trigger;
5110 * Reconstruct a RangeVar for my relation (not passed in, unfortunately).
5112 myRel = makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
5113 pstrdup(RelationGetRelationName(rel)));
5115 /* Make changes-so-far visible */
5116 CommandCounterIncrement();
5119 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the CHECK
5120 * action for both INSERTs and UPDATEs on the referencing table.
5122 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, true);
5123 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, false);
5126 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
5127 * DELETE action on the referenced table.
5129 fk_trigger = makeNode(CreateTrigStmt);
5130 fk_trigger->trigname = fkconstraint->constr_name;
5131 fk_trigger->relation = fkconstraint->pktable;
5132 fk_trigger->before = false;
5133 fk_trigger->row = true;
5134 fk_trigger->actions[0] = 'd';
5135 fk_trigger->actions[1] = '\0';
5137 fk_trigger->isconstraint = true;
5138 fk_trigger->constrrel = myRel;
5139 switch (fkconstraint->fk_del_action)
5141 case FKCONSTR_ACTION_NOACTION:
5142 fk_trigger->deferrable = fkconstraint->deferrable;
5143 fk_trigger->initdeferred = fkconstraint->initdeferred;
5144 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
5146 case FKCONSTR_ACTION_RESTRICT:
5147 fk_trigger->deferrable = false;
5148 fk_trigger->initdeferred = false;
5149 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
5151 case FKCONSTR_ACTION_CASCADE:
5152 fk_trigger->deferrable = false;
5153 fk_trigger->initdeferred = false;
5154 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
5156 case FKCONSTR_ACTION_SETNULL:
5157 fk_trigger->deferrable = false;
5158 fk_trigger->initdeferred = false;
5159 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
5161 case FKCONSTR_ACTION_SETDEFAULT:
5162 fk_trigger->deferrable = false;
5163 fk_trigger->initdeferred = false;
5164 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
5167 elog(ERROR, "unrecognized FK action type: %d",
5168 (int) fkconstraint->fk_del_action);
5171 fk_trigger->args = NIL;
5173 (void) CreateTrigger(fk_trigger, constraintOid);
5175 /* Make changes-so-far visible */
5176 CommandCounterIncrement();
5179 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
5180 * UPDATE action on the referenced table.
5182 fk_trigger = makeNode(CreateTrigStmt);
5183 fk_trigger->trigname = fkconstraint->constr_name;
5184 fk_trigger->relation = fkconstraint->pktable;
5185 fk_trigger->before = false;
5186 fk_trigger->row = true;
5187 fk_trigger->actions[0] = 'u';
5188 fk_trigger->actions[1] = '\0';
5189 fk_trigger->isconstraint = true;
5190 fk_trigger->constrrel = myRel;
5191 switch (fkconstraint->fk_upd_action)
5193 case FKCONSTR_ACTION_NOACTION:
5194 fk_trigger->deferrable = fkconstraint->deferrable;
5195 fk_trigger->initdeferred = fkconstraint->initdeferred;
5196 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
5198 case FKCONSTR_ACTION_RESTRICT:
5199 fk_trigger->deferrable = false;
5200 fk_trigger->initdeferred = false;
5201 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
5203 case FKCONSTR_ACTION_CASCADE:
5204 fk_trigger->deferrable = false;
5205 fk_trigger->initdeferred = false;
5206 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
5208 case FKCONSTR_ACTION_SETNULL:
5209 fk_trigger->deferrable = false;
5210 fk_trigger->initdeferred = false;
5211 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
5213 case FKCONSTR_ACTION_SETDEFAULT:
5214 fk_trigger->deferrable = false;
5215 fk_trigger->initdeferred = false;
5216 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
5219 elog(ERROR, "unrecognized FK action type: %d",
5220 (int) fkconstraint->fk_upd_action);
5223 fk_trigger->args = NIL;
5225 (void) CreateTrigger(fk_trigger, constraintOid);
5229 * ALTER TABLE DROP CONSTRAINT
5231 * Like DROP COLUMN, we can't use the normal ALTER TABLE recursion mechanism.
5234 ATExecDropConstraint(Relation rel, const char *constrName,
5235 DropBehavior behavior,
5236 bool recurse, bool recursing)
5241 Form_pg_constraint con;
5246 bool is_check_constraint = false;
5248 /* At top level, permission check was done in ATPrepCmd, else do it */
5250 ATSimplePermissions(rel, false);
5252 conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
5255 * Find and drop the target constraint
5258 Anum_pg_constraint_conrelid,
5259 BTEqualStrategyNumber, F_OIDEQ,
5260 ObjectIdGetDatum(RelationGetRelid(rel)));
5261 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
5262 true, SnapshotNow, 1, &key);
5264 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
5266 ObjectAddress conobj;
5268 con = (Form_pg_constraint) GETSTRUCT(tuple);
5270 if (strcmp(NameStr(con->conname), constrName) != 0)
5273 /* Don't drop inherited constraints */
5274 if (con->coninhcount > 0 && !recursing)
5276 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5277 errmsg("cannot drop inherited constraint \"%s\" of relation \"%s\"",
5278 constrName, RelationGetRelationName(rel))));
5280 /* Right now only CHECK constraints can be inherited */
5281 if (con->contype == CONSTRAINT_CHECK)
5282 is_check_constraint = true;
5285 * Perform the actual constraint deletion
5287 conobj.classId = ConstraintRelationId;
5288 conobj.objectId = HeapTupleGetOid(tuple);
5289 conobj.objectSubId = 0;
5291 performDeletion(&conobj, behavior);
5296 systable_endscan(scan);
5300 (errcode(ERRCODE_UNDEFINED_OBJECT),
5301 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
5302 constrName, RelationGetRelationName(rel))));
5305 * Propagate to children as appropriate. Unlike most other ALTER
5306 * routines, we have to do this one level of recursion at a time; we can't
5307 * use find_all_inheritors to do it in one pass.
5309 if (is_check_constraint)
5310 children = find_inheritance_children(RelationGetRelid(rel));
5314 foreach(child, children)
5316 Oid childrelid = lfirst_oid(child);
5319 childrel = heap_open(childrelid, AccessExclusiveLock);
5320 CheckTableNotInUse(childrel, "ALTER TABLE");
5323 Anum_pg_constraint_conrelid,
5324 BTEqualStrategyNumber, F_OIDEQ,
5325 ObjectIdGetDatum(childrelid));
5326 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
5327 true, SnapshotNow, 1, &key);
5331 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
5333 HeapTuple copy_tuple;
5335 con = (Form_pg_constraint) GETSTRUCT(tuple);
5337 /* Right now only CHECK constraints can be inherited */
5338 if (con->contype != CONSTRAINT_CHECK)
5341 if (strcmp(NameStr(con->conname), constrName) != 0)
5346 if (con->coninhcount <= 0) /* shouldn't happen */
5347 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
5348 childrelid, constrName);
5350 copy_tuple = heap_copytuple(tuple);
5351 con = (Form_pg_constraint) GETSTRUCT(copy_tuple);
5356 * If the child constraint has other definition sources,
5357 * just decrement its inheritance count; if not, recurse
5360 if (con->coninhcount == 1 && !con->conislocal)
5362 /* Time to delete this child constraint, too */
5363 ATExecDropConstraint(childrel, constrName, behavior,
5368 /* Child constraint must survive my deletion */
5370 simple_heap_update(conrel, ©_tuple->t_self, copy_tuple);
5371 CatalogUpdateIndexes(conrel, copy_tuple);
5373 /* Make update visible */
5374 CommandCounterIncrement();
5380 * If we were told to drop ONLY in this table (no
5381 * recursion), we need to mark the inheritors' constraints
5382 * as locally defined rather than inherited.
5385 con->conislocal = true;
5387 simple_heap_update(conrel, ©_tuple->t_self, copy_tuple);
5388 CatalogUpdateIndexes(conrel, copy_tuple);
5390 /* Make update visible */
5391 CommandCounterIncrement();
5394 heap_freetuple(copy_tuple);
5397 systable_endscan(scan);
5401 (errcode(ERRCODE_UNDEFINED_OBJECT),
5402 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
5404 RelationGetRelationName(childrel))));
5406 heap_close(childrel, NoLock);
5409 heap_close(conrel, RowExclusiveLock);
5416 ATPrepAlterColumnType(List **wqueue,
5417 AlteredTableInfo *tab, Relation rel,
5418 bool recurse, bool recursing,
5421 char *colName = cmd->name;
5422 TypeName *typename = (TypeName *) cmd->def;
5424 Form_pg_attribute attTup;
5429 NewColumnValue *newval;
5430 ParseState *pstate = make_parsestate(NULL);
5432 /* lookup the attribute so we can check inheritance status */
5433 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
5434 if (!HeapTupleIsValid(tuple))
5436 (errcode(ERRCODE_UNDEFINED_COLUMN),
5437 errmsg("column \"%s\" of relation \"%s\" does not exist",
5438 colName, RelationGetRelationName(rel))));
5439 attTup = (Form_pg_attribute) GETSTRUCT(tuple);
5440 attnum = attTup->attnum;
5442 /* Can't alter a system attribute */
5445 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5446 errmsg("cannot alter system column \"%s\"",
5449 /* Don't alter inherited columns */
5450 if (attTup->attinhcount > 0 && !recursing)
5452 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5453 errmsg("cannot alter inherited column \"%s\"",
5456 /* Look up the target type */
5457 targettype = typenameTypeId(NULL, typename, &targettypmod);
5459 /* make sure datatype is legal for a column */
5460 CheckAttributeType(colName, targettype);
5463 * Set up an expression to transform the old data value to the new type.
5464 * If a USING option was given, transform and use that expression, else
5465 * just take the old value and try to coerce it. We do this first so that
5466 * type incompatibility can be detected before we waste effort, and
5467 * because we need the expression to be parsed against the original table
5474 /* Expression must be able to access vars of old table */
5475 rte = addRangeTableEntryForRelation(pstate,
5480 addRTEtoQuery(pstate, rte, false, true, true);
5482 transform = transformExpr(pstate, cmd->transform);
5484 /* It can't return a set */
5485 if (expression_returns_set(transform))
5487 (errcode(ERRCODE_DATATYPE_MISMATCH),
5488 errmsg("transform expression must not return a set")));
5490 /* No subplans or aggregates, either... */
5491 if (pstate->p_hasSubLinks)
5493 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5494 errmsg("cannot use subquery in transform expression")));
5495 if (pstate->p_hasAggs)
5497 (errcode(ERRCODE_GROUPING_ERROR),
5498 errmsg("cannot use aggregate function in transform expression")));
5502 transform = (Node *) makeVar(1, attnum,
5503 attTup->atttypid, attTup->atttypmod,
5507 transform = coerce_to_target_type(pstate,
5508 transform, exprType(transform),
5509 targettype, targettypmod,
5510 COERCION_ASSIGNMENT,
5511 COERCE_IMPLICIT_CAST);
5512 if (transform == NULL)
5514 (errcode(ERRCODE_DATATYPE_MISMATCH),
5515 errmsg("column \"%s\" cannot be cast to type \"%s\"",
5516 colName, TypeNameToString(typename))));
5519 * Add a work queue item to make ATRewriteTable update the column
5522 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
5523 newval->attnum = attnum;
5524 newval->expr = (Expr *) transform;
5526 tab->newvals = lappend(tab->newvals, newval);
5528 ReleaseSysCache(tuple);
5531 * The recursion case is handled by ATSimpleRecursion. However, if we are
5532 * told not to recurse, there had better not be any child tables; else the
5533 * alter would put them out of step.
5536 ATSimpleRecursion(wqueue, rel, cmd, recurse);
5537 else if (!recursing &&
5538 find_inheritance_children(RelationGetRelid(rel)) != NIL)
5540 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5541 errmsg("type of inherited column \"%s\" must be changed in child tables too",
5546 ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
5547 const char *colName, TypeName *typename)
5550 Form_pg_attribute attTup;
5552 HeapTuple typeTuple;
5557 Relation attrelation;
5563 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
5565 /* Look up the target column */
5566 heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5567 if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
5569 (errcode(ERRCODE_UNDEFINED_COLUMN),
5570 errmsg("column \"%s\" of relation \"%s\" does not exist",
5571 colName, RelationGetRelationName(rel))));
5572 attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
5573 attnum = attTup->attnum;
5575 /* Check for multiple ALTER TYPE on same column --- can't cope */
5576 if (attTup->atttypid != tab->oldDesc->attrs[attnum - 1]->atttypid ||
5577 attTup->atttypmod != tab->oldDesc->attrs[attnum - 1]->atttypmod)
5579 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5580 errmsg("cannot alter type of column \"%s\" twice",
5583 /* Look up the target type (should not fail, since prep found it) */
5584 typeTuple = typenameType(NULL, typename, &targettypmod);
5585 tform = (Form_pg_type) GETSTRUCT(typeTuple);
5586 targettype = HeapTupleGetOid(typeTuple);
5589 * If there is a default expression for the column, get it and ensure we
5590 * can coerce it to the new datatype. (We must do this before changing
5591 * the column type, because build_column_default itself will try to
5592 * coerce, and will not issue the error message we want if it fails.)
5594 * We remove any implicit coercion steps at the top level of the old
5595 * default expression; this has been agreed to satisfy the principle of
5596 * least surprise. (The conversion to the new column type should act like
5597 * it started from what the user sees as the stored expression, and the
5598 * implicit coercions aren't going to be shown.)
5600 if (attTup->atthasdef)
5602 defaultexpr = build_column_default(rel, attnum);
5603 Assert(defaultexpr);
5604 defaultexpr = strip_implicit_coercions(defaultexpr);
5605 defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
5606 defaultexpr, exprType(defaultexpr),
5607 targettype, targettypmod,
5608 COERCION_ASSIGNMENT,
5609 COERCE_IMPLICIT_CAST);
5610 if (defaultexpr == NULL)
5612 (errcode(ERRCODE_DATATYPE_MISMATCH),
5613 errmsg("default for column \"%s\" cannot be cast to type \"%s\"",
5614 colName, TypeNameToString(typename))));
5620 * Find everything that depends on the column (constraints, indexes, etc),
5621 * and record enough information to let us recreate the objects.
5623 * The actual recreation does not happen here, but only after we have
5624 * performed all the individual ALTER TYPE operations. We have to save
5625 * the info before executing ALTER TYPE, though, else the deparser will
5628 * There could be multiple entries for the same object, so we must check
5629 * to ensure we process each one only once. Note: we assume that an index
5630 * that implements a constraint will not show a direct dependency on the
5633 depRel = heap_open(DependRelationId, RowExclusiveLock);
5635 ScanKeyInit(&key[0],
5636 Anum_pg_depend_refclassid,
5637 BTEqualStrategyNumber, F_OIDEQ,
5638 ObjectIdGetDatum(RelationRelationId));
5639 ScanKeyInit(&key[1],
5640 Anum_pg_depend_refobjid,
5641 BTEqualStrategyNumber, F_OIDEQ,
5642 ObjectIdGetDatum(RelationGetRelid(rel)));
5643 ScanKeyInit(&key[2],
5644 Anum_pg_depend_refobjsubid,
5645 BTEqualStrategyNumber, F_INT4EQ,
5646 Int32GetDatum((int32) attnum));
5648 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
5649 SnapshotNow, 3, key);
5651 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5653 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5654 ObjectAddress foundObject;
5656 /* We don't expect any PIN dependencies on columns */
5657 if (foundDep->deptype == DEPENDENCY_PIN)
5658 elog(ERROR, "cannot alter type of a pinned column");
5660 foundObject.classId = foundDep->classid;
5661 foundObject.objectId = foundDep->objid;
5662 foundObject.objectSubId = foundDep->objsubid;
5664 switch (getObjectClass(&foundObject))
5668 char relKind = get_rel_relkind(foundObject.objectId);
5670 if (relKind == RELKIND_INDEX)
5672 Assert(foundObject.objectSubId == 0);
5673 if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
5675 tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
5676 foundObject.objectId);
5677 tab->changedIndexDefs = lappend(tab->changedIndexDefs,
5678 pg_get_indexdef_string(foundObject.objectId));
5681 else if (relKind == RELKIND_SEQUENCE)
5684 * This must be a SERIAL column's sequence. We need
5685 * not do anything to it.
5687 Assert(foundObject.objectSubId == 0);
5691 /* Not expecting any other direct dependencies... */
5692 elog(ERROR, "unexpected object depending on column: %s",
5693 getObjectDescription(&foundObject));
5698 case OCLASS_CONSTRAINT:
5699 Assert(foundObject.objectSubId == 0);
5700 if (!list_member_oid(tab->changedConstraintOids,
5701 foundObject.objectId))
5703 char *defstring = pg_get_constraintdef_string(foundObject.objectId);
5706 * Put NORMAL dependencies at the front of the list and
5707 * AUTO dependencies at the back. This makes sure that
5708 * foreign-key constraints depending on this column will
5709 * be dropped before unique or primary-key constraints of
5710 * the column; which we must have because the FK
5711 * constraints depend on the indexes belonging to the
5712 * unique constraints.
5714 if (foundDep->deptype == DEPENDENCY_NORMAL)
5716 tab->changedConstraintOids =
5717 lcons_oid(foundObject.objectId,
5718 tab->changedConstraintOids);
5719 tab->changedConstraintDefs =
5721 tab->changedConstraintDefs);
5725 tab->changedConstraintOids =
5726 lappend_oid(tab->changedConstraintOids,
5727 foundObject.objectId);
5728 tab->changedConstraintDefs =
5729 lappend(tab->changedConstraintDefs,
5735 case OCLASS_REWRITE:
5736 /* XXX someday see if we can cope with revising views */
5738 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5739 errmsg("cannot alter type of a column used by a view or rule"),
5740 errdetail("%s depends on column \"%s\"",
5741 getObjectDescription(&foundObject),
5745 case OCLASS_DEFAULT:
5748 * Ignore the column's default expression, since we will fix
5751 Assert(defaultexpr);
5757 case OCLASS_CONVERSION:
5758 case OCLASS_LANGUAGE:
5759 case OCLASS_OPERATOR:
5760 case OCLASS_OPCLASS:
5761 case OCLASS_OPFAMILY:
5762 case OCLASS_TRIGGER:
5764 case OCLASS_TSPARSER:
5766 case OCLASS_TSTEMPLATE:
5767 case OCLASS_TSCONFIG:
5770 * We don't expect any of these sorts of objects to depend on
5773 elog(ERROR, "unexpected object depending on column: %s",
5774 getObjectDescription(&foundObject));
5778 elog(ERROR, "unrecognized object class: %u",
5779 foundObject.classId);
5783 systable_endscan(scan);
5786 * Now scan for dependencies of this column on other things. The only
5787 * thing we should find is the dependency on the column datatype, which we
5790 ScanKeyInit(&key[0],
5791 Anum_pg_depend_classid,
5792 BTEqualStrategyNumber, F_OIDEQ,
5793 ObjectIdGetDatum(RelationRelationId));
5794 ScanKeyInit(&key[1],
5795 Anum_pg_depend_objid,
5796 BTEqualStrategyNumber, F_OIDEQ,
5797 ObjectIdGetDatum(RelationGetRelid(rel)));
5798 ScanKeyInit(&key[2],
5799 Anum_pg_depend_objsubid,
5800 BTEqualStrategyNumber, F_INT4EQ,
5801 Int32GetDatum((int32) attnum));
5803 scan = systable_beginscan(depRel, DependDependerIndexId, true,
5804 SnapshotNow, 3, key);
5806 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5808 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5810 if (foundDep->deptype != DEPENDENCY_NORMAL)
5811 elog(ERROR, "found unexpected dependency type '%c'",
5813 if (foundDep->refclassid != TypeRelationId ||
5814 foundDep->refobjid != attTup->atttypid)
5815 elog(ERROR, "found unexpected dependency for column");
5817 simple_heap_delete(depRel, &depTup->t_self);
5820 systable_endscan(scan);
5822 heap_close(depRel, RowExclusiveLock);
5825 * Here we go --- change the recorded column type. (Note heapTup is a
5826 * copy of the syscache entry, so okay to scribble on.)
5828 attTup->atttypid = targettype;
5829 attTup->atttypmod = targettypmod;
5830 attTup->attndims = list_length(typename->arrayBounds);
5831 attTup->attlen = tform->typlen;
5832 attTup->attbyval = tform->typbyval;
5833 attTup->attalign = tform->typalign;
5834 attTup->attstorage = tform->typstorage;
5836 ReleaseSysCache(typeTuple);
5838 simple_heap_update(attrelation, &heapTup->t_self, heapTup);
5840 /* keep system catalog indexes current */
5841 CatalogUpdateIndexes(attrelation, heapTup);
5843 heap_close(attrelation, RowExclusiveLock);
5845 /* Install dependency on new datatype */
5846 add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
5849 * Drop any pg_statistic entry for the column, since it's now wrong type
5851 RemoveStatistics(RelationGetRelid(rel), attnum);
5854 * Update the default, if present, by brute force --- remove and re-add
5855 * the default. Probably unsafe to take shortcuts, since the new version
5856 * may well have additional dependencies. (It's okay to do this now,
5857 * rather than after other ALTER TYPE commands, since the default won't
5858 * depend on other column types.)
5862 /* Must make new row visible since it will be updated again */
5863 CommandCounterIncrement();
5866 * We use RESTRICT here for safety, but at present we do not expect
5867 * anything to depend on the default.
5869 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true);
5871 StoreAttrDefault(rel, attnum, defaultexpr);
5875 heap_freetuple(heapTup);
5879 * Cleanup after we've finished all the ALTER TYPE operations for a
5880 * particular relation. We have to drop and recreate all the indexes
5881 * and constraints that depend on the altered columns.
5884 ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab)
5890 * Re-parse the index and constraint definitions, and attach them to the
5891 * appropriate work queue entries. We do this before dropping because in
5892 * the case of a FOREIGN KEY constraint, we might not yet have exclusive
5893 * lock on the table the constraint is attached to, and we need to get
5894 * that before dropping. It's safe because the parser won't actually look
5895 * at the catalogs to detect the existing entry.
5897 foreach(l, tab->changedIndexDefs)
5898 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
5899 foreach(l, tab->changedConstraintDefs)
5900 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
5903 * Now we can drop the existing constraints and indexes --- constraints
5904 * first, since some of them might depend on the indexes. In fact, we
5905 * have to delete FOREIGN KEY constraints before UNIQUE constraints, but
5906 * we already ordered the constraint list to ensure that would happen. It
5907 * should be okay to use DROP_RESTRICT here, since nothing else should be
5908 * depending on these objects.
5910 foreach(l, tab->changedConstraintOids)
5912 obj.classId = ConstraintRelationId;
5913 obj.objectId = lfirst_oid(l);
5914 obj.objectSubId = 0;
5915 performDeletion(&obj, DROP_RESTRICT);
5918 foreach(l, tab->changedIndexOids)
5920 obj.classId = RelationRelationId;
5921 obj.objectId = lfirst_oid(l);
5922 obj.objectSubId = 0;
5923 performDeletion(&obj, DROP_RESTRICT);
5927 * The objects will get recreated during subsequent passes over the work
5933 ATPostAlterTypeParse(char *cmd, List **wqueue)
5935 List *raw_parsetree_list;
5936 List *querytree_list;
5937 ListCell *list_item;
5940 * We expect that we will get only ALTER TABLE and CREATE INDEX
5941 * statements. Hence, there is no need to pass them through
5942 * parse_analyze() or the rewriter, but instead we need to pass them
5943 * through parse_utilcmd.c to make them ready for execution.
5945 raw_parsetree_list = raw_parser(cmd);
5946 querytree_list = NIL;
5947 foreach(list_item, raw_parsetree_list)
5949 Node *stmt = (Node *) lfirst(list_item);
5951 if (IsA(stmt, IndexStmt))
5952 querytree_list = lappend(querytree_list,
5953 transformIndexStmt((IndexStmt *) stmt,
5955 else if (IsA(stmt, AlterTableStmt))
5956 querytree_list = list_concat(querytree_list,
5957 transformAlterTableStmt((AlterTableStmt *) stmt,
5960 querytree_list = lappend(querytree_list, stmt);
5964 * Attach each generated command to the proper place in the work queue.
5965 * Note this could result in creation of entirely new work-queue entries.
5967 foreach(list_item, querytree_list)
5969 Node *stm = (Node *) lfirst(list_item);
5971 AlteredTableInfo *tab;
5973 switch (nodeTag(stm))
5977 IndexStmt *stmt = (IndexStmt *) stm;
5978 AlterTableCmd *newcmd;
5980 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
5981 tab = ATGetQueueEntry(wqueue, rel);
5982 newcmd = makeNode(AlterTableCmd);
5983 newcmd->subtype = AT_ReAddIndex;
5984 newcmd->def = (Node *) stmt;
5985 tab->subcmds[AT_PASS_OLD_INDEX] =
5986 lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
5987 relation_close(rel, NoLock);
5990 case T_AlterTableStmt:
5992 AlterTableStmt *stmt = (AlterTableStmt *) stm;
5995 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
5996 tab = ATGetQueueEntry(wqueue, rel);
5997 foreach(lcmd, stmt->cmds)
5999 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
6001 switch (cmd->subtype)
6004 cmd->subtype = AT_ReAddIndex;
6005 tab->subcmds[AT_PASS_OLD_INDEX] =
6006 lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
6008 case AT_AddConstraint:
6009 tab->subcmds[AT_PASS_OLD_CONSTR] =
6010 lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
6013 elog(ERROR, "unexpected statement type: %d",
6014 (int) cmd->subtype);
6017 relation_close(rel, NoLock);
6021 elog(ERROR, "unexpected statement type: %d",
6022 (int) nodeTag(stm));
6031 * recursing is true if we are recursing from a table to its indexes,
6032 * sequences, or toast table. We don't allow the ownership of those things to
6033 * be changed separately from the parent table. Also, we can skip permission
6034 * checks (this is necessary not just an optimization, else we'd fail to
6035 * handle toast tables properly).
6037 * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
6038 * free-standing composite type.
6041 ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing)
6043 Relation target_rel;
6046 Form_pg_class tuple_class;
6049 * Get exclusive lock till end of transaction on the target table. Use
6050 * relation_open so that we can work on indexes and sequences.
6052 target_rel = relation_open(relationOid, AccessExclusiveLock);
6054 /* Get its pg_class tuple, too */
6055 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
6057 tuple = SearchSysCache(RELOID,
6058 ObjectIdGetDatum(relationOid),
6060 if (!HeapTupleIsValid(tuple))
6061 elog(ERROR, "cache lookup failed for relation %u", relationOid);
6062 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
6064 /* Can we change the ownership of this tuple? */
6065 switch (tuple_class->relkind)
6067 case RELKIND_RELATION:
6069 /* ok to change owner */
6075 * Because ALTER INDEX OWNER used to be allowed, and in fact
6076 * is generated by old versions of pg_dump, we give a warning
6077 * and do nothing rather than erroring out. Also, to avoid
6078 * unnecessary chatter while restoring those old dumps, say
6079 * nothing at all if the command would be a no-op anyway.
6081 if (tuple_class->relowner != newOwnerId)
6083 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6084 errmsg("cannot change owner of index \"%s\"",
6085 NameStr(tuple_class->relname)),
6086 errhint("Change the ownership of the index's table, instead.")));
6087 /* quick hack to exit via the no-op path */
6088 newOwnerId = tuple_class->relowner;
6091 case RELKIND_SEQUENCE:
6093 tuple_class->relowner != newOwnerId)
6095 /* if it's an owned sequence, disallow changing it by itself */
6099 if (sequenceIsOwned(relationOid, &tableId, &colId))
6101 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6102 errmsg("cannot change owner of sequence \"%s\"",
6103 NameStr(tuple_class->relname)),
6104 errdetail("Sequence \"%s\" is linked to table \"%s\".",
6105 NameStr(tuple_class->relname),
6106 get_rel_name(tableId))));
6109 case RELKIND_COMPOSITE_TYPE:
6113 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6114 errmsg("\"%s\" is a composite type",
6115 NameStr(tuple_class->relname)),
6116 errhint("Use ALTER TYPE instead.")));
6118 case RELKIND_TOASTVALUE:
6124 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6125 errmsg("\"%s\" is not a table, view, or sequence",
6126 NameStr(tuple_class->relname))));
6130 * If the new owner is the same as the existing owner, consider the
6131 * command to have succeeded. This is for dump restoration purposes.
6133 if (tuple_class->relowner != newOwnerId)
6135 Datum repl_val[Natts_pg_class];
6136 char repl_null[Natts_pg_class];
6137 char repl_repl[Natts_pg_class];
6143 /* skip permission checks when recursing to index or toast table */
6146 /* Superusers can always do it */
6149 Oid namespaceOid = tuple_class->relnamespace;
6150 AclResult aclresult;
6152 /* Otherwise, must be owner of the existing object */
6153 if (!pg_class_ownercheck(relationOid, GetUserId()))
6154 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
6155 RelationGetRelationName(target_rel));
6157 /* Must be able to become new owner */
6158 check_is_member_of_role(GetUserId(), newOwnerId);
6160 /* New owner must have CREATE privilege on namespace */
6161 aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
6163 if (aclresult != ACLCHECK_OK)
6164 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
6165 get_namespace_name(namespaceOid));
6169 memset(repl_null, ' ', sizeof(repl_null));
6170 memset(repl_repl, ' ', sizeof(repl_repl));
6172 repl_repl[Anum_pg_class_relowner - 1] = 'r';
6173 repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
6176 * Determine the modified ACL for the new owner. This is only
6177 * necessary when the ACL is non-null.
6179 aclDatum = SysCacheGetAttr(RELOID, tuple,
6180 Anum_pg_class_relacl,
6184 newAcl = aclnewowner(DatumGetAclP(aclDatum),
6185 tuple_class->relowner, newOwnerId);
6186 repl_repl[Anum_pg_class_relacl - 1] = 'r';
6187 repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
6190 newtuple = heap_modifytuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
6192 simple_heap_update(class_rel, &newtuple->t_self, newtuple);
6193 CatalogUpdateIndexes(class_rel, newtuple);
6195 heap_freetuple(newtuple);
6198 * Update owner dependency reference, if any. A composite type has
6199 * none, because it's tracked for the pg_type entry instead of here;
6200 * indexes and TOAST tables don't have their own entries either.
6202 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
6203 tuple_class->relkind != RELKIND_INDEX &&
6204 tuple_class->relkind != RELKIND_TOASTVALUE)
6205 changeDependencyOnOwner(RelationRelationId, relationOid,
6209 * Also change the ownership of the table's rowtype, if it has one
6211 if (tuple_class->relkind != RELKIND_INDEX)
6212 AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId,
6213 tuple_class->relkind == RELKIND_COMPOSITE_TYPE);
6216 * If we are operating on a table, also change the ownership of any
6217 * indexes and sequences that belong to the table, as well as the
6218 * table's toast table (if it has one)
6220 if (tuple_class->relkind == RELKIND_RELATION ||
6221 tuple_class->relkind == RELKIND_TOASTVALUE)
6223 List *index_oid_list;
6226 /* Find all the indexes belonging to this relation */
6227 index_oid_list = RelationGetIndexList(target_rel);
6229 /* For each index, recursively change its ownership */
6230 foreach(i, index_oid_list)
6231 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true);
6233 list_free(index_oid_list);
6236 if (tuple_class->relkind == RELKIND_RELATION)
6238 /* If it has a toast table, recurse to change its ownership */
6239 if (tuple_class->reltoastrelid != InvalidOid)
6240 ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
6243 /* If it has dependent sequences, recurse to change them too */
6244 change_owner_recurse_to_sequences(relationOid, newOwnerId);
6248 ReleaseSysCache(tuple);
6249 heap_close(class_rel, RowExclusiveLock);
6250 relation_close(target_rel, NoLock);
6254 * change_owner_recurse_to_sequences
6256 * Helper function for ATExecChangeOwner. Examines pg_depend searching
6257 * for sequences that are dependent on serial columns, and changes their
6261 change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId)
6269 * SERIAL sequences are those having an auto dependency on one of the
6270 * table's columns (we don't care *which* column, exactly).
6272 depRel = heap_open(DependRelationId, AccessShareLock);
6274 ScanKeyInit(&key[0],
6275 Anum_pg_depend_refclassid,
6276 BTEqualStrategyNumber, F_OIDEQ,
6277 ObjectIdGetDatum(RelationRelationId));
6278 ScanKeyInit(&key[1],
6279 Anum_pg_depend_refobjid,
6280 BTEqualStrategyNumber, F_OIDEQ,
6281 ObjectIdGetDatum(relationOid));
6282 /* we leave refobjsubid unspecified */
6284 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
6285 SnapshotNow, 2, key);
6287 while (HeapTupleIsValid(tup = systable_getnext(scan)))
6289 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
6292 /* skip dependencies other than auto dependencies on columns */
6293 if (depForm->refobjsubid == 0 ||
6294 depForm->classid != RelationRelationId ||
6295 depForm->objsubid != 0 ||
6296 depForm->deptype != DEPENDENCY_AUTO)
6299 /* Use relation_open just in case it's an index */
6300 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
6302 /* skip non-sequence relations */
6303 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
6305 /* No need to keep the lock */
6306 relation_close(seqRel, AccessExclusiveLock);
6310 /* We don't need to close the sequence while we alter it. */
6311 ATExecChangeOwner(depForm->objid, newOwnerId, true);
6313 /* Now we can close it. Keep the lock till end of transaction. */
6314 relation_close(seqRel, NoLock);
6317 systable_endscan(scan);
6319 relation_close(depRel, AccessShareLock);
6323 * ALTER TABLE CLUSTER ON
6325 * The only thing we have to do is to change the indisclustered bits.
6328 ATExecClusterOn(Relation rel, const char *indexName)
6332 indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
6334 if (!OidIsValid(indexOid))
6336 (errcode(ERRCODE_UNDEFINED_OBJECT),
6337 errmsg("index \"%s\" for table \"%s\" does not exist",
6338 indexName, RelationGetRelationName(rel))));
6340 /* Check index is valid to cluster on */
6341 check_index_is_clusterable(rel, indexOid, false);
6343 /* And do the work */
6344 mark_index_clustered(rel, indexOid);
6348 * ALTER TABLE SET WITHOUT CLUSTER
6350 * We have to find any indexes on the table that have indisclustered bit
6351 * set and turn it off.
6354 ATExecDropCluster(Relation rel)
6356 mark_index_clustered(rel, InvalidOid);
6360 * ALTER TABLE SET TABLESPACE
6363 ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, char *tablespacename)
6366 AclResult aclresult;
6368 /* Check that the tablespace exists */
6369 tablespaceId = get_tablespace_oid(tablespacename);
6370 if (!OidIsValid(tablespaceId))
6372 (errcode(ERRCODE_UNDEFINED_OBJECT),
6373 errmsg("tablespace \"%s\" does not exist", tablespacename)));
6375 /* Check its permissions */
6376 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(), ACL_CREATE);
6377 if (aclresult != ACLCHECK_OK)
6378 aclcheck_error(aclresult, ACL_KIND_TABLESPACE, tablespacename);
6380 /* Save info for Phase 3 to do the real work */
6381 if (OidIsValid(tab->newTableSpace))
6383 (errcode(ERRCODE_SYNTAX_ERROR),
6384 errmsg("cannot have multiple SET TABLESPACE subcommands")));
6385 tab->newTableSpace = tablespaceId;
6389 * ALTER TABLE/INDEX SET (...) or RESET (...)
6392 ATExecSetRelOptions(Relation rel, List *defList, bool isReset)
6401 Datum repl_val[Natts_pg_class];
6402 char repl_null[Natts_pg_class];
6403 char repl_repl[Natts_pg_class];
6406 return; /* nothing to do */
6408 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
6410 /* Get the old reloptions */
6411 relid = RelationGetRelid(rel);
6412 tuple = SearchSysCache(RELOID,
6413 ObjectIdGetDatum(relid),
6415 if (!HeapTupleIsValid(tuple))
6416 elog(ERROR, "cache lookup failed for relation %u", relid);
6418 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions, &isnull);
6420 /* Generate new proposed reloptions (text array) */
6421 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
6422 defList, false, isReset);
6425 switch (rel->rd_rel->relkind)
6427 case RELKIND_RELATION:
6428 case RELKIND_TOASTVALUE:
6429 (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
6432 (void) index_reloptions(rel->rd_am->amoptions, newOptions, true);
6436 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6437 errmsg("\"%s\" is not a table, index, or TOAST table",
6438 RelationGetRelationName(rel))));
6443 * All we need do here is update the pg_class row; the new options will be
6444 * propagated into relcaches during post-commit cache inval.
6446 memset(repl_val, 0, sizeof(repl_val));
6447 memset(repl_null, ' ', sizeof(repl_null));
6448 memset(repl_repl, ' ', sizeof(repl_repl));
6450 if (newOptions != (Datum) 0)
6451 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
6453 repl_null[Anum_pg_class_reloptions - 1] = 'n';
6455 repl_repl[Anum_pg_class_reloptions - 1] = 'r';
6457 newtuple = heap_modifytuple(tuple, RelationGetDescr(pgclass),
6458 repl_val, repl_null, repl_repl);
6460 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
6462 CatalogUpdateIndexes(pgclass, newtuple);
6464 heap_freetuple(newtuple);
6466 ReleaseSysCache(tuple);
6468 heap_close(pgclass, RowExclusiveLock);
6472 * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
6473 * rewriting to be done, so we just want to copy the data as fast as possible.
6476 ATExecSetTableSpace(Oid tableOid, Oid newTableSpace)
6482 RelFileNode newrnode;
6483 SMgrRelation dstrel;
6486 Form_pg_class rd_rel;
6490 * Need lock here in case we are recursing to toast table or index
6492 rel = relation_open(tableOid, AccessExclusiveLock);
6495 * We can never allow moving of shared or nailed-in-cache relations,
6496 * because we can't support changing their reltablespace values.
6498 if (rel->rd_rel->relisshared || rel->rd_isnailed)
6500 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6501 errmsg("cannot move system relation \"%s\"",
6502 RelationGetRelationName(rel))));
6504 /* Can't move a non-shared relation into pg_global */
6505 if (newTableSpace == GLOBALTABLESPACE_OID)
6507 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6508 errmsg("only shared relations can be placed in pg_global tablespace")));
6511 * Don't allow moving temp tables of other backends ... their local buffer
6512 * manager is not going to cope.
6514 if (isOtherTempNamespace(RelationGetNamespace(rel)))
6516 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6517 errmsg("cannot move temporary tables of other sessions")));
6520 * No work if no change in tablespace.
6522 oldTableSpace = rel->rd_rel->reltablespace;
6523 if (newTableSpace == oldTableSpace ||
6524 (newTableSpace == MyDatabaseTableSpace && oldTableSpace == 0))
6526 relation_close(rel, NoLock);
6530 reltoastrelid = rel->rd_rel->reltoastrelid;
6531 reltoastidxid = rel->rd_rel->reltoastidxid;
6533 /* Get a modifiable copy of the relation's pg_class row */
6534 pg_class = heap_open(RelationRelationId, RowExclusiveLock);
6536 tuple = SearchSysCacheCopy(RELOID,
6537 ObjectIdGetDatum(tableOid),
6539 if (!HeapTupleIsValid(tuple))
6540 elog(ERROR, "cache lookup failed for relation %u", tableOid);
6541 rd_rel = (Form_pg_class) GETSTRUCT(tuple);
6544 * Since we copy the file directly without looking at the shared buffers,
6545 * we'd better first flush out any pages of the source relation that are
6546 * in shared buffers. We assume no new changes will be made while we are
6547 * holding exclusive lock on the rel.
6549 FlushRelationBuffers(rel);
6551 /* Open old and new relation */
6552 newrnode = rel->rd_node;
6553 newrnode.spcNode = newTableSpace;
6554 dstrel = smgropen(newrnode);
6556 RelationOpenSmgr(rel);
6559 * Create and copy all forks of the relation, and schedule unlinking
6560 * of old physical files.
6562 * NOTE: any conflict in relfilenode value will be caught in
6563 * smgrcreate() below.
6565 for (forkNum = 0; forkNum <= MAX_FORKNUM; forkNum++)
6567 if (smgrexists(rel->rd_smgr, forkNum))
6569 smgrcreate(dstrel, forkNum, rel->rd_istemp, false);
6570 copy_relation_data(rel->rd_smgr, dstrel, forkNum, rel->rd_istemp);
6572 smgrscheduleunlink(rel->rd_smgr, forkNum, rel->rd_istemp);
6576 /* Close old and new relation */
6578 RelationCloseSmgr(rel);
6580 /* update the pg_class row */
6581 rd_rel->reltablespace = (newTableSpace == MyDatabaseTableSpace) ? InvalidOid : newTableSpace;
6582 simple_heap_update(pg_class, &tuple->t_self, tuple);
6583 CatalogUpdateIndexes(pg_class, tuple);
6585 heap_freetuple(tuple);
6587 heap_close(pg_class, RowExclusiveLock);
6589 relation_close(rel, NoLock);
6591 /* Make sure the reltablespace change is visible */
6592 CommandCounterIncrement();
6594 /* Move associated toast relation and/or index, too */
6595 if (OidIsValid(reltoastrelid))
6596 ATExecSetTableSpace(reltoastrelid, newTableSpace);
6597 if (OidIsValid(reltoastidxid))
6598 ATExecSetTableSpace(reltoastidxid, newTableSpace);
6602 * Copy data, block by block
6605 copy_relation_data(SMgrRelation src, SMgrRelation dst,
6606 ForkNumber forkNum, bool istemp)
6609 BlockNumber nblocks;
6612 Page page = (Page) buf;
6615 * We need to log the copied data in WAL iff WAL archiving is enabled AND
6616 * it's not a temp rel.
6618 use_wal = XLogArchivingActive() && !istemp;
6620 nblocks = smgrnblocks(src, forkNum);
6622 for (blkno = 0; blkno < nblocks; blkno++)
6624 smgrread(src, forkNum, blkno, buf);
6628 log_newpage(&dst->smgr_rnode, forkNum, blkno, page);
6631 * Now write the page. We say isTemp = true even if it's not a temp
6632 * rel, because there's no need for smgr to schedule an fsync for this
6633 * write; we'll do it ourselves below.
6635 smgrextend(dst, forkNum, blkno, buf, true);
6639 * If the rel isn't temp, we must fsync it down to disk before it's safe
6640 * to commit the transaction. (For a temp rel we don't care since the rel
6641 * will be uninteresting after a crash anyway.)
6643 * It's obvious that we must do this when not WAL-logging the copy. It's
6644 * less obvious that we have to do it even if we did WAL-log the copied
6645 * pages. The reason is that since we're copying outside shared buffers, a
6646 * CHECKPOINT occurring during the copy has no way to flush the previously
6647 * written data to disk (indeed it won't know the new rel even exists). A
6648 * crash later on would replay WAL from the checkpoint, therefore it
6649 * wouldn't replay our earlier WAL entries. If we do not fsync those pages
6650 * here, they might still not be on disk when the crash occurs.
6653 smgrimmedsync(dst, forkNum);
6657 * ALTER TABLE ENABLE/DISABLE TRIGGER
6659 * We just pass this off to trigger.c.
6662 ATExecEnableDisableTrigger(Relation rel, char *trigname,
6663 char fires_when, bool skip_system)
6665 EnableDisableTrigger(rel, trigname, fires_when, skip_system);
6669 * ALTER TABLE ENABLE/DISABLE RULE
6671 * We just pass this off to rewriteDefine.c.
6674 ATExecEnableDisableRule(Relation rel, char *trigname,
6677 EnableDisableRule(rel, trigname, fires_when);
6681 * ALTER TABLE INHERIT
6683 * Add a parent to the child's parents. This verifies that all the columns and
6684 * check constraints of the parent appear in the child and that they have the
6685 * same data types and expressions.
6688 ATExecAddInherit(Relation child_rel, RangeVar *parent)
6690 Relation parent_rel,
6694 HeapTuple inheritsTuple;
6699 * AccessShareLock on the parent is what's obtained during normal CREATE
6700 * TABLE ... INHERITS ..., so should be enough here.
6702 parent_rel = heap_openrv(parent, AccessShareLock);
6705 * Must be owner of both parent and child -- child was checked by
6706 * ATSimplePermissions call in ATPrepCmd
6708 ATSimplePermissions(parent_rel, false);
6710 /* Permanent rels cannot inherit from temporary ones */
6711 if (!isTempNamespace(RelationGetNamespace(child_rel)) &&
6712 isTempNamespace(RelationGetNamespace(parent_rel)))
6714 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6715 errmsg("cannot inherit from temporary relation \"%s\"",
6716 RelationGetRelationName(parent_rel))));
6719 * Check for duplicates in the list of parents, and determine the highest
6720 * inhseqno already present; we'll use the next one for the new parent.
6721 * (Note: get RowExclusiveLock because we will write pg_inherits below.)
6723 * Note: we do not reject the case where the child already inherits from
6724 * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
6726 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
6728 Anum_pg_inherits_inhrelid,
6729 BTEqualStrategyNumber, F_OIDEQ,
6730 ObjectIdGetDatum(RelationGetRelid(child_rel)));
6731 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
6732 true, SnapshotNow, 1, &key);
6734 /* inhseqno sequences start at 1 */
6736 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
6738 Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
6740 if (inh->inhparent == RelationGetRelid(parent_rel))
6742 (errcode(ERRCODE_DUPLICATE_TABLE),
6743 errmsg("relation \"%s\" would be inherited from more than once",
6744 RelationGetRelationName(parent_rel))));
6745 if (inh->inhseqno > inhseqno)
6746 inhseqno = inh->inhseqno;
6748 systable_endscan(scan);
6751 * Prevent circularity by seeing if proposed parent inherits from child.
6752 * (In particular, this disallows making a rel inherit from itself.)
6754 * This is not completely bulletproof because of race conditions: in
6755 * multi-level inheritance trees, someone else could concurrently be
6756 * making another inheritance link that closes the loop but does not join
6757 * either of the rels we have locked. Preventing that seems to require
6758 * exclusive locks on the entire inheritance tree, which is a cure worse
6759 * than the disease. find_all_inheritors() will cope with circularity
6760 * anyway, so don't sweat it too much.
6762 children = find_all_inheritors(RelationGetRelid(child_rel));
6764 if (list_member_oid(children, RelationGetRelid(parent_rel)))
6766 (errcode(ERRCODE_DUPLICATE_TABLE),
6767 errmsg("circular inheritance not allowed"),
6768 errdetail("\"%s\" is already a child of \"%s\".",
6770 RelationGetRelationName(child_rel))));
6772 /* If parent has OIDs then child must have OIDs */
6773 if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
6775 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6776 errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
6777 RelationGetRelationName(child_rel),
6778 RelationGetRelationName(parent_rel))));
6780 /* Match up the columns and bump attinhcount as needed */
6781 MergeAttributesIntoExisting(child_rel, parent_rel);
6783 /* Match up the constraints and bump coninhcount as needed */
6784 MergeConstraintsIntoExisting(child_rel, parent_rel);
6787 * OK, it looks valid. Make the catalog entries that show inheritance.
6789 StoreCatalogInheritance1(RelationGetRelid(child_rel),
6790 RelationGetRelid(parent_rel),
6794 /* Now we're done with pg_inherits */
6795 heap_close(catalogRelation, RowExclusiveLock);
6797 /* keep our lock on the parent relation until commit */
6798 heap_close(parent_rel, NoLock);
6802 * Obtain the source-text form of the constraint expression for a check
6803 * constraint, given its pg_constraint tuple
6806 decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
6808 Form_pg_constraint con;
6813 con = (Form_pg_constraint) GETSTRUCT(contup);
6814 attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
6816 elog(ERROR, "null conbin for constraint %u", HeapTupleGetOid(contup));
6818 expr = DirectFunctionCall2(pg_get_expr, attr,
6819 ObjectIdGetDatum(con->conrelid));
6820 return TextDatumGetCString(expr);
6824 * Determine whether two check constraints are functionally equivalent
6826 * The test we apply is to see whether they reverse-compile to the same
6827 * source string. This insulates us from issues like whether attributes
6828 * have the same physical column numbers in parent and child relations.
6831 constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
6833 Form_pg_constraint acon = (Form_pg_constraint) GETSTRUCT(a);
6834 Form_pg_constraint bcon = (Form_pg_constraint) GETSTRUCT(b);
6836 if (acon->condeferrable != bcon->condeferrable ||
6837 acon->condeferred != bcon->condeferred ||
6838 strcmp(decompile_conbin(a, tupleDesc),
6839 decompile_conbin(b, tupleDesc)) != 0)
6846 * Check columns in child table match up with columns in parent, and increment
6847 * their attinhcount.
6849 * Called by ATExecAddInherit
6851 * Currently all parent columns must be found in child. Missing columns are an
6852 * error. One day we might consider creating new columns like CREATE TABLE
6853 * does. However, that is widely unpopular --- in the common use case of
6854 * partitioned tables it's a foot-gun.
6856 * The data type must match exactly. If the parent column is NOT NULL then
6857 * the child must be as well. Defaults are not compared, however.
6860 MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel)
6863 AttrNumber parent_attno;
6865 TupleDesc tupleDesc;
6866 TupleConstr *constr;
6869 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
6871 tupleDesc = RelationGetDescr(parent_rel);
6872 parent_natts = tupleDesc->natts;
6873 constr = tupleDesc->constr;
6875 for (parent_attno = 1; parent_attno <= parent_natts; parent_attno++)
6877 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
6878 char *attributeName = NameStr(attribute->attname);
6880 /* Ignore dropped columns in the parent. */
6881 if (attribute->attisdropped)
6884 /* Find same column in child (matching on column name). */
6885 tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel),
6887 if (HeapTupleIsValid(tuple))
6889 /* Check they are same type and typmod */
6890 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
6892 if (attribute->atttypid != childatt->atttypid ||
6893 attribute->atttypmod != childatt->atttypmod)
6895 (errcode(ERRCODE_DATATYPE_MISMATCH),
6896 errmsg("child table \"%s\" has different type for column \"%s\"",
6897 RelationGetRelationName(child_rel),
6900 if (attribute->attnotnull && !childatt->attnotnull)
6902 (errcode(ERRCODE_DATATYPE_MISMATCH),
6903 errmsg("column \"%s\" in child table must be marked NOT NULL",
6907 * OK, bump the child column's inheritance count. (If we fail
6908 * later on, this change will just roll back.)
6910 childatt->attinhcount++;
6911 simple_heap_update(attrrel, &tuple->t_self, tuple);
6912 CatalogUpdateIndexes(attrrel, tuple);
6913 heap_freetuple(tuple);
6918 (errcode(ERRCODE_DATATYPE_MISMATCH),
6919 errmsg("child table is missing column \"%s\"",
6924 heap_close(attrrel, RowExclusiveLock);
6928 * Check constraints in child table match up with constraints in parent,
6929 * and increment their coninhcount.
6931 * Called by ATExecAddInherit
6933 * Currently all constraints in parent must be present in the child. One day we
6934 * may consider adding new constraints like CREATE TABLE does. We may also want
6935 * to allow an optional flag on parent table constraints indicating they are
6936 * intended to ONLY apply to the master table, not to the children. That would
6937 * make it possible to ensure no records are mistakenly inserted into the
6938 * master in partitioned tables rather than the appropriate child.
6940 * XXX This is O(N^2) which may be an issue with tables with hundreds of
6941 * constraints. As long as tables have more like 10 constraints it shouldn't be
6942 * a problem though. Even 100 constraints ought not be the end of the world.
6945 MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
6947 Relation catalog_relation;
6948 TupleDesc tuple_desc;
6949 SysScanDesc parent_scan;
6950 ScanKeyData parent_key;
6951 HeapTuple parent_tuple;
6953 catalog_relation = heap_open(ConstraintRelationId, RowExclusiveLock);
6954 tuple_desc = RelationGetDescr(catalog_relation);
6956 /* Outer loop scans through the parent's constraint definitions */
6957 ScanKeyInit(&parent_key,
6958 Anum_pg_constraint_conrelid,
6959 BTEqualStrategyNumber, F_OIDEQ,
6960 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
6961 parent_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
6962 true, SnapshotNow, 1, &parent_key);
6964 while (HeapTupleIsValid(parent_tuple = systable_getnext(parent_scan)))
6966 Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(parent_tuple);
6967 SysScanDesc child_scan;
6968 ScanKeyData child_key;
6969 HeapTuple child_tuple;
6972 if (parent_con->contype != CONSTRAINT_CHECK)
6975 /* Search for a child constraint matching this one */
6976 ScanKeyInit(&child_key,
6977 Anum_pg_constraint_conrelid,
6978 BTEqualStrategyNumber, F_OIDEQ,
6979 ObjectIdGetDatum(RelationGetRelid(child_rel)));
6980 child_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
6981 true, SnapshotNow, 1, &child_key);
6983 while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
6985 Form_pg_constraint child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
6986 HeapTuple child_copy;
6988 if (child_con->contype != CONSTRAINT_CHECK)
6991 if (strcmp(NameStr(parent_con->conname),
6992 NameStr(child_con->conname)) != 0)
6995 if (!constraints_equivalent(parent_tuple, child_tuple, tuple_desc))
6997 (errcode(ERRCODE_DATATYPE_MISMATCH),
6998 errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
6999 RelationGetRelationName(child_rel),
7000 NameStr(parent_con->conname))));
7003 * OK, bump the child constraint's inheritance count. (If we fail
7004 * later on, this change will just roll back.)
7006 child_copy = heap_copytuple(child_tuple);
7007 child_con = (Form_pg_constraint) GETSTRUCT(child_copy);
7008 child_con->coninhcount++;
7009 simple_heap_update(catalog_relation, &child_copy->t_self, child_copy);
7010 CatalogUpdateIndexes(catalog_relation, child_copy);
7011 heap_freetuple(child_copy);
7017 systable_endscan(child_scan);
7021 (errcode(ERRCODE_DATATYPE_MISMATCH),
7022 errmsg("child table is missing constraint \"%s\"",
7023 NameStr(parent_con->conname))));
7026 systable_endscan(parent_scan);
7027 heap_close(catalog_relation, RowExclusiveLock);
7031 * ALTER TABLE NO INHERIT
7033 * Drop a parent from the child's parents. This just adjusts the attinhcount
7034 * and attislocal of the columns and removes the pg_inherit and pg_depend
7037 * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
7038 * up attislocal stays true, which means if a child is ever removed from a
7039 * parent then its columns will never be automatically dropped which may
7040 * surprise. But at least we'll never surprise by dropping columns someone
7041 * isn't expecting to be dropped which would actually mean data loss.
7043 * coninhcount and conislocal for inherited constraints are adjusted in
7044 * exactly the same way.
7047 ATExecDropInherit(Relation rel, RangeVar *parent)
7049 Relation parent_rel;
7050 Relation catalogRelation;
7053 HeapTuple inheritsTuple,
7061 * AccessShareLock on the parent is probably enough, seeing that DROP
7062 * TABLE doesn't lock parent tables at all. We need some lock since we'll
7063 * be inspecting the parent's schema.
7065 parent_rel = heap_openrv(parent, AccessShareLock);
7068 * We don't bother to check ownership of the parent table --- ownership of
7069 * the child is presumed enough rights.
7073 * Find and destroy the pg_inherits entry linking the two, or error out if
7076 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
7077 ScanKeyInit(&key[0],
7078 Anum_pg_inherits_inhrelid,
7079 BTEqualStrategyNumber, F_OIDEQ,
7080 ObjectIdGetDatum(RelationGetRelid(rel)));
7081 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
7082 true, SnapshotNow, 1, key);
7084 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
7088 inhparent = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
7089 if (inhparent == RelationGetRelid(parent_rel))
7091 simple_heap_delete(catalogRelation, &inheritsTuple->t_self);
7097 systable_endscan(scan);
7098 heap_close(catalogRelation, RowExclusiveLock);
7102 (errcode(ERRCODE_UNDEFINED_TABLE),
7103 errmsg("relation \"%s\" is not a parent of relation \"%s\"",
7104 RelationGetRelationName(parent_rel),
7105 RelationGetRelationName(rel))));
7108 * Search through child columns looking for ones matching parent rel
7110 catalogRelation = heap_open(AttributeRelationId, RowExclusiveLock);
7111 ScanKeyInit(&key[0],
7112 Anum_pg_attribute_attrelid,
7113 BTEqualStrategyNumber, F_OIDEQ,
7114 ObjectIdGetDatum(RelationGetRelid(rel)));
7115 scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
7116 true, SnapshotNow, 1, key);
7117 while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
7119 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
7121 /* Ignore if dropped or not inherited */
7122 if (att->attisdropped)
7124 if (att->attinhcount <= 0)
7127 if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
7128 NameStr(att->attname)))
7130 /* Decrement inhcount and possibly set islocal to true */
7131 HeapTuple copyTuple = heap_copytuple(attributeTuple);
7132 Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
7134 copy_att->attinhcount--;
7135 if (copy_att->attinhcount == 0)
7136 copy_att->attislocal = true;
7138 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
7139 CatalogUpdateIndexes(catalogRelation, copyTuple);
7140 heap_freetuple(copyTuple);
7143 systable_endscan(scan);
7144 heap_close(catalogRelation, RowExclusiveLock);
7147 * Likewise, find inherited check constraints and disinherit them.
7148 * To do this, we first need a list of the names of the parent's check
7149 * constraints. (We cheat a bit by only checking for name matches,
7150 * assuming that the expressions will match.)
7152 catalogRelation = heap_open(ConstraintRelationId, RowExclusiveLock);
7153 ScanKeyInit(&key[0],
7154 Anum_pg_constraint_conrelid,
7155 BTEqualStrategyNumber, F_OIDEQ,
7156 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
7157 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
7158 true, SnapshotNow, 1, key);
7162 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
7164 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
7166 if (con->contype == CONSTRAINT_CHECK)
7167 connames = lappend(connames, pstrdup(NameStr(con->conname)));
7170 systable_endscan(scan);
7172 /* Now scan the child's constraints */
7173 ScanKeyInit(&key[0],
7174 Anum_pg_constraint_conrelid,
7175 BTEqualStrategyNumber, F_OIDEQ,
7176 ObjectIdGetDatum(RelationGetRelid(rel)));
7177 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
7178 true, SnapshotNow, 1, key);
7180 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
7182 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
7186 if (con->contype != CONSTRAINT_CHECK)
7190 foreach (lc, connames)
7192 if (strcmp(NameStr(con->conname), (char *) lfirst(lc)) == 0)
7201 /* Decrement inhcount and possibly set islocal to true */
7202 HeapTuple copyTuple = heap_copytuple(constraintTuple);
7203 Form_pg_constraint copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
7204 if (copy_con->coninhcount <= 0) /* shouldn't happen */
7205 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
7206 RelationGetRelid(rel), NameStr(copy_con->conname));
7208 copy_con->coninhcount--;
7209 if (copy_con->coninhcount == 0)
7210 copy_con->conislocal = true;
7212 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
7213 CatalogUpdateIndexes(catalogRelation, copyTuple);
7214 heap_freetuple(copyTuple);
7218 systable_endscan(scan);
7219 heap_close(catalogRelation, RowExclusiveLock);
7222 * Drop the dependency
7224 * There's no convenient way to do this, so go trawling through pg_depend
7226 catalogRelation = heap_open(DependRelationId, RowExclusiveLock);
7228 ScanKeyInit(&key[0],
7229 Anum_pg_depend_classid,
7230 BTEqualStrategyNumber, F_OIDEQ,
7231 ObjectIdGetDatum(RelationRelationId));
7232 ScanKeyInit(&key[1],
7233 Anum_pg_depend_objid,
7234 BTEqualStrategyNumber, F_OIDEQ,
7235 ObjectIdGetDatum(RelationGetRelid(rel)));
7236 ScanKeyInit(&key[2],
7237 Anum_pg_depend_objsubid,
7238 BTEqualStrategyNumber, F_INT4EQ,
7241 scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
7242 SnapshotNow, 3, key);
7244 while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
7246 Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
7248 if (dep->refclassid == RelationRelationId &&
7249 dep->refobjid == RelationGetRelid(parent_rel) &&
7250 dep->refobjsubid == 0 &&
7251 dep->deptype == DEPENDENCY_NORMAL)
7252 simple_heap_delete(catalogRelation, &depTuple->t_self);
7255 systable_endscan(scan);
7256 heap_close(catalogRelation, RowExclusiveLock);
7258 /* keep our lock on the parent relation until commit */
7259 heap_close(parent_rel, NoLock);
7264 * Execute ALTER TABLE SET SCHEMA
7266 * Note: caller must have checked ownership of the relation already
7269 AlterTableNamespace(RangeVar *relation, const char *newschema,
7270 ObjectType stmttype)
7278 rel = relation_openrv(relation, AccessExclusiveLock);
7280 relid = RelationGetRelid(rel);
7281 oldNspOid = RelationGetNamespace(rel);
7283 /* Check relation type against type specified in the ALTER command */
7288 * For mostly-historical reasons, we allow ALTER TABLE to apply
7289 * to all relation types.
7293 case OBJECT_SEQUENCE:
7294 if (rel->rd_rel->relkind != RELKIND_SEQUENCE)
7296 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7297 errmsg("\"%s\" is not a sequence",
7298 RelationGetRelationName(rel))));
7302 if (rel->rd_rel->relkind != RELKIND_VIEW)
7304 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7305 errmsg("\"%s\" is not a view",
7306 RelationGetRelationName(rel))));
7310 elog(ERROR, "unrecognized object type: %d", (int) stmttype);
7313 /* Can we change the schema of this tuple? */
7314 switch (rel->rd_rel->relkind)
7316 case RELKIND_RELATION:
7318 /* ok to change schema */
7320 case RELKIND_SEQUENCE:
7322 /* if it's an owned sequence, disallow moving it by itself */
7326 if (sequenceIsOwned(relid, &tableId, &colId))
7328 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7329 errmsg("cannot move an owned sequence into another schema"),
7330 errdetail("Sequence \"%s\" is linked to table \"%s\".",
7331 RelationGetRelationName(rel),
7332 get_rel_name(tableId))));
7335 case RELKIND_COMPOSITE_TYPE:
7337 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7338 errmsg("\"%s\" is a composite type",
7339 RelationGetRelationName(rel)),
7340 errhint("Use ALTER TYPE instead.")));
7343 case RELKIND_TOASTVALUE:
7347 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7348 errmsg("\"%s\" is not a table, view, or sequence",
7349 RelationGetRelationName(rel))));
7352 /* get schema OID and check its permissions */
7353 nspOid = LookupCreationNamespace(newschema);
7355 if (oldNspOid == nspOid)
7357 (errcode(ERRCODE_DUPLICATE_TABLE),
7358 errmsg("relation \"%s\" is already in schema \"%s\"",
7359 RelationGetRelationName(rel),
7362 /* disallow renaming into or out of temp schemas */
7363 if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
7365 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7366 errmsg("cannot move objects into or out of temporary schemas")));
7368 /* same for TOAST schema */
7369 if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
7371 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7372 errmsg("cannot move objects into or out of TOAST schema")));
7374 /* OK, modify the pg_class row and pg_depend entry */
7375 classRel = heap_open(RelationRelationId, RowExclusiveLock);
7377 AlterRelationNamespaceInternal(classRel, relid, oldNspOid, nspOid, true);
7379 /* Fix the table's rowtype too */
7380 AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid, false, false);
7382 /* Fix other dependent stuff */
7383 if (rel->rd_rel->relkind == RELKIND_RELATION)
7385 AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid);
7386 AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid, newschema);
7387 AlterConstraintNamespaces(relid, oldNspOid, nspOid, false);
7390 heap_close(classRel, RowExclusiveLock);
7392 /* close rel, but keep lock until commit */
7393 relation_close(rel, NoLock);
7397 * The guts of relocating a relation to another namespace: fix the pg_class
7398 * entry, and the pg_depend entry if any. Caller must already have
7399 * opened and write-locked pg_class.
7402 AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
7403 Oid oldNspOid, Oid newNspOid,
7404 bool hasDependEntry)
7407 Form_pg_class classForm;
7409 classTup = SearchSysCacheCopy(RELOID,
7410 ObjectIdGetDatum(relOid),
7412 if (!HeapTupleIsValid(classTup))
7413 elog(ERROR, "cache lookup failed for relation %u", relOid);
7414 classForm = (Form_pg_class) GETSTRUCT(classTup);
7416 Assert(classForm->relnamespace == oldNspOid);
7418 /* check for duplicate name (more friendly than unique-index failure) */
7419 if (get_relname_relid(NameStr(classForm->relname),
7420 newNspOid) != InvalidOid)
7422 (errcode(ERRCODE_DUPLICATE_TABLE),
7423 errmsg("relation \"%s\" already exists in schema \"%s\"",
7424 NameStr(classForm->relname),
7425 get_namespace_name(newNspOid))));
7427 /* classTup is a copy, so OK to scribble on */
7428 classForm->relnamespace = newNspOid;
7430 simple_heap_update(classRel, &classTup->t_self, classTup);
7431 CatalogUpdateIndexes(classRel, classTup);
7433 /* Update dependency on schema if caller said so */
7434 if (hasDependEntry &&
7435 changeDependencyFor(RelationRelationId, relOid,
7436 NamespaceRelationId, oldNspOid, newNspOid) != 1)
7437 elog(ERROR, "failed to change schema dependency for relation \"%s\"",
7438 NameStr(classForm->relname));
7440 heap_freetuple(classTup);
7444 * Move all indexes for the specified relation to another namespace.
7446 * Note: we assume adequate permission checking was done by the caller,
7447 * and that the caller has a suitable lock on the owning relation.
7450 AlterIndexNamespaces(Relation classRel, Relation rel,
7451 Oid oldNspOid, Oid newNspOid)
7456 indexList = RelationGetIndexList(rel);
7458 foreach(l, indexList)
7460 Oid indexOid = lfirst_oid(l);
7463 * Note: currently, the index will not have its own dependency on the
7464 * namespace, so we don't need to do changeDependencyFor(). There's no
7465 * rowtype in pg_type, either.
7467 AlterRelationNamespaceInternal(classRel, indexOid,
7468 oldNspOid, newNspOid,
7472 list_free(indexList);
7476 * Move all SERIAL-column sequences of the specified relation to another
7479 * Note: we assume adequate permission checking was done by the caller,
7480 * and that the caller has a suitable lock on the owning relation.
7483 AlterSeqNamespaces(Relation classRel, Relation rel,
7484 Oid oldNspOid, Oid newNspOid, const char *newNspName)
7492 * SERIAL sequences are those having an auto dependency on one of the
7493 * table's columns (we don't care *which* column, exactly).
7495 depRel = heap_open(DependRelationId, AccessShareLock);
7497 ScanKeyInit(&key[0],
7498 Anum_pg_depend_refclassid,
7499 BTEqualStrategyNumber, F_OIDEQ,
7500 ObjectIdGetDatum(RelationRelationId));
7501 ScanKeyInit(&key[1],
7502 Anum_pg_depend_refobjid,
7503 BTEqualStrategyNumber, F_OIDEQ,
7504 ObjectIdGetDatum(RelationGetRelid(rel)));
7505 /* we leave refobjsubid unspecified */
7507 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
7508 SnapshotNow, 2, key);
7510 while (HeapTupleIsValid(tup = systable_getnext(scan)))
7512 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
7515 /* skip dependencies other than auto dependencies on columns */
7516 if (depForm->refobjsubid == 0 ||
7517 depForm->classid != RelationRelationId ||
7518 depForm->objsubid != 0 ||
7519 depForm->deptype != DEPENDENCY_AUTO)
7522 /* Use relation_open just in case it's an index */
7523 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
7525 /* skip non-sequence relations */
7526 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
7528 /* No need to keep the lock */
7529 relation_close(seqRel, AccessExclusiveLock);
7533 /* Fix the pg_class and pg_depend entries */
7534 AlterRelationNamespaceInternal(classRel, depForm->objid,
7535 oldNspOid, newNspOid,
7539 * Sequences have entries in pg_type. We need to be careful to move
7540 * them to the new namespace, too.
7542 AlterTypeNamespaceInternal(RelationGetForm(seqRel)->reltype,
7543 newNspOid, false, false);
7545 /* Now we can close it. Keep the lock till end of transaction. */
7546 relation_close(seqRel, NoLock);
7549 systable_endscan(scan);
7551 relation_close(depRel, AccessShareLock);
7556 * This code supports
7557 * CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
7559 * Because we only support this for TEMP tables, it's sufficient to remember
7560 * the state in a backend-local data structure.
7564 * Register a newly-created relation's ON COMMIT action.
7567 register_on_commit_action(Oid relid, OnCommitAction action)
7570 MemoryContext oldcxt;
7573 * We needn't bother registering the relation unless there is an ON COMMIT
7574 * action we need to take.
7576 if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
7579 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
7581 oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
7583 oc->oncommit = action;
7584 oc->creating_subid = GetCurrentSubTransactionId();
7585 oc->deleting_subid = InvalidSubTransactionId;
7587 on_commits = lcons(oc, on_commits);
7589 MemoryContextSwitchTo(oldcxt);
7593 * Unregister any ON COMMIT action when a relation is deleted.
7595 * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
7598 remove_on_commit_action(Oid relid)
7602 foreach(l, on_commits)
7604 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
7606 if (oc->relid == relid)
7608 oc->deleting_subid = GetCurrentSubTransactionId();
7615 * Perform ON COMMIT actions.
7617 * This is invoked just before actually committing, since it's possible
7618 * to encounter errors.
7621 PreCommit_on_commit_actions(void)
7624 List *oids_to_truncate = NIL;
7626 foreach(l, on_commits)
7628 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
7630 /* Ignore entry if already dropped in this xact */
7631 if (oc->deleting_subid != InvalidSubTransactionId)
7634 switch (oc->oncommit)
7637 case ONCOMMIT_PRESERVE_ROWS:
7638 /* Do nothing (there shouldn't be such entries, actually) */
7640 case ONCOMMIT_DELETE_ROWS:
7641 oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
7645 ObjectAddress object;
7647 object.classId = RelationRelationId;
7648 object.objectId = oc->relid;
7649 object.objectSubId = 0;
7650 performDeletion(&object, DROP_CASCADE);
7653 * Note that table deletion will call
7654 * remove_on_commit_action, so the entry should get marked
7657 Assert(oc->deleting_subid != InvalidSubTransactionId);
7662 if (oids_to_truncate != NIL)
7664 heap_truncate(oids_to_truncate);
7665 CommandCounterIncrement(); /* XXX needed? */
7670 * Post-commit or post-abort cleanup for ON COMMIT management.
7672 * All we do here is remove no-longer-needed OnCommitItem entries.
7674 * During commit, remove entries that were deleted during this transaction;
7675 * during abort, remove those created during this transaction.
7678 AtEOXact_on_commit_actions(bool isCommit)
7681 ListCell *prev_item;
7684 cur_item = list_head(on_commits);
7686 while (cur_item != NULL)
7688 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
7690 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
7691 oc->creating_subid != InvalidSubTransactionId)
7693 /* cur_item must be removed */
7694 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
7697 cur_item = lnext(prev_item);
7699 cur_item = list_head(on_commits);
7703 /* cur_item must be preserved */
7704 oc->creating_subid = InvalidSubTransactionId;
7705 oc->deleting_subid = InvalidSubTransactionId;
7706 prev_item = cur_item;
7707 cur_item = lnext(prev_item);
7713 * Post-subcommit or post-subabort cleanup for ON COMMIT management.
7715 * During subabort, we can immediately remove entries created during this
7716 * subtransaction. During subcommit, just relabel entries marked during
7717 * this subtransaction as being the parent's responsibility.
7720 AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
7721 SubTransactionId parentSubid)
7724 ListCell *prev_item;
7727 cur_item = list_head(on_commits);
7729 while (cur_item != NULL)
7731 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
7733 if (!isCommit && oc->creating_subid == mySubid)
7735 /* cur_item must be removed */
7736 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
7739 cur_item = lnext(prev_item);
7741 cur_item = list_head(on_commits);
7745 /* cur_item must be preserved */
7746 if (oc->creating_subid == mySubid)
7747 oc->creating_subid = parentSubid;
7748 if (oc->deleting_subid == mySubid)
7749 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
7750 prev_item = cur_item;
7751 cur_item = lnext(prev_item);