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.258 2008/06/15 16:29:05 tgl Exp $
13 *-------------------------------------------------------------------------
17 #include "access/genam.h"
18 #include "access/heapam.h"
19 #include "access/reloptions.h"
20 #include "access/sysattr.h"
21 #include "access/xact.h"
22 #include "catalog/catalog.h"
23 #include "catalog/dependency.h"
24 #include "catalog/heap.h"
25 #include "catalog/index.h"
26 #include "catalog/indexing.h"
27 #include "catalog/namespace.h"
28 #include "catalog/pg_constraint.h"
29 #include "catalog/pg_depend.h"
30 #include "catalog/pg_inherits.h"
31 #include "catalog/pg_namespace.h"
32 #include "catalog/pg_opclass.h"
33 #include "catalog/pg_tablespace.h"
34 #include "catalog/pg_trigger.h"
35 #include "catalog/pg_type.h"
36 #include "catalog/pg_type_fn.h"
37 #include "catalog/toasting.h"
38 #include "commands/cluster.h"
39 #include "commands/defrem.h"
40 #include "commands/sequence.h"
41 #include "commands/tablecmds.h"
42 #include "commands/tablespace.h"
43 #include "commands/trigger.h"
44 #include "commands/typecmds.h"
45 #include "executor/executor.h"
46 #include "miscadmin.h"
47 #include "nodes/makefuncs.h"
48 #include "nodes/parsenodes.h"
49 #include "optimizer/clauses.h"
50 #include "optimizer/plancat.h"
51 #include "optimizer/prep.h"
52 #include "parser/gramparse.h"
53 #include "parser/parse_clause.h"
54 #include "parser/parse_coerce.h"
55 #include "parser/parse_expr.h"
56 #include "parser/parse_oper.h"
57 #include "parser/parse_relation.h"
58 #include "parser/parse_type.h"
59 #include "parser/parse_utilcmd.h"
60 #include "parser/parser.h"
61 #include "rewrite/rewriteDefine.h"
62 #include "rewrite/rewriteHandler.h"
63 #include "storage/bufmgr.h"
64 #include "storage/lmgr.h"
65 #include "storage/smgr.h"
66 #include "utils/acl.h"
67 #include "utils/builtins.h"
68 #include "utils/fmgroids.h"
69 #include "utils/inval.h"
70 #include "utils/lsyscache.h"
71 #include "utils/memutils.h"
72 #include "utils/relcache.h"
73 #include "utils/snapmgr.h"
74 #include "utils/syscache.h"
75 #include "utils/tqual.h"
79 * ON COMMIT action list
81 typedef struct OnCommitItem
83 Oid relid; /* relid of relation */
84 OnCommitAction oncommit; /* what to do at end of xact */
87 * If this entry was created during the current transaction,
88 * creating_subid is the ID of the creating subxact; if created in a prior
89 * transaction, creating_subid is zero. If deleted during the current
90 * transaction, deleting_subid is the ID of the deleting subxact; if no
91 * deletion request is pending, deleting_subid is zero.
93 SubTransactionId creating_subid;
94 SubTransactionId deleting_subid;
97 static List *on_commits = NIL;
101 * State information for ALTER TABLE
103 * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
104 * structs, one for each table modified by the operation (the named table
105 * plus any child tables that are affected). We save lists of subcommands
106 * to apply to this table (possibly modified by parse transformation steps);
107 * these lists will be executed in Phase 2. If a Phase 3 step is needed,
108 * necessary information is stored in the constraints and newvals lists.
110 * Phase 2 is divided into multiple passes; subcommands are executed in
111 * a pass determined by subcommand type.
114 #define AT_PASS_DROP 0 /* DROP (all flavors) */
115 #define AT_PASS_ALTER_TYPE 1 /* ALTER COLUMN TYPE */
116 #define AT_PASS_OLD_INDEX 2 /* re-add existing indexes */
117 #define AT_PASS_OLD_CONSTR 3 /* re-add existing constraints */
118 #define AT_PASS_COL_ATTRS 4 /* set other column attributes */
119 /* We could support a RENAME COLUMN pass here, but not currently used */
120 #define AT_PASS_ADD_COL 5 /* ADD COLUMN */
121 #define AT_PASS_ADD_INDEX 6 /* ADD indexes */
122 #define AT_PASS_ADD_CONSTR 7 /* ADD constraints, defaults */
123 #define AT_PASS_MISC 8 /* other stuff */
124 #define AT_NUM_PASSES 9
126 typedef struct AlteredTableInfo
128 /* Information saved before any work commences: */
129 Oid relid; /* Relation to work on */
130 char relkind; /* Its relkind */
131 TupleDesc oldDesc; /* Pre-modification tuple descriptor */
132 /* Information saved by Phase 1 for Phase 2: */
133 List *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
134 /* Information saved by Phases 1/2 for Phase 3: */
135 List *constraints; /* List of NewConstraint */
136 List *newvals; /* List of NewColumnValue */
137 bool new_notnull; /* T if we added new NOT NULL constraints */
138 Oid newTableSpace; /* new tablespace; 0 means no change */
139 /* Objects to rebuild after completing ALTER TYPE operations */
140 List *changedConstraintOids; /* OIDs of constraints to rebuild */
141 List *changedConstraintDefs; /* string definitions of same */
142 List *changedIndexOids; /* OIDs of indexes to rebuild */
143 List *changedIndexDefs; /* string definitions of same */
146 /* Struct describing one new constraint to check in Phase 3 scan */
147 /* Note: new NOT NULL constraints are handled elsewhere */
148 typedef struct NewConstraint
150 char *name; /* Constraint name, or NULL if none */
151 ConstrType contype; /* CHECK or FOREIGN */
152 Oid refrelid; /* PK rel, if FOREIGN */
153 Oid conid; /* OID of pg_constraint entry, if FOREIGN */
154 Node *qual; /* Check expr or FkConstraint struct */
155 List *qualstate; /* Execution state for CHECK */
159 * Struct describing one new column value that needs to be computed during
160 * Phase 3 copy (this could be either a new column with a non-null default, or
161 * a column that we're changing the type of). Columns without such an entry
162 * are just copied from the old table during ATRewriteTable. Note that the
163 * expr is an expression over *old* table values.
165 typedef struct NewColumnValue
167 AttrNumber attnum; /* which column */
168 Expr *expr; /* expression to compute */
169 ExprState *exprstate; /* execution state */
173 * Error-reporting support for RemoveRelations
175 struct dropmsgstrings
178 int nonexistent_code;
179 const char *nonexistent_msg;
180 const char *skipping_msg;
181 const char *nota_msg;
182 const char *drophint_msg;
185 static const struct dropmsgstrings dropmsgstringarray[] = {
187 ERRCODE_UNDEFINED_TABLE,
188 gettext_noop("table \"%s\" does not exist"),
189 gettext_noop("table \"%s\" does not exist, skipping"),
190 gettext_noop("\"%s\" is not a table"),
191 gettext_noop("Use DROP TABLE to remove a table.")},
193 ERRCODE_UNDEFINED_TABLE,
194 gettext_noop("sequence \"%s\" does not exist"),
195 gettext_noop("sequence \"%s\" does not exist, skipping"),
196 gettext_noop("\"%s\" is not a sequence"),
197 gettext_noop("Use DROP SEQUENCE to remove a sequence.")},
199 ERRCODE_UNDEFINED_TABLE,
200 gettext_noop("view \"%s\" does not exist"),
201 gettext_noop("view \"%s\" does not exist, skipping"),
202 gettext_noop("\"%s\" is not a view"),
203 gettext_noop("Use DROP VIEW to remove a view.")},
205 ERRCODE_UNDEFINED_OBJECT,
206 gettext_noop("index \"%s\" does not exist"),
207 gettext_noop("index \"%s\" does not exist, skipping"),
208 gettext_noop("\"%s\" is not an index"),
209 gettext_noop("Use DROP INDEX to remove an index.")},
210 {RELKIND_COMPOSITE_TYPE,
211 ERRCODE_UNDEFINED_OBJECT,
212 gettext_noop("type \"%s\" does not exist"),
213 gettext_noop("type \"%s\" does not exist, skipping"),
214 gettext_noop("\"%s\" is not a type"),
215 gettext_noop("Use DROP TYPE to remove a type.")},
216 {'\0', 0, NULL, NULL, NULL, NULL}
220 static void truncate_check_rel(Relation rel);
221 static List *MergeAttributes(List *schema, List *supers, bool istemp,
222 List **supOids, List **supconstr, int *supOidCount);
223 static bool MergeCheckConstraint(List *constraints, char *name, Node *expr);
224 static bool change_varattnos_walker(Node *node, const AttrNumber *newattno);
225 static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel);
226 static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
227 static void StoreCatalogInheritance(Oid relationId, List *supers);
228 static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
229 int16 seqNumber, Relation inhRelation);
230 static int findAttrByName(const char *attributeName, List *schema);
231 static void setRelhassubclassInRelation(Oid relationId, bool relhassubclass);
232 static void AlterIndexNamespaces(Relation classRel, Relation rel,
233 Oid oldNspOid, Oid newNspOid);
234 static void AlterSeqNamespaces(Relation classRel, Relation rel,
235 Oid oldNspOid, Oid newNspOid,
236 const char *newNspName);
237 static int transformColumnNameList(Oid relId, List *colList,
238 int16 *attnums, Oid *atttypids);
239 static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
241 int16 *attnums, Oid *atttypids,
243 static Oid transformFkeyCheckAttrs(Relation pkrel,
244 int numattrs, int16 *attnums,
246 static void validateForeignKeyConstraint(FkConstraint *fkconstraint,
247 Relation rel, Relation pkrel, Oid constraintOid);
248 static void createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
250 static void ATController(Relation rel, List *cmds, bool recurse);
251 static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
252 bool recurse, bool recursing);
253 static void ATRewriteCatalogs(List **wqueue);
254 static void ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
256 static void ATRewriteTables(List **wqueue);
257 static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap);
258 static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
259 static void ATSimplePermissions(Relation rel, bool allowView);
260 static void ATSimplePermissionsRelationOrIndex(Relation rel);
261 static void ATSimpleRecursion(List **wqueue, Relation rel,
262 AlterTableCmd *cmd, bool recurse);
263 static void ATOneLevelRecursion(List **wqueue, Relation rel,
265 static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
267 static void ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
269 static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
270 static void ATExecDropNotNull(Relation rel, const char *colName);
271 static void ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
272 const char *colName);
273 static void ATExecColumnDefault(Relation rel, const char *colName,
275 static void ATPrepSetStatistics(Relation rel, const char *colName,
277 static void ATExecSetStatistics(Relation rel, const char *colName,
279 static void ATExecSetStorage(Relation rel, const char *colName,
281 static void ATExecDropColumn(Relation rel, const char *colName,
282 DropBehavior behavior,
283 bool recurse, bool recursing);
284 static void ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
285 IndexStmt *stmt, bool is_rebuild);
286 static void ATExecAddConstraint(List **wqueue,
287 AlteredTableInfo *tab, Relation rel,
288 Node *newConstraint, bool recurse);
289 static void ATAddCheckConstraint(List **wqueue,
290 AlteredTableInfo *tab, Relation rel,
292 bool recurse, bool recursing);
293 static void ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
294 FkConstraint *fkconstraint);
295 static void ATExecDropConstraint(Relation rel, const char *constrName,
296 DropBehavior behavior,
297 bool recurse, bool recursing);
298 static void ATPrepAlterColumnType(List **wqueue,
299 AlteredTableInfo *tab, Relation rel,
300 bool recurse, bool recursing,
302 static void ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
303 const char *colName, TypeName *typename);
304 static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab);
305 static void ATPostAlterTypeParse(char *cmd, List **wqueue);
306 static void change_owner_recurse_to_sequences(Oid relationOid,
308 static void ATExecClusterOn(Relation rel, const char *indexName);
309 static void ATExecDropCluster(Relation rel);
310 static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
311 char *tablespacename);
312 static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace);
313 static void ATExecSetRelOptions(Relation rel, List *defList, bool isReset);
314 static void ATExecEnableDisableTrigger(Relation rel, char *trigname,
315 char fires_when, bool skip_system);
316 static void ATExecEnableDisableRule(Relation rel, char *rulename,
318 static void ATExecAddInherit(Relation rel, RangeVar *parent);
319 static void ATExecDropInherit(Relation rel, RangeVar *parent);
320 static void copy_relation_data(Relation rel, SMgrRelation dst);
323 /* ----------------------------------------------------------------
325 * Creates a new relation.
327 * If successful, returns the OID of the new relation.
328 * ----------------------------------------------------------------
331 DefineRelation(CreateStmt *stmt, char relkind)
333 char relname[NAMEDATALEN];
335 List *schema = stmt->tableElts;
339 TupleDesc descriptor;
341 List *old_constraints;
345 List *cookedDefaults;
351 * Truncate relname to appropriate length (probably a waste of time, as
352 * parser should have done this already).
354 StrNCpy(relname, stmt->relation->relname, NAMEDATALEN);
357 * Check consistency of arguments
359 if (stmt->oncommit != ONCOMMIT_NOOP && !stmt->relation->istemp)
361 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
362 errmsg("ON COMMIT can only be used on temporary tables")));
365 * Look up the namespace in which we are supposed to create the relation.
366 * Check we have permission to create there. Skip check if bootstrapping,
367 * since permissions machinery may not be working yet.
369 namespaceId = RangeVarGetCreationNamespace(stmt->relation);
371 if (!IsBootstrapProcessingMode())
375 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
377 if (aclresult != ACLCHECK_OK)
378 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
379 get_namespace_name(namespaceId));
383 * Select tablespace to use. If not specified, use default tablespace
384 * (which may in turn default to database's default).
386 if (stmt->tablespacename)
388 tablespaceId = get_tablespace_oid(stmt->tablespacename);
389 if (!OidIsValid(tablespaceId))
391 (errcode(ERRCODE_UNDEFINED_OBJECT),
392 errmsg("tablespace \"%s\" does not exist",
393 stmt->tablespacename)));
397 tablespaceId = GetDefaultTablespace(stmt->relation->istemp);
398 /* note InvalidOid is OK in this case */
401 /* Check permissions except when using database's default */
402 if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
406 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
408 if (aclresult != ACLCHECK_OK)
409 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
410 get_tablespace_name(tablespaceId));
414 * Parse and validate reloptions, if any.
416 reloptions = transformRelOptions((Datum) 0, stmt->options, true, false);
418 (void) heap_reloptions(relkind, reloptions, true);
421 * Look up inheritance ancestors and generate relation schema, including
422 * inherited attributes.
424 schema = MergeAttributes(schema, stmt->inhRelations,
425 stmt->relation->istemp,
426 &inheritOids, &old_constraints, &parentOidCount);
429 * Create a tuple descriptor from the relation schema. Note that this
430 * deals with column names, types, and NOT NULL constraints, but not
431 * default values or CHECK constraints; we handle those below.
433 descriptor = BuildDescForRelation(schema);
435 localHasOids = interpretOidsOption(stmt->options);
436 descriptor->tdhasoid = (localHasOids || parentOidCount > 0);
439 * Find columns with default values and prepare for insertion of the
440 * defaults. Pre-cooked (that is, inherited) defaults go into a list of
441 * CookedConstraint structs that we'll pass to heap_create_with_catalog,
442 * while raw defaults go into a list of RawColumnDefault structs that
443 * will be processed by AddRelationNewConstraints. (We can't deal with
444 * raw expressions until we can do transformExpr.)
446 * We can set the atthasdef flags now in the tuple descriptor; this just
447 * saves StoreAttrDefault from having to do an immediate update of the
451 cookedDefaults = NIL;
454 foreach(listptr, schema)
456 ColumnDef *colDef = lfirst(listptr);
460 if (colDef->raw_default != NULL)
462 RawColumnDefault *rawEnt;
464 Assert(colDef->cooked_default == NULL);
466 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
467 rawEnt->attnum = attnum;
468 rawEnt->raw_default = colDef->raw_default;
469 rawDefaults = lappend(rawDefaults, rawEnt);
470 descriptor->attrs[attnum - 1]->atthasdef = true;
472 else if (colDef->cooked_default != NULL)
474 CookedConstraint *cooked;
476 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
477 cooked->contype = CONSTR_DEFAULT;
479 cooked->attnum = attnum;
480 cooked->expr = stringToNode(colDef->cooked_default);
481 cooked->is_local = true; /* not used for defaults */
482 cooked->inhcount = 0; /* ditto */
483 cookedDefaults = lappend(cookedDefaults, cooked);
484 descriptor->attrs[attnum - 1]->atthasdef = true;
489 * Create the relation. Inherited defaults and constraints are passed
490 * in for immediate handling --- since they don't need parsing, they
491 * can be stored immediately.
493 relationId = heap_create_with_catalog(relname,
499 list_concat(cookedDefaults,
507 allowSystemTableMods);
509 StoreCatalogInheritance(relationId, inheritOids);
512 * We must bump the command counter to make the newly-created relation
513 * tuple visible for opening.
515 CommandCounterIncrement();
518 * Open the new relation and acquire exclusive lock on it. This isn't
519 * really necessary for locking out other backends (since they can't see
520 * the new rel anyway until we commit), but it keeps the lock manager from
521 * complaining about deadlock risks.
523 rel = relation_open(relationId, AccessExclusiveLock);
526 * Now add any newly specified column default values and CHECK constraints
527 * to the new relation. These are passed to us in the form of raw
528 * parsetrees; we need to transform them to executable expression trees
529 * before they can be added. The most convenient way to do that is to
530 * apply the parser's transformExpr routine, but transformExpr doesn't
531 * work unless we have a pre-existing relation. So, the transformation has
532 * to be postponed to this final step of CREATE TABLE.
534 if (rawDefaults || stmt->constraints)
535 AddRelationNewConstraints(rel, rawDefaults, stmt->constraints,
539 * Clean up. We keep lock on new relation (although it shouldn't be
540 * visible to anyone else anyway, until commit).
542 relation_close(rel, NoLock);
548 * Emit the right error or warning message for a "DROP" command issued on a
549 * non-existent relation
552 DropErrorMsgNonExistent(const char *relname, char rightkind, bool missing_ok)
554 const struct dropmsgstrings *rentry;
556 for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
558 if (rentry->kind == rightkind)
563 (errcode(rentry->nonexistent_code),
564 errmsg(rentry->nonexistent_msg, relname)));
568 ereport(NOTICE, (errmsg(rentry->skipping_msg, relname)));
574 Assert(rentry->kind != '\0'); /* Should be impossible */
578 * Emit the right error message for a "DROP" command issued on a
579 * relation of the wrong type
582 DropErrorMsgWrongType(const char *relname, char wrongkind, char rightkind)
584 const struct dropmsgstrings *rentry;
585 const struct dropmsgstrings *wentry;
587 for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
588 if (rentry->kind == rightkind)
590 Assert(rentry->kind != '\0');
592 for (wentry = dropmsgstringarray; wentry->kind != '\0'; wentry++)
593 if (wentry->kind == wrongkind)
595 /* wrongkind could be something we don't have in our table... */
598 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
599 errmsg(rentry->nota_msg, relname),
600 (wentry->kind != '\0') ? errhint(wentry->drophint_msg) : 0));
605 * Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW
608 RemoveRelations(DropStmt *drop)
610 ObjectAddresses *objects;
615 * First we identify all the relations, then we delete them in a single
616 * performMultipleDeletions() call. This is to avoid unwanted
617 * DROP RESTRICT errors if one of the relations depends on another.
620 /* Determine required relkind */
621 switch (drop->removeType)
624 relkind = RELKIND_RELATION;
628 relkind = RELKIND_INDEX;
631 case OBJECT_SEQUENCE:
632 relkind = RELKIND_SEQUENCE;
636 relkind = RELKIND_VIEW;
640 elog(ERROR, "unrecognized drop object type: %d",
641 (int) drop->removeType);
642 relkind = 0; /* keep compiler quiet */
646 /* Lock and validate each relation; build a list of object addresses */
647 objects = new_object_addresses();
649 foreach(cell, drop->objects)
651 RangeVar *rel = makeRangeVarFromNameList((List *) lfirst(cell));
654 Form_pg_class classform;
658 * These next few steps are a great deal like relation_openrv, but we
659 * don't bother building a relcache entry since we don't need it.
661 * Check for shared-cache-inval messages before trying to access the
662 * relation. This is needed to cover the case where the name
663 * identifies a rel that has been dropped and recreated since the
664 * start of our transaction: if we don't flush the old syscache entry,
665 * then we'll latch onto that entry and suffer an error later.
667 AcceptInvalidationMessages();
669 /* Look up the appropriate relation using namespace search */
670 relOid = RangeVarGetRelid(rel, true);
673 if (!OidIsValid(relOid))
675 DropErrorMsgNonExistent(rel->relname, relkind, drop->missing_ok);
680 * In DROP INDEX, attempt to acquire lock on the parent table before
681 * locking the index. index_drop() will need this anyway, and since
682 * regular queries lock tables before their indexes, we risk deadlock
683 * if we do it the other way around. No error if we don't find a
684 * pg_index entry, though --- that most likely means it isn't an
685 * index, and we'll fail below.
687 if (relkind == RELKIND_INDEX)
689 tuple = SearchSysCache(INDEXRELID,
690 ObjectIdGetDatum(relOid),
692 if (HeapTupleIsValid(tuple))
694 Form_pg_index index = (Form_pg_index) GETSTRUCT(tuple);
696 LockRelationOid(index->indrelid, AccessExclusiveLock);
697 ReleaseSysCache(tuple);
701 /* Get the lock before trying to fetch the syscache entry */
702 LockRelationOid(relOid, AccessExclusiveLock);
704 tuple = SearchSysCache(RELOID,
705 ObjectIdGetDatum(relOid),
707 if (!HeapTupleIsValid(tuple))
708 elog(ERROR, "cache lookup failed for relation %u", relOid);
709 classform = (Form_pg_class) GETSTRUCT(tuple);
711 if (classform->relkind != relkind)
712 DropErrorMsgWrongType(rel->relname, classform->relkind, relkind);
714 /* Allow DROP to either table owner or schema owner */
715 if (!pg_class_ownercheck(relOid, GetUserId()) &&
716 !pg_namespace_ownercheck(classform->relnamespace, GetUserId()))
717 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
720 if (!allowSystemTableMods && IsSystemClass(classform))
722 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
723 errmsg("permission denied: \"%s\" is a system catalog",
726 /* OK, we're ready to delete this one */
727 obj.classId = RelationRelationId;
728 obj.objectId = relOid;
731 add_exact_object_address(&obj, objects);
733 ReleaseSysCache(tuple);
736 performMultipleDeletions(objects, drop->behavior);
738 free_object_addresses(objects);
743 * Executes a TRUNCATE command.
745 * This is a multi-relation truncate. We first open and grab exclusive
746 * lock on all relations involved, checking permissions and otherwise
747 * verifying that the relation is OK for truncation. In CASCADE mode,
748 * relations having FK references to the targeted relations are automatically
749 * added to the group; in RESTRICT mode, we check that all FK references are
750 * internal to the group that's being truncated. Finally all the relations
751 * are truncated and reindexed.
754 ExecuteTruncate(TruncateStmt *stmt)
758 List *seq_relids = NIL;
760 ResultRelInfo *resultRelInfos;
761 ResultRelInfo *resultRelInfo;
765 * Open, exclusive-lock, and check all the explicitly-specified relations
767 foreach(cell, stmt->relations)
769 RangeVar *rv = lfirst(cell);
772 rel = heap_openrv(rv, AccessExclusiveLock);
773 truncate_check_rel(rel);
774 rels = lappend(rels, rel);
775 relids = lappend_oid(relids, RelationGetRelid(rel));
779 * In CASCADE mode, suck in all referencing relations as well. This
780 * requires multiple iterations to find indirectly-dependent relations. At
781 * each phase, we need to exclusive-lock new rels before looking for their
782 * dependencies, else we might miss something. Also, we check each rel as
783 * soon as we open it, to avoid a faux pas such as holding lock for a long
784 * time on a rel we have no permissions for.
786 if (stmt->behavior == DROP_CASCADE)
792 newrelids = heap_truncate_find_FKs(relids);
793 if (newrelids == NIL)
794 break; /* nothing else to add */
796 foreach(cell, newrelids)
798 Oid relid = lfirst_oid(cell);
801 rel = heap_open(relid, AccessExclusiveLock);
803 (errmsg("truncate cascades to table \"%s\"",
804 RelationGetRelationName(rel))));
805 truncate_check_rel(rel);
806 rels = lappend(rels, rel);
807 relids = lappend_oid(relids, relid);
813 * Check foreign key references. In CASCADE mode, this should be
814 * unnecessary since we just pulled in all the references; but as a
815 * cross-check, do it anyway if in an Assert-enabled build.
817 #ifdef USE_ASSERT_CHECKING
818 heap_truncate_check_FKs(rels, false);
820 if (stmt->behavior == DROP_RESTRICT)
821 heap_truncate_check_FKs(rels, false);
825 * If we are asked to restart sequences, find all the sequences,
826 * lock them (we only need AccessShareLock because that's all that
827 * ALTER SEQUENCE takes), and check permissions. We want to do this
828 * early since it's pointless to do all the truncation work only to fail
829 * on sequence permissions.
831 if (stmt->restart_seqs)
835 Relation rel = (Relation) lfirst(cell);
836 List *seqlist = getOwnedSequences(RelationGetRelid(rel));
839 foreach(seqcell, seqlist)
841 Oid seq_relid = lfirst_oid(seqcell);
844 seq_rel = relation_open(seq_relid, AccessShareLock);
846 /* This check must match AlterSequence! */
847 if (!pg_class_ownercheck(seq_relid, GetUserId()))
848 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
849 RelationGetRelationName(seq_rel));
851 seq_relids = lappend_oid(seq_relids, seq_relid);
853 relation_close(seq_rel, NoLock);
858 /* Prepare to catch AFTER triggers. */
859 AfterTriggerBeginQuery();
862 * To fire triggers, we'll need an EState as well as a ResultRelInfo
865 estate = CreateExecutorState();
866 resultRelInfos = (ResultRelInfo *)
867 palloc(list_length(rels) * sizeof(ResultRelInfo));
868 resultRelInfo = resultRelInfos;
871 Relation rel = (Relation) lfirst(cell);
873 InitResultRelInfo(resultRelInfo,
875 0, /* dummy rangetable index */
876 CMD_DELETE, /* don't need any index info */
880 estate->es_result_relations = resultRelInfos;
881 estate->es_num_result_relations = list_length(rels);
884 * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
885 * truncating (this is because one of them might throw an error).
886 * Also, if we were to allow them to prevent statement execution,
887 * that would need to be handled here.
889 resultRelInfo = resultRelInfos;
892 estate->es_result_relation_info = resultRelInfo;
893 ExecBSTruncateTriggers(estate, resultRelInfo);
898 * OK, truncate each table.
902 Relation rel = (Relation) lfirst(cell);
907 * Create a new empty storage file for the relation, and assign it as
908 * the relfilenode value. The old storage file is scheduled for
909 * deletion at commit.
911 setNewRelfilenode(rel, RecentXmin);
913 heap_relid = RelationGetRelid(rel);
914 toast_relid = rel->rd_rel->reltoastrelid;
917 * The same for the toast table, if any.
919 if (OidIsValid(toast_relid))
921 rel = relation_open(toast_relid, AccessExclusiveLock);
922 setNewRelfilenode(rel, RecentXmin);
923 heap_close(rel, NoLock);
927 * Reconstruct the indexes to match, and we're done.
929 reindex_relation(heap_relid, true);
933 * Process all AFTER STATEMENT TRUNCATE triggers.
935 resultRelInfo = resultRelInfos;
938 estate->es_result_relation_info = resultRelInfo;
939 ExecASTruncateTriggers(estate, resultRelInfo);
943 /* Handle queued AFTER triggers */
944 AfterTriggerEndQuery(estate);
946 /* We can clean up the EState now */
947 FreeExecutorState(estate);
949 /* And close the rels (can't do this while EState still holds refs) */
952 Relation rel = (Relation) lfirst(cell);
954 heap_close(rel, NoLock);
958 * Lastly, restart any owned sequences if we were asked to. This is done
959 * last because it's nontransactional: restarts will not roll back if
960 * we abort later. Hence it's important to postpone them as long as
961 * possible. (This is also a big reason why we locked and
962 * permission-checked the sequences beforehand.)
964 if (stmt->restart_seqs)
966 List *options = list_make1(makeDefElem("restart", NULL));
968 foreach(cell, seq_relids)
970 Oid seq_relid = lfirst_oid(cell);
972 AlterSequenceInternal(seq_relid, options);
978 * Check that a given rel is safe to truncate. Subroutine for ExecuteTruncate
981 truncate_check_rel(Relation rel)
983 /* Only allow truncate on regular tables */
984 if (rel->rd_rel->relkind != RELKIND_RELATION)
986 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
987 errmsg("\"%s\" is not a table",
988 RelationGetRelationName(rel))));
990 /* Permissions checks */
991 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
992 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
993 RelationGetRelationName(rel));
995 if (!allowSystemTableMods && IsSystemRelation(rel))
997 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
998 errmsg("permission denied: \"%s\" is a system catalog",
999 RelationGetRelationName(rel))));
1002 * We can never allow truncation of shared or nailed-in-cache relations,
1003 * because we can't support changing their relfilenode values.
1005 if (rel->rd_rel->relisshared || rel->rd_isnailed)
1007 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1008 errmsg("cannot truncate system relation \"%s\"",
1009 RelationGetRelationName(rel))));
1012 * Don't allow truncate on temp tables of other backends ... their local
1013 * buffer manager is not going to cope.
1015 if (isOtherTempNamespace(RelationGetNamespace(rel)))
1017 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1018 errmsg("cannot truncate temporary tables of other sessions")));
1021 * Also check for active uses of the relation in the current transaction,
1022 * including open scans and pending AFTER trigger events.
1024 CheckTableNotInUse(rel, "TRUNCATE");
1029 * Returns new schema given initial schema and superclasses.
1032 * 'schema' is the column/attribute definition for the table. (It's a list
1033 * of ColumnDef's.) It is destructively changed.
1034 * 'supers' is a list of names (as RangeVar nodes) of parent relations.
1035 * 'istemp' is TRUE if we are creating a temp relation.
1038 * 'supOids' receives a list of the OIDs of the parent relations.
1039 * 'supconstr' receives a list of constraints belonging to the parents,
1040 * updated as necessary to be valid for the child.
1041 * 'supOidCount' is set to the number of parents that have OID columns.
1044 * Completed schema list.
1047 * The order in which the attributes are inherited is very important.
1048 * Intuitively, the inherited attributes should come first. If a table
1049 * inherits from multiple parents, the order of those attributes are
1050 * according to the order of the parents specified in CREATE TABLE.
1052 * Here's an example:
1054 * create table person (name text, age int4, location point);
1055 * create table emp (salary int4, manager text) inherits(person);
1056 * create table student (gpa float8) inherits (person);
1057 * create table stud_emp (percent int4) inherits (emp, student);
1059 * The order of the attributes of stud_emp is:
1061 * person {1:name, 2:age, 3:location}
1063 * {6:gpa} student emp {4:salary, 5:manager}
1065 * stud_emp {7:percent}
1067 * If the same attribute name appears multiple times, then it appears
1068 * in the result table in the proper location for its first appearance.
1070 * Constraints (including NOT NULL constraints) for the child table
1071 * are the union of all relevant constraints, from both the child schema
1072 * and parent tables.
1074 * The default value for a child column is defined as:
1075 * (1) If the child schema specifies a default, that value is used.
1076 * (2) If neither the child nor any parent specifies a default, then
1077 * the column will not have a default.
1078 * (3) If conflicting defaults are inherited from different parents
1079 * (and not overridden by the child), an error is raised.
1080 * (4) Otherwise the inherited default is used.
1081 * Rule (3) is new in Postgres 7.1; in earlier releases you got a
1082 * rather arbitrary choice of which parent default to use.
1086 MergeAttributes(List *schema, List *supers, bool istemp,
1087 List **supOids, List **supconstr, int *supOidCount)
1090 List *inhSchema = NIL;
1091 List *parentOids = NIL;
1092 List *constraints = NIL;
1093 int parentsWithOids = 0;
1094 bool have_bogus_defaults = false;
1095 char *bogus_marker = "Bogus!"; /* marks conflicting defaults */
1099 * Check for and reject tables with too many columns. We perform this
1100 * check relatively early for two reasons: (a) we don't run the risk of
1101 * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
1102 * okay if we're processing <= 1600 columns, but could take minutes to
1103 * execute if the user attempts to create a table with hundreds of
1104 * thousands of columns.
1106 * Note that we also need to check that any we do not exceed this figure
1107 * after including columns from inherited relations.
1109 if (list_length(schema) > MaxHeapAttributeNumber)
1111 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1112 errmsg("tables can have at most %d columns",
1113 MaxHeapAttributeNumber)));
1116 * Check for duplicate names in the explicit list of attributes.
1118 * Although we might consider merging such entries in the same way that we
1119 * handle name conflicts for inherited attributes, it seems to make more
1120 * sense to assume such conflicts are errors.
1122 foreach(entry, schema)
1124 ColumnDef *coldef = lfirst(entry);
1127 for_each_cell(rest, lnext(entry))
1129 ColumnDef *restdef = lfirst(rest);
1131 if (strcmp(coldef->colname, restdef->colname) == 0)
1133 (errcode(ERRCODE_DUPLICATE_COLUMN),
1134 errmsg("column \"%s\" specified more than once",
1140 * Scan the parents left-to-right, and merge their attributes to form a
1141 * list of inherited attributes (inhSchema). Also check to see if we need
1142 * to inherit an OID column.
1145 foreach(entry, supers)
1147 RangeVar *parent = (RangeVar *) lfirst(entry);
1149 TupleDesc tupleDesc;
1150 TupleConstr *constr;
1151 AttrNumber *newattno;
1152 AttrNumber parent_attno;
1154 relation = heap_openrv(parent, AccessShareLock);
1156 if (relation->rd_rel->relkind != RELKIND_RELATION)
1158 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1159 errmsg("inherited relation \"%s\" is not a table",
1161 /* Permanent rels cannot inherit from temporary ones */
1162 if (!istemp && isTempNamespace(RelationGetNamespace(relation)))
1164 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1165 errmsg("cannot inherit from temporary relation \"%s\"",
1169 * We should have an UNDER permission flag for this, but for now,
1170 * demand that creator of a child table own the parent.
1172 if (!pg_class_ownercheck(RelationGetRelid(relation), GetUserId()))
1173 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1174 RelationGetRelationName(relation));
1177 * Reject duplications in the list of parents.
1179 if (list_member_oid(parentOids, RelationGetRelid(relation)))
1181 (errcode(ERRCODE_DUPLICATE_TABLE),
1182 errmsg("relation \"%s\" would be inherited from more than once",
1185 parentOids = lappend_oid(parentOids, RelationGetRelid(relation));
1187 if (relation->rd_rel->relhasoids)
1190 tupleDesc = RelationGetDescr(relation);
1191 constr = tupleDesc->constr;
1194 * newattno[] will contain the child-table attribute numbers for the
1195 * attributes of this parent table. (They are not the same for
1196 * parents after the first one, nor if we have dropped columns.)
1198 newattno = (AttrNumber *)
1199 palloc(tupleDesc->natts * sizeof(AttrNumber));
1201 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1204 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
1205 char *attributeName = NameStr(attribute->attname);
1210 * Ignore dropped columns in the parent.
1212 if (attribute->attisdropped)
1215 * change_varattnos_of_a_node asserts that this is greater
1216 * than zero, so if anything tries to use it, we should find
1219 newattno[parent_attno - 1] = 0;
1224 * Does it conflict with some previously inherited column?
1226 exist_attno = findAttrByName(attributeName, inhSchema);
1227 if (exist_attno > 0)
1233 * Yes, try to merge the two column definitions. They must
1234 * have the same type and typmod.
1237 (errmsg("merging multiple inherited definitions of column \"%s\"",
1239 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1240 defTypeId = typenameTypeId(NULL, def->typename, &deftypmod);
1241 if (defTypeId != attribute->atttypid ||
1242 deftypmod != attribute->atttypmod)
1244 (errcode(ERRCODE_DATATYPE_MISMATCH),
1245 errmsg("inherited column \"%s\" has a type conflict",
1247 errdetail("%s versus %s",
1248 TypeNameToString(def->typename),
1249 format_type_be(attribute->atttypid))));
1251 /* Merge of NOT NULL constraints = OR 'em together */
1252 def->is_not_null |= attribute->attnotnull;
1253 /* Default and other constraints are handled below */
1254 newattno[parent_attno - 1] = exist_attno;
1259 * No, create a new inherited column
1261 def = makeNode(ColumnDef);
1262 def->colname = pstrdup(attributeName);
1263 def->typename = makeTypeNameFromOid(attribute->atttypid,
1264 attribute->atttypmod);
1266 def->is_local = false;
1267 def->is_not_null = attribute->attnotnull;
1268 def->raw_default = NULL;
1269 def->cooked_default = NULL;
1270 def->constraints = NIL;
1271 inhSchema = lappend(inhSchema, def);
1272 newattno[parent_attno - 1] = ++child_attno;
1276 * Copy default if any
1278 if (attribute->atthasdef)
1280 char *this_default = NULL;
1281 AttrDefault *attrdef;
1284 /* Find default in constraint structure */
1285 Assert(constr != NULL);
1286 attrdef = constr->defval;
1287 for (i = 0; i < constr->num_defval; i++)
1289 if (attrdef[i].adnum == parent_attno)
1291 this_default = attrdef[i].adbin;
1295 Assert(this_default != NULL);
1298 * If default expr could contain any vars, we'd need to fix
1299 * 'em, but it can't; so default is ready to apply to child.
1301 * If we already had a default from some prior parent, check
1302 * to see if they are the same. If so, no problem; if not,
1303 * mark the column as having a bogus default. Below, we will
1304 * complain if the bogus default isn't overridden by the child
1307 Assert(def->raw_default == NULL);
1308 if (def->cooked_default == NULL)
1309 def->cooked_default = pstrdup(this_default);
1310 else if (strcmp(def->cooked_default, this_default) != 0)
1312 def->cooked_default = bogus_marker;
1313 have_bogus_defaults = true;
1319 * Now copy the CHECK constraints of this parent, adjusting attnos
1320 * using the completed newattno[] map. Identically named constraints
1321 * are merged if possible, else we throw error.
1323 if (constr && constr->num_check > 0)
1325 ConstrCheck *check = constr->check;
1328 for (i = 0; i < constr->num_check; i++)
1330 char *name = check[i].ccname;
1333 /* adjust varattnos of ccbin here */
1334 expr = stringToNode(check[i].ccbin);
1335 change_varattnos_of_a_node(expr, newattno);
1337 /* check for duplicate */
1338 if (!MergeCheckConstraint(constraints, name, expr))
1340 /* nope, this is a new one */
1341 CookedConstraint *cooked;
1343 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1344 cooked->contype = CONSTR_CHECK;
1345 cooked->name = pstrdup(name);
1346 cooked->attnum = 0; /* not used for constraints */
1347 cooked->expr = expr;
1348 cooked->is_local = false;
1349 cooked->inhcount = 1;
1350 constraints = lappend(constraints, cooked);
1358 * Close the parent rel, but keep our AccessShareLock on it until xact
1359 * commit. That will prevent someone else from deleting or ALTERing
1360 * the parent before the child is committed.
1362 heap_close(relation, NoLock);
1366 * If we had no inherited attributes, the result schema is just the
1367 * explicitly declared columns. Otherwise, we need to merge the declared
1368 * columns into the inherited schema list.
1370 if (inhSchema != NIL)
1372 foreach(entry, schema)
1374 ColumnDef *newdef = lfirst(entry);
1375 char *attributeName = newdef->colname;
1379 * Does it conflict with some previously inherited column?
1381 exist_attno = findAttrByName(attributeName, inhSchema);
1382 if (exist_attno > 0)
1391 * Yes, try to merge the two column definitions. They must
1392 * have the same type and typmod.
1395 (errmsg("merging column \"%s\" with inherited definition",
1397 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1398 defTypeId = typenameTypeId(NULL, def->typename, &deftypmod);
1399 newTypeId = typenameTypeId(NULL, newdef->typename, &newtypmod);
1400 if (defTypeId != newTypeId || deftypmod != newtypmod)
1402 (errcode(ERRCODE_DATATYPE_MISMATCH),
1403 errmsg("column \"%s\" has a type conflict",
1405 errdetail("%s versus %s",
1406 TypeNameToString(def->typename),
1407 TypeNameToString(newdef->typename))));
1408 /* Mark the column as locally defined */
1409 def->is_local = true;
1410 /* Merge of NOT NULL constraints = OR 'em together */
1411 def->is_not_null |= newdef->is_not_null;
1412 /* If new def has a default, override previous default */
1413 if (newdef->raw_default != NULL)
1415 def->raw_default = newdef->raw_default;
1416 def->cooked_default = newdef->cooked_default;
1422 * No, attach new column to result schema
1424 inhSchema = lappend(inhSchema, newdef);
1431 * Check that we haven't exceeded the legal # of columns after merging
1432 * in inherited columns.
1434 if (list_length(schema) > MaxHeapAttributeNumber)
1436 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1437 errmsg("tables can have at most %d columns",
1438 MaxHeapAttributeNumber)));
1442 * If we found any conflicting parent default values, check to make sure
1443 * they were overridden by the child.
1445 if (have_bogus_defaults)
1447 foreach(entry, schema)
1449 ColumnDef *def = lfirst(entry);
1451 if (def->cooked_default == bogus_marker)
1453 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
1454 errmsg("column \"%s\" inherits conflicting default values",
1456 errhint("To resolve the conflict, specify a default explicitly.")));
1460 *supOids = parentOids;
1461 *supconstr = constraints;
1462 *supOidCount = parentsWithOids;
1468 * MergeCheckConstraint
1469 * Try to merge an inherited CHECK constraint with previous ones
1471 * If we inherit identically-named constraints from multiple parents, we must
1472 * merge them, or throw an error if they don't have identical definitions.
1474 * constraints is a list of CookedConstraint structs for previous constraints.
1476 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
1477 * got a so-far-unique name, or throws error if conflict.
1480 MergeCheckConstraint(List *constraints, char *name, Node *expr)
1484 foreach(lc, constraints)
1486 CookedConstraint *ccon = (CookedConstraint *) lfirst(lc);
1488 Assert(ccon->contype == CONSTR_CHECK);
1490 /* Non-matching names never conflict */
1491 if (strcmp(ccon->name, name) != 0)
1494 if (equal(expr, ccon->expr))
1502 (errcode(ERRCODE_DUPLICATE_OBJECT),
1503 errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
1512 * Replace varattno values in an expression tree according to the given
1513 * map array, that is, varattno N is replaced by newattno[N-1]. It is
1514 * caller's responsibility to ensure that the array is long enough to
1515 * define values for all user varattnos present in the tree. System column
1516 * attnos remain unchanged.
1518 * Note that the passed node tree is modified in-place!
1521 change_varattnos_of_a_node(Node *node, const AttrNumber *newattno)
1523 /* no setup needed, so away we go */
1524 (void) change_varattnos_walker(node, newattno);
1528 change_varattnos_walker(Node *node, const AttrNumber *newattno)
1534 Var *var = (Var *) node;
1536 if (var->varlevelsup == 0 && var->varno == 1 &&
1540 * ??? the following may be a problem when the node is multiply
1541 * referenced though stringToNode() doesn't create such a node
1544 Assert(newattno[var->varattno - 1] > 0);
1545 var->varattno = var->varoattno = newattno[var->varattno - 1];
1549 return expression_tree_walker(node, change_varattnos_walker,
1554 * Generate a map for change_varattnos_of_a_node from old and new TupleDesc's,
1555 * matching according to column name.
1558 varattnos_map(TupleDesc old, TupleDesc new)
1564 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * old->natts);
1565 for (i = 1; i <= old->natts; i++)
1567 if (old->attrs[i - 1]->attisdropped)
1568 continue; /* leave the entry as zero */
1570 for (j = 1; j <= new->natts; j++)
1572 if (strcmp(NameStr(old->attrs[i - 1]->attname),
1573 NameStr(new->attrs[j - 1]->attname)) == 0)
1584 * Generate a map for change_varattnos_of_a_node from a TupleDesc and a list
1588 varattnos_map_schema(TupleDesc old, List *schema)
1593 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * old->natts);
1594 for (i = 1; i <= old->natts; i++)
1596 if (old->attrs[i - 1]->attisdropped)
1597 continue; /* leave the entry as zero */
1599 attmap[i - 1] = findAttrByName(NameStr(old->attrs[i - 1]->attname),
1607 * StoreCatalogInheritance
1608 * Updates the system catalogs with proper inheritance information.
1610 * supers is a list of the OIDs of the new relation's direct ancestors.
1613 StoreCatalogInheritance(Oid relationId, List *supers)
1622 AssertArg(OidIsValid(relationId));
1628 * Store INHERITS information in pg_inherits using direct ancestors only.
1629 * Also enter dependencies on the direct ancestors, and make sure they are
1630 * marked with relhassubclass = true.
1632 * (Once upon a time, both direct and indirect ancestors were found here
1633 * and then entered into pg_ipl. Since that catalog doesn't exist
1634 * anymore, there's no need to look for indirect ancestors.)
1636 relation = heap_open(InheritsRelationId, RowExclusiveLock);
1639 foreach(entry, supers)
1641 Oid parentOid = lfirst_oid(entry);
1643 StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation);
1647 heap_close(relation, RowExclusiveLock);
1651 * Make catalog entries showing relationId as being an inheritance child
1652 * of parentOid. inhRelation is the already-opened pg_inherits catalog.
1655 StoreCatalogInheritance1(Oid relationId, Oid parentOid,
1656 int16 seqNumber, Relation inhRelation)
1658 TupleDesc desc = RelationGetDescr(inhRelation);
1659 Datum datum[Natts_pg_inherits];
1660 char nullarr[Natts_pg_inherits];
1661 ObjectAddress childobject,
1666 * Make the pg_inherits entry
1668 datum[0] = ObjectIdGetDatum(relationId); /* inhrelid */
1669 datum[1] = ObjectIdGetDatum(parentOid); /* inhparent */
1670 datum[2] = Int16GetDatum(seqNumber); /* inhseqno */
1676 tuple = heap_formtuple(desc, datum, nullarr);
1678 simple_heap_insert(inhRelation, tuple);
1680 CatalogUpdateIndexes(inhRelation, tuple);
1682 heap_freetuple(tuple);
1685 * Store a dependency too
1687 parentobject.classId = RelationRelationId;
1688 parentobject.objectId = parentOid;
1689 parentobject.objectSubId = 0;
1690 childobject.classId = RelationRelationId;
1691 childobject.objectId = relationId;
1692 childobject.objectSubId = 0;
1694 recordDependencyOn(&childobject, &parentobject, DEPENDENCY_NORMAL);
1697 * Mark the parent as having subclasses.
1699 setRelhassubclassInRelation(parentOid, true);
1703 * Look for an existing schema entry with the given name.
1705 * Returns the index (starting with 1) if attribute already exists in schema,
1709 findAttrByName(const char *attributeName, List *schema)
1716 ColumnDef *def = lfirst(s);
1718 if (strcmp(attributeName, def->colname) == 0)
1727 * Update a relation's pg_class.relhassubclass entry to the given value
1730 setRelhassubclassInRelation(Oid relationId, bool relhassubclass)
1732 Relation relationRelation;
1734 Form_pg_class classtuple;
1737 * Fetch a modifiable copy of the tuple, modify it, update pg_class.
1739 * If the tuple already has the right relhassubclass setting, we don't
1740 * need to update it, but we still need to issue an SI inval message.
1742 relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
1743 tuple = SearchSysCacheCopy(RELOID,
1744 ObjectIdGetDatum(relationId),
1746 if (!HeapTupleIsValid(tuple))
1747 elog(ERROR, "cache lookup failed for relation %u", relationId);
1748 classtuple = (Form_pg_class) GETSTRUCT(tuple);
1750 if (classtuple->relhassubclass != relhassubclass)
1752 classtuple->relhassubclass = relhassubclass;
1753 simple_heap_update(relationRelation, &tuple->t_self, tuple);
1755 /* keep the catalog indexes up to date */
1756 CatalogUpdateIndexes(relationRelation, tuple);
1760 /* no need to change tuple, but force relcache rebuild anyway */
1761 CacheInvalidateRelcacheByTuple(tuple);
1764 heap_freetuple(tuple);
1765 heap_close(relationRelation, RowExclusiveLock);
1770 * renameatt - changes the name of a attribute in a relation
1772 * Attname attribute is changed in attribute catalog.
1773 * No record of the previous attname is kept (correct?).
1775 * get proper relrelation from relation catalog (if not arg)
1776 * scan attribute catalog
1777 * for name conflict (within rel)
1778 * for original attribute (if not arg)
1779 * modify attname in attribute tuple
1780 * insert modified attribute in attribute catalog
1781 * delete original attribute from attribute catalog
1784 renameatt(Oid myrelid,
1785 const char *oldattname,
1786 const char *newattname,
1790 Relation targetrelation;
1791 Relation attrelation;
1793 Form_pg_attribute attform;
1796 ListCell *indexoidscan;
1799 * Grab an exclusive lock on the target table, which we will NOT release
1800 * until end of transaction.
1802 targetrelation = relation_open(myrelid, AccessExclusiveLock);
1805 * permissions checking. this would normally be done in utility.c, but
1806 * this particular routine is recursive.
1808 * normally, only the owner of a class can change its schema.
1810 if (!pg_class_ownercheck(myrelid, GetUserId()))
1811 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1812 RelationGetRelationName(targetrelation));
1813 if (!allowSystemTableMods && IsSystemRelation(targetrelation))
1815 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1816 errmsg("permission denied: \"%s\" is a system catalog",
1817 RelationGetRelationName(targetrelation))));
1820 * if the 'recurse' flag is set then we are supposed to rename this
1821 * attribute in all classes that inherit from 'relname' (as well as in
1824 * any permissions or problems with duplicate attributes will cause the
1825 * whole transaction to abort, which is what we want -- all or nothing.
1832 /* this routine is actually in the planner */
1833 children = find_all_inheritors(myrelid);
1836 * find_all_inheritors does the recursive search of the inheritance
1837 * hierarchy, so all we have to do is process all of the relids in the
1838 * list that it returns.
1840 foreach(child, children)
1842 Oid childrelid = lfirst_oid(child);
1844 if (childrelid == myrelid)
1846 /* note we need not recurse again */
1847 renameatt(childrelid, oldattname, newattname, false, true);
1853 * If we are told not to recurse, there had better not be any child
1854 * tables; else the rename would put them out of step.
1857 find_inheritance_children(myrelid) != NIL)
1859 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1860 errmsg("inherited column \"%s\" must be renamed in child tables too",
1864 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
1866 atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
1867 if (!HeapTupleIsValid(atttup))
1869 (errcode(ERRCODE_UNDEFINED_COLUMN),
1870 errmsg("column \"%s\" does not exist",
1872 attform = (Form_pg_attribute) GETSTRUCT(atttup);
1874 attnum = attform->attnum;
1877 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1878 errmsg("cannot rename system column \"%s\"",
1882 * if the attribute is inherited, forbid the renaming, unless we are
1883 * already inside a recursive rename.
1885 if (attform->attinhcount > 0 && !recursing)
1887 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1888 errmsg("cannot rename inherited column \"%s\"",
1891 /* should not already exist */
1892 /* this test is deliberately not attisdropped-aware */
1893 if (SearchSysCacheExists(ATTNAME,
1894 ObjectIdGetDatum(myrelid),
1895 PointerGetDatum(newattname),
1898 (errcode(ERRCODE_DUPLICATE_COLUMN),
1899 errmsg("column \"%s\" of relation \"%s\" already exists",
1900 newattname, RelationGetRelationName(targetrelation))));
1902 namestrcpy(&(attform->attname), newattname);
1904 simple_heap_update(attrelation, &atttup->t_self, atttup);
1906 /* keep system catalog indexes current */
1907 CatalogUpdateIndexes(attrelation, atttup);
1909 heap_freetuple(atttup);
1912 * Update column names of indexes that refer to the column being renamed.
1914 indexoidlist = RelationGetIndexList(targetrelation);
1916 foreach(indexoidscan, indexoidlist)
1918 Oid indexoid = lfirst_oid(indexoidscan);
1920 Form_pg_index indexform;
1924 * Scan through index columns to see if there's any simple index
1925 * entries for this attribute. We ignore expressional entries.
1927 indextup = SearchSysCache(INDEXRELID,
1928 ObjectIdGetDatum(indexoid),
1930 if (!HeapTupleIsValid(indextup))
1931 elog(ERROR, "cache lookup failed for index %u", indexoid);
1932 indexform = (Form_pg_index) GETSTRUCT(indextup);
1934 for (i = 0; i < indexform->indnatts; i++)
1936 if (attnum != indexform->indkey.values[i])
1940 * Found one, rename it.
1942 atttup = SearchSysCacheCopy(ATTNUM,
1943 ObjectIdGetDatum(indexoid),
1944 Int16GetDatum(i + 1),
1946 if (!HeapTupleIsValid(atttup))
1947 continue; /* should we raise an error? */
1950 * Update the (copied) attribute tuple.
1952 namestrcpy(&(((Form_pg_attribute) GETSTRUCT(atttup))->attname),
1955 simple_heap_update(attrelation, &atttup->t_self, atttup);
1957 /* keep system catalog indexes current */
1958 CatalogUpdateIndexes(attrelation, atttup);
1960 heap_freetuple(atttup);
1963 ReleaseSysCache(indextup);
1966 list_free(indexoidlist);
1968 heap_close(attrelation, RowExclusiveLock);
1970 relation_close(targetrelation, NoLock); /* close rel but keep lock */
1975 * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW RENAME
1977 * Caller has already done permissions checks.
1980 RenameRelation(Oid myrelid, const char *newrelname, ObjectType reltype)
1982 Relation targetrelation;
1987 * Grab an exclusive lock on the target table, index, sequence or view,
1988 * which we will NOT release until end of transaction.
1990 targetrelation = relation_open(myrelid, AccessExclusiveLock);
1992 namespaceId = RelationGetNamespace(targetrelation);
1993 relkind = targetrelation->rd_rel->relkind;
1996 * For compatibility with prior releases, we don't complain if ALTER TABLE
1997 * or ALTER INDEX is used to rename a sequence or view.
1999 if (reltype == OBJECT_SEQUENCE && relkind != RELKIND_SEQUENCE)
2001 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2002 errmsg("\"%s\" is not a sequence",
2003 RelationGetRelationName(targetrelation))));
2005 if (reltype == OBJECT_VIEW && relkind != RELKIND_VIEW)
2007 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2008 errmsg("\"%s\" is not a view",
2009 RelationGetRelationName(targetrelation))));
2012 * Don't allow ALTER TABLE on composite types.
2013 * We want people to use ALTER TYPE for that.
2015 if (relkind == RELKIND_COMPOSITE_TYPE)
2017 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2018 errmsg("\"%s\" is a composite type",
2019 RelationGetRelationName(targetrelation)),
2020 errhint("Use ALTER TYPE instead.")));
2023 RenameRelationInternal(myrelid, newrelname, namespaceId);
2026 * Close rel, but keep exclusive lock!
2028 relation_close(targetrelation, NoLock);
2032 * RenameRelationInternal - change the name of a relation
2034 * XXX - When renaming sequences, we don't bother to modify the
2035 * sequence name that is stored within the sequence itself
2036 * (this would cause problems with MVCC). In the future,
2037 * the sequence name should probably be removed from the
2038 * sequence, AFAIK there's no need for it to be there.
2041 RenameRelationInternal(Oid myrelid, const char *newrelname, Oid namespaceId)
2043 Relation targetrelation;
2044 Relation relrelation; /* for RELATION relation */
2046 Form_pg_class relform;
2049 * Grab an exclusive lock on the target table, index, sequence or
2050 * view, which we will NOT release until end of transaction.
2052 targetrelation = relation_open(myrelid, AccessExclusiveLock);
2055 * Find relation's pg_class tuple, and make sure newrelname isn't in use.
2057 relrelation = heap_open(RelationRelationId, RowExclusiveLock);
2059 reltup = SearchSysCacheCopy(RELOID,
2060 ObjectIdGetDatum(myrelid),
2062 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
2063 elog(ERROR, "cache lookup failed for relation %u", myrelid);
2064 relform = (Form_pg_class) GETSTRUCT(reltup);
2066 if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
2068 (errcode(ERRCODE_DUPLICATE_TABLE),
2069 errmsg("relation \"%s\" already exists",
2073 * Update pg_class tuple with new relname. (Scribbling on reltup is OK
2074 * because it's a copy...)
2076 namestrcpy(&(relform->relname), newrelname);
2078 simple_heap_update(relrelation, &reltup->t_self, reltup);
2080 /* keep the system catalog indexes current */
2081 CatalogUpdateIndexes(relrelation, reltup);
2083 heap_freetuple(reltup);
2084 heap_close(relrelation, RowExclusiveLock);
2087 * Also rename the associated type, if any.
2089 if (OidIsValid(targetrelation->rd_rel->reltype))
2090 RenameTypeInternal(targetrelation->rd_rel->reltype,
2091 newrelname, namespaceId);
2094 * Also rename the associated constraint, if any.
2096 if (targetrelation->rd_rel->relkind == RELKIND_INDEX)
2098 Oid constraintId = get_index_constraint(myrelid);
2100 if (OidIsValid(constraintId))
2101 RenameConstraintById(constraintId, newrelname);
2105 * Close rel, but keep exclusive lock!
2107 relation_close(targetrelation, NoLock);
2111 * Disallow ALTER TABLE (and similar commands) when the current backend has
2112 * any open reference to the target table besides the one just acquired by
2113 * the calling command; this implies there's an open cursor or active plan.
2114 * We need this check because our AccessExclusiveLock doesn't protect us
2115 * against stomping on our own foot, only other people's feet!
2117 * For ALTER TABLE, the only case known to cause serious trouble is ALTER
2118 * COLUMN TYPE, and some changes are obviously pretty benign, so this could
2119 * possibly be relaxed to only error out for certain types of alterations.
2120 * But the use-case for allowing any of these things is not obvious, so we
2121 * won't work hard at it for now.
2123 * We also reject these commands if there are any pending AFTER trigger events
2124 * for the rel. This is certainly necessary for the rewriting variants of
2125 * ALTER TABLE, because they don't preserve tuple TIDs and so the pending
2126 * events would try to fetch the wrong tuples. It might be overly cautious
2127 * in other cases, but again it seems better to err on the side of paranoia.
2129 * REINDEX calls this with "rel" referencing the index to be rebuilt; here
2130 * we are worried about active indexscans on the index. The trigger-event
2131 * check can be skipped, since we are doing no damage to the parent table.
2133 * The statement name (eg, "ALTER TABLE") is passed for use in error messages.
2136 CheckTableNotInUse(Relation rel, const char *stmt)
2138 int expected_refcnt;
2140 expected_refcnt = rel->rd_isnailed ? 2 : 1;
2141 if (rel->rd_refcnt != expected_refcnt)
2143 (errcode(ERRCODE_OBJECT_IN_USE),
2144 /* translator: first %s is a SQL command, eg ALTER TABLE */
2145 errmsg("cannot %s \"%s\" because "
2146 "it is being used by active queries in this session",
2147 stmt, RelationGetRelationName(rel))));
2149 if (rel->rd_rel->relkind != RELKIND_INDEX &&
2150 AfterTriggerPendingOnRel(RelationGetRelid(rel)))
2152 (errcode(ERRCODE_OBJECT_IN_USE),
2153 /* translator: first %s is a SQL command, eg ALTER TABLE */
2154 errmsg("cannot %s \"%s\" because "
2155 "it has pending trigger events",
2156 stmt, RelationGetRelationName(rel))));
2161 * Execute ALTER TABLE, which can be a list of subcommands
2163 * ALTER TABLE is performed in three phases:
2164 * 1. Examine subcommands and perform pre-transformation checking.
2165 * 2. Update system catalogs.
2166 * 3. Scan table(s) to check new constraints, and optionally recopy
2167 * the data into new table(s).
2168 * Phase 3 is not performed unless one or more of the subcommands requires
2169 * it. The intention of this design is to allow multiple independent
2170 * updates of the table schema to be performed with only one pass over the
2173 * ATPrepCmd performs phase 1. A "work queue" entry is created for
2174 * each table to be affected (there may be multiple affected tables if the
2175 * commands traverse a table inheritance hierarchy). Also we do preliminary
2176 * validation of the subcommands, including parse transformation of those
2177 * expressions that need to be evaluated with respect to the old table
2180 * ATRewriteCatalogs performs phase 2 for each affected table. (Note that
2181 * phases 2 and 3 normally do no explicit recursion, since phase 1 already
2182 * did it --- although some subcommands have to recurse in phase 2 instead.)
2183 * Certain subcommands need to be performed before others to avoid
2184 * unnecessary conflicts; for example, DROP COLUMN should come before
2185 * ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
2186 * lists, one for each logical "pass" of phase 2.
2188 * ATRewriteTables performs phase 3 for those tables that need it.
2190 * Thanks to the magic of MVCC, an error anywhere along the way rolls back
2191 * the whole operation; we don't have to do anything special to clean up.
2194 AlterTable(AlterTableStmt *stmt)
2196 Relation rel = relation_openrv(stmt->relation, AccessExclusiveLock);
2198 CheckTableNotInUse(rel, "ALTER TABLE");
2200 /* Check relation type against type specified in the ALTER command */
2201 switch (stmt->relkind)
2205 * For mostly-historical reasons, we allow ALTER TABLE to apply
2206 * to all relation types.
2211 if (rel->rd_rel->relkind != RELKIND_INDEX)
2213 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2214 errmsg("\"%s\" is not an index",
2215 RelationGetRelationName(rel))));
2218 case OBJECT_SEQUENCE:
2219 if (rel->rd_rel->relkind != RELKIND_SEQUENCE)
2221 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2222 errmsg("\"%s\" is not a sequence",
2223 RelationGetRelationName(rel))));
2227 if (rel->rd_rel->relkind != RELKIND_VIEW)
2229 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2230 errmsg("\"%s\" is not a view",
2231 RelationGetRelationName(rel))));
2235 elog(ERROR, "unrecognized object type: %d", (int) stmt->relkind);
2238 ATController(rel, stmt->cmds, interpretInhOption(stmt->relation->inhOpt));
2242 * AlterTableInternal
2244 * ALTER TABLE with target specified by OID
2246 * We do not reject if the relation is already open, because it's quite
2247 * likely that one or more layers of caller have it open. That means it
2248 * is unsafe to use this entry point for alterations that could break
2249 * existing query plans. On the assumption it's not used for such, we
2250 * don't have to reject pending AFTER triggers, either.
2253 AlterTableInternal(Oid relid, List *cmds, bool recurse)
2255 Relation rel = relation_open(relid, AccessExclusiveLock);
2257 ATController(rel, cmds, recurse);
2261 ATController(Relation rel, List *cmds, bool recurse)
2266 /* Phase 1: preliminary examination of commands, create work queue */
2269 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2271 ATPrepCmd(&wqueue, rel, cmd, recurse, false);
2274 /* Close the relation, but keep lock until commit */
2275 relation_close(rel, NoLock);
2277 /* Phase 2: update system catalogs */
2278 ATRewriteCatalogs(&wqueue);
2280 /* Phase 3: scan/rewrite tables as needed */
2281 ATRewriteTables(&wqueue);
2287 * Traffic cop for ALTER TABLE Phase 1 operations, including simple
2288 * recursion and permission checks.
2290 * Caller must have acquired AccessExclusiveLock on relation already.
2291 * This lock should be held until commit.
2294 ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
2295 bool recurse, bool recursing)
2297 AlteredTableInfo *tab;
2300 /* Find or create work queue entry for this table */
2301 tab = ATGetQueueEntry(wqueue, rel);
2304 * Copy the original subcommand for each table. This avoids conflicts
2305 * when different child tables need to make different parse
2306 * transformations (for example, the same column may have different column
2307 * numbers in different children).
2309 cmd = copyObject(cmd);
2312 * Do permissions checking, recursion to child tables if needed, and any
2313 * additional phase-1 processing needed.
2315 switch (cmd->subtype)
2317 case AT_AddColumn: /* ADD COLUMN */
2318 ATSimplePermissions(rel, false);
2319 /* Performs own recursion */
2320 ATPrepAddColumn(wqueue, rel, recurse, cmd);
2321 pass = AT_PASS_ADD_COL;
2323 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
2326 * We allow defaults on views so that INSERT into a view can have
2327 * default-ish behavior. This works because the rewriter
2328 * substitutes default values into INSERTs before it expands
2331 ATSimplePermissions(rel, true);
2332 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2333 /* No command-specific prep needed */
2334 pass = cmd->def ? AT_PASS_ADD_CONSTR : AT_PASS_DROP;
2336 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
2337 ATSimplePermissions(rel, false);
2338 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2339 /* No command-specific prep needed */
2340 pass = AT_PASS_DROP;
2342 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
2343 ATSimplePermissions(rel, false);
2344 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2345 /* No command-specific prep needed */
2346 pass = AT_PASS_ADD_CONSTR;
2348 case AT_SetStatistics: /* ALTER COLUMN STATISTICS */
2349 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2350 /* Performs own permission checks */
2351 ATPrepSetStatistics(rel, cmd->name, cmd->def);
2352 pass = AT_PASS_COL_ATTRS;
2354 case AT_SetStorage: /* ALTER COLUMN STORAGE */
2355 ATSimplePermissions(rel, false);
2356 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2357 /* No command-specific prep needed */
2358 pass = AT_PASS_COL_ATTRS;
2360 case AT_DropColumn: /* DROP COLUMN */
2361 ATSimplePermissions(rel, false);
2362 /* Recursion occurs during execution phase */
2363 /* No command-specific prep needed except saving recurse flag */
2365 cmd->subtype = AT_DropColumnRecurse;
2366 pass = AT_PASS_DROP;
2368 case AT_AddIndex: /* ADD INDEX */
2369 ATSimplePermissions(rel, false);
2370 /* This command never recurses */
2371 /* No command-specific prep needed */
2372 pass = AT_PASS_ADD_INDEX;
2374 case AT_AddConstraint: /* ADD CONSTRAINT */
2375 ATSimplePermissions(rel, false);
2376 /* Recursion occurs during execution phase */
2377 /* No command-specific prep needed except saving recurse flag */
2379 cmd->subtype = AT_AddConstraintRecurse;
2380 pass = AT_PASS_ADD_CONSTR;
2382 case AT_DropConstraint: /* DROP 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_DropConstraintRecurse;
2388 pass = AT_PASS_DROP;
2390 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
2391 ATSimplePermissions(rel, false);
2392 /* Performs own recursion */
2393 ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd);
2394 pass = AT_PASS_ALTER_TYPE;
2396 case AT_ChangeOwner: /* ALTER OWNER */
2397 /* This command never recurses */
2398 /* No command-specific prep needed */
2399 pass = AT_PASS_MISC;
2401 case AT_ClusterOn: /* CLUSTER ON */
2402 case AT_DropCluster: /* SET WITHOUT CLUSTER */
2403 ATSimplePermissions(rel, false);
2404 /* These commands never recurse */
2405 /* No command-specific prep needed */
2406 pass = AT_PASS_MISC;
2408 case AT_DropOids: /* SET WITHOUT OIDS */
2409 ATSimplePermissions(rel, false);
2410 /* Performs own recursion */
2411 if (rel->rd_rel->relhasoids)
2413 AlterTableCmd *dropCmd = makeNode(AlterTableCmd);
2415 dropCmd->subtype = AT_DropColumn;
2416 dropCmd->name = pstrdup("oid");
2417 dropCmd->behavior = cmd->behavior;
2418 ATPrepCmd(wqueue, rel, dropCmd, recurse, false);
2420 pass = AT_PASS_DROP;
2422 case AT_SetTableSpace: /* SET TABLESPACE */
2423 ATSimplePermissionsRelationOrIndex(rel);
2424 /* This command never recurses */
2425 ATPrepSetTableSpace(tab, rel, cmd->name);
2426 pass = AT_PASS_MISC; /* doesn't actually matter */
2428 case AT_SetRelOptions: /* SET (...) */
2429 case AT_ResetRelOptions: /* RESET (...) */
2430 ATSimplePermissionsRelationOrIndex(rel);
2431 /* This command never recurses */
2432 /* No command-specific prep needed */
2433 pass = AT_PASS_MISC;
2435 case AT_EnableTrig: /* ENABLE TRIGGER variants */
2436 case AT_EnableAlwaysTrig:
2437 case AT_EnableReplicaTrig:
2438 case AT_EnableTrigAll:
2439 case AT_EnableTrigUser:
2440 case AT_DisableTrig: /* DISABLE TRIGGER variants */
2441 case AT_DisableTrigAll:
2442 case AT_DisableTrigUser:
2443 case AT_EnableRule: /* ENABLE/DISABLE RULE variants */
2444 case AT_EnableAlwaysRule:
2445 case AT_EnableReplicaRule:
2446 case AT_DisableRule:
2447 case AT_AddInherit: /* INHERIT / NO INHERIT */
2448 case AT_DropInherit:
2449 ATSimplePermissions(rel, false);
2450 /* These commands never recurse */
2451 /* No command-specific prep needed */
2452 pass = AT_PASS_MISC;
2455 elog(ERROR, "unrecognized alter table type: %d",
2456 (int) cmd->subtype);
2457 pass = 0; /* keep compiler quiet */
2461 /* Add the subcommand to the appropriate list for phase 2 */
2462 tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
2468 * Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
2469 * dispatched in a "safe" execution order (designed to avoid unnecessary
2473 ATRewriteCatalogs(List **wqueue)
2479 * We process all the tables "in parallel", one pass at a time. This is
2480 * needed because we may have to propagate work from one table to another
2481 * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
2482 * re-adding of the foreign key constraint to the other table). Work can
2483 * only be propagated into later passes, however.
2485 for (pass = 0; pass < AT_NUM_PASSES; pass++)
2487 /* Go through each table that needs to be processed */
2488 foreach(ltab, *wqueue)
2490 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2491 List *subcmds = tab->subcmds[pass];
2499 * Exclusive lock was obtained by phase 1, needn't get it again
2501 rel = relation_open(tab->relid, NoLock);
2503 foreach(lcmd, subcmds)
2504 ATExecCmd(wqueue, tab, rel, (AlterTableCmd *) lfirst(lcmd));
2507 * After the ALTER TYPE pass, do cleanup work (this is not done in
2508 * ATExecAlterColumnType since it should be done only once if
2509 * multiple columns of a table are altered).
2511 if (pass == AT_PASS_ALTER_TYPE)
2512 ATPostAlterTypeCleanup(wqueue, tab);
2514 relation_close(rel, NoLock);
2519 * Check to see if a toast table must be added, if we executed any
2520 * subcommands that might have added a column or changed column storage.
2522 foreach(ltab, *wqueue)
2524 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2526 if (tab->relkind == RELKIND_RELATION &&
2527 (tab->subcmds[AT_PASS_ADD_COL] ||
2528 tab->subcmds[AT_PASS_ALTER_TYPE] ||
2529 tab->subcmds[AT_PASS_COL_ATTRS]))
2530 AlterTableCreateToastTable(tab->relid);
2535 * ATExecCmd: dispatch a subcommand to appropriate execution routine
2538 ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
2541 switch (cmd->subtype)
2543 case AT_AddColumn: /* ADD COLUMN */
2544 ATExecAddColumn(tab, rel, (ColumnDef *) cmd->def);
2546 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
2547 ATExecColumnDefault(rel, cmd->name, cmd->def);
2549 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
2550 ATExecDropNotNull(rel, cmd->name);
2552 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
2553 ATExecSetNotNull(tab, rel, cmd->name);
2555 case AT_SetStatistics: /* ALTER COLUMN STATISTICS */
2556 ATExecSetStatistics(rel, cmd->name, cmd->def);
2558 case AT_SetStorage: /* ALTER COLUMN STORAGE */
2559 ATExecSetStorage(rel, cmd->name, cmd->def);
2561 case AT_DropColumn: /* DROP COLUMN */
2562 ATExecDropColumn(rel, cmd->name, cmd->behavior, false, false);
2564 case AT_DropColumnRecurse: /* DROP COLUMN with recursion */
2565 ATExecDropColumn(rel, cmd->name, cmd->behavior, true, false);
2567 case AT_AddIndex: /* ADD INDEX */
2568 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false);
2570 case AT_ReAddIndex: /* ADD INDEX */
2571 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true);
2573 case AT_AddConstraint: /* ADD CONSTRAINT */
2574 ATExecAddConstraint(wqueue, tab, rel, cmd->def, false);
2576 case AT_AddConstraintRecurse: /* ADD CONSTRAINT with recursion */
2577 ATExecAddConstraint(wqueue, tab, rel, cmd->def, true);
2579 case AT_DropConstraint: /* DROP CONSTRAINT */
2580 ATExecDropConstraint(rel, cmd->name, cmd->behavior, false, false);
2582 case AT_DropConstraintRecurse: /* DROP CONSTRAINT with recursion */
2583 ATExecDropConstraint(rel, cmd->name, cmd->behavior, true, false);
2585 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
2586 ATExecAlterColumnType(tab, rel, cmd->name, (TypeName *) cmd->def);
2588 case AT_ChangeOwner: /* ALTER OWNER */
2589 ATExecChangeOwner(RelationGetRelid(rel),
2590 get_roleid_checked(cmd->name),
2593 case AT_ClusterOn: /* CLUSTER ON */
2594 ATExecClusterOn(rel, cmd->name);
2596 case AT_DropCluster: /* SET WITHOUT CLUSTER */
2597 ATExecDropCluster(rel);
2599 case AT_DropOids: /* SET WITHOUT OIDS */
2602 * Nothing to do here; we'll have generated a DropColumn
2603 * subcommand to do the real work
2606 case AT_SetTableSpace: /* SET TABLESPACE */
2609 * Nothing to do here; Phase 3 does the work
2612 case AT_SetRelOptions: /* SET (...) */
2613 ATExecSetRelOptions(rel, (List *) cmd->def, false);
2615 case AT_ResetRelOptions: /* RESET (...) */
2616 ATExecSetRelOptions(rel, (List *) cmd->def, true);
2619 case AT_EnableTrig: /* ENABLE TRIGGER name */
2620 ATExecEnableDisableTrigger(rel, cmd->name,
2621 TRIGGER_FIRES_ON_ORIGIN, false);
2623 case AT_EnableAlwaysTrig: /* ENABLE ALWAYS TRIGGER name */
2624 ATExecEnableDisableTrigger(rel, cmd->name,
2625 TRIGGER_FIRES_ALWAYS, false);
2627 case AT_EnableReplicaTrig: /* ENABLE REPLICA TRIGGER name */
2628 ATExecEnableDisableTrigger(rel, cmd->name,
2629 TRIGGER_FIRES_ON_REPLICA, false);
2631 case AT_DisableTrig: /* DISABLE TRIGGER name */
2632 ATExecEnableDisableTrigger(rel, cmd->name,
2633 TRIGGER_DISABLED, false);
2635 case AT_EnableTrigAll: /* ENABLE TRIGGER ALL */
2636 ATExecEnableDisableTrigger(rel, NULL,
2637 TRIGGER_FIRES_ON_ORIGIN, false);
2639 case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
2640 ATExecEnableDisableTrigger(rel, NULL,
2641 TRIGGER_DISABLED, false);
2643 case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
2644 ATExecEnableDisableTrigger(rel, NULL,
2645 TRIGGER_FIRES_ON_ORIGIN, true);
2647 case AT_DisableTrigUser: /* DISABLE TRIGGER USER */
2648 ATExecEnableDisableTrigger(rel, NULL,
2649 TRIGGER_DISABLED, true);
2652 case AT_EnableRule: /* ENABLE RULE name */
2653 ATExecEnableDisableRule(rel, cmd->name,
2654 RULE_FIRES_ON_ORIGIN);
2656 case AT_EnableAlwaysRule: /* ENABLE ALWAYS RULE name */
2657 ATExecEnableDisableRule(rel, cmd->name,
2660 case AT_EnableReplicaRule: /* ENABLE REPLICA RULE name */
2661 ATExecEnableDisableRule(rel, cmd->name,
2662 RULE_FIRES_ON_REPLICA);
2664 case AT_DisableRule: /* DISABLE RULE name */
2665 ATExecEnableDisableRule(rel, cmd->name,
2670 ATExecAddInherit(rel, (RangeVar *) cmd->def);
2672 case AT_DropInherit:
2673 ATExecDropInherit(rel, (RangeVar *) cmd->def);
2676 elog(ERROR, "unrecognized alter table type: %d",
2677 (int) cmd->subtype);
2682 * Bump the command counter to ensure the next subcommand in the sequence
2683 * can see the changes so far
2685 CommandCounterIncrement();
2689 * ATRewriteTables: ALTER TABLE phase 3
2692 ATRewriteTables(List **wqueue)
2696 /* Go through each table that needs to be checked or rewritten */
2697 foreach(ltab, *wqueue)
2699 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2702 * We only need to rewrite the table if at least one column needs to
2705 if (tab->newvals != NIL)
2707 /* Build a temporary relation and copy data */
2709 char NewHeapName[NAMEDATALEN];
2712 ObjectAddress object;
2714 OldHeap = heap_open(tab->relid, NoLock);
2717 * We can never allow rewriting of shared or nailed-in-cache
2718 * relations, because we can't support changing their relfilenode
2721 if (OldHeap->rd_rel->relisshared || OldHeap->rd_isnailed)
2723 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2724 errmsg("cannot rewrite system relation \"%s\"",
2725 RelationGetRelationName(OldHeap))));
2728 * Don't allow rewrite on temp tables of other backends ... their
2729 * local buffer manager is not going to cope.
2731 if (isOtherTempNamespace(RelationGetNamespace(OldHeap)))
2733 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2734 errmsg("cannot rewrite temporary tables of other sessions")));
2737 * Select destination tablespace (same as original unless user
2738 * requested a change)
2740 if (tab->newTableSpace)
2741 NewTableSpace = tab->newTableSpace;
2743 NewTableSpace = OldHeap->rd_rel->reltablespace;
2745 heap_close(OldHeap, NoLock);
2748 * Create the new heap, using a temporary name in the same
2749 * namespace as the existing table. NOTE: there is some risk of
2750 * collision with user relnames. Working around this seems more
2751 * trouble than it's worth; in particular, we can't create the new
2752 * heap in a different namespace from the old, or we will have
2753 * problems with the TEMP status of temp tables.
2755 snprintf(NewHeapName, sizeof(NewHeapName),
2756 "pg_temp_%u", tab->relid);
2758 OIDNewHeap = make_new_heap(tab->relid, NewHeapName, NewTableSpace);
2761 * Copy the heap data into the new table with the desired
2762 * modifications, and test the current data within the table
2763 * against new constraints generated by ALTER TABLE commands.
2765 ATRewriteTable(tab, OIDNewHeap);
2768 * Swap the physical files of the old and new heaps. Since we are
2769 * generating a new heap, we can use RecentXmin for the table's
2770 * new relfrozenxid because we rewrote all the tuples on
2771 * ATRewriteTable, so no older Xid remains on the table.
2773 swap_relation_files(tab->relid, OIDNewHeap, RecentXmin);
2775 CommandCounterIncrement();
2777 /* Destroy new heap with old filenode */
2778 object.classId = RelationRelationId;
2779 object.objectId = OIDNewHeap;
2780 object.objectSubId = 0;
2783 * The new relation is local to our transaction and we know
2784 * nothing depends on it, so DROP_RESTRICT should be OK.
2786 performDeletion(&object, DROP_RESTRICT);
2787 /* performDeletion does CommandCounterIncrement at end */
2790 * Rebuild each index on the relation (but not the toast table,
2791 * which is all-new anyway). We do not need
2792 * CommandCounterIncrement() because reindex_relation does it.
2794 reindex_relation(tab->relid, false);
2799 * Test the current data within the table against new constraints
2800 * generated by ALTER TABLE commands, but don't rebuild data.
2802 if (tab->constraints != NIL || tab->new_notnull)
2803 ATRewriteTable(tab, InvalidOid);
2806 * If we had SET TABLESPACE but no reason to reconstruct tuples,
2807 * just do a block-by-block copy.
2809 if (tab->newTableSpace)
2810 ATExecSetTableSpace(tab->relid, tab->newTableSpace);
2815 * Foreign key constraints are checked in a final pass, since (a) it's
2816 * generally best to examine each one separately, and (b) it's at least
2817 * theoretically possible that we have changed both relations of the
2818 * foreign key, and we'd better have finished both rewrites before we try
2819 * to read the tables.
2821 foreach(ltab, *wqueue)
2823 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2824 Relation rel = NULL;
2827 foreach(lcon, tab->constraints)
2829 NewConstraint *con = lfirst(lcon);
2831 if (con->contype == CONSTR_FOREIGN)
2833 FkConstraint *fkconstraint = (FkConstraint *) con->qual;
2838 /* Long since locked, no need for another */
2839 rel = heap_open(tab->relid, NoLock);
2842 refrel = heap_open(con->refrelid, RowShareLock);
2844 validateForeignKeyConstraint(fkconstraint, rel, refrel,
2847 heap_close(refrel, NoLock);
2852 heap_close(rel, NoLock);
2857 * ATRewriteTable: scan or rewrite one table
2859 * OIDNewHeap is InvalidOid if we don't need to rewrite
2862 ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap)
2866 TupleDesc oldTupDesc;
2867 TupleDesc newTupDesc;
2868 bool needscan = false;
2869 List *notnull_attrs;
2875 * Open the relation(s). We have surely already locked the existing
2878 oldrel = heap_open(tab->relid, NoLock);
2879 oldTupDesc = tab->oldDesc;
2880 newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
2882 if (OidIsValid(OIDNewHeap))
2883 newrel = heap_open(OIDNewHeap, AccessExclusiveLock);
2888 * If we need to rewrite the table, the operation has to be propagated to
2889 * tables that use this table's rowtype as a column type.
2891 * (Eventually this will probably become true for scans as well, but at
2892 * the moment a composite type does not enforce any constraints, so it's
2893 * not necessary/appropriate to enforce them just during ALTER.)
2896 find_composite_type_dependencies(oldrel->rd_rel->reltype,
2897 RelationGetRelationName(oldrel),
2901 * Generate the constraint and default execution states
2904 estate = CreateExecutorState();
2906 /* Build the needed expression execution states */
2907 foreach(l, tab->constraints)
2909 NewConstraint *con = lfirst(l);
2911 switch (con->contype)
2915 con->qualstate = (List *)
2916 ExecPrepareExpr((Expr *) con->qual, estate);
2918 case CONSTR_FOREIGN:
2919 /* Nothing to do here */
2922 elog(ERROR, "unrecognized constraint type: %d",
2923 (int) con->contype);
2927 foreach(l, tab->newvals)
2929 NewColumnValue *ex = lfirst(l);
2933 ex->exprstate = ExecPrepareExpr((Expr *) ex->expr, estate);
2936 notnull_attrs = NIL;
2937 if (newrel || tab->new_notnull)
2940 * If we are rebuilding the tuples OR if we added any new NOT NULL
2941 * constraints, check all not-null constraints. This is a bit of
2942 * overkill but it minimizes risk of bugs, and heap_attisnull is a
2943 * pretty cheap test anyway.
2945 for (i = 0; i < newTupDesc->natts; i++)
2947 if (newTupDesc->attrs[i]->attnotnull &&
2948 !newTupDesc->attrs[i]->attisdropped)
2949 notnull_attrs = lappend_int(notnull_attrs, i);
2957 ExprContext *econtext;
2960 TupleTableSlot *oldslot;
2961 TupleTableSlot *newslot;
2964 MemoryContext oldCxt;
2965 List *dropped_attrs = NIL;
2968 econtext = GetPerTupleExprContext(estate);
2971 * Make tuple slots for old and new tuples. Note that even when the
2972 * tuples are the same, the tupDescs might not be (consider ADD COLUMN
2973 * without a default).
2975 oldslot = MakeSingleTupleTableSlot(oldTupDesc);
2976 newslot = MakeSingleTupleTableSlot(newTupDesc);
2978 /* Preallocate values/isnull arrays */
2979 i = Max(newTupDesc->natts, oldTupDesc->natts);
2980 values = (Datum *) palloc(i * sizeof(Datum));
2981 isnull = (bool *) palloc(i * sizeof(bool));
2982 memset(values, 0, i * sizeof(Datum));
2983 memset(isnull, true, i * sizeof(bool));
2986 * Any attributes that are dropped according to the new tuple
2987 * descriptor can be set to NULL. We precompute the list of dropped
2988 * attributes to avoid needing to do so in the per-tuple loop.
2990 for (i = 0; i < newTupDesc->natts; i++)
2992 if (newTupDesc->attrs[i]->attisdropped)
2993 dropped_attrs = lappend_int(dropped_attrs, i);
2997 * Scan through the rows, generating a new row if needed and then
2998 * checking all the constraints.
3000 scan = heap_beginscan(oldrel, SnapshotNow, 0, NULL);
3003 * Switch to per-tuple memory context and reset it for each tuple
3004 * produced, so we don't leak memory.
3006 oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
3008 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
3012 Oid tupOid = InvalidOid;
3014 /* Extract data from old tuple */
3015 heap_deform_tuple(tuple, oldTupDesc, values, isnull);
3016 if (oldTupDesc->tdhasoid)
3017 tupOid = HeapTupleGetOid(tuple);
3019 /* Set dropped attributes to null in new tuple */
3020 foreach(lc, dropped_attrs)
3021 isnull[lfirst_int(lc)] = true;
3024 * Process supplied expressions to replace selected columns.
3025 * Expression inputs come from the old tuple.
3027 ExecStoreTuple(tuple, oldslot, InvalidBuffer, false);
3028 econtext->ecxt_scantuple = oldslot;
3030 foreach(l, tab->newvals)
3032 NewColumnValue *ex = lfirst(l);
3034 values[ex->attnum - 1] = ExecEvalExpr(ex->exprstate,
3036 &isnull[ex->attnum - 1],
3041 * Form the new tuple. Note that we don't explicitly pfree it,
3042 * since the per-tuple memory context will be reset shortly.
3044 tuple = heap_form_tuple(newTupDesc, values, isnull);
3046 /* Preserve OID, if any */
3047 if (newTupDesc->tdhasoid)
3048 HeapTupleSetOid(tuple, tupOid);
3051 /* Now check any constraints on the possibly-changed tuple */
3052 ExecStoreTuple(tuple, newslot, InvalidBuffer, false);
3053 econtext->ecxt_scantuple = newslot;
3055 foreach(l, notnull_attrs)
3057 int attn = lfirst_int(l);
3059 if (heap_attisnull(tuple, attn + 1))
3061 (errcode(ERRCODE_NOT_NULL_VIOLATION),
3062 errmsg("column \"%s\" contains null values",
3063 NameStr(newTupDesc->attrs[attn]->attname))));
3066 foreach(l, tab->constraints)
3068 NewConstraint *con = lfirst(l);
3070 switch (con->contype)
3073 if (!ExecQual(con->qualstate, econtext, true))
3075 (errcode(ERRCODE_CHECK_VIOLATION),
3076 errmsg("check constraint \"%s\" is violated by some row",
3079 case CONSTR_FOREIGN:
3080 /* Nothing to do here */
3083 elog(ERROR, "unrecognized constraint type: %d",
3084 (int) con->contype);
3088 /* Write the tuple out to the new relation */
3090 simple_heap_insert(newrel, tuple);
3092 ResetExprContext(econtext);
3094 CHECK_FOR_INTERRUPTS();
3097 MemoryContextSwitchTo(oldCxt);
3100 ExecDropSingleTupleTableSlot(oldslot);
3101 ExecDropSingleTupleTableSlot(newslot);
3104 FreeExecutorState(estate);
3106 heap_close(oldrel, NoLock);
3108 heap_close(newrel, NoLock);
3112 * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
3114 static AlteredTableInfo *
3115 ATGetQueueEntry(List **wqueue, Relation rel)
3117 Oid relid = RelationGetRelid(rel);
3118 AlteredTableInfo *tab;
3121 foreach(ltab, *wqueue)
3123 tab = (AlteredTableInfo *) lfirst(ltab);
3124 if (tab->relid == relid)
3129 * Not there, so add it. Note that we make a copy of the relation's
3130 * existing descriptor before anything interesting can happen to it.
3132 tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
3134 tab->relkind = rel->rd_rel->relkind;
3135 tab->oldDesc = CreateTupleDescCopy(RelationGetDescr(rel));
3137 *wqueue = lappend(*wqueue, tab);
3143 * ATSimplePermissions
3145 * - Ensure that it is a relation (or possibly a view)
3146 * - Ensure this user is the owner
3147 * - Ensure that it is not a system table
3150 ATSimplePermissions(Relation rel, bool allowView)
3152 if (rel->rd_rel->relkind != RELKIND_RELATION)
3156 if (rel->rd_rel->relkind != RELKIND_VIEW)
3158 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3159 errmsg("\"%s\" is not a table or view",
3160 RelationGetRelationName(rel))));
3164 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3165 errmsg("\"%s\" is not a table",
3166 RelationGetRelationName(rel))));
3169 /* Permissions checks */
3170 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3171 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3172 RelationGetRelationName(rel));
3174 if (!allowSystemTableMods && IsSystemRelation(rel))
3176 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3177 errmsg("permission denied: \"%s\" is a system catalog",
3178 RelationGetRelationName(rel))));
3182 * ATSimplePermissionsRelationOrIndex
3184 * - Ensure that it is a relation or an index
3185 * - Ensure this user is the owner
3186 * - Ensure that it is not a system table
3189 ATSimplePermissionsRelationOrIndex(Relation rel)
3191 if (rel->rd_rel->relkind != RELKIND_RELATION &&
3192 rel->rd_rel->relkind != RELKIND_INDEX)
3194 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3195 errmsg("\"%s\" is not a table or index",
3196 RelationGetRelationName(rel))));
3198 /* Permissions checks */
3199 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3200 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3201 RelationGetRelationName(rel));
3203 if (!allowSystemTableMods && IsSystemRelation(rel))
3205 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3206 errmsg("permission denied: \"%s\" is a system catalog",
3207 RelationGetRelationName(rel))));
3213 * Simple table recursion sufficient for most ALTER TABLE operations.
3214 * All direct and indirect children are processed in an unspecified order.
3215 * Note that if a child inherits from the original table via multiple
3216 * inheritance paths, it will be visited just once.
3219 ATSimpleRecursion(List **wqueue, Relation rel,
3220 AlterTableCmd *cmd, bool recurse)
3223 * Propagate to children if desired. Non-table relations never have
3224 * children, so no need to search in that case.
3226 if (recurse && rel->rd_rel->relkind == RELKIND_RELATION)
3228 Oid relid = RelationGetRelid(rel);
3232 /* this routine is actually in the planner */
3233 children = find_all_inheritors(relid);
3236 * find_all_inheritors does the recursive search of the inheritance
3237 * hierarchy, so all we have to do is process all of the relids in the
3238 * list that it returns.
3240 foreach(child, children)
3242 Oid childrelid = lfirst_oid(child);
3245 if (childrelid == relid)
3247 childrel = relation_open(childrelid, AccessExclusiveLock);
3248 CheckTableNotInUse(childrel, "ALTER TABLE");
3249 ATPrepCmd(wqueue, childrel, cmd, false, true);
3250 relation_close(childrel, NoLock);
3256 * ATOneLevelRecursion
3258 * Here, we visit only direct inheritance children. It is expected that
3259 * the command's prep routine will recurse again to find indirect children.
3260 * When using this technique, a multiply-inheriting child will be visited
3264 ATOneLevelRecursion(List **wqueue, Relation rel,
3267 Oid relid = RelationGetRelid(rel);
3271 /* this routine is actually in the planner */
3272 children = find_inheritance_children(relid);
3274 foreach(child, children)
3276 Oid childrelid = lfirst_oid(child);
3279 childrel = relation_open(childrelid, AccessExclusiveLock);
3280 CheckTableNotInUse(childrel, "ALTER TABLE");
3281 ATPrepCmd(wqueue, childrel, cmd, true, true);
3282 relation_close(childrel, NoLock);
3288 * find_composite_type_dependencies
3290 * Check to see if a composite type is being used as a column in some
3291 * other table (possibly nested several levels deep in composite types!).
3292 * Eventually, we'd like to propagate the check or rewrite operation
3293 * into other such tables, but for now, just error out if we find any.
3295 * Caller should provide either a table name or a type name (not both) to
3296 * report in the error message, if any.
3298 * We assume that functions and views depending on the type are not reasons
3299 * to reject the ALTER. (How safe is this really?)
3302 find_composite_type_dependencies(Oid typeOid,
3303 const char *origTblName,
3304 const char *origTypeName)
3308 SysScanDesc depScan;
3313 * We scan pg_depend to find those things that depend on the rowtype. (We
3314 * assume we can ignore refobjsubid for a rowtype.)
3316 depRel = heap_open(DependRelationId, AccessShareLock);
3318 ScanKeyInit(&key[0],
3319 Anum_pg_depend_refclassid,
3320 BTEqualStrategyNumber, F_OIDEQ,
3321 ObjectIdGetDatum(TypeRelationId));
3322 ScanKeyInit(&key[1],
3323 Anum_pg_depend_refobjid,
3324 BTEqualStrategyNumber, F_OIDEQ,
3325 ObjectIdGetDatum(typeOid));
3327 depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
3328 SnapshotNow, 2, key);
3330 while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
3332 Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
3334 Form_pg_attribute att;
3336 /* Ignore dependees that aren't user columns of relations */
3337 /* (we assume system columns are never of rowtypes) */
3338 if (pg_depend->classid != RelationRelationId ||
3339 pg_depend->objsubid <= 0)
3342 rel = relation_open(pg_depend->objid, AccessShareLock);
3343 att = rel->rd_att->attrs[pg_depend->objsubid - 1];
3345 if (rel->rd_rel->relkind == RELKIND_RELATION)
3349 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3350 errmsg("cannot alter table \"%s\" because column \"%s\".\"%s\" uses its rowtype",
3352 RelationGetRelationName(rel),
3353 NameStr(att->attname))));
3356 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3357 errmsg("cannot alter type \"%s\" because column \"%s\".\"%s\" uses it",
3359 RelationGetRelationName(rel),
3360 NameStr(att->attname))));
3362 else if (OidIsValid(rel->rd_rel->reltype))
3365 * A view or composite type itself isn't a problem, but we must
3366 * recursively check for indirect dependencies via its rowtype.
3368 find_composite_type_dependencies(rel->rd_rel->reltype,
3369 origTblName, origTypeName);
3372 relation_close(rel, AccessShareLock);
3375 systable_endscan(depScan);
3377 relation_close(depRel, AccessShareLock);
3380 * If there's an array type for the rowtype, must check for uses of it,
3383 arrayOid = get_array_type(typeOid);
3384 if (OidIsValid(arrayOid))
3385 find_composite_type_dependencies(arrayOid, origTblName, origTypeName);
3390 * ALTER TABLE ADD COLUMN
3392 * Adds an additional attribute to a relation making the assumption that
3393 * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
3394 * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
3398 ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
3402 * Recurse to add the column to child classes, if requested.
3404 * We must recurse one level at a time, so that multiply-inheriting
3405 * children are visited the right number of times and end up with the
3406 * right attinhcount.
3410 AlterTableCmd *childCmd = copyObject(cmd);
3411 ColumnDef *colDefChild = (ColumnDef *) childCmd->def;
3413 /* Child should see column as singly inherited */
3414 colDefChild->inhcount = 1;
3415 colDefChild->is_local = false;
3417 ATOneLevelRecursion(wqueue, rel, childCmd);
3422 * If we are told not to recurse, there had better not be any child
3423 * tables; else the addition would put them out of step.
3425 if (find_inheritance_children(RelationGetRelid(rel)) != NIL)
3427 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3428 errmsg("column must be added to child tables too")));
3433 ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
3436 Oid myrelid = RelationGetRelid(rel);
3440 HeapTuple attributeTuple;
3441 Form_pg_attribute attribute;
3442 FormData_pg_attribute attributeD;
3446 HeapTuple typeTuple;
3452 attrdesc = heap_open(AttributeRelationId, RowExclusiveLock);
3455 * Are we adding the column to a recursion child? If so, check whether to
3456 * merge with an existing definition for the column.
3458 if (colDef->inhcount > 0)
3462 /* Does child already have a column by this name? */
3463 tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
3464 if (HeapTupleIsValid(tuple))
3466 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
3470 /* Okay if child matches by type */
3471 ctypeId = typenameTypeId(NULL, colDef->typename, &ctypmod);
3472 if (ctypeId != childatt->atttypid ||
3473 ctypmod != childatt->atttypmod)
3475 (errcode(ERRCODE_DATATYPE_MISMATCH),
3476 errmsg("child table \"%s\" has different type for column \"%s\"",
3477 RelationGetRelationName(rel), colDef->colname)));
3479 /* Bump the existing child att's inhcount */
3480 childatt->attinhcount++;
3481 simple_heap_update(attrdesc, &tuple->t_self, tuple);
3482 CatalogUpdateIndexes(attrdesc, tuple);
3484 heap_freetuple(tuple);
3486 /* Inform the user about the merge */
3488 (errmsg("merging definition of column \"%s\" for child \"%s\"",
3489 colDef->colname, RelationGetRelationName(rel))));
3491 heap_close(attrdesc, RowExclusiveLock);
3496 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
3498 reltup = SearchSysCacheCopy(RELOID,
3499 ObjectIdGetDatum(myrelid),
3501 if (!HeapTupleIsValid(reltup))
3502 elog(ERROR, "cache lookup failed for relation %u", myrelid);
3505 * this test is deliberately not attisdropped-aware, since if one tries to
3506 * add a column matching a dropped column name, it's gonna fail anyway.
3508 if (SearchSysCacheExists(ATTNAME,
3509 ObjectIdGetDatum(myrelid),
3510 PointerGetDatum(colDef->colname),
3513 (errcode(ERRCODE_DUPLICATE_COLUMN),
3514 errmsg("column \"%s\" of relation \"%s\" already exists",
3515 colDef->colname, RelationGetRelationName(rel))));
3517 minattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts;
3518 maxatts = minattnum + 1;
3519 if (maxatts > MaxHeapAttributeNumber)
3521 (errcode(ERRCODE_TOO_MANY_COLUMNS),
3522 errmsg("tables can have at most %d columns",
3523 MaxHeapAttributeNumber)));
3526 typeTuple = typenameType(NULL, colDef->typename, &typmod);
3527 tform = (Form_pg_type) GETSTRUCT(typeTuple);
3528 typeOid = HeapTupleGetOid(typeTuple);
3530 /* make sure datatype is legal for a column */
3531 CheckAttributeType(colDef->colname, typeOid);
3533 attributeTuple = heap_addheader(Natts_pg_attribute,
3535 ATTRIBUTE_TUPLE_SIZE,
3536 (void *) &attributeD);
3538 attribute = (Form_pg_attribute) GETSTRUCT(attributeTuple);
3540 attribute->attrelid = myrelid;
3541 namestrcpy(&(attribute->attname), colDef->colname);
3542 attribute->atttypid = typeOid;
3543 attribute->attstattarget = -1;
3544 attribute->attlen = tform->typlen;
3545 attribute->attcacheoff = -1;
3546 attribute->atttypmod = typmod;
3547 attribute->attnum = i;
3548 attribute->attbyval = tform->typbyval;
3549 attribute->attndims = list_length(colDef->typename->arrayBounds);
3550 attribute->attstorage = tform->typstorage;
3551 attribute->attalign = tform->typalign;
3552 attribute->attnotnull = colDef->is_not_null;
3553 attribute->atthasdef = false;
3554 attribute->attisdropped = false;
3555 attribute->attislocal = colDef->is_local;
3556 attribute->attinhcount = colDef->inhcount;
3558 ReleaseSysCache(typeTuple);
3560 simple_heap_insert(attrdesc, attributeTuple);
3562 /* Update indexes on pg_attribute */
3563 CatalogUpdateIndexes(attrdesc, attributeTuple);
3565 heap_close(attrdesc, RowExclusiveLock);
3568 * Update number of attributes in pg_class tuple
3570 ((Form_pg_class) GETSTRUCT(reltup))->relnatts = maxatts;
3572 simple_heap_update(pgclass, &reltup->t_self, reltup);
3574 /* keep catalog indexes current */
3575 CatalogUpdateIndexes(pgclass, reltup);
3577 heap_freetuple(reltup);
3579 heap_close(pgclass, RowExclusiveLock);
3581 /* Make the attribute's catalog entry visible */
3582 CommandCounterIncrement();
3585 * Store the DEFAULT, if any, in the catalogs
3587 if (colDef->raw_default)
3589 RawColumnDefault *rawEnt;
3591 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3592 rawEnt->attnum = attribute->attnum;
3593 rawEnt->raw_default = copyObject(colDef->raw_default);
3596 * This function is intended for CREATE TABLE, so it processes a
3597 * _list_ of defaults, but we just do one.
3599 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL, false, true);
3601 /* Make the additional catalog changes visible */
3602 CommandCounterIncrement();
3606 * Tell Phase 3 to fill in the default expression, if there is one.
3608 * If there is no default, Phase 3 doesn't have to do anything, because
3609 * that effectively means that the default is NULL. The heap tuple access
3610 * routines always check for attnum > # of attributes in tuple, and return
3611 * NULL if so, so without any modification of the tuple data we will get
3612 * the effect of NULL values in the new column.
3614 * An exception occurs when the new column is of a domain type: the domain
3615 * might have a NOT NULL constraint, or a check constraint that indirectly
3616 * rejects nulls. If there are any domain constraints then we construct
3617 * an explicit NULL default value that will be passed through
3618 * CoerceToDomain processing. (This is a tad inefficient, since it causes
3619 * rewriting the table which we really don't have to do, but the present
3620 * design of domain processing doesn't offer any simple way of checking
3621 * the constraints more directly.)
3623 * Note: we use build_column_default, and not just the cooked default
3624 * returned by AddRelationNewConstraints, so that the right thing happens
3625 * when a datatype's default applies.
3627 defval = (Expr *) build_column_default(rel, attribute->attnum);
3629 if (!defval && GetDomainConstraints(typeOid) != NIL)
3634 baseTypeMod = typmod;
3635 baseTypeId = getBaseTypeAndTypmod(typeOid, &baseTypeMod);
3636 defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod);
3637 defval = (Expr *) coerce_to_target_type(NULL,
3642 COERCION_ASSIGNMENT,
3643 COERCE_IMPLICIT_CAST);
3644 if (defval == NULL) /* should not happen */
3645 elog(ERROR, "failed to coerce base type to domain");
3650 NewColumnValue *newval;
3652 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
3653 newval->attnum = attribute->attnum;
3654 newval->expr = defval;
3656 tab->newvals = lappend(tab->newvals, newval);
3660 * If the new column is NOT NULL, tell Phase 3 it needs to test that.
3662 tab->new_notnull |= colDef->is_not_null;
3665 * Add needed dependency entries for the new column.
3667 add_column_datatype_dependency(myrelid, i, attribute->atttypid);
3671 * Install a column's dependency on its datatype.
3674 add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
3676 ObjectAddress myself,
3679 myself.classId = RelationRelationId;
3680 myself.objectId = relid;
3681 myself.objectSubId = attnum;
3682 referenced.classId = TypeRelationId;
3683 referenced.objectId = typid;
3684 referenced.objectSubId = 0;
3685 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
3689 * ALTER TABLE ALTER COLUMN DROP NOT NULL
3692 ATExecDropNotNull(Relation rel, const char *colName)
3698 ListCell *indexoidscan;
3701 * lookup the attribute
3703 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3705 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3707 if (!HeapTupleIsValid(tuple))
3709 (errcode(ERRCODE_UNDEFINED_COLUMN),
3710 errmsg("column \"%s\" of relation \"%s\" does not exist",
3711 colName, RelationGetRelationName(rel))));
3713 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3715 /* Prevent them from altering a system attribute */
3718 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3719 errmsg("cannot alter system column \"%s\"",
3723 * Check that the attribute is not in a primary key
3726 /* Loop over all indexes on the relation */
3727 indexoidlist = RelationGetIndexList(rel);
3729 foreach(indexoidscan, indexoidlist)
3731 Oid indexoid = lfirst_oid(indexoidscan);
3732 HeapTuple indexTuple;
3733 Form_pg_index indexStruct;
3736 indexTuple = SearchSysCache(INDEXRELID,
3737 ObjectIdGetDatum(indexoid),
3739 if (!HeapTupleIsValid(indexTuple))
3740 elog(ERROR, "cache lookup failed for index %u", indexoid);
3741 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
3743 /* If the index is not a primary key, skip the check */
3744 if (indexStruct->indisprimary)
3747 * Loop over each attribute in the primary key and see if it
3748 * matches the to-be-altered attribute
3750 for (i = 0; i < indexStruct->indnatts; i++)
3752 if (indexStruct->indkey.values[i] == attnum)
3754 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3755 errmsg("column \"%s\" is in a primary key",
3760 ReleaseSysCache(indexTuple);
3763 list_free(indexoidlist);
3766 * Okay, actually perform the catalog change ... if needed
3768 if (((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3770 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = FALSE;
3772 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3774 /* keep the system catalog indexes current */
3775 CatalogUpdateIndexes(attr_rel, tuple);
3778 heap_close(attr_rel, RowExclusiveLock);
3782 * ALTER TABLE ALTER COLUMN SET NOT NULL
3785 ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
3786 const char *colName)
3793 * lookup the attribute
3795 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3797 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3799 if (!HeapTupleIsValid(tuple))
3801 (errcode(ERRCODE_UNDEFINED_COLUMN),
3802 errmsg("column \"%s\" of relation \"%s\" does not exist",
3803 colName, RelationGetRelationName(rel))));
3805 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3807 /* Prevent them from altering a system attribute */
3810 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3811 errmsg("cannot alter system column \"%s\"",
3815 * Okay, actually perform the catalog change ... if needed
3817 if (!((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3819 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = TRUE;
3821 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3823 /* keep the system catalog indexes current */
3824 CatalogUpdateIndexes(attr_rel, tuple);
3826 /* Tell Phase 3 it needs to test the constraint */
3827 tab->new_notnull = true;
3830 heap_close(attr_rel, RowExclusiveLock);
3834 * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
3837 ATExecColumnDefault(Relation rel, const char *colName,
3843 * get the number of the attribute
3845 attnum = get_attnum(RelationGetRelid(rel), colName);
3846 if (attnum == InvalidAttrNumber)
3848 (errcode(ERRCODE_UNDEFINED_COLUMN),
3849 errmsg("column \"%s\" of relation \"%s\" does not exist",
3850 colName, RelationGetRelationName(rel))));
3852 /* Prevent them from altering a system attribute */
3855 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3856 errmsg("cannot alter system column \"%s\"",
3860 * Remove any old default for the column. We use RESTRICT here for
3861 * safety, but at present we do not expect anything to depend on the
3864 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false);
3869 RawColumnDefault *rawEnt;
3871 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3872 rawEnt->attnum = attnum;
3873 rawEnt->raw_default = newDefault;
3876 * This function is intended for CREATE TABLE, so it processes a
3877 * _list_ of defaults, but we just do one.
3879 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL, false, true);
3884 * ALTER TABLE ALTER COLUMN SET STATISTICS
3887 ATPrepSetStatistics(Relation rel, const char *colName, Node *flagValue)
3890 * We do our own permission checking because (a) we want to allow SET
3891 * STATISTICS on indexes (for expressional index columns), and (b) we want
3892 * to allow SET STATISTICS on system catalogs without requiring
3893 * allowSystemTableMods to be turned on.
3895 if (rel->rd_rel->relkind != RELKIND_RELATION &&
3896 rel->rd_rel->relkind != RELKIND_INDEX)
3898 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3899 errmsg("\"%s\" is not a table or index",
3900 RelationGetRelationName(rel))));
3902 /* Permissions checks */
3903 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3904 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3905 RelationGetRelationName(rel));
3909 ATExecSetStatistics(Relation rel, const char *colName, Node *newValue)
3912 Relation attrelation;
3914 Form_pg_attribute attrtuple;
3916 Assert(IsA(newValue, Integer));
3917 newtarget = intVal(newValue);
3920 * Limit target to a sane range
3925 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3926 errmsg("statistics target %d is too low",
3929 else if (newtarget > 1000)
3933 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3934 errmsg("lowering statistics target to %d",
3938 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
3940 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3942 if (!HeapTupleIsValid(tuple))
3944 (errcode(ERRCODE_UNDEFINED_COLUMN),
3945 errmsg("column \"%s\" of relation \"%s\" does not exist",
3946 colName, RelationGetRelationName(rel))));
3947 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
3949 if (attrtuple->attnum <= 0)
3951 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3952 errmsg("cannot alter system column \"%s\"",
3955 attrtuple->attstattarget = newtarget;
3957 simple_heap_update(attrelation, &tuple->t_self, tuple);
3959 /* keep system catalog indexes current */
3960 CatalogUpdateIndexes(attrelation, tuple);
3962 heap_freetuple(tuple);
3964 heap_close(attrelation, RowExclusiveLock);
3968 * ALTER TABLE ALTER COLUMN SET STORAGE
3971 ATExecSetStorage(Relation rel, const char *colName, Node *newValue)
3975 Relation attrelation;
3977 Form_pg_attribute attrtuple;
3979 Assert(IsA(newValue, String));
3980 storagemode = strVal(newValue);
3982 if (pg_strcasecmp(storagemode, "plain") == 0)
3984 else if (pg_strcasecmp(storagemode, "external") == 0)
3986 else if (pg_strcasecmp(storagemode, "extended") == 0)
3988 else if (pg_strcasecmp(storagemode, "main") == 0)
3993 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3994 errmsg("invalid storage type \"%s\"",
3996 newstorage = 0; /* keep compiler quiet */
3999 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
4001 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4003 if (!HeapTupleIsValid(tuple))
4005 (errcode(ERRCODE_UNDEFINED_COLUMN),
4006 errmsg("column \"%s\" of relation \"%s\" does not exist",
4007 colName, RelationGetRelationName(rel))));
4008 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
4010 if (attrtuple->attnum <= 0)
4012 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4013 errmsg("cannot alter system column \"%s\"",
4017 * safety check: do not allow toasted storage modes unless column datatype
4020 if (newstorage == 'p' || TypeIsToastable(attrtuple->atttypid))
4021 attrtuple->attstorage = newstorage;
4024 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4025 errmsg("column data type %s can only have storage PLAIN",
4026 format_type_be(attrtuple->atttypid))));
4028 simple_heap_update(attrelation, &tuple->t_self, tuple);
4030 /* keep system catalog indexes current */
4031 CatalogUpdateIndexes(attrelation, tuple);
4033 heap_freetuple(tuple);
4035 heap_close(attrelation, RowExclusiveLock);
4040 * ALTER TABLE DROP COLUMN
4042 * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
4043 * because we have to decide at runtime whether to recurse or not depending
4044 * on whether attinhcount goes to zero or not. (We can't check this in a
4045 * static pre-pass because it won't handle multiple inheritance situations
4046 * correctly.) Since DROP COLUMN doesn't need to create any work queue
4047 * entries for Phase 3, it's okay to recurse internally in this routine
4048 * without considering the work queue.
4051 ATExecDropColumn(Relation rel, const char *colName,
4052 DropBehavior behavior,
4053 bool recurse, bool recursing)
4056 Form_pg_attribute targetatt;
4059 ObjectAddress object;
4061 /* At top level, permission check was done in ATPrepCmd, else do it */
4063 ATSimplePermissions(rel, false);
4066 * get the number of the attribute
4068 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
4069 if (!HeapTupleIsValid(tuple))
4071 (errcode(ERRCODE_UNDEFINED_COLUMN),
4072 errmsg("column \"%s\" of relation \"%s\" does not exist",
4073 colName, RelationGetRelationName(rel))));
4074 targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
4076 attnum = targetatt->attnum;
4078 /* Can't drop a system attribute, except OID */
4079 if (attnum <= 0 && attnum != ObjectIdAttributeNumber)
4081 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4082 errmsg("cannot drop system column \"%s\"",
4085 /* Don't drop inherited columns */
4086 if (targetatt->attinhcount > 0 && !recursing)
4088 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4089 errmsg("cannot drop inherited column \"%s\"",
4092 ReleaseSysCache(tuple);
4095 * Propagate to children as appropriate. Unlike most other ALTER
4096 * routines, we have to do this one level of recursion at a time; we can't
4097 * use find_all_inheritors to do it in one pass.
4099 children = find_inheritance_children(RelationGetRelid(rel));
4106 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
4107 foreach(child, children)
4109 Oid childrelid = lfirst_oid(child);
4111 Form_pg_attribute childatt;
4113 childrel = heap_open(childrelid, AccessExclusiveLock);
4114 CheckTableNotInUse(childrel, "ALTER TABLE");
4116 tuple = SearchSysCacheCopyAttName(childrelid, colName);
4117 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
4118 elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
4119 colName, childrelid);
4120 childatt = (Form_pg_attribute) GETSTRUCT(tuple);
4122 if (childatt->attinhcount <= 0) /* shouldn't happen */
4123 elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
4124 childrelid, colName);
4129 * If the child column has other definition sources, just
4130 * decrement its inheritance count; if not, recurse to delete
4133 if (childatt->attinhcount == 1 && !childatt->attislocal)
4135 /* Time to delete this child column, too */
4136 ATExecDropColumn(childrel, colName, behavior, true, true);
4140 /* Child column must survive my deletion */
4141 childatt->attinhcount--;
4143 simple_heap_update(attr_rel, &tuple->t_self, tuple);
4145 /* keep the system catalog indexes current */
4146 CatalogUpdateIndexes(attr_rel, tuple);
4148 /* Make update visible */
4149 CommandCounterIncrement();
4155 * If we were told to drop ONLY in this table (no recursion),
4156 * we need to mark the inheritors' attributes as locally
4157 * defined rather than inherited.
4159 childatt->attinhcount--;
4160 childatt->attislocal = true;
4162 simple_heap_update(attr_rel, &tuple->t_self, tuple);
4164 /* keep the system catalog indexes current */
4165 CatalogUpdateIndexes(attr_rel, tuple);
4167 /* Make update visible */
4168 CommandCounterIncrement();
4171 heap_freetuple(tuple);
4173 heap_close(childrel, NoLock);
4175 heap_close(attr_rel, RowExclusiveLock);
4179 * Perform the actual column deletion
4181 object.classId = RelationRelationId;
4182 object.objectId = RelationGetRelid(rel);
4183 object.objectSubId = attnum;
4185 performDeletion(&object, behavior);
4188 * If we dropped the OID column, must adjust pg_class.relhasoids
4190 if (attnum == ObjectIdAttributeNumber)
4193 Form_pg_class tuple_class;
4195 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
4197 tuple = SearchSysCacheCopy(RELOID,
4198 ObjectIdGetDatum(RelationGetRelid(rel)),
4200 if (!HeapTupleIsValid(tuple))
4201 elog(ERROR, "cache lookup failed for relation %u",
4202 RelationGetRelid(rel));
4203 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
4205 tuple_class->relhasoids = false;
4206 simple_heap_update(class_rel, &tuple->t_self, tuple);
4208 /* Keep the catalog indexes up to date */
4209 CatalogUpdateIndexes(class_rel, tuple);
4211 heap_close(class_rel, RowExclusiveLock);
4216 * ALTER TABLE ADD INDEX
4218 * There is no such command in the grammar, but parse_utilcmd.c converts
4219 * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands. This lets
4220 * us schedule creation of the index at the appropriate time during ALTER.
4223 ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
4224 IndexStmt *stmt, bool is_rebuild)
4230 Assert(IsA(stmt, IndexStmt));
4232 /* suppress schema rights check when rebuilding existing index */
4233 check_rights = !is_rebuild;
4234 /* skip index build if phase 3 will have to rewrite table anyway */
4235 skip_build = (tab->newvals != NIL);
4236 /* suppress notices when rebuilding existing index */
4239 /* The IndexStmt has already been through transformIndexStmt */
4241 DefineIndex(stmt->relation, /* relation */
4242 stmt->idxname, /* index name */
4243 InvalidOid, /* no predefined OID */
4244 stmt->accessMethod, /* am name */
4246 stmt->indexParams, /* parameters */
4247 (Expr *) stmt->whereClause,
4252 true, /* is_alter_table */
4260 * ALTER TABLE ADD CONSTRAINT
4263 ATExecAddConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
4264 Node *newConstraint, bool recurse)
4266 switch (nodeTag(newConstraint))
4270 Constraint *constr = (Constraint *) newConstraint;
4273 * Currently, we only expect to see CONSTR_CHECK nodes
4274 * arriving here (see the preprocessing done in
4275 * parse_utilcmd.c). Use a switch anyway to make it easier to
4276 * add more code later.
4278 switch (constr->contype)
4281 ATAddCheckConstraint(wqueue, tab, rel,
4282 constr, recurse, false);
4285 elog(ERROR, "unrecognized constraint type: %d",
4286 (int) constr->contype);
4290 case T_FkConstraint:
4292 FkConstraint *fkconstraint = (FkConstraint *) newConstraint;
4295 * Note that we currently never recurse for FK constraints,
4296 * so the "recurse" flag is silently ignored.
4298 * Assign or validate constraint name
4300 if (fkconstraint->constr_name)
4302 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
4303 RelationGetRelid(rel),
4304 RelationGetNamespace(rel),
4305 fkconstraint->constr_name))
4307 (errcode(ERRCODE_DUPLICATE_OBJECT),
4308 errmsg("constraint \"%s\" for relation \"%s\" already exists",
4309 fkconstraint->constr_name,
4310 RelationGetRelationName(rel))));
4313 fkconstraint->constr_name =
4314 ChooseConstraintName(RelationGetRelationName(rel),
4315 strVal(linitial(fkconstraint->fk_attrs)),
4317 RelationGetNamespace(rel),
4320 ATAddForeignKeyConstraint(tab, rel, fkconstraint);
4325 elog(ERROR, "unrecognized node type: %d",
4326 (int) nodeTag(newConstraint));
4331 * Add a check constraint to a single table and its children
4333 * Subroutine for ATExecAddConstraint.
4335 * We must recurse to child tables during execution, rather than using
4336 * ALTER TABLE's normal prep-time recursion. The reason is that all the
4337 * constraints *must* be given the same name, else they won't be seen as
4338 * related later. If the user didn't explicitly specify a name, then
4339 * AddRelationNewConstraints would normally assign different names to the
4340 * child constraints. To fix that, we must capture the name assigned at
4341 * the parent table and pass that down.
4344 ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
4345 Constraint *constr, bool recurse, bool recursing)
4352 /* At top level, permission check was done in ATPrepCmd, else do it */
4354 ATSimplePermissions(rel, false);
4357 * Call AddRelationNewConstraints to do the work, making sure it works on
4358 * a copy of the Constraint so transformExpr can't modify the original.
4359 * It returns a list of cooked constraints.
4361 * If the constraint ends up getting merged with a pre-existing one, it's
4362 * omitted from the returned list, which is what we want: we do not need
4363 * to do any validation work. That can only happen at child tables,
4364 * though, since we disallow merging at the top level.
4366 newcons = AddRelationNewConstraints(rel, NIL,
4367 list_make1(copyObject(constr)),
4368 recursing, !recursing);
4370 /* Add each constraint to Phase 3's queue */
4371 foreach(lcon, newcons)
4373 CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
4374 NewConstraint *newcon;
4376 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
4377 newcon->name = ccon->name;
4378 newcon->contype = ccon->contype;
4379 /* ExecQual wants implicit-AND format */
4380 newcon->qual = (Node *) make_ands_implicit((Expr *) ccon->expr);
4382 tab->constraints = lappend(tab->constraints, newcon);
4384 /* Save the actually assigned name if it was defaulted */
4385 if (constr->name == NULL)
4386 constr->name = ccon->name;
4389 /* At this point we must have a locked-down name to use */
4390 Assert(constr->name != NULL);
4392 /* Advance command counter in case same table is visited multiple times */
4393 CommandCounterIncrement();
4396 * Propagate to children as appropriate. Unlike most other ALTER
4397 * routines, we have to do this one level of recursion at a time; we can't
4398 * use find_all_inheritors to do it in one pass.
4400 children = find_inheritance_children(RelationGetRelid(rel));
4403 * If we are told not to recurse, there had better not be any child
4404 * tables; else the addition would put them out of step.
4406 if (children && !recurse)
4408 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4409 errmsg("constraint must be added to child tables too")));
4411 foreach(child, children)
4413 Oid childrelid = lfirst_oid(child);
4415 AlteredTableInfo *childtab;
4417 childrel = heap_open(childrelid, AccessExclusiveLock);
4418 CheckTableNotInUse(childrel, "ALTER TABLE");
4420 /* Find or create work queue entry for this table */
4421 childtab = ATGetQueueEntry(wqueue, childrel);
4423 /* Recurse to child */
4424 ATAddCheckConstraint(wqueue, childtab, childrel,
4425 constr, recurse, true);
4427 heap_close(childrel, NoLock);
4432 * Add a foreign-key constraint to a single table
4434 * Subroutine for ATExecAddConstraint. Must already hold exclusive
4435 * lock on the rel, and have done appropriate validity/permissions checks
4439 ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
4440 FkConstraint *fkconstraint)
4443 AclResult aclresult;
4444 int16 pkattnum[INDEX_MAX_KEYS];
4445 int16 fkattnum[INDEX_MAX_KEYS];
4446 Oid pktypoid[INDEX_MAX_KEYS];
4447 Oid fktypoid[INDEX_MAX_KEYS];
4448 Oid opclasses[INDEX_MAX_KEYS];
4449 Oid pfeqoperators[INDEX_MAX_KEYS];
4450 Oid ppeqoperators[INDEX_MAX_KEYS];
4451 Oid ffeqoperators[INDEX_MAX_KEYS];
4459 * Grab an exclusive lock on the pk table, so that someone doesn't delete
4460 * rows out from under us. (Although a lesser lock would do for that
4461 * purpose, we'll need exclusive lock anyway to add triggers to the pk
4462 * table; trying to start with a lesser lock will just create a risk of
4465 pkrel = heap_openrv(fkconstraint->pktable, AccessExclusiveLock);
4468 * Validity and permissions checks
4470 * Note: REFERENCES permissions checks are redundant with CREATE TRIGGER,
4471 * but we may as well error out sooner instead of later.
4473 if (pkrel->rd_rel->relkind != RELKIND_RELATION)
4475 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4476 errmsg("referenced relation \"%s\" is not a table",
4477 RelationGetRelationName(pkrel))));
4479 aclresult = pg_class_aclcheck(RelationGetRelid(pkrel), GetUserId(),
4481 if (aclresult != ACLCHECK_OK)
4482 aclcheck_error(aclresult, ACL_KIND_CLASS,
4483 RelationGetRelationName(pkrel));
4485 if (!allowSystemTableMods && IsSystemRelation(pkrel))
4487 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4488 errmsg("permission denied: \"%s\" is a system catalog",
4489 RelationGetRelationName(pkrel))));
4491 aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
4493 if (aclresult != ACLCHECK_OK)
4494 aclcheck_error(aclresult, ACL_KIND_CLASS,
4495 RelationGetRelationName(rel));
4498 * Disallow reference from permanent table to temp table or vice versa.
4499 * (The ban on perm->temp is for fairly obvious reasons. The ban on
4500 * temp->perm is because other backends might need to run the RI triggers
4501 * on the perm table, but they can't reliably see tuples the owning
4502 * backend has created in the temp table, because non-shared buffers are
4503 * used for temp tables.)
4505 if (isTempNamespace(RelationGetNamespace(pkrel)))
4507 if (!isTempNamespace(RelationGetNamespace(rel)))
4509 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4510 errmsg("cannot reference temporary table from permanent table constraint")));
4514 if (isTempNamespace(RelationGetNamespace(rel)))
4516 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4517 errmsg("cannot reference permanent table from temporary table constraint")));
4521 * Look up the referencing attributes to make sure they exist, and record
4522 * their attnums and type OIDs.
4524 MemSet(pkattnum, 0, sizeof(pkattnum));
4525 MemSet(fkattnum, 0, sizeof(fkattnum));
4526 MemSet(pktypoid, 0, sizeof(pktypoid));
4527 MemSet(fktypoid, 0, sizeof(fktypoid));
4528 MemSet(opclasses, 0, sizeof(opclasses));
4529 MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
4530 MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
4531 MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
4533 numfks = transformColumnNameList(RelationGetRelid(rel),
4534 fkconstraint->fk_attrs,
4535 fkattnum, fktypoid);
4538 * If the attribute list for the referenced table was omitted, lookup the
4539 * definition of the primary key and use it. Otherwise, validate the
4540 * supplied attribute list. In either case, discover the index OID and
4541 * index opclasses, and the attnums and type OIDs of the attributes.
4543 if (fkconstraint->pk_attrs == NIL)
4545 numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
4546 &fkconstraint->pk_attrs,
4552 numpks = transformColumnNameList(RelationGetRelid(pkrel),
4553 fkconstraint->pk_attrs,
4554 pkattnum, pktypoid);
4555 /* Look for an index matching the column list */
4556 indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
4561 * Look up the equality operators to use in the constraint.
4563 * Note that we have to be careful about the difference between the actual
4564 * PK column type and the opclass' declared input type, which might be
4565 * only binary-compatible with it. The declared opcintype is the right
4566 * thing to probe pg_amop with.
4568 if (numfks != numpks)
4570 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4571 errmsg("number of referencing and referenced columns for foreign key disagree")));
4573 for (i = 0; i < numpks; i++)
4575 Oid pktype = pktypoid[i];
4576 Oid fktype = fktypoid[i];
4579 Form_pg_opclass cla_tup;
4588 /* We need several fields out of the pg_opclass entry */
4589 cla_ht = SearchSysCache(CLAOID,
4590 ObjectIdGetDatum(opclasses[i]),
4592 if (!HeapTupleIsValid(cla_ht))
4593 elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
4594 cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
4595 amid = cla_tup->opcmethod;
4596 opfamily = cla_tup->opcfamily;
4597 opcintype = cla_tup->opcintype;
4598 ReleaseSysCache(cla_ht);
4601 * Check it's a btree; currently this can never fail since no other
4602 * index AMs support unique indexes. If we ever did have other types
4603 * of unique indexes, we'd need a way to determine which operator
4604 * strategy number is equality. (Is it reasonable to insist that
4605 * every such index AM use btree's number for equality?)
4607 if (amid != BTREE_AM_OID)
4608 elog(ERROR, "only b-tree indexes are supported for foreign keys");
4609 eqstrategy = BTEqualStrategyNumber;
4612 * There had better be a primary equality operator for the index.
4613 * We'll use it for PK = PK comparisons.
4615 ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
4618 if (!OidIsValid(ppeqop))
4619 elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
4620 eqstrategy, opcintype, opcintype, opfamily);
4623 * Are there equality operators that take exactly the FK type? Assume
4624 * we should look through any domain here.
4626 fktyped = getBaseType(fktype);
4628 pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
4630 if (OidIsValid(pfeqop))
4631 ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
4634 ffeqop = InvalidOid; /* keep compiler quiet */
4636 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4639 * Otherwise, look for an implicit cast from the FK type to the
4640 * opcintype, and if found, use the primary equality operator.
4641 * This is a bit tricky because opcintype might be a polymorphic
4642 * type such as ANYARRAY or ANYENUM; so what we have to test is
4643 * whether the two actual column types can be concurrently cast to
4644 * that type. (Otherwise, we'd fail to reject combinations such
4645 * as int[] and point[].)
4647 Oid input_typeids[2];
4648 Oid target_typeids[2];
4650 input_typeids[0] = pktype;
4651 input_typeids[1] = fktype;
4652 target_typeids[0] = opcintype;
4653 target_typeids[1] = opcintype;
4654 if (can_coerce_type(2, input_typeids, target_typeids,
4656 pfeqop = ffeqop = ppeqop;
4659 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4661 (errcode(ERRCODE_DATATYPE_MISMATCH),
4662 errmsg("foreign key constraint \"%s\" "
4663 "cannot be implemented",
4664 fkconstraint->constr_name),
4665 errdetail("Key columns \"%s\" and \"%s\" "
4666 "are of incompatible types: %s and %s.",
4667 strVal(list_nth(fkconstraint->fk_attrs, i)),
4668 strVal(list_nth(fkconstraint->pk_attrs, i)),
4669 format_type_be(fktype),
4670 format_type_be(pktype))));
4672 pfeqoperators[i] = pfeqop;
4673 ppeqoperators[i] = ppeqop;
4674 ffeqoperators[i] = ffeqop;
4678 * Record the FK constraint in pg_constraint.
4680 constrOid = CreateConstraintEntry(fkconstraint->constr_name,
4681 RelationGetNamespace(rel),
4683 fkconstraint->deferrable,
4684 fkconstraint->initdeferred,
4685 RelationGetRelid(rel),
4688 InvalidOid, /* not a domain
4690 RelationGetRelid(pkrel),
4696 fkconstraint->fk_upd_action,
4697 fkconstraint->fk_del_action,
4698 fkconstraint->fk_matchtype,
4700 NULL, /* no check constraint */
4707 * Create the triggers that will enforce the constraint.
4709 createForeignKeyTriggers(rel, fkconstraint, constrOid);
4712 * Tell Phase 3 to check that the constraint is satisfied by existing rows
4713 * (we can skip this during table creation).
4715 if (!fkconstraint->skip_validation)
4717 NewConstraint *newcon;
4719 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
4720 newcon->name = fkconstraint->constr_name;
4721 newcon->contype = CONSTR_FOREIGN;
4722 newcon->refrelid = RelationGetRelid(pkrel);
4723 newcon->conid = constrOid;
4724 newcon->qual = (Node *) fkconstraint;
4726 tab->constraints = lappend(tab->constraints, newcon);
4730 * Close pk table, but keep lock until we've committed.
4732 heap_close(pkrel, NoLock);
4737 * transformColumnNameList - transform list of column names
4739 * Lookup each name and return its attnum and type OID
4742 transformColumnNameList(Oid relId, List *colList,
4743 int16 *attnums, Oid *atttypids)
4751 char *attname = strVal(lfirst(l));
4754 atttuple = SearchSysCacheAttName(relId, attname);
4755 if (!HeapTupleIsValid(atttuple))
4757 (errcode(ERRCODE_UNDEFINED_COLUMN),
4758 errmsg("column \"%s\" referenced in foreign key constraint does not exist",
4760 if (attnum >= INDEX_MAX_KEYS)
4762 (errcode(ERRCODE_TOO_MANY_COLUMNS),
4763 errmsg("cannot have more than %d keys in a foreign key",
4765 attnums[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->attnum;
4766 atttypids[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->atttypid;
4767 ReleaseSysCache(atttuple);
4775 * transformFkeyGetPrimaryKey -
4777 * Look up the names, attnums, and types of the primary key attributes
4778 * for the pkrel. Also return the index OID and index opclasses of the
4779 * index supporting the primary key.
4781 * All parameters except pkrel are output parameters. Also, the function
4782 * return value is the number of attributes in the primary key.
4784 * Used when the column list in the REFERENCES specification is omitted.
4787 transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
4789 int16 *attnums, Oid *atttypids,
4793 ListCell *indexoidscan;
4794 HeapTuple indexTuple = NULL;
4795 Form_pg_index indexStruct = NULL;
4796 Datum indclassDatum;
4798 oidvector *indclass;
4802 * Get the list of index OIDs for the table from the relcache, and look up
4803 * each one in the pg_index syscache until we find one marked primary key
4804 * (hopefully there isn't more than one such).
4806 *indexOid = InvalidOid;
4808 indexoidlist = RelationGetIndexList(pkrel);
4810 foreach(indexoidscan, indexoidlist)
4812 Oid indexoid = lfirst_oid(indexoidscan);
4814 indexTuple = SearchSysCache(INDEXRELID,
4815 ObjectIdGetDatum(indexoid),
4817 if (!HeapTupleIsValid(indexTuple))
4818 elog(ERROR, "cache lookup failed for index %u", indexoid);
4819 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4820 if (indexStruct->indisprimary)
4822 *indexOid = indexoid;
4825 ReleaseSysCache(indexTuple);
4828 list_free(indexoidlist);
4831 * Check that we found it
4833 if (!OidIsValid(*indexOid))
4835 (errcode(ERRCODE_UNDEFINED_OBJECT),
4836 errmsg("there is no primary key for referenced table \"%s\"",
4837 RelationGetRelationName(pkrel))));
4839 /* Must get indclass the hard way */
4840 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4841 Anum_pg_index_indclass, &isnull);
4843 indclass = (oidvector *) DatumGetPointer(indclassDatum);
4846 * Now build the list of PK attributes from the indkey definition (we
4847 * assume a primary key cannot have expressional elements)
4850 for (i = 0; i < indexStruct->indnatts; i++)
4852 int pkattno = indexStruct->indkey.values[i];
4854 attnums[i] = pkattno;
4855 atttypids[i] = attnumTypeId(pkrel, pkattno);
4856 opclasses[i] = indclass->values[i];
4857 *attnamelist = lappend(*attnamelist,
4858 makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
4861 ReleaseSysCache(indexTuple);
4867 * transformFkeyCheckAttrs -
4869 * Make sure that the attributes of a referenced table belong to a unique
4870 * (or primary key) constraint. Return the OID of the index supporting
4871 * the constraint, as well as the opclasses associated with the index
4875 transformFkeyCheckAttrs(Relation pkrel,
4876 int numattrs, int16 *attnums,
4877 Oid *opclasses) /* output parameter */
4879 Oid indexoid = InvalidOid;
4882 ListCell *indexoidscan;
4885 * Get the list of index OIDs for the table from the relcache, and look up
4886 * each one in the pg_index syscache, and match unique indexes to the list
4887 * of attnums we are given.
4889 indexoidlist = RelationGetIndexList(pkrel);
4891 foreach(indexoidscan, indexoidlist)
4893 HeapTuple indexTuple;
4894 Form_pg_index indexStruct;
4898 indexoid = lfirst_oid(indexoidscan);
4899 indexTuple = SearchSysCache(INDEXRELID,
4900 ObjectIdGetDatum(indexoid),
4902 if (!HeapTupleIsValid(indexTuple))
4903 elog(ERROR, "cache lookup failed for index %u", indexoid);
4904 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4907 * Must have the right number of columns; must be unique and not a
4908 * partial index; forget it if there are any expressions, too
4910 if (indexStruct->indnatts == numattrs &&
4911 indexStruct->indisunique &&
4912 heap_attisnull(indexTuple, Anum_pg_index_indpred) &&
4913 heap_attisnull(indexTuple, Anum_pg_index_indexprs))
4915 /* Must get indclass the hard way */
4916 Datum indclassDatum;
4918 oidvector *indclass;
4920 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4921 Anum_pg_index_indclass, &isnull);
4923 indclass = (oidvector *) DatumGetPointer(indclassDatum);
4926 * The given attnum list may match the index columns in any order.
4927 * Check that each list is a subset of the other.
4929 for (i = 0; i < numattrs; i++)
4932 for (j = 0; j < numattrs; j++)
4934 if (attnums[i] == indexStruct->indkey.values[j])
4945 for (i = 0; i < numattrs; i++)
4948 for (j = 0; j < numattrs; j++)
4950 if (attnums[j] == indexStruct->indkey.values[i])
4952 opclasses[j] = indclass->values[i];
4962 ReleaseSysCache(indexTuple);
4969 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4970 errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
4971 RelationGetRelationName(pkrel))));
4973 list_free(indexoidlist);
4979 * Scan the existing rows in a table to verify they meet a proposed FK
4982 * Caller must have opened and locked both relations.
4985 validateForeignKeyConstraint(FkConstraint *fkconstraint,
4995 * Build a trigger call structure; we'll need it either way.
4997 MemSet(&trig, 0, sizeof(trig));
4998 trig.tgoid = InvalidOid;
4999 trig.tgname = fkconstraint->constr_name;
5000 trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
5001 trig.tgisconstraint = TRUE;
5002 trig.tgconstrrelid = RelationGetRelid(pkrel);
5003 trig.tgconstraint = constraintOid;
5004 trig.tgdeferrable = FALSE;
5005 trig.tginitdeferred = FALSE;
5006 /* we needn't fill in tgargs */
5009 * See if we can do it with a single LEFT JOIN query. A FALSE result
5010 * indicates we must proceed with the fire-the-trigger method.
5012 if (RI_Initial_Check(&trig, rel, pkrel))
5016 * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
5017 * if that tuple had just been inserted. If any of those fail, it should
5018 * ereport(ERROR) and that's that.
5020 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
5022 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
5024 FunctionCallInfoData fcinfo;
5025 TriggerData trigdata;
5028 * Make a call to the trigger function
5030 * No parameters are passed, but we do set a context
5032 MemSet(&fcinfo, 0, sizeof(fcinfo));
5035 * We assume RI_FKey_check_ins won't look at flinfo...
5037 trigdata.type = T_TriggerData;
5038 trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
5039 trigdata.tg_relation = rel;
5040 trigdata.tg_trigtuple = tuple;
5041 trigdata.tg_newtuple = NULL;
5042 trigdata.tg_trigger = &trig;
5043 trigdata.tg_trigtuplebuf = scan->rs_cbuf;
5044 trigdata.tg_newtuplebuf = InvalidBuffer;
5046 fcinfo.context = (Node *) &trigdata;
5048 RI_FKey_check_ins(&fcinfo);
5055 CreateFKCheckTrigger(RangeVar *myRel, FkConstraint *fkconstraint,
5056 Oid constraintOid, bool on_insert)
5058 CreateTrigStmt *fk_trigger;
5060 fk_trigger = makeNode(CreateTrigStmt);
5061 fk_trigger->trigname = fkconstraint->constr_name;
5062 fk_trigger->relation = myRel;
5063 fk_trigger->before = false;
5064 fk_trigger->row = true;
5066 /* Either ON INSERT or ON UPDATE */
5069 fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
5070 fk_trigger->actions[0] = 'i';
5074 fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
5075 fk_trigger->actions[0] = 'u';
5077 fk_trigger->actions[1] = '\0';
5079 fk_trigger->isconstraint = true;
5080 fk_trigger->deferrable = fkconstraint->deferrable;
5081 fk_trigger->initdeferred = fkconstraint->initdeferred;
5082 fk_trigger->constrrel = fkconstraint->pktable;
5083 fk_trigger->args = NIL;
5085 (void) CreateTrigger(fk_trigger, constraintOid);
5087 /* Make changes-so-far visible */
5088 CommandCounterIncrement();
5092 * Create the triggers that implement an FK constraint.
5095 createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
5099 CreateTrigStmt *fk_trigger;
5102 * Reconstruct a RangeVar for my relation (not passed in, unfortunately).
5104 myRel = makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
5105 pstrdup(RelationGetRelationName(rel)));
5107 /* Make changes-so-far visible */
5108 CommandCounterIncrement();
5111 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the CHECK
5112 * action for both INSERTs and UPDATEs on the referencing table.
5114 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, true);
5115 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, false);
5118 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
5119 * DELETE action on the referenced table.
5121 fk_trigger = makeNode(CreateTrigStmt);
5122 fk_trigger->trigname = fkconstraint->constr_name;
5123 fk_trigger->relation = fkconstraint->pktable;
5124 fk_trigger->before = false;
5125 fk_trigger->row = true;
5126 fk_trigger->actions[0] = 'd';
5127 fk_trigger->actions[1] = '\0';
5129 fk_trigger->isconstraint = true;
5130 fk_trigger->constrrel = myRel;
5131 switch (fkconstraint->fk_del_action)
5133 case FKCONSTR_ACTION_NOACTION:
5134 fk_trigger->deferrable = fkconstraint->deferrable;
5135 fk_trigger->initdeferred = fkconstraint->initdeferred;
5136 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
5138 case FKCONSTR_ACTION_RESTRICT:
5139 fk_trigger->deferrable = false;
5140 fk_trigger->initdeferred = false;
5141 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
5143 case FKCONSTR_ACTION_CASCADE:
5144 fk_trigger->deferrable = false;
5145 fk_trigger->initdeferred = false;
5146 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
5148 case FKCONSTR_ACTION_SETNULL:
5149 fk_trigger->deferrable = false;
5150 fk_trigger->initdeferred = false;
5151 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
5153 case FKCONSTR_ACTION_SETDEFAULT:
5154 fk_trigger->deferrable = false;
5155 fk_trigger->initdeferred = false;
5156 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
5159 elog(ERROR, "unrecognized FK action type: %d",
5160 (int) fkconstraint->fk_del_action);
5163 fk_trigger->args = NIL;
5165 (void) CreateTrigger(fk_trigger, constraintOid);
5167 /* Make changes-so-far visible */
5168 CommandCounterIncrement();
5171 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
5172 * UPDATE action on the referenced table.
5174 fk_trigger = makeNode(CreateTrigStmt);
5175 fk_trigger->trigname = fkconstraint->constr_name;
5176 fk_trigger->relation = fkconstraint->pktable;
5177 fk_trigger->before = false;
5178 fk_trigger->row = true;
5179 fk_trigger->actions[0] = 'u';
5180 fk_trigger->actions[1] = '\0';
5181 fk_trigger->isconstraint = true;
5182 fk_trigger->constrrel = myRel;
5183 switch (fkconstraint->fk_upd_action)
5185 case FKCONSTR_ACTION_NOACTION:
5186 fk_trigger->deferrable = fkconstraint->deferrable;
5187 fk_trigger->initdeferred = fkconstraint->initdeferred;
5188 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
5190 case FKCONSTR_ACTION_RESTRICT:
5191 fk_trigger->deferrable = false;
5192 fk_trigger->initdeferred = false;
5193 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
5195 case FKCONSTR_ACTION_CASCADE:
5196 fk_trigger->deferrable = false;
5197 fk_trigger->initdeferred = false;
5198 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
5200 case FKCONSTR_ACTION_SETNULL:
5201 fk_trigger->deferrable = false;
5202 fk_trigger->initdeferred = false;
5203 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
5205 case FKCONSTR_ACTION_SETDEFAULT:
5206 fk_trigger->deferrable = false;
5207 fk_trigger->initdeferred = false;
5208 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
5211 elog(ERROR, "unrecognized FK action type: %d",
5212 (int) fkconstraint->fk_upd_action);
5215 fk_trigger->args = NIL;
5217 (void) CreateTrigger(fk_trigger, constraintOid);
5221 * ALTER TABLE DROP CONSTRAINT
5223 * Like DROP COLUMN, we can't use the normal ALTER TABLE recursion mechanism.
5226 ATExecDropConstraint(Relation rel, const char *constrName,
5227 DropBehavior behavior,
5228 bool recurse, bool recursing)
5233 Form_pg_constraint con;
5238 bool is_check_constraint = false;
5240 /* At top level, permission check was done in ATPrepCmd, else do it */
5242 ATSimplePermissions(rel, false);
5244 conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
5247 * Find and drop the target constraint
5250 Anum_pg_constraint_conrelid,
5251 BTEqualStrategyNumber, F_OIDEQ,
5252 ObjectIdGetDatum(RelationGetRelid(rel)));
5253 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
5254 true, SnapshotNow, 1, &key);
5256 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
5258 ObjectAddress conobj;
5260 con = (Form_pg_constraint) GETSTRUCT(tuple);
5262 if (strcmp(NameStr(con->conname), constrName) != 0)
5265 /* Don't drop inherited constraints */
5266 if (con->coninhcount > 0 && !recursing)
5268 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5269 errmsg("cannot drop inherited constraint \"%s\" of relation \"%s\"",
5270 constrName, RelationGetRelationName(rel))));
5272 /* Right now only CHECK constraints can be inherited */
5273 if (con->contype == CONSTRAINT_CHECK)
5274 is_check_constraint = true;
5277 * Perform the actual constraint deletion
5279 conobj.classId = ConstraintRelationId;
5280 conobj.objectId = HeapTupleGetOid(tuple);
5281 conobj.objectSubId = 0;
5283 performDeletion(&conobj, behavior);
5288 systable_endscan(scan);
5292 (errcode(ERRCODE_UNDEFINED_OBJECT),
5293 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
5294 constrName, RelationGetRelationName(rel))));
5297 * Propagate to children as appropriate. Unlike most other ALTER
5298 * routines, we have to do this one level of recursion at a time; we can't
5299 * use find_all_inheritors to do it in one pass.
5301 if (is_check_constraint)
5302 children = find_inheritance_children(RelationGetRelid(rel));
5306 foreach(child, children)
5308 Oid childrelid = lfirst_oid(child);
5311 childrel = heap_open(childrelid, AccessExclusiveLock);
5312 CheckTableNotInUse(childrel, "ALTER TABLE");
5315 Anum_pg_constraint_conrelid,
5316 BTEqualStrategyNumber, F_OIDEQ,
5317 ObjectIdGetDatum(childrelid));
5318 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
5319 true, SnapshotNow, 1, &key);
5323 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
5325 HeapTuple copy_tuple;
5327 con = (Form_pg_constraint) GETSTRUCT(tuple);
5329 /* Right now only CHECK constraints can be inherited */
5330 if (con->contype != CONSTRAINT_CHECK)
5333 if (strcmp(NameStr(con->conname), constrName) != 0)
5338 if (con->coninhcount <= 0) /* shouldn't happen */
5339 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
5340 childrelid, constrName);
5342 copy_tuple = heap_copytuple(tuple);
5343 con = (Form_pg_constraint) GETSTRUCT(copy_tuple);
5348 * If the child constraint has other definition sources,
5349 * just decrement its inheritance count; if not, recurse
5352 if (con->coninhcount == 1 && !con->conislocal)
5354 /* Time to delete this child constraint, too */
5355 ATExecDropConstraint(childrel, constrName, behavior,
5360 /* Child constraint must survive my deletion */
5362 simple_heap_update(conrel, ©_tuple->t_self, copy_tuple);
5363 CatalogUpdateIndexes(conrel, copy_tuple);
5365 /* Make update visible */
5366 CommandCounterIncrement();
5372 * If we were told to drop ONLY in this table (no
5373 * recursion), we need to mark the inheritors' constraints
5374 * as locally defined rather than inherited.
5377 con->conislocal = true;
5379 simple_heap_update(conrel, ©_tuple->t_self, copy_tuple);
5380 CatalogUpdateIndexes(conrel, copy_tuple);
5382 /* Make update visible */
5383 CommandCounterIncrement();
5386 heap_freetuple(copy_tuple);
5389 systable_endscan(scan);
5393 (errcode(ERRCODE_UNDEFINED_OBJECT),
5394 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
5396 RelationGetRelationName(childrel))));
5398 heap_close(childrel, NoLock);
5401 heap_close(conrel, RowExclusiveLock);
5408 ATPrepAlterColumnType(List **wqueue,
5409 AlteredTableInfo *tab, Relation rel,
5410 bool recurse, bool recursing,
5413 char *colName = cmd->name;
5414 TypeName *typename = (TypeName *) cmd->def;
5416 Form_pg_attribute attTup;
5421 NewColumnValue *newval;
5422 ParseState *pstate = make_parsestate(NULL);
5424 /* lookup the attribute so we can check inheritance status */
5425 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
5426 if (!HeapTupleIsValid(tuple))
5428 (errcode(ERRCODE_UNDEFINED_COLUMN),
5429 errmsg("column \"%s\" of relation \"%s\" does not exist",
5430 colName, RelationGetRelationName(rel))));
5431 attTup = (Form_pg_attribute) GETSTRUCT(tuple);
5432 attnum = attTup->attnum;
5434 /* Can't alter a system attribute */
5437 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5438 errmsg("cannot alter system column \"%s\"",
5441 /* Don't alter inherited columns */
5442 if (attTup->attinhcount > 0 && !recursing)
5444 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5445 errmsg("cannot alter inherited column \"%s\"",
5448 /* Look up the target type */
5449 targettype = typenameTypeId(NULL, typename, &targettypmod);
5451 /* make sure datatype is legal for a column */
5452 CheckAttributeType(colName, targettype);
5455 * Set up an expression to transform the old data value to the new type.
5456 * If a USING option was given, transform and use that expression, else
5457 * just take the old value and try to coerce it. We do this first so that
5458 * type incompatibility can be detected before we waste effort, and
5459 * because we need the expression to be parsed against the original table
5466 /* Expression must be able to access vars of old table */
5467 rte = addRangeTableEntryForRelation(pstate,
5472 addRTEtoQuery(pstate, rte, false, true, true);
5474 transform = transformExpr(pstate, cmd->transform);
5476 /* It can't return a set */
5477 if (expression_returns_set(transform))
5479 (errcode(ERRCODE_DATATYPE_MISMATCH),
5480 errmsg("transform expression must not return a set")));
5482 /* No subplans or aggregates, either... */
5483 if (pstate->p_hasSubLinks)
5485 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5486 errmsg("cannot use subquery in transform expression")));
5487 if (pstate->p_hasAggs)
5489 (errcode(ERRCODE_GROUPING_ERROR),
5490 errmsg("cannot use aggregate function in transform expression")));
5494 transform = (Node *) makeVar(1, attnum,
5495 attTup->atttypid, attTup->atttypmod,
5499 transform = coerce_to_target_type(pstate,
5500 transform, exprType(transform),
5501 targettype, targettypmod,
5502 COERCION_ASSIGNMENT,
5503 COERCE_IMPLICIT_CAST);
5504 if (transform == NULL)
5506 (errcode(ERRCODE_DATATYPE_MISMATCH),
5507 errmsg("column \"%s\" cannot be cast to type \"%s\"",
5508 colName, TypeNameToString(typename))));
5511 * Add a work queue item to make ATRewriteTable update the column
5514 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
5515 newval->attnum = attnum;
5516 newval->expr = (Expr *) transform;
5518 tab->newvals = lappend(tab->newvals, newval);
5520 ReleaseSysCache(tuple);
5523 * The recursion case is handled by ATSimpleRecursion. However, if we are
5524 * told not to recurse, there had better not be any child tables; else the
5525 * alter would put them out of step.
5528 ATSimpleRecursion(wqueue, rel, cmd, recurse);
5529 else if (!recursing &&
5530 find_inheritance_children(RelationGetRelid(rel)) != NIL)
5532 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5533 errmsg("type of inherited column \"%s\" must be changed in child tables too",
5538 ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
5539 const char *colName, TypeName *typename)
5542 Form_pg_attribute attTup;
5544 HeapTuple typeTuple;
5549 Relation attrelation;
5555 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
5557 /* Look up the target column */
5558 heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5559 if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
5561 (errcode(ERRCODE_UNDEFINED_COLUMN),
5562 errmsg("column \"%s\" of relation \"%s\" does not exist",
5563 colName, RelationGetRelationName(rel))));
5564 attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
5565 attnum = attTup->attnum;
5567 /* Check for multiple ALTER TYPE on same column --- can't cope */
5568 if (attTup->atttypid != tab->oldDesc->attrs[attnum - 1]->atttypid ||
5569 attTup->atttypmod != tab->oldDesc->attrs[attnum - 1]->atttypmod)
5571 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5572 errmsg("cannot alter type of column \"%s\" twice",
5575 /* Look up the target type (should not fail, since prep found it) */
5576 typeTuple = typenameType(NULL, typename, &targettypmod);
5577 tform = (Form_pg_type) GETSTRUCT(typeTuple);
5578 targettype = HeapTupleGetOid(typeTuple);
5581 * If there is a default expression for the column, get it and ensure we
5582 * can coerce it to the new datatype. (We must do this before changing
5583 * the column type, because build_column_default itself will try to
5584 * coerce, and will not issue the error message we want if it fails.)
5586 * We remove any implicit coercion steps at the top level of the old
5587 * default expression; this has been agreed to satisfy the principle of
5588 * least surprise. (The conversion to the new column type should act like
5589 * it started from what the user sees as the stored expression, and the
5590 * implicit coercions aren't going to be shown.)
5592 if (attTup->atthasdef)
5594 defaultexpr = build_column_default(rel, attnum);
5595 Assert(defaultexpr);
5596 defaultexpr = strip_implicit_coercions(defaultexpr);
5597 defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
5598 defaultexpr, exprType(defaultexpr),
5599 targettype, targettypmod,
5600 COERCION_ASSIGNMENT,
5601 COERCE_IMPLICIT_CAST);
5602 if (defaultexpr == NULL)
5604 (errcode(ERRCODE_DATATYPE_MISMATCH),
5605 errmsg("default for column \"%s\" cannot be cast to type \"%s\"",
5606 colName, TypeNameToString(typename))));
5612 * Find everything that depends on the column (constraints, indexes, etc),
5613 * and record enough information to let us recreate the objects.
5615 * The actual recreation does not happen here, but only after we have
5616 * performed all the individual ALTER TYPE operations. We have to save
5617 * the info before executing ALTER TYPE, though, else the deparser will
5620 * There could be multiple entries for the same object, so we must check
5621 * to ensure we process each one only once. Note: we assume that an index
5622 * that implements a constraint will not show a direct dependency on the
5625 depRel = heap_open(DependRelationId, RowExclusiveLock);
5627 ScanKeyInit(&key[0],
5628 Anum_pg_depend_refclassid,
5629 BTEqualStrategyNumber, F_OIDEQ,
5630 ObjectIdGetDatum(RelationRelationId));
5631 ScanKeyInit(&key[1],
5632 Anum_pg_depend_refobjid,
5633 BTEqualStrategyNumber, F_OIDEQ,
5634 ObjectIdGetDatum(RelationGetRelid(rel)));
5635 ScanKeyInit(&key[2],
5636 Anum_pg_depend_refobjsubid,
5637 BTEqualStrategyNumber, F_INT4EQ,
5638 Int32GetDatum((int32) attnum));
5640 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
5641 SnapshotNow, 3, key);
5643 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5645 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5646 ObjectAddress foundObject;
5648 /* We don't expect any PIN dependencies on columns */
5649 if (foundDep->deptype == DEPENDENCY_PIN)
5650 elog(ERROR, "cannot alter type of a pinned column");
5652 foundObject.classId = foundDep->classid;
5653 foundObject.objectId = foundDep->objid;
5654 foundObject.objectSubId = foundDep->objsubid;
5656 switch (getObjectClass(&foundObject))
5660 char relKind = get_rel_relkind(foundObject.objectId);
5662 if (relKind == RELKIND_INDEX)
5664 Assert(foundObject.objectSubId == 0);
5665 if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
5667 tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
5668 foundObject.objectId);
5669 tab->changedIndexDefs = lappend(tab->changedIndexDefs,
5670 pg_get_indexdef_string(foundObject.objectId));
5673 else if (relKind == RELKIND_SEQUENCE)
5676 * This must be a SERIAL column's sequence. We need
5677 * not do anything to it.
5679 Assert(foundObject.objectSubId == 0);
5683 /* Not expecting any other direct dependencies... */
5684 elog(ERROR, "unexpected object depending on column: %s",
5685 getObjectDescription(&foundObject));
5690 case OCLASS_CONSTRAINT:
5691 Assert(foundObject.objectSubId == 0);
5692 if (!list_member_oid(tab->changedConstraintOids,
5693 foundObject.objectId))
5695 char *defstring = pg_get_constraintdef_string(foundObject.objectId);
5698 * Put NORMAL dependencies at the front of the list and
5699 * AUTO dependencies at the back. This makes sure that
5700 * foreign-key constraints depending on this column will
5701 * be dropped before unique or primary-key constraints of
5702 * the column; which we must have because the FK
5703 * constraints depend on the indexes belonging to the
5704 * unique constraints.
5706 if (foundDep->deptype == DEPENDENCY_NORMAL)
5708 tab->changedConstraintOids =
5709 lcons_oid(foundObject.objectId,
5710 tab->changedConstraintOids);
5711 tab->changedConstraintDefs =
5713 tab->changedConstraintDefs);
5717 tab->changedConstraintOids =
5718 lappend_oid(tab->changedConstraintOids,
5719 foundObject.objectId);
5720 tab->changedConstraintDefs =
5721 lappend(tab->changedConstraintDefs,
5727 case OCLASS_REWRITE:
5728 /* XXX someday see if we can cope with revising views */
5730 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5731 errmsg("cannot alter type of a column used by a view or rule"),
5732 errdetail("%s depends on column \"%s\"",
5733 getObjectDescription(&foundObject),
5737 case OCLASS_DEFAULT:
5740 * Ignore the column's default expression, since we will fix
5743 Assert(defaultexpr);
5749 case OCLASS_CONVERSION:
5750 case OCLASS_LANGUAGE:
5751 case OCLASS_OPERATOR:
5752 case OCLASS_OPCLASS:
5753 case OCLASS_OPFAMILY:
5754 case OCLASS_TRIGGER:
5756 case OCLASS_TSPARSER:
5758 case OCLASS_TSTEMPLATE:
5759 case OCLASS_TSCONFIG:
5762 * We don't expect any of these sorts of objects to depend on
5765 elog(ERROR, "unexpected object depending on column: %s",
5766 getObjectDescription(&foundObject));
5770 elog(ERROR, "unrecognized object class: %u",
5771 foundObject.classId);
5775 systable_endscan(scan);
5778 * Now scan for dependencies of this column on other things. The only
5779 * thing we should find is the dependency on the column datatype, which we
5782 ScanKeyInit(&key[0],
5783 Anum_pg_depend_classid,
5784 BTEqualStrategyNumber, F_OIDEQ,
5785 ObjectIdGetDatum(RelationRelationId));
5786 ScanKeyInit(&key[1],
5787 Anum_pg_depend_objid,
5788 BTEqualStrategyNumber, F_OIDEQ,
5789 ObjectIdGetDatum(RelationGetRelid(rel)));
5790 ScanKeyInit(&key[2],
5791 Anum_pg_depend_objsubid,
5792 BTEqualStrategyNumber, F_INT4EQ,
5793 Int32GetDatum((int32) attnum));
5795 scan = systable_beginscan(depRel, DependDependerIndexId, true,
5796 SnapshotNow, 3, key);
5798 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5800 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5802 if (foundDep->deptype != DEPENDENCY_NORMAL)
5803 elog(ERROR, "found unexpected dependency type '%c'",
5805 if (foundDep->refclassid != TypeRelationId ||
5806 foundDep->refobjid != attTup->atttypid)
5807 elog(ERROR, "found unexpected dependency for column");
5809 simple_heap_delete(depRel, &depTup->t_self);
5812 systable_endscan(scan);
5814 heap_close(depRel, RowExclusiveLock);
5817 * Here we go --- change the recorded column type. (Note heapTup is a
5818 * copy of the syscache entry, so okay to scribble on.)
5820 attTup->atttypid = targettype;
5821 attTup->atttypmod = targettypmod;
5822 attTup->attndims = list_length(typename->arrayBounds);
5823 attTup->attlen = tform->typlen;
5824 attTup->attbyval = tform->typbyval;
5825 attTup->attalign = tform->typalign;
5826 attTup->attstorage = tform->typstorage;
5828 ReleaseSysCache(typeTuple);
5830 simple_heap_update(attrelation, &heapTup->t_self, heapTup);
5832 /* keep system catalog indexes current */
5833 CatalogUpdateIndexes(attrelation, heapTup);
5835 heap_close(attrelation, RowExclusiveLock);
5837 /* Install dependency on new datatype */
5838 add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
5841 * Drop any pg_statistic entry for the column, since it's now wrong type
5843 RemoveStatistics(RelationGetRelid(rel), attnum);
5846 * Update the default, if present, by brute force --- remove and re-add
5847 * the default. Probably unsafe to take shortcuts, since the new version
5848 * may well have additional dependencies. (It's okay to do this now,
5849 * rather than after other ALTER TYPE commands, since the default won't
5850 * depend on other column types.)
5854 /* Must make new row visible since it will be updated again */
5855 CommandCounterIncrement();
5858 * We use RESTRICT here for safety, but at present we do not expect
5859 * anything to depend on the default.
5861 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true);
5863 StoreAttrDefault(rel, attnum, defaultexpr);
5867 heap_freetuple(heapTup);
5871 * Cleanup after we've finished all the ALTER TYPE operations for a
5872 * particular relation. We have to drop and recreate all the indexes
5873 * and constraints that depend on the altered columns.
5876 ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab)
5882 * Re-parse the index and constraint definitions, and attach them to the
5883 * appropriate work queue entries. We do this before dropping because in
5884 * the case of a FOREIGN KEY constraint, we might not yet have exclusive
5885 * lock on the table the constraint is attached to, and we need to get
5886 * that before dropping. It's safe because the parser won't actually look
5887 * at the catalogs to detect the existing entry.
5889 foreach(l, tab->changedIndexDefs)
5890 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
5891 foreach(l, tab->changedConstraintDefs)
5892 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
5895 * Now we can drop the existing constraints and indexes --- constraints
5896 * first, since some of them might depend on the indexes. In fact, we
5897 * have to delete FOREIGN KEY constraints before UNIQUE constraints, but
5898 * we already ordered the constraint list to ensure that would happen. It
5899 * should be okay to use DROP_RESTRICT here, since nothing else should be
5900 * depending on these objects.
5902 foreach(l, tab->changedConstraintOids)
5904 obj.classId = ConstraintRelationId;
5905 obj.objectId = lfirst_oid(l);
5906 obj.objectSubId = 0;
5907 performDeletion(&obj, DROP_RESTRICT);
5910 foreach(l, tab->changedIndexOids)
5912 obj.classId = RelationRelationId;
5913 obj.objectId = lfirst_oid(l);
5914 obj.objectSubId = 0;
5915 performDeletion(&obj, DROP_RESTRICT);
5919 * The objects will get recreated during subsequent passes over the work
5925 ATPostAlterTypeParse(char *cmd, List **wqueue)
5927 List *raw_parsetree_list;
5928 List *querytree_list;
5929 ListCell *list_item;
5932 * We expect that we will get only ALTER TABLE and CREATE INDEX
5933 * statements. Hence, there is no need to pass them through
5934 * parse_analyze() or the rewriter, but instead we need to pass them
5935 * through parse_utilcmd.c to make them ready for execution.
5937 raw_parsetree_list = raw_parser(cmd);
5938 querytree_list = NIL;
5939 foreach(list_item, raw_parsetree_list)
5941 Node *stmt = (Node *) lfirst(list_item);
5943 if (IsA(stmt, IndexStmt))
5944 querytree_list = lappend(querytree_list,
5945 transformIndexStmt((IndexStmt *) stmt,
5947 else if (IsA(stmt, AlterTableStmt))
5948 querytree_list = list_concat(querytree_list,
5949 transformAlterTableStmt((AlterTableStmt *) stmt,
5952 querytree_list = lappend(querytree_list, stmt);
5956 * Attach each generated command to the proper place in the work queue.
5957 * Note this could result in creation of entirely new work-queue entries.
5959 foreach(list_item, querytree_list)
5961 Node *stm = (Node *) lfirst(list_item);
5963 AlteredTableInfo *tab;
5965 switch (nodeTag(stm))
5969 IndexStmt *stmt = (IndexStmt *) stm;
5970 AlterTableCmd *newcmd;
5972 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
5973 tab = ATGetQueueEntry(wqueue, rel);
5974 newcmd = makeNode(AlterTableCmd);
5975 newcmd->subtype = AT_ReAddIndex;
5976 newcmd->def = (Node *) stmt;
5977 tab->subcmds[AT_PASS_OLD_INDEX] =
5978 lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
5979 relation_close(rel, NoLock);
5982 case T_AlterTableStmt:
5984 AlterTableStmt *stmt = (AlterTableStmt *) stm;
5987 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
5988 tab = ATGetQueueEntry(wqueue, rel);
5989 foreach(lcmd, stmt->cmds)
5991 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
5993 switch (cmd->subtype)
5996 cmd->subtype = AT_ReAddIndex;
5997 tab->subcmds[AT_PASS_OLD_INDEX] =
5998 lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
6000 case AT_AddConstraint:
6001 tab->subcmds[AT_PASS_OLD_CONSTR] =
6002 lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
6005 elog(ERROR, "unexpected statement type: %d",
6006 (int) cmd->subtype);
6009 relation_close(rel, NoLock);
6013 elog(ERROR, "unexpected statement type: %d",
6014 (int) nodeTag(stm));
6023 * recursing is true if we are recursing from a table to its indexes,
6024 * sequences, or toast table. We don't allow the ownership of those things to
6025 * be changed separately from the parent table. Also, we can skip permission
6026 * checks (this is necessary not just an optimization, else we'd fail to
6027 * handle toast tables properly).
6029 * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
6030 * free-standing composite type.
6033 ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing)
6035 Relation target_rel;
6038 Form_pg_class tuple_class;
6041 * Get exclusive lock till end of transaction on the target table. Use
6042 * relation_open so that we can work on indexes and sequences.
6044 target_rel = relation_open(relationOid, AccessExclusiveLock);
6046 /* Get its pg_class tuple, too */
6047 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
6049 tuple = SearchSysCache(RELOID,
6050 ObjectIdGetDatum(relationOid),
6052 if (!HeapTupleIsValid(tuple))
6053 elog(ERROR, "cache lookup failed for relation %u", relationOid);
6054 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
6056 /* Can we change the ownership of this tuple? */
6057 switch (tuple_class->relkind)
6059 case RELKIND_RELATION:
6061 /* ok to change owner */
6067 * Because ALTER INDEX OWNER used to be allowed, and in fact
6068 * is generated by old versions of pg_dump, we give a warning
6069 * and do nothing rather than erroring out. Also, to avoid
6070 * unnecessary chatter while restoring those old dumps, say
6071 * nothing at all if the command would be a no-op anyway.
6073 if (tuple_class->relowner != newOwnerId)
6075 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6076 errmsg("cannot change owner of index \"%s\"",
6077 NameStr(tuple_class->relname)),
6078 errhint("Change the ownership of the index's table, instead.")));
6079 /* quick hack to exit via the no-op path */
6080 newOwnerId = tuple_class->relowner;
6083 case RELKIND_SEQUENCE:
6085 tuple_class->relowner != newOwnerId)
6087 /* if it's an owned sequence, disallow changing it by itself */
6091 if (sequenceIsOwned(relationOid, &tableId, &colId))
6093 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6094 errmsg("cannot change owner of sequence \"%s\"",
6095 NameStr(tuple_class->relname)),
6096 errdetail("Sequence \"%s\" is linked to table \"%s\".",
6097 NameStr(tuple_class->relname),
6098 get_rel_name(tableId))));
6101 case RELKIND_COMPOSITE_TYPE:
6105 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6106 errmsg("\"%s\" is a composite type",
6107 NameStr(tuple_class->relname)),
6108 errhint("Use ALTER TYPE instead.")));
6110 case RELKIND_TOASTVALUE:
6116 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6117 errmsg("\"%s\" is not a table, view, or sequence",
6118 NameStr(tuple_class->relname))));
6122 * If the new owner is the same as the existing owner, consider the
6123 * command to have succeeded. This is for dump restoration purposes.
6125 if (tuple_class->relowner != newOwnerId)
6127 Datum repl_val[Natts_pg_class];
6128 char repl_null[Natts_pg_class];
6129 char repl_repl[Natts_pg_class];
6135 /* skip permission checks when recursing to index or toast table */
6138 /* Superusers can always do it */
6141 Oid namespaceOid = tuple_class->relnamespace;
6142 AclResult aclresult;
6144 /* Otherwise, must be owner of the existing object */
6145 if (!pg_class_ownercheck(relationOid, GetUserId()))
6146 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
6147 RelationGetRelationName(target_rel));
6149 /* Must be able to become new owner */
6150 check_is_member_of_role(GetUserId(), newOwnerId);
6152 /* New owner must have CREATE privilege on namespace */
6153 aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
6155 if (aclresult != ACLCHECK_OK)
6156 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
6157 get_namespace_name(namespaceOid));
6161 memset(repl_null, ' ', sizeof(repl_null));
6162 memset(repl_repl, ' ', sizeof(repl_repl));
6164 repl_repl[Anum_pg_class_relowner - 1] = 'r';
6165 repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
6168 * Determine the modified ACL for the new owner. This is only
6169 * necessary when the ACL is non-null.
6171 aclDatum = SysCacheGetAttr(RELOID, tuple,
6172 Anum_pg_class_relacl,
6176 newAcl = aclnewowner(DatumGetAclP(aclDatum),
6177 tuple_class->relowner, newOwnerId);
6178 repl_repl[Anum_pg_class_relacl - 1] = 'r';
6179 repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
6182 newtuple = heap_modifytuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
6184 simple_heap_update(class_rel, &newtuple->t_self, newtuple);
6185 CatalogUpdateIndexes(class_rel, newtuple);
6187 heap_freetuple(newtuple);
6190 * Update owner dependency reference, if any. A composite type has
6191 * none, because it's tracked for the pg_type entry instead of here;
6192 * indexes and TOAST tables don't have their own entries either.
6194 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
6195 tuple_class->relkind != RELKIND_INDEX &&
6196 tuple_class->relkind != RELKIND_TOASTVALUE)
6197 changeDependencyOnOwner(RelationRelationId, relationOid,
6201 * Also change the ownership of the table's rowtype, if it has one
6203 if (tuple_class->relkind != RELKIND_INDEX)
6204 AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId,
6205 tuple_class->relkind == RELKIND_COMPOSITE_TYPE);
6208 * If we are operating on a table, also change the ownership of any
6209 * indexes and sequences that belong to the table, as well as the
6210 * table's toast table (if it has one)
6212 if (tuple_class->relkind == RELKIND_RELATION ||
6213 tuple_class->relkind == RELKIND_TOASTVALUE)
6215 List *index_oid_list;
6218 /* Find all the indexes belonging to this relation */
6219 index_oid_list = RelationGetIndexList(target_rel);
6221 /* For each index, recursively change its ownership */
6222 foreach(i, index_oid_list)
6223 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true);
6225 list_free(index_oid_list);
6228 if (tuple_class->relkind == RELKIND_RELATION)
6230 /* If it has a toast table, recurse to change its ownership */
6231 if (tuple_class->reltoastrelid != InvalidOid)
6232 ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
6235 /* If it has dependent sequences, recurse to change them too */
6236 change_owner_recurse_to_sequences(relationOid, newOwnerId);
6240 ReleaseSysCache(tuple);
6241 heap_close(class_rel, RowExclusiveLock);
6242 relation_close(target_rel, NoLock);
6246 * change_owner_recurse_to_sequences
6248 * Helper function for ATExecChangeOwner. Examines pg_depend searching
6249 * for sequences that are dependent on serial columns, and changes their
6253 change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId)
6261 * SERIAL sequences are those having an auto dependency on one of the
6262 * table's columns (we don't care *which* column, exactly).
6264 depRel = heap_open(DependRelationId, AccessShareLock);
6266 ScanKeyInit(&key[0],
6267 Anum_pg_depend_refclassid,
6268 BTEqualStrategyNumber, F_OIDEQ,
6269 ObjectIdGetDatum(RelationRelationId));
6270 ScanKeyInit(&key[1],
6271 Anum_pg_depend_refobjid,
6272 BTEqualStrategyNumber, F_OIDEQ,
6273 ObjectIdGetDatum(relationOid));
6274 /* we leave refobjsubid unspecified */
6276 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
6277 SnapshotNow, 2, key);
6279 while (HeapTupleIsValid(tup = systable_getnext(scan)))
6281 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
6284 /* skip dependencies other than auto dependencies on columns */
6285 if (depForm->refobjsubid == 0 ||
6286 depForm->classid != RelationRelationId ||
6287 depForm->objsubid != 0 ||
6288 depForm->deptype != DEPENDENCY_AUTO)
6291 /* Use relation_open just in case it's an index */
6292 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
6294 /* skip non-sequence relations */
6295 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
6297 /* No need to keep the lock */
6298 relation_close(seqRel, AccessExclusiveLock);
6302 /* We don't need to close the sequence while we alter it. */
6303 ATExecChangeOwner(depForm->objid, newOwnerId, true);
6305 /* Now we can close it. Keep the lock till end of transaction. */
6306 relation_close(seqRel, NoLock);
6309 systable_endscan(scan);
6311 relation_close(depRel, AccessShareLock);
6315 * ALTER TABLE CLUSTER ON
6317 * The only thing we have to do is to change the indisclustered bits.
6320 ATExecClusterOn(Relation rel, const char *indexName)
6324 indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
6326 if (!OidIsValid(indexOid))
6328 (errcode(ERRCODE_UNDEFINED_OBJECT),
6329 errmsg("index \"%s\" for table \"%s\" does not exist",
6330 indexName, RelationGetRelationName(rel))));
6332 /* Check index is valid to cluster on */
6333 check_index_is_clusterable(rel, indexOid, false);
6335 /* And do the work */
6336 mark_index_clustered(rel, indexOid);
6340 * ALTER TABLE SET WITHOUT CLUSTER
6342 * We have to find any indexes on the table that have indisclustered bit
6343 * set and turn it off.
6346 ATExecDropCluster(Relation rel)
6348 mark_index_clustered(rel, InvalidOid);
6352 * ALTER TABLE SET TABLESPACE
6355 ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, char *tablespacename)
6358 AclResult aclresult;
6360 /* Check that the tablespace exists */
6361 tablespaceId = get_tablespace_oid(tablespacename);
6362 if (!OidIsValid(tablespaceId))
6364 (errcode(ERRCODE_UNDEFINED_OBJECT),
6365 errmsg("tablespace \"%s\" does not exist", tablespacename)));
6367 /* Check its permissions */
6368 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(), ACL_CREATE);
6369 if (aclresult != ACLCHECK_OK)
6370 aclcheck_error(aclresult, ACL_KIND_TABLESPACE, tablespacename);
6372 /* Save info for Phase 3 to do the real work */
6373 if (OidIsValid(tab->newTableSpace))
6375 (errcode(ERRCODE_SYNTAX_ERROR),
6376 errmsg("cannot have multiple SET TABLESPACE subcommands")));
6377 tab->newTableSpace = tablespaceId;
6381 * ALTER TABLE/INDEX SET (...) or RESET (...)
6384 ATExecSetRelOptions(Relation rel, List *defList, bool isReset)
6393 Datum repl_val[Natts_pg_class];
6394 char repl_null[Natts_pg_class];
6395 char repl_repl[Natts_pg_class];
6398 return; /* nothing to do */
6400 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
6402 /* Get the old reloptions */
6403 relid = RelationGetRelid(rel);
6404 tuple = SearchSysCache(RELOID,
6405 ObjectIdGetDatum(relid),
6407 if (!HeapTupleIsValid(tuple))
6408 elog(ERROR, "cache lookup failed for relation %u", relid);
6410 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions, &isnull);
6412 /* Generate new proposed reloptions (text array) */
6413 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
6414 defList, false, isReset);
6417 switch (rel->rd_rel->relkind)
6419 case RELKIND_RELATION:
6420 case RELKIND_TOASTVALUE:
6421 (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
6424 (void) index_reloptions(rel->rd_am->amoptions, newOptions, true);
6428 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6429 errmsg("\"%s\" is not a table, index, or TOAST table",
6430 RelationGetRelationName(rel))));
6435 * All we need do here is update the pg_class row; the new options will be
6436 * propagated into relcaches during post-commit cache inval.
6438 memset(repl_val, 0, sizeof(repl_val));
6439 memset(repl_null, ' ', sizeof(repl_null));
6440 memset(repl_repl, ' ', sizeof(repl_repl));
6442 if (newOptions != (Datum) 0)
6443 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
6445 repl_null[Anum_pg_class_reloptions - 1] = 'n';
6447 repl_repl[Anum_pg_class_reloptions - 1] = 'r';
6449 newtuple = heap_modifytuple(tuple, RelationGetDescr(pgclass),
6450 repl_val, repl_null, repl_repl);
6452 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
6454 CatalogUpdateIndexes(pgclass, newtuple);
6456 heap_freetuple(newtuple);
6458 ReleaseSysCache(tuple);
6460 heap_close(pgclass, RowExclusiveLock);
6464 * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
6465 * rewriting to be done, so we just want to copy the data as fast as possible.
6468 ATExecSetTableSpace(Oid tableOid, Oid newTableSpace)
6474 RelFileNode newrnode;
6475 SMgrRelation dstrel;
6478 Form_pg_class rd_rel;
6481 * Need lock here in case we are recursing to toast table or index
6483 rel = relation_open(tableOid, AccessExclusiveLock);
6486 * We can never allow moving of shared or nailed-in-cache relations,
6487 * because we can't support changing their reltablespace values.
6489 if (rel->rd_rel->relisshared || rel->rd_isnailed)
6491 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6492 errmsg("cannot move system relation \"%s\"",
6493 RelationGetRelationName(rel))));
6495 /* Can't move a non-shared relation into pg_global */
6496 if (newTableSpace == GLOBALTABLESPACE_OID)
6498 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6499 errmsg("only shared relations can be placed in pg_global tablespace")));
6502 * Don't allow moving temp tables of other backends ... their local buffer
6503 * manager is not going to cope.
6505 if (isOtherTempNamespace(RelationGetNamespace(rel)))
6507 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6508 errmsg("cannot move temporary tables of other sessions")));
6511 * No work if no change in tablespace.
6513 oldTableSpace = rel->rd_rel->reltablespace;
6514 if (newTableSpace == oldTableSpace ||
6515 (newTableSpace == MyDatabaseTableSpace && oldTableSpace == 0))
6517 relation_close(rel, NoLock);
6521 reltoastrelid = rel->rd_rel->reltoastrelid;
6522 reltoastidxid = rel->rd_rel->reltoastidxid;
6524 /* Get a modifiable copy of the relation's pg_class row */
6525 pg_class = heap_open(RelationRelationId, RowExclusiveLock);
6527 tuple = SearchSysCacheCopy(RELOID,
6528 ObjectIdGetDatum(tableOid),
6530 if (!HeapTupleIsValid(tuple))
6531 elog(ERROR, "cache lookup failed for relation %u", tableOid);
6532 rd_rel = (Form_pg_class) GETSTRUCT(tuple);
6534 /* create another storage file. Is it a little ugly ? */
6535 /* NOTE: any conflict in relfilenode value will be caught here */
6536 newrnode = rel->rd_node;
6537 newrnode.spcNode = newTableSpace;
6539 dstrel = smgropen(newrnode);
6540 smgrcreate(dstrel, rel->rd_istemp, false);
6542 /* copy relation data to the new physical file */
6543 copy_relation_data(rel, dstrel);
6545 /* schedule unlinking old physical file */
6546 RelationOpenSmgr(rel);
6547 smgrscheduleunlink(rel->rd_smgr, rel->rd_istemp);
6550 * Now drop smgr references. The source was already dropped by
6551 * smgrscheduleunlink.
6555 /* update the pg_class row */
6556 rd_rel->reltablespace = (newTableSpace == MyDatabaseTableSpace) ? InvalidOid : newTableSpace;
6557 simple_heap_update(pg_class, &tuple->t_self, tuple);
6558 CatalogUpdateIndexes(pg_class, tuple);
6560 heap_freetuple(tuple);
6562 heap_close(pg_class, RowExclusiveLock);
6564 relation_close(rel, NoLock);
6566 /* Make sure the reltablespace change is visible */
6567 CommandCounterIncrement();
6569 /* Move associated toast relation and/or index, too */
6570 if (OidIsValid(reltoastrelid))
6571 ATExecSetTableSpace(reltoastrelid, newTableSpace);
6572 if (OidIsValid(reltoastidxid))
6573 ATExecSetTableSpace(reltoastidxid, newTableSpace);
6577 * Copy data, block by block
6580 copy_relation_data(Relation rel, SMgrRelation dst)
6584 BlockNumber nblocks;
6587 Page page = (Page) buf;
6590 * Since we copy the file directly without looking at the shared buffers,
6591 * we'd better first flush out any pages of the source relation that are
6592 * in shared buffers. We assume no new changes will be made while we are
6593 * holding exclusive lock on the rel.
6595 FlushRelationBuffers(rel);
6598 * We need to log the copied data in WAL iff WAL archiving is enabled AND
6599 * it's not a temp rel.
6601 use_wal = XLogArchivingActive() && !rel->rd_istemp;
6603 nblocks = RelationGetNumberOfBlocks(rel);
6604 /* RelationGetNumberOfBlocks will certainly have opened rd_smgr */
6607 for (blkno = 0; blkno < nblocks; blkno++)
6609 smgrread(src, blkno, buf);
6613 log_newpage(&dst->smgr_rnode, blkno, page);
6616 * Now write the page. We say isTemp = true even if it's not a temp
6617 * rel, because there's no need for smgr to schedule an fsync for this
6618 * write; we'll do it ourselves below.
6620 smgrextend(dst, blkno, buf, true);
6624 * If the rel isn't temp, we must fsync it down to disk before it's safe
6625 * to commit the transaction. (For a temp rel we don't care since the rel
6626 * will be uninteresting after a crash anyway.)
6628 * It's obvious that we must do this when not WAL-logging the copy. It's
6629 * less obvious that we have to do it even if we did WAL-log the copied
6630 * pages. The reason is that since we're copying outside shared buffers, a
6631 * CHECKPOINT occurring during the copy has no way to flush the previously
6632 * written data to disk (indeed it won't know the new rel even exists). A
6633 * crash later on would replay WAL from the checkpoint, therefore it
6634 * wouldn't replay our earlier WAL entries. If we do not fsync those pages
6635 * here, they might still not be on disk when the crash occurs.
6637 if (!rel->rd_istemp)
6642 * ALTER TABLE ENABLE/DISABLE TRIGGER
6644 * We just pass this off to trigger.c.
6647 ATExecEnableDisableTrigger(Relation rel, char *trigname,
6648 char fires_when, bool skip_system)
6650 EnableDisableTrigger(rel, trigname, fires_when, skip_system);
6654 * ALTER TABLE ENABLE/DISABLE RULE
6656 * We just pass this off to rewriteDefine.c.
6659 ATExecEnableDisableRule(Relation rel, char *trigname,
6662 EnableDisableRule(rel, trigname, fires_when);
6666 * ALTER TABLE INHERIT
6668 * Add a parent to the child's parents. This verifies that all the columns and
6669 * check constraints of the parent appear in the child and that they have the
6670 * same data types and expressions.
6673 ATExecAddInherit(Relation child_rel, RangeVar *parent)
6675 Relation parent_rel,
6679 HeapTuple inheritsTuple;
6684 * AccessShareLock on the parent is what's obtained during normal CREATE
6685 * TABLE ... INHERITS ..., so should be enough here.
6687 parent_rel = heap_openrv(parent, AccessShareLock);
6690 * Must be owner of both parent and child -- child was checked by
6691 * ATSimplePermissions call in ATPrepCmd
6693 ATSimplePermissions(parent_rel, false);
6695 /* Permanent rels cannot inherit from temporary ones */
6696 if (!isTempNamespace(RelationGetNamespace(child_rel)) &&
6697 isTempNamespace(RelationGetNamespace(parent_rel)))
6699 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6700 errmsg("cannot inherit from temporary relation \"%s\"",
6701 RelationGetRelationName(parent_rel))));
6704 * Check for duplicates in the list of parents, and determine the highest
6705 * inhseqno already present; we'll use the next one for the new parent.
6706 * (Note: get RowExclusiveLock because we will write pg_inherits below.)
6708 * Note: we do not reject the case where the child already inherits from
6709 * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
6711 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
6713 Anum_pg_inherits_inhrelid,
6714 BTEqualStrategyNumber, F_OIDEQ,
6715 ObjectIdGetDatum(RelationGetRelid(child_rel)));
6716 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
6717 true, SnapshotNow, 1, &key);
6719 /* inhseqno sequences start at 1 */
6721 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
6723 Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
6725 if (inh->inhparent == RelationGetRelid(parent_rel))
6727 (errcode(ERRCODE_DUPLICATE_TABLE),
6728 errmsg("relation \"%s\" would be inherited from more than once",
6729 RelationGetRelationName(parent_rel))));
6730 if (inh->inhseqno > inhseqno)
6731 inhseqno = inh->inhseqno;
6733 systable_endscan(scan);
6736 * Prevent circularity by seeing if proposed parent inherits from child.
6737 * (In particular, this disallows making a rel inherit from itself.)
6739 * This is not completely bulletproof because of race conditions: in
6740 * multi-level inheritance trees, someone else could concurrently be
6741 * making another inheritance link that closes the loop but does not join
6742 * either of the rels we have locked. Preventing that seems to require
6743 * exclusive locks on the entire inheritance tree, which is a cure worse
6744 * than the disease. find_all_inheritors() will cope with circularity
6745 * anyway, so don't sweat it too much.
6747 children = find_all_inheritors(RelationGetRelid(child_rel));
6749 if (list_member_oid(children, RelationGetRelid(parent_rel)))
6751 (errcode(ERRCODE_DUPLICATE_TABLE),
6752 errmsg("circular inheritance not allowed"),
6753 errdetail("\"%s\" is already a child of \"%s\".",
6755 RelationGetRelationName(child_rel))));
6757 /* If parent has OIDs then child must have OIDs */
6758 if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
6760 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6761 errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
6762 RelationGetRelationName(child_rel),
6763 RelationGetRelationName(parent_rel))));
6765 /* Match up the columns and bump attinhcount as needed */
6766 MergeAttributesIntoExisting(child_rel, parent_rel);
6768 /* Match up the constraints and bump coninhcount as needed */
6769 MergeConstraintsIntoExisting(child_rel, parent_rel);
6772 * OK, it looks valid. Make the catalog entries that show inheritance.
6774 StoreCatalogInheritance1(RelationGetRelid(child_rel),
6775 RelationGetRelid(parent_rel),
6779 /* Now we're done with pg_inherits */
6780 heap_close(catalogRelation, RowExclusiveLock);
6782 /* keep our lock on the parent relation until commit */
6783 heap_close(parent_rel, NoLock);
6787 * Obtain the source-text form of the constraint expression for a check
6788 * constraint, given its pg_constraint tuple
6791 decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
6793 Form_pg_constraint con;
6798 con = (Form_pg_constraint) GETSTRUCT(contup);
6799 attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
6801 elog(ERROR, "null conbin for constraint %u", HeapTupleGetOid(contup));
6803 expr = DirectFunctionCall2(pg_get_expr, attr,
6804 ObjectIdGetDatum(con->conrelid));
6805 return TextDatumGetCString(expr);
6809 * Determine whether two check constraints are functionally equivalent
6811 * The test we apply is to see whether they reverse-compile to the same
6812 * source string. This insulates us from issues like whether attributes
6813 * have the same physical column numbers in parent and child relations.
6816 constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
6818 Form_pg_constraint acon = (Form_pg_constraint) GETSTRUCT(a);
6819 Form_pg_constraint bcon = (Form_pg_constraint) GETSTRUCT(b);
6821 if (acon->condeferrable != bcon->condeferrable ||
6822 acon->condeferred != bcon->condeferred ||
6823 strcmp(decompile_conbin(a, tupleDesc),
6824 decompile_conbin(b, tupleDesc)) != 0)
6831 * Check columns in child table match up with columns in parent, and increment
6832 * their attinhcount.
6834 * Called by ATExecAddInherit
6836 * Currently all parent columns must be found in child. Missing columns are an
6837 * error. One day we might consider creating new columns like CREATE TABLE
6838 * does. However, that is widely unpopular --- in the common use case of
6839 * partitioned tables it's a foot-gun.
6841 * The data type must match exactly. If the parent column is NOT NULL then
6842 * the child must be as well. Defaults are not compared, however.
6845 MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel)
6848 AttrNumber parent_attno;
6850 TupleDesc tupleDesc;
6851 TupleConstr *constr;
6854 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
6856 tupleDesc = RelationGetDescr(parent_rel);
6857 parent_natts = tupleDesc->natts;
6858 constr = tupleDesc->constr;
6860 for (parent_attno = 1; parent_attno <= parent_natts; parent_attno++)
6862 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
6863 char *attributeName = NameStr(attribute->attname);
6865 /* Ignore dropped columns in the parent. */
6866 if (attribute->attisdropped)
6869 /* Find same column in child (matching on column name). */
6870 tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel),
6872 if (HeapTupleIsValid(tuple))
6874 /* Check they are same type and typmod */
6875 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
6877 if (attribute->atttypid != childatt->atttypid ||
6878 attribute->atttypmod != childatt->atttypmod)
6880 (errcode(ERRCODE_DATATYPE_MISMATCH),
6881 errmsg("child table \"%s\" has different type for column \"%s\"",
6882 RelationGetRelationName(child_rel),
6885 if (attribute->attnotnull && !childatt->attnotnull)
6887 (errcode(ERRCODE_DATATYPE_MISMATCH),
6888 errmsg("column \"%s\" in child table must be marked NOT NULL",
6892 * OK, bump the child column's inheritance count. (If we fail
6893 * later on, this change will just roll back.)
6895 childatt->attinhcount++;
6896 simple_heap_update(attrrel, &tuple->t_self, tuple);
6897 CatalogUpdateIndexes(attrrel, tuple);
6898 heap_freetuple(tuple);
6903 (errcode(ERRCODE_DATATYPE_MISMATCH),
6904 errmsg("child table is missing column \"%s\"",
6909 heap_close(attrrel, RowExclusiveLock);
6913 * Check constraints in child table match up with constraints in parent,
6914 * and increment their coninhcount.
6916 * Called by ATExecAddInherit
6918 * Currently all constraints in parent must be present in the child. One day we
6919 * may consider adding new constraints like CREATE TABLE does. We may also want
6920 * to allow an optional flag on parent table constraints indicating they are
6921 * intended to ONLY apply to the master table, not to the children. That would
6922 * make it possible to ensure no records are mistakenly inserted into the
6923 * master in partitioned tables rather than the appropriate child.
6925 * XXX This is O(N^2) which may be an issue with tables with hundreds of
6926 * constraints. As long as tables have more like 10 constraints it shouldn't be
6927 * a problem though. Even 100 constraints ought not be the end of the world.
6930 MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
6932 Relation catalog_relation;
6933 TupleDesc tuple_desc;
6934 SysScanDesc parent_scan;
6935 ScanKeyData parent_key;
6936 HeapTuple parent_tuple;
6938 catalog_relation = heap_open(ConstraintRelationId, RowExclusiveLock);
6939 tuple_desc = RelationGetDescr(catalog_relation);
6941 /* Outer loop scans through the parent's constraint definitions */
6942 ScanKeyInit(&parent_key,
6943 Anum_pg_constraint_conrelid,
6944 BTEqualStrategyNumber, F_OIDEQ,
6945 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
6946 parent_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
6947 true, SnapshotNow, 1, &parent_key);
6949 while (HeapTupleIsValid(parent_tuple = systable_getnext(parent_scan)))
6951 Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(parent_tuple);
6952 SysScanDesc child_scan;
6953 ScanKeyData child_key;
6954 HeapTuple child_tuple;
6957 if (parent_con->contype != CONSTRAINT_CHECK)
6960 /* Search for a child constraint matching this one */
6961 ScanKeyInit(&child_key,
6962 Anum_pg_constraint_conrelid,
6963 BTEqualStrategyNumber, F_OIDEQ,
6964 ObjectIdGetDatum(RelationGetRelid(child_rel)));
6965 child_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
6966 true, SnapshotNow, 1, &child_key);
6968 while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
6970 Form_pg_constraint child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
6971 HeapTuple child_copy;
6973 if (child_con->contype != CONSTRAINT_CHECK)
6976 if (strcmp(NameStr(parent_con->conname),
6977 NameStr(child_con->conname)) != 0)
6980 if (!constraints_equivalent(parent_tuple, child_tuple, tuple_desc))
6982 (errcode(ERRCODE_DATATYPE_MISMATCH),
6983 errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
6984 RelationGetRelationName(child_rel),
6985 NameStr(parent_con->conname))));
6988 * OK, bump the child constraint's inheritance count. (If we fail
6989 * later on, this change will just roll back.)
6991 child_copy = heap_copytuple(child_tuple);
6992 child_con = (Form_pg_constraint) GETSTRUCT(child_copy);
6993 child_con->coninhcount++;
6994 simple_heap_update(catalog_relation, &child_copy->t_self, child_copy);
6995 CatalogUpdateIndexes(catalog_relation, child_copy);
6996 heap_freetuple(child_copy);
7002 systable_endscan(child_scan);
7006 (errcode(ERRCODE_DATATYPE_MISMATCH),
7007 errmsg("child table is missing constraint \"%s\"",
7008 NameStr(parent_con->conname))));
7011 systable_endscan(parent_scan);
7012 heap_close(catalog_relation, RowExclusiveLock);
7016 * ALTER TABLE NO INHERIT
7018 * Drop a parent from the child's parents. This just adjusts the attinhcount
7019 * and attislocal of the columns and removes the pg_inherit and pg_depend
7022 * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
7023 * up attislocal stays true, which means if a child is ever removed from a
7024 * parent then its columns will never be automatically dropped which may
7025 * surprise. But at least we'll never surprise by dropping columns someone
7026 * isn't expecting to be dropped which would actually mean data loss.
7028 * coninhcount and conislocal for inherited constraints are adjusted in
7029 * exactly the same way.
7032 ATExecDropInherit(Relation rel, RangeVar *parent)
7034 Relation parent_rel;
7035 Relation catalogRelation;
7038 HeapTuple inheritsTuple,
7046 * AccessShareLock on the parent is probably enough, seeing that DROP
7047 * TABLE doesn't lock parent tables at all. We need some lock since we'll
7048 * be inspecting the parent's schema.
7050 parent_rel = heap_openrv(parent, AccessShareLock);
7053 * We don't bother to check ownership of the parent table --- ownership of
7054 * the child is presumed enough rights.
7058 * Find and destroy the pg_inherits entry linking the two, or error out if
7061 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
7062 ScanKeyInit(&key[0],
7063 Anum_pg_inherits_inhrelid,
7064 BTEqualStrategyNumber, F_OIDEQ,
7065 ObjectIdGetDatum(RelationGetRelid(rel)));
7066 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
7067 true, SnapshotNow, 1, key);
7069 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
7073 inhparent = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
7074 if (inhparent == RelationGetRelid(parent_rel))
7076 simple_heap_delete(catalogRelation, &inheritsTuple->t_self);
7082 systable_endscan(scan);
7083 heap_close(catalogRelation, RowExclusiveLock);
7087 (errcode(ERRCODE_UNDEFINED_TABLE),
7088 errmsg("relation \"%s\" is not a parent of relation \"%s\"",
7089 RelationGetRelationName(parent_rel),
7090 RelationGetRelationName(rel))));
7093 * Search through child columns looking for ones matching parent rel
7095 catalogRelation = heap_open(AttributeRelationId, RowExclusiveLock);
7096 ScanKeyInit(&key[0],
7097 Anum_pg_attribute_attrelid,
7098 BTEqualStrategyNumber, F_OIDEQ,
7099 ObjectIdGetDatum(RelationGetRelid(rel)));
7100 scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
7101 true, SnapshotNow, 1, key);
7102 while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
7104 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
7106 /* Ignore if dropped or not inherited */
7107 if (att->attisdropped)
7109 if (att->attinhcount <= 0)
7112 if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
7113 NameStr(att->attname)))
7115 /* Decrement inhcount and possibly set islocal to true */
7116 HeapTuple copyTuple = heap_copytuple(attributeTuple);
7117 Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
7119 copy_att->attinhcount--;
7120 if (copy_att->attinhcount == 0)
7121 copy_att->attislocal = true;
7123 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
7124 CatalogUpdateIndexes(catalogRelation, copyTuple);
7125 heap_freetuple(copyTuple);
7128 systable_endscan(scan);
7129 heap_close(catalogRelation, RowExclusiveLock);
7132 * Likewise, find inherited check constraints and disinherit them.
7133 * To do this, we first need a list of the names of the parent's check
7134 * constraints. (We cheat a bit by only checking for name matches,
7135 * assuming that the expressions will match.)
7137 catalogRelation = heap_open(ConstraintRelationId, RowExclusiveLock);
7138 ScanKeyInit(&key[0],
7139 Anum_pg_constraint_conrelid,
7140 BTEqualStrategyNumber, F_OIDEQ,
7141 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
7142 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
7143 true, SnapshotNow, 1, key);
7147 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
7149 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
7151 if (con->contype == CONSTRAINT_CHECK)
7152 connames = lappend(connames, pstrdup(NameStr(con->conname)));
7155 systable_endscan(scan);
7157 /* Now scan the child's constraints */
7158 ScanKeyInit(&key[0],
7159 Anum_pg_constraint_conrelid,
7160 BTEqualStrategyNumber, F_OIDEQ,
7161 ObjectIdGetDatum(RelationGetRelid(rel)));
7162 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
7163 true, SnapshotNow, 1, key);
7165 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
7167 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
7171 if (con->contype != CONSTRAINT_CHECK)
7175 foreach (lc, connames)
7177 if (strcmp(NameStr(con->conname), (char *) lfirst(lc)) == 0)
7186 /* Decrement inhcount and possibly set islocal to true */
7187 HeapTuple copyTuple = heap_copytuple(constraintTuple);
7188 Form_pg_constraint copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
7189 if (copy_con->coninhcount <= 0) /* shouldn't happen */
7190 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
7191 RelationGetRelid(rel), NameStr(copy_con->conname));
7193 copy_con->coninhcount--;
7194 if (copy_con->coninhcount == 0)
7195 copy_con->conislocal = true;
7197 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
7198 CatalogUpdateIndexes(catalogRelation, copyTuple);
7199 heap_freetuple(copyTuple);
7203 systable_endscan(scan);
7204 heap_close(catalogRelation, RowExclusiveLock);
7207 * Drop the dependency
7209 * There's no convenient way to do this, so go trawling through pg_depend
7211 catalogRelation = heap_open(DependRelationId, RowExclusiveLock);
7213 ScanKeyInit(&key[0],
7214 Anum_pg_depend_classid,
7215 BTEqualStrategyNumber, F_OIDEQ,
7216 ObjectIdGetDatum(RelationRelationId));
7217 ScanKeyInit(&key[1],
7218 Anum_pg_depend_objid,
7219 BTEqualStrategyNumber, F_OIDEQ,
7220 ObjectIdGetDatum(RelationGetRelid(rel)));
7221 ScanKeyInit(&key[2],
7222 Anum_pg_depend_objsubid,
7223 BTEqualStrategyNumber, F_INT4EQ,
7226 scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
7227 SnapshotNow, 3, key);
7229 while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
7231 Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
7233 if (dep->refclassid == RelationRelationId &&
7234 dep->refobjid == RelationGetRelid(parent_rel) &&
7235 dep->refobjsubid == 0 &&
7236 dep->deptype == DEPENDENCY_NORMAL)
7237 simple_heap_delete(catalogRelation, &depTuple->t_self);
7240 systable_endscan(scan);
7241 heap_close(catalogRelation, RowExclusiveLock);
7243 /* keep our lock on the parent relation until commit */
7244 heap_close(parent_rel, NoLock);
7249 * Execute ALTER TABLE SET SCHEMA
7251 * Note: caller must have checked ownership of the relation already
7254 AlterTableNamespace(RangeVar *relation, const char *newschema,
7255 ObjectType stmttype)
7263 rel = relation_openrv(relation, AccessExclusiveLock);
7265 relid = RelationGetRelid(rel);
7266 oldNspOid = RelationGetNamespace(rel);
7268 /* Check relation type against type specified in the ALTER command */
7273 * For mostly-historical reasons, we allow ALTER TABLE to apply
7274 * to all relation types.
7278 case OBJECT_SEQUENCE:
7279 if (rel->rd_rel->relkind != RELKIND_SEQUENCE)
7281 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7282 errmsg("\"%s\" is not a sequence",
7283 RelationGetRelationName(rel))));
7287 if (rel->rd_rel->relkind != RELKIND_VIEW)
7289 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7290 errmsg("\"%s\" is not a view",
7291 RelationGetRelationName(rel))));
7295 elog(ERROR, "unrecognized object type: %d", (int) stmttype);
7298 /* Can we change the schema of this tuple? */
7299 switch (rel->rd_rel->relkind)
7301 case RELKIND_RELATION:
7303 /* ok to change schema */
7305 case RELKIND_SEQUENCE:
7307 /* if it's an owned sequence, disallow moving it by itself */
7311 if (sequenceIsOwned(relid, &tableId, &colId))
7313 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7314 errmsg("cannot move an owned sequence into another schema"),
7315 errdetail("Sequence \"%s\" is linked to table \"%s\".",
7316 RelationGetRelationName(rel),
7317 get_rel_name(tableId))));
7320 case RELKIND_COMPOSITE_TYPE:
7322 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7323 errmsg("\"%s\" is a composite type",
7324 RelationGetRelationName(rel)),
7325 errhint("Use ALTER TYPE instead.")));
7328 case RELKIND_TOASTVALUE:
7332 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7333 errmsg("\"%s\" is not a table, view, or sequence",
7334 RelationGetRelationName(rel))));
7337 /* get schema OID and check its permissions */
7338 nspOid = LookupCreationNamespace(newschema);
7340 if (oldNspOid == nspOid)
7342 (errcode(ERRCODE_DUPLICATE_TABLE),
7343 errmsg("relation \"%s\" is already in schema \"%s\"",
7344 RelationGetRelationName(rel),
7347 /* disallow renaming into or out of temp schemas */
7348 if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
7350 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7351 errmsg("cannot move objects into or out of temporary schemas")));
7353 /* same for TOAST schema */
7354 if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
7356 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7357 errmsg("cannot move objects into or out of TOAST schema")));
7359 /* OK, modify the pg_class row and pg_depend entry */
7360 classRel = heap_open(RelationRelationId, RowExclusiveLock);
7362 AlterRelationNamespaceInternal(classRel, relid, oldNspOid, nspOid, true);
7364 /* Fix the table's rowtype too */
7365 AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid, false, false);
7367 /* Fix other dependent stuff */
7368 if (rel->rd_rel->relkind == RELKIND_RELATION)
7370 AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid);
7371 AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid, newschema);
7372 AlterConstraintNamespaces(relid, oldNspOid, nspOid, false);
7375 heap_close(classRel, RowExclusiveLock);
7377 /* close rel, but keep lock until commit */
7378 relation_close(rel, NoLock);
7382 * The guts of relocating a relation to another namespace: fix the pg_class
7383 * entry, and the pg_depend entry if any. Caller must already have
7384 * opened and write-locked pg_class.
7387 AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
7388 Oid oldNspOid, Oid newNspOid,
7389 bool hasDependEntry)
7392 Form_pg_class classForm;
7394 classTup = SearchSysCacheCopy(RELOID,
7395 ObjectIdGetDatum(relOid),
7397 if (!HeapTupleIsValid(classTup))
7398 elog(ERROR, "cache lookup failed for relation %u", relOid);
7399 classForm = (Form_pg_class) GETSTRUCT(classTup);
7401 Assert(classForm->relnamespace == oldNspOid);
7403 /* check for duplicate name (more friendly than unique-index failure) */
7404 if (get_relname_relid(NameStr(classForm->relname),
7405 newNspOid) != InvalidOid)
7407 (errcode(ERRCODE_DUPLICATE_TABLE),
7408 errmsg("relation \"%s\" already exists in schema \"%s\"",
7409 NameStr(classForm->relname),
7410 get_namespace_name(newNspOid))));
7412 /* classTup is a copy, so OK to scribble on */
7413 classForm->relnamespace = newNspOid;
7415 simple_heap_update(classRel, &classTup->t_self, classTup);
7416 CatalogUpdateIndexes(classRel, classTup);
7418 /* Update dependency on schema if caller said so */
7419 if (hasDependEntry &&
7420 changeDependencyFor(RelationRelationId, relOid,
7421 NamespaceRelationId, oldNspOid, newNspOid) != 1)
7422 elog(ERROR, "failed to change schema dependency for relation \"%s\"",
7423 NameStr(classForm->relname));
7425 heap_freetuple(classTup);
7429 * Move all indexes for the specified relation to another namespace.
7431 * Note: we assume adequate permission checking was done by the caller,
7432 * and that the caller has a suitable lock on the owning relation.
7435 AlterIndexNamespaces(Relation classRel, Relation rel,
7436 Oid oldNspOid, Oid newNspOid)
7441 indexList = RelationGetIndexList(rel);
7443 foreach(l, indexList)
7445 Oid indexOid = lfirst_oid(l);
7448 * Note: currently, the index will not have its own dependency on the
7449 * namespace, so we don't need to do changeDependencyFor(). There's no
7450 * rowtype in pg_type, either.
7452 AlterRelationNamespaceInternal(classRel, indexOid,
7453 oldNspOid, newNspOid,
7457 list_free(indexList);
7461 * Move all SERIAL-column sequences of the specified relation to another
7464 * Note: we assume adequate permission checking was done by the caller,
7465 * and that the caller has a suitable lock on the owning relation.
7468 AlterSeqNamespaces(Relation classRel, Relation rel,
7469 Oid oldNspOid, Oid newNspOid, const char *newNspName)
7477 * SERIAL sequences are those having an auto dependency on one of the
7478 * table's columns (we don't care *which* column, exactly).
7480 depRel = heap_open(DependRelationId, AccessShareLock);
7482 ScanKeyInit(&key[0],
7483 Anum_pg_depend_refclassid,
7484 BTEqualStrategyNumber, F_OIDEQ,
7485 ObjectIdGetDatum(RelationRelationId));
7486 ScanKeyInit(&key[1],
7487 Anum_pg_depend_refobjid,
7488 BTEqualStrategyNumber, F_OIDEQ,
7489 ObjectIdGetDatum(RelationGetRelid(rel)));
7490 /* we leave refobjsubid unspecified */
7492 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
7493 SnapshotNow, 2, key);
7495 while (HeapTupleIsValid(tup = systable_getnext(scan)))
7497 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
7500 /* skip dependencies other than auto dependencies on columns */
7501 if (depForm->refobjsubid == 0 ||
7502 depForm->classid != RelationRelationId ||
7503 depForm->objsubid != 0 ||
7504 depForm->deptype != DEPENDENCY_AUTO)
7507 /* Use relation_open just in case it's an index */
7508 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
7510 /* skip non-sequence relations */
7511 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
7513 /* No need to keep the lock */
7514 relation_close(seqRel, AccessExclusiveLock);
7518 /* Fix the pg_class and pg_depend entries */
7519 AlterRelationNamespaceInternal(classRel, depForm->objid,
7520 oldNspOid, newNspOid,
7524 * Sequences have entries in pg_type. We need to be careful to move
7525 * them to the new namespace, too.
7527 AlterTypeNamespaceInternal(RelationGetForm(seqRel)->reltype,
7528 newNspOid, false, false);
7530 /* Now we can close it. Keep the lock till end of transaction. */
7531 relation_close(seqRel, NoLock);
7534 systable_endscan(scan);
7536 relation_close(depRel, AccessShareLock);
7541 * This code supports
7542 * CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
7544 * Because we only support this for TEMP tables, it's sufficient to remember
7545 * the state in a backend-local data structure.
7549 * Register a newly-created relation's ON COMMIT action.
7552 register_on_commit_action(Oid relid, OnCommitAction action)
7555 MemoryContext oldcxt;
7558 * We needn't bother registering the relation unless there is an ON COMMIT
7559 * action we need to take.
7561 if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
7564 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
7566 oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
7568 oc->oncommit = action;
7569 oc->creating_subid = GetCurrentSubTransactionId();
7570 oc->deleting_subid = InvalidSubTransactionId;
7572 on_commits = lcons(oc, on_commits);
7574 MemoryContextSwitchTo(oldcxt);
7578 * Unregister any ON COMMIT action when a relation is deleted.
7580 * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
7583 remove_on_commit_action(Oid relid)
7587 foreach(l, on_commits)
7589 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
7591 if (oc->relid == relid)
7593 oc->deleting_subid = GetCurrentSubTransactionId();
7600 * Perform ON COMMIT actions.
7602 * This is invoked just before actually committing, since it's possible
7603 * to encounter errors.
7606 PreCommit_on_commit_actions(void)
7609 List *oids_to_truncate = NIL;
7611 foreach(l, on_commits)
7613 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
7615 /* Ignore entry if already dropped in this xact */
7616 if (oc->deleting_subid != InvalidSubTransactionId)
7619 switch (oc->oncommit)
7622 case ONCOMMIT_PRESERVE_ROWS:
7623 /* Do nothing (there shouldn't be such entries, actually) */
7625 case ONCOMMIT_DELETE_ROWS:
7626 oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
7630 ObjectAddress object;
7632 object.classId = RelationRelationId;
7633 object.objectId = oc->relid;
7634 object.objectSubId = 0;
7635 performDeletion(&object, DROP_CASCADE);
7638 * Note that table deletion will call
7639 * remove_on_commit_action, so the entry should get marked
7642 Assert(oc->deleting_subid != InvalidSubTransactionId);
7647 if (oids_to_truncate != NIL)
7649 heap_truncate(oids_to_truncate);
7650 CommandCounterIncrement(); /* XXX needed? */
7655 * Post-commit or post-abort cleanup for ON COMMIT management.
7657 * All we do here is remove no-longer-needed OnCommitItem entries.
7659 * During commit, remove entries that were deleted during this transaction;
7660 * during abort, remove those created during this transaction.
7663 AtEOXact_on_commit_actions(bool isCommit)
7666 ListCell *prev_item;
7669 cur_item = list_head(on_commits);
7671 while (cur_item != NULL)
7673 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
7675 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
7676 oc->creating_subid != InvalidSubTransactionId)
7678 /* cur_item must be removed */
7679 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
7682 cur_item = lnext(prev_item);
7684 cur_item = list_head(on_commits);
7688 /* cur_item must be preserved */
7689 oc->creating_subid = InvalidSubTransactionId;
7690 oc->deleting_subid = InvalidSubTransactionId;
7691 prev_item = cur_item;
7692 cur_item = lnext(prev_item);
7698 * Post-subcommit or post-subabort cleanup for ON COMMIT management.
7700 * During subabort, we can immediately remove entries created during this
7701 * subtransaction. During subcommit, just relabel entries marked during
7702 * this subtransaction as being the parent's responsibility.
7705 AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
7706 SubTransactionId parentSubid)
7709 ListCell *prev_item;
7712 cur_item = list_head(on_commits);
7714 while (cur_item != NULL)
7716 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
7718 if (!isCommit && oc->creating_subid == mySubid)
7720 /* cur_item must be removed */
7721 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
7724 cur_item = lnext(prev_item);
7726 cur_item = list_head(on_commits);
7730 /* cur_item must be preserved */
7731 if (oc->creating_subid == mySubid)
7732 oc->creating_subid = parentSubid;
7733 if (oc->deleting_subid == mySubid)
7734 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
7735 prev_item = cur_item;
7736 cur_item = lnext(prev_item);