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.261 2008/07/16 19:33:25 tgl Exp $
13 *-------------------------------------------------------------------------
17 #include "access/genam.h"
18 #include "access/heapam.h"
19 #include "access/reloptions.h"
20 #include "access/relscan.h"
21 #include "access/sysattr.h"
22 #include "access/xact.h"
23 #include "catalog/catalog.h"
24 #include "catalog/dependency.h"
25 #include "catalog/heap.h"
26 #include "catalog/index.h"
27 #include "catalog/indexing.h"
28 #include "catalog/namespace.h"
29 #include "catalog/pg_constraint.h"
30 #include "catalog/pg_depend.h"
31 #include "catalog/pg_inherits.h"
32 #include "catalog/pg_namespace.h"
33 #include "catalog/pg_opclass.h"
34 #include "catalog/pg_tablespace.h"
35 #include "catalog/pg_trigger.h"
36 #include "catalog/pg_type.h"
37 #include "catalog/pg_type_fn.h"
38 #include "catalog/toasting.h"
39 #include "commands/cluster.h"
40 #include "commands/defrem.h"
41 #include "commands/sequence.h"
42 #include "commands/tablecmds.h"
43 #include "commands/tablespace.h"
44 #include "commands/trigger.h"
45 #include "commands/typecmds.h"
46 #include "executor/executor.h"
47 #include "miscadmin.h"
48 #include "nodes/makefuncs.h"
49 #include "nodes/parsenodes.h"
50 #include "optimizer/clauses.h"
51 #include "optimizer/plancat.h"
52 #include "optimizer/prep.h"
53 #include "parser/gramparse.h"
54 #include "parser/parse_clause.h"
55 #include "parser/parse_coerce.h"
56 #include "parser/parse_expr.h"
57 #include "parser/parse_oper.h"
58 #include "parser/parse_relation.h"
59 #include "parser/parse_type.h"
60 #include "parser/parse_utilcmd.h"
61 #include "parser/parser.h"
62 #include "rewrite/rewriteDefine.h"
63 #include "rewrite/rewriteHandler.h"
64 #include "storage/bufmgr.h"
65 #include "storage/lmgr.h"
66 #include "storage/smgr.h"
67 #include "utils/acl.h"
68 #include "utils/builtins.h"
69 #include "utils/fmgroids.h"
70 #include "utils/inval.h"
71 #include "utils/lsyscache.h"
72 #include "utils/memutils.h"
73 #include "utils/relcache.h"
74 #include "utils/snapmgr.h"
75 #include "utils/syscache.h"
76 #include "utils/tqual.h"
80 * ON COMMIT action list
82 typedef struct OnCommitItem
84 Oid relid; /* relid of relation */
85 OnCommitAction oncommit; /* what to do at end of xact */
88 * If this entry was created during the current transaction,
89 * creating_subid is the ID of the creating subxact; if created in a prior
90 * transaction, creating_subid is zero. If deleted during the current
91 * transaction, deleting_subid is the ID of the deleting subxact; if no
92 * deletion request is pending, deleting_subid is zero.
94 SubTransactionId creating_subid;
95 SubTransactionId deleting_subid;
98 static List *on_commits = NIL;
102 * State information for ALTER TABLE
104 * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
105 * structs, one for each table modified by the operation (the named table
106 * plus any child tables that are affected). We save lists of subcommands
107 * to apply to this table (possibly modified by parse transformation steps);
108 * these lists will be executed in Phase 2. If a Phase 3 step is needed,
109 * necessary information is stored in the constraints and newvals lists.
111 * Phase 2 is divided into multiple passes; subcommands are executed in
112 * a pass determined by subcommand type.
115 #define AT_PASS_DROP 0 /* DROP (all flavors) */
116 #define AT_PASS_ALTER_TYPE 1 /* ALTER COLUMN TYPE */
117 #define AT_PASS_OLD_INDEX 2 /* re-add existing indexes */
118 #define AT_PASS_OLD_CONSTR 3 /* re-add existing constraints */
119 #define AT_PASS_COL_ATTRS 4 /* set other column attributes */
120 /* We could support a RENAME COLUMN pass here, but not currently used */
121 #define AT_PASS_ADD_COL 5 /* ADD COLUMN */
122 #define AT_PASS_ADD_INDEX 6 /* ADD indexes */
123 #define AT_PASS_ADD_CONSTR 7 /* ADD constraints, defaults */
124 #define AT_PASS_MISC 8 /* other stuff */
125 #define AT_NUM_PASSES 9
127 typedef struct AlteredTableInfo
129 /* Information saved before any work commences: */
130 Oid relid; /* Relation to work on */
131 char relkind; /* Its relkind */
132 TupleDesc oldDesc; /* Pre-modification tuple descriptor */
133 /* Information saved by Phase 1 for Phase 2: */
134 List *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
135 /* Information saved by Phases 1/2 for Phase 3: */
136 List *constraints; /* List of NewConstraint */
137 List *newvals; /* List of NewColumnValue */
138 bool new_notnull; /* T if we added new NOT NULL constraints */
139 Oid newTableSpace; /* new tablespace; 0 means no change */
140 /* Objects to rebuild after completing ALTER TYPE operations */
141 List *changedConstraintOids; /* OIDs of constraints to rebuild */
142 List *changedConstraintDefs; /* string definitions of same */
143 List *changedIndexOids; /* OIDs of indexes to rebuild */
144 List *changedIndexDefs; /* string definitions of same */
147 /* Struct describing one new constraint to check in Phase 3 scan */
148 /* Note: new NOT NULL constraints are handled elsewhere */
149 typedef struct NewConstraint
151 char *name; /* Constraint name, or NULL if none */
152 ConstrType contype; /* CHECK or FOREIGN */
153 Oid refrelid; /* PK rel, if FOREIGN */
154 Oid conid; /* OID of pg_constraint entry, if FOREIGN */
155 Node *qual; /* Check expr or FkConstraint struct */
156 List *qualstate; /* Execution state for CHECK */
160 * Struct describing one new column value that needs to be computed during
161 * Phase 3 copy (this could be either a new column with a non-null default, or
162 * a column that we're changing the type of). Columns without such an entry
163 * are just copied from the old table during ATRewriteTable. Note that the
164 * expr is an expression over *old* table values.
166 typedef struct NewColumnValue
168 AttrNumber attnum; /* which column */
169 Expr *expr; /* expression to compute */
170 ExprState *exprstate; /* execution state */
174 * Error-reporting support for RemoveRelations
176 struct dropmsgstrings
179 int nonexistent_code;
180 const char *nonexistent_msg;
181 const char *skipping_msg;
182 const char *nota_msg;
183 const char *drophint_msg;
186 static const struct dropmsgstrings dropmsgstringarray[] = {
188 ERRCODE_UNDEFINED_TABLE,
189 gettext_noop("table \"%s\" does not exist"),
190 gettext_noop("table \"%s\" does not exist, skipping"),
191 gettext_noop("\"%s\" is not a table"),
192 gettext_noop("Use DROP TABLE to remove a table.")},
194 ERRCODE_UNDEFINED_TABLE,
195 gettext_noop("sequence \"%s\" does not exist"),
196 gettext_noop("sequence \"%s\" does not exist, skipping"),
197 gettext_noop("\"%s\" is not a sequence"),
198 gettext_noop("Use DROP SEQUENCE to remove a sequence.")},
200 ERRCODE_UNDEFINED_TABLE,
201 gettext_noop("view \"%s\" does not exist"),
202 gettext_noop("view \"%s\" does not exist, skipping"),
203 gettext_noop("\"%s\" is not a view"),
204 gettext_noop("Use DROP VIEW to remove a view.")},
206 ERRCODE_UNDEFINED_OBJECT,
207 gettext_noop("index \"%s\" does not exist"),
208 gettext_noop("index \"%s\" does not exist, skipping"),
209 gettext_noop("\"%s\" is not an index"),
210 gettext_noop("Use DROP INDEX to remove an index.")},
211 {RELKIND_COMPOSITE_TYPE,
212 ERRCODE_UNDEFINED_OBJECT,
213 gettext_noop("type \"%s\" does not exist"),
214 gettext_noop("type \"%s\" does not exist, skipping"),
215 gettext_noop("\"%s\" is not a type"),
216 gettext_noop("Use DROP TYPE to remove a type.")},
217 {'\0', 0, NULL, NULL, NULL, NULL}
221 static void truncate_check_rel(Relation rel);
222 static List *MergeAttributes(List *schema, List *supers, bool istemp,
223 List **supOids, List **supconstr, int *supOidCount);
224 static bool MergeCheckConstraint(List *constraints, char *name, Node *expr);
225 static bool change_varattnos_walker(Node *node, const AttrNumber *newattno);
226 static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel);
227 static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
228 static void StoreCatalogInheritance(Oid relationId, List *supers);
229 static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
230 int16 seqNumber, Relation inhRelation);
231 static int findAttrByName(const char *attributeName, List *schema);
232 static void setRelhassubclassInRelation(Oid relationId, bool relhassubclass);
233 static void AlterIndexNamespaces(Relation classRel, Relation rel,
234 Oid oldNspOid, Oid newNspOid);
235 static void AlterSeqNamespaces(Relation classRel, Relation rel,
236 Oid oldNspOid, Oid newNspOid,
237 const char *newNspName);
238 static int transformColumnNameList(Oid relId, List *colList,
239 int16 *attnums, Oid *atttypids);
240 static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
242 int16 *attnums, Oid *atttypids,
244 static Oid transformFkeyCheckAttrs(Relation pkrel,
245 int numattrs, int16 *attnums,
247 static void validateForeignKeyConstraint(FkConstraint *fkconstraint,
248 Relation rel, Relation pkrel, Oid constraintOid);
249 static void createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
251 static void ATController(Relation rel, List *cmds, bool recurse);
252 static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
253 bool recurse, bool recursing);
254 static void ATRewriteCatalogs(List **wqueue);
255 static void ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
257 static void ATRewriteTables(List **wqueue);
258 static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap);
259 static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
260 static void ATSimplePermissions(Relation rel, bool allowView);
261 static void ATSimplePermissionsRelationOrIndex(Relation rel);
262 static void ATSimpleRecursion(List **wqueue, Relation rel,
263 AlterTableCmd *cmd, bool recurse);
264 static void ATOneLevelRecursion(List **wqueue, Relation rel,
266 static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
268 static void ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
270 static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
271 static void ATExecDropNotNull(Relation rel, const char *colName);
272 static void ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
273 const char *colName);
274 static void ATExecColumnDefault(Relation rel, const char *colName,
276 static void ATPrepSetStatistics(Relation rel, const char *colName,
278 static void ATExecSetStatistics(Relation rel, const char *colName,
280 static void ATExecSetStorage(Relation rel, const char *colName,
282 static void ATExecDropColumn(Relation rel, const char *colName,
283 DropBehavior behavior,
284 bool recurse, bool recursing);
285 static void ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
286 IndexStmt *stmt, bool is_rebuild);
287 static void ATExecAddConstraint(List **wqueue,
288 AlteredTableInfo *tab, Relation rel,
289 Node *newConstraint, bool recurse);
290 static void ATAddCheckConstraint(List **wqueue,
291 AlteredTableInfo *tab, Relation rel,
293 bool recurse, bool recursing);
294 static void ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
295 FkConstraint *fkconstraint);
296 static void ATExecDropConstraint(Relation rel, const char *constrName,
297 DropBehavior behavior,
298 bool recurse, bool recursing);
299 static void ATPrepAlterColumnType(List **wqueue,
300 AlteredTableInfo *tab, Relation rel,
301 bool recurse, bool recursing,
303 static void ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
304 const char *colName, TypeName *typename);
305 static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab);
306 static void ATPostAlterTypeParse(char *cmd, List **wqueue);
307 static void change_owner_recurse_to_sequences(Oid relationOid,
309 static void ATExecClusterOn(Relation rel, const char *indexName);
310 static void ATExecDropCluster(Relation rel);
311 static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
312 char *tablespacename);
313 static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace);
314 static void ATExecSetRelOptions(Relation rel, List *defList, bool isReset);
315 static void ATExecEnableDisableTrigger(Relation rel, char *trigname,
316 char fires_when, bool skip_system);
317 static void ATExecEnableDisableRule(Relation rel, char *rulename,
319 static void ATExecAddInherit(Relation rel, RangeVar *parent);
320 static void ATExecDropInherit(Relation rel, RangeVar *parent);
321 static void copy_relation_data(Relation rel, SMgrRelation dst);
324 /* ----------------------------------------------------------------
326 * Creates a new relation.
328 * If successful, returns the OID of the new relation.
329 * ----------------------------------------------------------------
332 DefineRelation(CreateStmt *stmt, char relkind)
334 char relname[NAMEDATALEN];
336 List *schema = stmt->tableElts;
340 TupleDesc descriptor;
342 List *old_constraints;
346 List *cookedDefaults;
352 * Truncate relname to appropriate length (probably a waste of time, as
353 * parser should have done this already).
355 StrNCpy(relname, stmt->relation->relname, NAMEDATALEN);
358 * Check consistency of arguments
360 if (stmt->oncommit != ONCOMMIT_NOOP && !stmt->relation->istemp)
362 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
363 errmsg("ON COMMIT can only be used on temporary tables")));
366 * Look up the namespace in which we are supposed to create the relation.
367 * Check we have permission to create there. Skip check if bootstrapping,
368 * since permissions machinery may not be working yet.
370 namespaceId = RangeVarGetCreationNamespace(stmt->relation);
372 if (!IsBootstrapProcessingMode())
376 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
378 if (aclresult != ACLCHECK_OK)
379 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
380 get_namespace_name(namespaceId));
384 * Select tablespace to use. If not specified, use default tablespace
385 * (which may in turn default to database's default).
387 if (stmt->tablespacename)
389 tablespaceId = get_tablespace_oid(stmt->tablespacename);
390 if (!OidIsValid(tablespaceId))
392 (errcode(ERRCODE_UNDEFINED_OBJECT),
393 errmsg("tablespace \"%s\" does not exist",
394 stmt->tablespacename)));
398 tablespaceId = GetDefaultTablespace(stmt->relation->istemp);
399 /* note InvalidOid is OK in this case */
402 /* Check permissions except when using database's default */
403 if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
407 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
409 if (aclresult != ACLCHECK_OK)
410 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
411 get_tablespace_name(tablespaceId));
415 * Parse and validate reloptions, if any.
417 reloptions = transformRelOptions((Datum) 0, stmt->options, true, false);
419 (void) heap_reloptions(relkind, reloptions, true);
422 * Look up inheritance ancestors and generate relation schema, including
423 * inherited attributes.
425 schema = MergeAttributes(schema, stmt->inhRelations,
426 stmt->relation->istemp,
427 &inheritOids, &old_constraints, &parentOidCount);
430 * Create a tuple descriptor from the relation schema. Note that this
431 * deals with column names, types, and NOT NULL constraints, but not
432 * default values or CHECK constraints; we handle those below.
434 descriptor = BuildDescForRelation(schema);
436 localHasOids = interpretOidsOption(stmt->options);
437 descriptor->tdhasoid = (localHasOids || parentOidCount > 0);
440 * Find columns with default values and prepare for insertion of the
441 * defaults. Pre-cooked (that is, inherited) defaults go into a list of
442 * CookedConstraint structs that we'll pass to heap_create_with_catalog,
443 * while raw defaults go into a list of RawColumnDefault structs that
444 * will be processed by AddRelationNewConstraints. (We can't deal with
445 * raw expressions until we can do transformExpr.)
447 * We can set the atthasdef flags now in the tuple descriptor; this just
448 * saves StoreAttrDefault from having to do an immediate update of the
452 cookedDefaults = NIL;
455 foreach(listptr, schema)
457 ColumnDef *colDef = lfirst(listptr);
461 if (colDef->raw_default != NULL)
463 RawColumnDefault *rawEnt;
465 Assert(colDef->cooked_default == NULL);
467 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
468 rawEnt->attnum = attnum;
469 rawEnt->raw_default = colDef->raw_default;
470 rawDefaults = lappend(rawDefaults, rawEnt);
471 descriptor->attrs[attnum - 1]->atthasdef = true;
473 else if (colDef->cooked_default != NULL)
475 CookedConstraint *cooked;
477 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
478 cooked->contype = CONSTR_DEFAULT;
480 cooked->attnum = attnum;
481 cooked->expr = stringToNode(colDef->cooked_default);
482 cooked->is_local = true; /* not used for defaults */
483 cooked->inhcount = 0; /* ditto */
484 cookedDefaults = lappend(cookedDefaults, cooked);
485 descriptor->attrs[attnum - 1]->atthasdef = true;
490 * Create the relation. Inherited defaults and constraints are passed
491 * in for immediate handling --- since they don't need parsing, they
492 * can be stored immediately.
494 relationId = heap_create_with_catalog(relname,
500 list_concat(cookedDefaults,
508 allowSystemTableMods);
510 StoreCatalogInheritance(relationId, inheritOids);
513 * We must bump the command counter to make the newly-created relation
514 * tuple visible for opening.
516 CommandCounterIncrement();
519 * Open the new relation and acquire exclusive lock on it. This isn't
520 * really necessary for locking out other backends (since they can't see
521 * the new rel anyway until we commit), but it keeps the lock manager from
522 * complaining about deadlock risks.
524 rel = relation_open(relationId, AccessExclusiveLock);
527 * Now add any newly specified column default values and CHECK constraints
528 * to the new relation. These are passed to us in the form of raw
529 * parsetrees; we need to transform them to executable expression trees
530 * before they can be added. The most convenient way to do that is to
531 * apply the parser's transformExpr routine, but transformExpr doesn't
532 * work unless we have a pre-existing relation. So, the transformation has
533 * to be postponed to this final step of CREATE TABLE.
535 if (rawDefaults || stmt->constraints)
536 AddRelationNewConstraints(rel, rawDefaults, stmt->constraints,
540 * Clean up. We keep lock on new relation (although it shouldn't be
541 * visible to anyone else anyway, until commit).
543 relation_close(rel, NoLock);
549 * Emit the right error or warning message for a "DROP" command issued on a
550 * non-existent relation
553 DropErrorMsgNonExistent(const char *relname, char rightkind, bool missing_ok)
555 const struct dropmsgstrings *rentry;
557 for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
559 if (rentry->kind == rightkind)
564 (errcode(rentry->nonexistent_code),
565 errmsg(rentry->nonexistent_msg, relname)));
569 ereport(NOTICE, (errmsg(rentry->skipping_msg, relname)));
575 Assert(rentry->kind != '\0'); /* Should be impossible */
579 * Emit the right error message for a "DROP" command issued on a
580 * relation of the wrong type
583 DropErrorMsgWrongType(const char *relname, char wrongkind, char rightkind)
585 const struct dropmsgstrings *rentry;
586 const struct dropmsgstrings *wentry;
588 for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
589 if (rentry->kind == rightkind)
591 Assert(rentry->kind != '\0');
593 for (wentry = dropmsgstringarray; wentry->kind != '\0'; wentry++)
594 if (wentry->kind == wrongkind)
596 /* wrongkind could be something we don't have in our table... */
599 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
600 errmsg(rentry->nota_msg, relname),
601 (wentry->kind != '\0') ? errhint(wentry->drophint_msg) : 0));
606 * Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW
609 RemoveRelations(DropStmt *drop)
611 ObjectAddresses *objects;
616 * First we identify all the relations, then we delete them in a single
617 * performMultipleDeletions() call. This is to avoid unwanted
618 * DROP RESTRICT errors if one of the relations depends on another.
621 /* Determine required relkind */
622 switch (drop->removeType)
625 relkind = RELKIND_RELATION;
629 relkind = RELKIND_INDEX;
632 case OBJECT_SEQUENCE:
633 relkind = RELKIND_SEQUENCE;
637 relkind = RELKIND_VIEW;
641 elog(ERROR, "unrecognized drop object type: %d",
642 (int) drop->removeType);
643 relkind = 0; /* keep compiler quiet */
647 /* Lock and validate each relation; build a list of object addresses */
648 objects = new_object_addresses();
650 foreach(cell, drop->objects)
652 RangeVar *rel = makeRangeVarFromNameList((List *) lfirst(cell));
655 Form_pg_class classform;
659 * These next few steps are a great deal like relation_openrv, but we
660 * don't bother building a relcache entry since we don't need it.
662 * Check for shared-cache-inval messages before trying to access the
663 * relation. This is needed to cover the case where the name
664 * identifies a rel that has been dropped and recreated since the
665 * start of our transaction: if we don't flush the old syscache entry,
666 * then we'll latch onto that entry and suffer an error later.
668 AcceptInvalidationMessages();
670 /* Look up the appropriate relation using namespace search */
671 relOid = RangeVarGetRelid(rel, true);
674 if (!OidIsValid(relOid))
676 DropErrorMsgNonExistent(rel->relname, relkind, drop->missing_ok);
681 * In DROP INDEX, attempt to acquire lock on the parent table before
682 * locking the index. index_drop() will need this anyway, and since
683 * regular queries lock tables before their indexes, we risk deadlock
684 * if we do it the other way around. No error if we don't find a
685 * pg_index entry, though --- that most likely means it isn't an
686 * index, and we'll fail below.
688 if (relkind == RELKIND_INDEX)
690 tuple = SearchSysCache(INDEXRELID,
691 ObjectIdGetDatum(relOid),
693 if (HeapTupleIsValid(tuple))
695 Form_pg_index index = (Form_pg_index) GETSTRUCT(tuple);
697 LockRelationOid(index->indrelid, AccessExclusiveLock);
698 ReleaseSysCache(tuple);
702 /* Get the lock before trying to fetch the syscache entry */
703 LockRelationOid(relOid, AccessExclusiveLock);
705 tuple = SearchSysCache(RELOID,
706 ObjectIdGetDatum(relOid),
708 if (!HeapTupleIsValid(tuple))
709 elog(ERROR, "cache lookup failed for relation %u", relOid);
710 classform = (Form_pg_class) GETSTRUCT(tuple);
712 if (classform->relkind != relkind)
713 DropErrorMsgWrongType(rel->relname, classform->relkind, relkind);
715 /* Allow DROP to either table owner or schema owner */
716 if (!pg_class_ownercheck(relOid, GetUserId()) &&
717 !pg_namespace_ownercheck(classform->relnamespace, GetUserId()))
718 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
721 if (!allowSystemTableMods && IsSystemClass(classform))
723 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
724 errmsg("permission denied: \"%s\" is a system catalog",
727 /* OK, we're ready to delete this one */
728 obj.classId = RelationRelationId;
729 obj.objectId = relOid;
732 add_exact_object_address(&obj, objects);
734 ReleaseSysCache(tuple);
737 performMultipleDeletions(objects, drop->behavior);
739 free_object_addresses(objects);
744 * Executes a TRUNCATE command.
746 * This is a multi-relation truncate. We first open and grab exclusive
747 * lock on all relations involved, checking permissions and otherwise
748 * verifying that the relation is OK for truncation. In CASCADE mode,
749 * relations having FK references to the targeted relations are automatically
750 * added to the group; in RESTRICT mode, we check that all FK references are
751 * internal to the group that's being truncated. Finally all the relations
752 * are truncated and reindexed.
755 ExecuteTruncate(TruncateStmt *stmt)
759 List *seq_relids = NIL;
761 ResultRelInfo *resultRelInfos;
762 ResultRelInfo *resultRelInfo;
766 * Open, exclusive-lock, and check all the explicitly-specified relations
768 foreach(cell, stmt->relations)
770 RangeVar *rv = lfirst(cell);
773 rel = heap_openrv(rv, AccessExclusiveLock);
774 /* don't throw error for "TRUNCATE foo, foo" */
775 if (list_member_oid(relids, RelationGetRelid(rel)))
777 heap_close(rel, AccessExclusiveLock);
780 truncate_check_rel(rel);
781 rels = lappend(rels, rel);
782 relids = lappend_oid(relids, RelationGetRelid(rel));
786 * In CASCADE mode, suck in all referencing relations as well. This
787 * requires multiple iterations to find indirectly-dependent relations. At
788 * each phase, we need to exclusive-lock new rels before looking for their
789 * dependencies, else we might miss something. Also, we check each rel as
790 * soon as we open it, to avoid a faux pas such as holding lock for a long
791 * time on a rel we have no permissions for.
793 if (stmt->behavior == DROP_CASCADE)
799 newrelids = heap_truncate_find_FKs(relids);
800 if (newrelids == NIL)
801 break; /* nothing else to add */
803 foreach(cell, newrelids)
805 Oid relid = lfirst_oid(cell);
808 rel = heap_open(relid, AccessExclusiveLock);
810 (errmsg("truncate cascades to table \"%s\"",
811 RelationGetRelationName(rel))));
812 truncate_check_rel(rel);
813 rels = lappend(rels, rel);
814 relids = lappend_oid(relids, relid);
820 * Check foreign key references. In CASCADE mode, this should be
821 * unnecessary since we just pulled in all the references; but as a
822 * cross-check, do it anyway if in an Assert-enabled build.
824 #ifdef USE_ASSERT_CHECKING
825 heap_truncate_check_FKs(rels, false);
827 if (stmt->behavior == DROP_RESTRICT)
828 heap_truncate_check_FKs(rels, false);
832 * If we are asked to restart sequences, find all the sequences,
833 * lock them (we only need AccessShareLock because that's all that
834 * ALTER SEQUENCE takes), and check permissions. We want to do this
835 * early since it's pointless to do all the truncation work only to fail
836 * on sequence permissions.
838 if (stmt->restart_seqs)
842 Relation rel = (Relation) lfirst(cell);
843 List *seqlist = getOwnedSequences(RelationGetRelid(rel));
846 foreach(seqcell, seqlist)
848 Oid seq_relid = lfirst_oid(seqcell);
851 seq_rel = relation_open(seq_relid, AccessShareLock);
853 /* This check must match AlterSequence! */
854 if (!pg_class_ownercheck(seq_relid, GetUserId()))
855 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
856 RelationGetRelationName(seq_rel));
858 seq_relids = lappend_oid(seq_relids, seq_relid);
860 relation_close(seq_rel, NoLock);
865 /* Prepare to catch AFTER triggers. */
866 AfterTriggerBeginQuery();
869 * To fire triggers, we'll need an EState as well as a ResultRelInfo
872 estate = CreateExecutorState();
873 resultRelInfos = (ResultRelInfo *)
874 palloc(list_length(rels) * sizeof(ResultRelInfo));
875 resultRelInfo = resultRelInfos;
878 Relation rel = (Relation) lfirst(cell);
880 InitResultRelInfo(resultRelInfo,
882 0, /* dummy rangetable index */
883 CMD_DELETE, /* don't need any index info */
887 estate->es_result_relations = resultRelInfos;
888 estate->es_num_result_relations = list_length(rels);
891 * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
892 * truncating (this is because one of them might throw an error).
893 * Also, if we were to allow them to prevent statement execution,
894 * that would need to be handled here.
896 resultRelInfo = resultRelInfos;
899 estate->es_result_relation_info = resultRelInfo;
900 ExecBSTruncateTriggers(estate, resultRelInfo);
905 * OK, truncate each table.
909 Relation rel = (Relation) lfirst(cell);
914 * Create a new empty storage file for the relation, and assign it as
915 * the relfilenode value. The old storage file is scheduled for
916 * deletion at commit.
918 setNewRelfilenode(rel, RecentXmin);
920 heap_relid = RelationGetRelid(rel);
921 toast_relid = rel->rd_rel->reltoastrelid;
924 * The same for the toast table, if any.
926 if (OidIsValid(toast_relid))
928 rel = relation_open(toast_relid, AccessExclusiveLock);
929 setNewRelfilenode(rel, RecentXmin);
930 heap_close(rel, NoLock);
934 * Reconstruct the indexes to match, and we're done.
936 reindex_relation(heap_relid, true);
940 * Process all AFTER STATEMENT TRUNCATE triggers.
942 resultRelInfo = resultRelInfos;
945 estate->es_result_relation_info = resultRelInfo;
946 ExecASTruncateTriggers(estate, resultRelInfo);
950 /* Handle queued AFTER triggers */
951 AfterTriggerEndQuery(estate);
953 /* We can clean up the EState now */
954 FreeExecutorState(estate);
956 /* And close the rels (can't do this while EState still holds refs) */
959 Relation rel = (Relation) lfirst(cell);
961 heap_close(rel, NoLock);
965 * Lastly, restart any owned sequences if we were asked to. This is done
966 * last because it's nontransactional: restarts will not roll back if
967 * we abort later. Hence it's important to postpone them as long as
968 * possible. (This is also a big reason why we locked and
969 * permission-checked the sequences beforehand.)
971 if (stmt->restart_seqs)
973 List *options = list_make1(makeDefElem("restart", NULL));
975 foreach(cell, seq_relids)
977 Oid seq_relid = lfirst_oid(cell);
979 AlterSequenceInternal(seq_relid, options);
985 * Check that a given rel is safe to truncate. Subroutine for ExecuteTruncate
988 truncate_check_rel(Relation rel)
990 /* Only allow truncate on regular tables */
991 if (rel->rd_rel->relkind != RELKIND_RELATION)
993 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
994 errmsg("\"%s\" is not a table",
995 RelationGetRelationName(rel))));
997 /* Permissions checks */
998 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
999 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1000 RelationGetRelationName(rel));
1002 if (!allowSystemTableMods && IsSystemRelation(rel))
1004 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1005 errmsg("permission denied: \"%s\" is a system catalog",
1006 RelationGetRelationName(rel))));
1009 * We can never allow truncation of shared or nailed-in-cache relations,
1010 * because we can't support changing their relfilenode values.
1012 if (rel->rd_rel->relisshared || rel->rd_isnailed)
1014 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1015 errmsg("cannot truncate system relation \"%s\"",
1016 RelationGetRelationName(rel))));
1019 * Don't allow truncate on temp tables of other backends ... their local
1020 * buffer manager is not going to cope.
1022 if (isOtherTempNamespace(RelationGetNamespace(rel)))
1024 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1025 errmsg("cannot truncate temporary tables of other sessions")));
1028 * Also check for active uses of the relation in the current transaction,
1029 * including open scans and pending AFTER trigger events.
1031 CheckTableNotInUse(rel, "TRUNCATE");
1036 * Returns new schema given initial schema and superclasses.
1039 * 'schema' is the column/attribute definition for the table. (It's a list
1040 * of ColumnDef's.) It is destructively changed.
1041 * 'supers' is a list of names (as RangeVar nodes) of parent relations.
1042 * 'istemp' is TRUE if we are creating a temp relation.
1045 * 'supOids' receives a list of the OIDs of the parent relations.
1046 * 'supconstr' receives a list of constraints belonging to the parents,
1047 * updated as necessary to be valid for the child.
1048 * 'supOidCount' is set to the number of parents that have OID columns.
1051 * Completed schema list.
1054 * The order in which the attributes are inherited is very important.
1055 * Intuitively, the inherited attributes should come first. If a table
1056 * inherits from multiple parents, the order of those attributes are
1057 * according to the order of the parents specified in CREATE TABLE.
1059 * Here's an example:
1061 * create table person (name text, age int4, location point);
1062 * create table emp (salary int4, manager text) inherits(person);
1063 * create table student (gpa float8) inherits (person);
1064 * create table stud_emp (percent int4) inherits (emp, student);
1066 * The order of the attributes of stud_emp is:
1068 * person {1:name, 2:age, 3:location}
1070 * {6:gpa} student emp {4:salary, 5:manager}
1072 * stud_emp {7:percent}
1074 * If the same attribute name appears multiple times, then it appears
1075 * in the result table in the proper location for its first appearance.
1077 * Constraints (including NOT NULL constraints) for the child table
1078 * are the union of all relevant constraints, from both the child schema
1079 * and parent tables.
1081 * The default value for a child column is defined as:
1082 * (1) If the child schema specifies a default, that value is used.
1083 * (2) If neither the child nor any parent specifies a default, then
1084 * the column will not have a default.
1085 * (3) If conflicting defaults are inherited from different parents
1086 * (and not overridden by the child), an error is raised.
1087 * (4) Otherwise the inherited default is used.
1088 * Rule (3) is new in Postgres 7.1; in earlier releases you got a
1089 * rather arbitrary choice of which parent default to use.
1093 MergeAttributes(List *schema, List *supers, bool istemp,
1094 List **supOids, List **supconstr, int *supOidCount)
1097 List *inhSchema = NIL;
1098 List *parentOids = NIL;
1099 List *constraints = NIL;
1100 int parentsWithOids = 0;
1101 bool have_bogus_defaults = false;
1102 char *bogus_marker = "Bogus!"; /* marks conflicting defaults */
1106 * Check for and reject tables with too many columns. We perform this
1107 * check relatively early for two reasons: (a) we don't run the risk of
1108 * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
1109 * okay if we're processing <= 1600 columns, but could take minutes to
1110 * execute if the user attempts to create a table with hundreds of
1111 * thousands of columns.
1113 * Note that we also need to check that any we do not exceed this figure
1114 * after including columns from inherited relations.
1116 if (list_length(schema) > MaxHeapAttributeNumber)
1118 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1119 errmsg("tables can have at most %d columns",
1120 MaxHeapAttributeNumber)));
1123 * Check for duplicate names in the explicit list of attributes.
1125 * Although we might consider merging such entries in the same way that we
1126 * handle name conflicts for inherited attributes, it seems to make more
1127 * sense to assume such conflicts are errors.
1129 foreach(entry, schema)
1131 ColumnDef *coldef = lfirst(entry);
1134 for_each_cell(rest, lnext(entry))
1136 ColumnDef *restdef = lfirst(rest);
1138 if (strcmp(coldef->colname, restdef->colname) == 0)
1140 (errcode(ERRCODE_DUPLICATE_COLUMN),
1141 errmsg("column \"%s\" specified more than once",
1147 * Scan the parents left-to-right, and merge their attributes to form a
1148 * list of inherited attributes (inhSchema). Also check to see if we need
1149 * to inherit an OID column.
1152 foreach(entry, supers)
1154 RangeVar *parent = (RangeVar *) lfirst(entry);
1156 TupleDesc tupleDesc;
1157 TupleConstr *constr;
1158 AttrNumber *newattno;
1159 AttrNumber parent_attno;
1161 relation = heap_openrv(parent, AccessShareLock);
1163 if (relation->rd_rel->relkind != RELKIND_RELATION)
1165 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1166 errmsg("inherited relation \"%s\" is not a table",
1168 /* Permanent rels cannot inherit from temporary ones */
1169 if (!istemp && isTempNamespace(RelationGetNamespace(relation)))
1171 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1172 errmsg("cannot inherit from temporary relation \"%s\"",
1176 * We should have an UNDER permission flag for this, but for now,
1177 * demand that creator of a child table own the parent.
1179 if (!pg_class_ownercheck(RelationGetRelid(relation), GetUserId()))
1180 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1181 RelationGetRelationName(relation));
1184 * Reject duplications in the list of parents.
1186 if (list_member_oid(parentOids, RelationGetRelid(relation)))
1188 (errcode(ERRCODE_DUPLICATE_TABLE),
1189 errmsg("relation \"%s\" would be inherited from more than once",
1192 parentOids = lappend_oid(parentOids, RelationGetRelid(relation));
1194 if (relation->rd_rel->relhasoids)
1197 tupleDesc = RelationGetDescr(relation);
1198 constr = tupleDesc->constr;
1201 * newattno[] will contain the child-table attribute numbers for the
1202 * attributes of this parent table. (They are not the same for
1203 * parents after the first one, nor if we have dropped columns.)
1205 newattno = (AttrNumber *)
1206 palloc(tupleDesc->natts * sizeof(AttrNumber));
1208 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1211 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
1212 char *attributeName = NameStr(attribute->attname);
1217 * Ignore dropped columns in the parent.
1219 if (attribute->attisdropped)
1222 * change_varattnos_of_a_node asserts that this is greater
1223 * than zero, so if anything tries to use it, we should find
1226 newattno[parent_attno - 1] = 0;
1231 * Does it conflict with some previously inherited column?
1233 exist_attno = findAttrByName(attributeName, inhSchema);
1234 if (exist_attno > 0)
1240 * Yes, try to merge the two column definitions. They must
1241 * have the same type and typmod.
1244 (errmsg("merging multiple inherited definitions of column \"%s\"",
1246 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1247 defTypeId = typenameTypeId(NULL, def->typename, &deftypmod);
1248 if (defTypeId != attribute->atttypid ||
1249 deftypmod != attribute->atttypmod)
1251 (errcode(ERRCODE_DATATYPE_MISMATCH),
1252 errmsg("inherited column \"%s\" has a type conflict",
1254 errdetail("%s versus %s",
1255 TypeNameToString(def->typename),
1256 format_type_be(attribute->atttypid))));
1258 /* Merge of NOT NULL constraints = OR 'em together */
1259 def->is_not_null |= attribute->attnotnull;
1260 /* Default and other constraints are handled below */
1261 newattno[parent_attno - 1] = exist_attno;
1266 * No, create a new inherited column
1268 def = makeNode(ColumnDef);
1269 def->colname = pstrdup(attributeName);
1270 def->typename = makeTypeNameFromOid(attribute->atttypid,
1271 attribute->atttypmod);
1273 def->is_local = false;
1274 def->is_not_null = attribute->attnotnull;
1275 def->raw_default = NULL;
1276 def->cooked_default = NULL;
1277 def->constraints = NIL;
1278 inhSchema = lappend(inhSchema, def);
1279 newattno[parent_attno - 1] = ++child_attno;
1283 * Copy default if any
1285 if (attribute->atthasdef)
1287 char *this_default = NULL;
1288 AttrDefault *attrdef;
1291 /* Find default in constraint structure */
1292 Assert(constr != NULL);
1293 attrdef = constr->defval;
1294 for (i = 0; i < constr->num_defval; i++)
1296 if (attrdef[i].adnum == parent_attno)
1298 this_default = attrdef[i].adbin;
1302 Assert(this_default != NULL);
1305 * If default expr could contain any vars, we'd need to fix
1306 * 'em, but it can't; so default is ready to apply to child.
1308 * If we already had a default from some prior parent, check
1309 * to see if they are the same. If so, no problem; if not,
1310 * mark the column as having a bogus default. Below, we will
1311 * complain if the bogus default isn't overridden by the child
1314 Assert(def->raw_default == NULL);
1315 if (def->cooked_default == NULL)
1316 def->cooked_default = pstrdup(this_default);
1317 else if (strcmp(def->cooked_default, this_default) != 0)
1319 def->cooked_default = bogus_marker;
1320 have_bogus_defaults = true;
1326 * Now copy the CHECK constraints of this parent, adjusting attnos
1327 * using the completed newattno[] map. Identically named constraints
1328 * are merged if possible, else we throw error.
1330 if (constr && constr->num_check > 0)
1332 ConstrCheck *check = constr->check;
1335 for (i = 0; i < constr->num_check; i++)
1337 char *name = check[i].ccname;
1340 /* adjust varattnos of ccbin here */
1341 expr = stringToNode(check[i].ccbin);
1342 change_varattnos_of_a_node(expr, newattno);
1344 /* check for duplicate */
1345 if (!MergeCheckConstraint(constraints, name, expr))
1347 /* nope, this is a new one */
1348 CookedConstraint *cooked;
1350 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1351 cooked->contype = CONSTR_CHECK;
1352 cooked->name = pstrdup(name);
1353 cooked->attnum = 0; /* not used for constraints */
1354 cooked->expr = expr;
1355 cooked->is_local = false;
1356 cooked->inhcount = 1;
1357 constraints = lappend(constraints, cooked);
1365 * Close the parent rel, but keep our AccessShareLock on it until xact
1366 * commit. That will prevent someone else from deleting or ALTERing
1367 * the parent before the child is committed.
1369 heap_close(relation, NoLock);
1373 * If we had no inherited attributes, the result schema is just the
1374 * explicitly declared columns. Otherwise, we need to merge the declared
1375 * columns into the inherited schema list.
1377 if (inhSchema != NIL)
1379 foreach(entry, schema)
1381 ColumnDef *newdef = lfirst(entry);
1382 char *attributeName = newdef->colname;
1386 * Does it conflict with some previously inherited column?
1388 exist_attno = findAttrByName(attributeName, inhSchema);
1389 if (exist_attno > 0)
1398 * Yes, try to merge the two column definitions. They must
1399 * have the same type and typmod.
1402 (errmsg("merging column \"%s\" with inherited definition",
1404 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1405 defTypeId = typenameTypeId(NULL, def->typename, &deftypmod);
1406 newTypeId = typenameTypeId(NULL, newdef->typename, &newtypmod);
1407 if (defTypeId != newTypeId || deftypmod != newtypmod)
1409 (errcode(ERRCODE_DATATYPE_MISMATCH),
1410 errmsg("column \"%s\" has a type conflict",
1412 errdetail("%s versus %s",
1413 TypeNameToString(def->typename),
1414 TypeNameToString(newdef->typename))));
1415 /* Mark the column as locally defined */
1416 def->is_local = true;
1417 /* Merge of NOT NULL constraints = OR 'em together */
1418 def->is_not_null |= newdef->is_not_null;
1419 /* If new def has a default, override previous default */
1420 if (newdef->raw_default != NULL)
1422 def->raw_default = newdef->raw_default;
1423 def->cooked_default = newdef->cooked_default;
1429 * No, attach new column to result schema
1431 inhSchema = lappend(inhSchema, newdef);
1438 * Check that we haven't exceeded the legal # of columns after merging
1439 * in inherited columns.
1441 if (list_length(schema) > MaxHeapAttributeNumber)
1443 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1444 errmsg("tables can have at most %d columns",
1445 MaxHeapAttributeNumber)));
1449 * If we found any conflicting parent default values, check to make sure
1450 * they were overridden by the child.
1452 if (have_bogus_defaults)
1454 foreach(entry, schema)
1456 ColumnDef *def = lfirst(entry);
1458 if (def->cooked_default == bogus_marker)
1460 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
1461 errmsg("column \"%s\" inherits conflicting default values",
1463 errhint("To resolve the conflict, specify a default explicitly.")));
1467 *supOids = parentOids;
1468 *supconstr = constraints;
1469 *supOidCount = parentsWithOids;
1475 * MergeCheckConstraint
1476 * Try to merge an inherited CHECK constraint with previous ones
1478 * If we inherit identically-named constraints from multiple parents, we must
1479 * merge them, or throw an error if they don't have identical definitions.
1481 * constraints is a list of CookedConstraint structs for previous constraints.
1483 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
1484 * got a so-far-unique name, or throws error if conflict.
1487 MergeCheckConstraint(List *constraints, char *name, Node *expr)
1491 foreach(lc, constraints)
1493 CookedConstraint *ccon = (CookedConstraint *) lfirst(lc);
1495 Assert(ccon->contype == CONSTR_CHECK);
1497 /* Non-matching names never conflict */
1498 if (strcmp(ccon->name, name) != 0)
1501 if (equal(expr, ccon->expr))
1509 (errcode(ERRCODE_DUPLICATE_OBJECT),
1510 errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
1519 * Replace varattno values in an expression tree according to the given
1520 * map array, that is, varattno N is replaced by newattno[N-1]. It is
1521 * caller's responsibility to ensure that the array is long enough to
1522 * define values for all user varattnos present in the tree. System column
1523 * attnos remain unchanged.
1525 * Note that the passed node tree is modified in-place!
1528 change_varattnos_of_a_node(Node *node, const AttrNumber *newattno)
1530 /* no setup needed, so away we go */
1531 (void) change_varattnos_walker(node, newattno);
1535 change_varattnos_walker(Node *node, const AttrNumber *newattno)
1541 Var *var = (Var *) node;
1543 if (var->varlevelsup == 0 && var->varno == 1 &&
1547 * ??? the following may be a problem when the node is multiply
1548 * referenced though stringToNode() doesn't create such a node
1551 Assert(newattno[var->varattno - 1] > 0);
1552 var->varattno = var->varoattno = newattno[var->varattno - 1];
1556 return expression_tree_walker(node, change_varattnos_walker,
1561 * Generate a map for change_varattnos_of_a_node from old and new TupleDesc's,
1562 * matching according to column name.
1565 varattnos_map(TupleDesc old, TupleDesc new)
1571 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * old->natts);
1572 for (i = 1; i <= old->natts; i++)
1574 if (old->attrs[i - 1]->attisdropped)
1575 continue; /* leave the entry as zero */
1577 for (j = 1; j <= new->natts; j++)
1579 if (strcmp(NameStr(old->attrs[i - 1]->attname),
1580 NameStr(new->attrs[j - 1]->attname)) == 0)
1591 * Generate a map for change_varattnos_of_a_node from a TupleDesc and a list
1595 varattnos_map_schema(TupleDesc old, List *schema)
1600 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * old->natts);
1601 for (i = 1; i <= old->natts; i++)
1603 if (old->attrs[i - 1]->attisdropped)
1604 continue; /* leave the entry as zero */
1606 attmap[i - 1] = findAttrByName(NameStr(old->attrs[i - 1]->attname),
1614 * StoreCatalogInheritance
1615 * Updates the system catalogs with proper inheritance information.
1617 * supers is a list of the OIDs of the new relation's direct ancestors.
1620 StoreCatalogInheritance(Oid relationId, List *supers)
1629 AssertArg(OidIsValid(relationId));
1635 * Store INHERITS information in pg_inherits using direct ancestors only.
1636 * Also enter dependencies on the direct ancestors, and make sure they are
1637 * marked with relhassubclass = true.
1639 * (Once upon a time, both direct and indirect ancestors were found here
1640 * and then entered into pg_ipl. Since that catalog doesn't exist
1641 * anymore, there's no need to look for indirect ancestors.)
1643 relation = heap_open(InheritsRelationId, RowExclusiveLock);
1646 foreach(entry, supers)
1648 Oid parentOid = lfirst_oid(entry);
1650 StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation);
1654 heap_close(relation, RowExclusiveLock);
1658 * Make catalog entries showing relationId as being an inheritance child
1659 * of parentOid. inhRelation is the already-opened pg_inherits catalog.
1662 StoreCatalogInheritance1(Oid relationId, Oid parentOid,
1663 int16 seqNumber, Relation inhRelation)
1665 TupleDesc desc = RelationGetDescr(inhRelation);
1666 Datum datum[Natts_pg_inherits];
1667 char nullarr[Natts_pg_inherits];
1668 ObjectAddress childobject,
1673 * Make the pg_inherits entry
1675 datum[0] = ObjectIdGetDatum(relationId); /* inhrelid */
1676 datum[1] = ObjectIdGetDatum(parentOid); /* inhparent */
1677 datum[2] = Int16GetDatum(seqNumber); /* inhseqno */
1683 tuple = heap_formtuple(desc, datum, nullarr);
1685 simple_heap_insert(inhRelation, tuple);
1687 CatalogUpdateIndexes(inhRelation, tuple);
1689 heap_freetuple(tuple);
1692 * Store a dependency too
1694 parentobject.classId = RelationRelationId;
1695 parentobject.objectId = parentOid;
1696 parentobject.objectSubId = 0;
1697 childobject.classId = RelationRelationId;
1698 childobject.objectId = relationId;
1699 childobject.objectSubId = 0;
1701 recordDependencyOn(&childobject, &parentobject, DEPENDENCY_NORMAL);
1704 * Mark the parent as having subclasses.
1706 setRelhassubclassInRelation(parentOid, true);
1710 * Look for an existing schema entry with the given name.
1712 * Returns the index (starting with 1) if attribute already exists in schema,
1716 findAttrByName(const char *attributeName, List *schema)
1723 ColumnDef *def = lfirst(s);
1725 if (strcmp(attributeName, def->colname) == 0)
1734 * Update a relation's pg_class.relhassubclass entry to the given value
1737 setRelhassubclassInRelation(Oid relationId, bool relhassubclass)
1739 Relation relationRelation;
1741 Form_pg_class classtuple;
1744 * Fetch a modifiable copy of the tuple, modify it, update pg_class.
1746 * If the tuple already has the right relhassubclass setting, we don't
1747 * need to update it, but we still need to issue an SI inval message.
1749 relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
1750 tuple = SearchSysCacheCopy(RELOID,
1751 ObjectIdGetDatum(relationId),
1753 if (!HeapTupleIsValid(tuple))
1754 elog(ERROR, "cache lookup failed for relation %u", relationId);
1755 classtuple = (Form_pg_class) GETSTRUCT(tuple);
1757 if (classtuple->relhassubclass != relhassubclass)
1759 classtuple->relhassubclass = relhassubclass;
1760 simple_heap_update(relationRelation, &tuple->t_self, tuple);
1762 /* keep the catalog indexes up to date */
1763 CatalogUpdateIndexes(relationRelation, tuple);
1767 /* no need to change tuple, but force relcache rebuild anyway */
1768 CacheInvalidateRelcacheByTuple(tuple);
1771 heap_freetuple(tuple);
1772 heap_close(relationRelation, RowExclusiveLock);
1777 * renameatt - changes the name of a attribute in a relation
1779 * Attname attribute is changed in attribute catalog.
1780 * No record of the previous attname is kept (correct?).
1782 * get proper relrelation from relation catalog (if not arg)
1783 * scan attribute catalog
1784 * for name conflict (within rel)
1785 * for original attribute (if not arg)
1786 * modify attname in attribute tuple
1787 * insert modified attribute in attribute catalog
1788 * delete original attribute from attribute catalog
1791 renameatt(Oid myrelid,
1792 const char *oldattname,
1793 const char *newattname,
1797 Relation targetrelation;
1798 Relation attrelation;
1800 Form_pg_attribute attform;
1803 ListCell *indexoidscan;
1806 * Grab an exclusive lock on the target table, which we will NOT release
1807 * until end of transaction.
1809 targetrelation = relation_open(myrelid, AccessExclusiveLock);
1812 * permissions checking. this would normally be done in utility.c, but
1813 * this particular routine is recursive.
1815 * normally, only the owner of a class can change its schema.
1817 if (!pg_class_ownercheck(myrelid, GetUserId()))
1818 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1819 RelationGetRelationName(targetrelation));
1820 if (!allowSystemTableMods && IsSystemRelation(targetrelation))
1822 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1823 errmsg("permission denied: \"%s\" is a system catalog",
1824 RelationGetRelationName(targetrelation))));
1827 * if the 'recurse' flag is set then we are supposed to rename this
1828 * attribute in all classes that inherit from 'relname' (as well as in
1831 * any permissions or problems with duplicate attributes will cause the
1832 * whole transaction to abort, which is what we want -- all or nothing.
1839 /* this routine is actually in the planner */
1840 children = find_all_inheritors(myrelid);
1843 * find_all_inheritors does the recursive search of the inheritance
1844 * hierarchy, so all we have to do is process all of the relids in the
1845 * list that it returns.
1847 foreach(child, children)
1849 Oid childrelid = lfirst_oid(child);
1851 if (childrelid == myrelid)
1853 /* note we need not recurse again */
1854 renameatt(childrelid, oldattname, newattname, false, true);
1860 * If we are told not to recurse, there had better not be any child
1861 * tables; else the rename would put them out of step.
1864 find_inheritance_children(myrelid) != NIL)
1866 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1867 errmsg("inherited column \"%s\" must be renamed in child tables too",
1871 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
1873 atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
1874 if (!HeapTupleIsValid(atttup))
1876 (errcode(ERRCODE_UNDEFINED_COLUMN),
1877 errmsg("column \"%s\" does not exist",
1879 attform = (Form_pg_attribute) GETSTRUCT(atttup);
1881 attnum = attform->attnum;
1884 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1885 errmsg("cannot rename system column \"%s\"",
1889 * if the attribute is inherited, forbid the renaming, unless we are
1890 * already inside a recursive rename.
1892 if (attform->attinhcount > 0 && !recursing)
1894 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1895 errmsg("cannot rename inherited column \"%s\"",
1898 /* should not already exist */
1899 /* this test is deliberately not attisdropped-aware */
1900 if (SearchSysCacheExists(ATTNAME,
1901 ObjectIdGetDatum(myrelid),
1902 PointerGetDatum(newattname),
1905 (errcode(ERRCODE_DUPLICATE_COLUMN),
1906 errmsg("column \"%s\" of relation \"%s\" already exists",
1907 newattname, RelationGetRelationName(targetrelation))));
1909 namestrcpy(&(attform->attname), newattname);
1911 simple_heap_update(attrelation, &atttup->t_self, atttup);
1913 /* keep system catalog indexes current */
1914 CatalogUpdateIndexes(attrelation, atttup);
1916 heap_freetuple(atttup);
1919 * Update column names of indexes that refer to the column being renamed.
1921 indexoidlist = RelationGetIndexList(targetrelation);
1923 foreach(indexoidscan, indexoidlist)
1925 Oid indexoid = lfirst_oid(indexoidscan);
1927 Form_pg_index indexform;
1931 * Scan through index columns to see if there's any simple index
1932 * entries for this attribute. We ignore expressional entries.
1934 indextup = SearchSysCache(INDEXRELID,
1935 ObjectIdGetDatum(indexoid),
1937 if (!HeapTupleIsValid(indextup))
1938 elog(ERROR, "cache lookup failed for index %u", indexoid);
1939 indexform = (Form_pg_index) GETSTRUCT(indextup);
1941 for (i = 0; i < indexform->indnatts; i++)
1943 if (attnum != indexform->indkey.values[i])
1947 * Found one, rename it.
1949 atttup = SearchSysCacheCopy(ATTNUM,
1950 ObjectIdGetDatum(indexoid),
1951 Int16GetDatum(i + 1),
1953 if (!HeapTupleIsValid(atttup))
1954 continue; /* should we raise an error? */
1957 * Update the (copied) attribute tuple.
1959 namestrcpy(&(((Form_pg_attribute) GETSTRUCT(atttup))->attname),
1962 simple_heap_update(attrelation, &atttup->t_self, atttup);
1964 /* keep system catalog indexes current */
1965 CatalogUpdateIndexes(attrelation, atttup);
1967 heap_freetuple(atttup);
1970 ReleaseSysCache(indextup);
1973 list_free(indexoidlist);
1975 heap_close(attrelation, RowExclusiveLock);
1977 relation_close(targetrelation, NoLock); /* close rel but keep lock */
1982 * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW RENAME
1984 * Caller has already done permissions checks.
1987 RenameRelation(Oid myrelid, const char *newrelname, ObjectType reltype)
1989 Relation targetrelation;
1994 * Grab an exclusive lock on the target table, index, sequence or view,
1995 * which we will NOT release until end of transaction.
1997 targetrelation = relation_open(myrelid, AccessExclusiveLock);
1999 namespaceId = RelationGetNamespace(targetrelation);
2000 relkind = targetrelation->rd_rel->relkind;
2003 * For compatibility with prior releases, we don't complain if ALTER TABLE
2004 * or ALTER INDEX is used to rename a sequence or view.
2006 if (reltype == OBJECT_SEQUENCE && relkind != RELKIND_SEQUENCE)
2008 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2009 errmsg("\"%s\" is not a sequence",
2010 RelationGetRelationName(targetrelation))));
2012 if (reltype == OBJECT_VIEW && relkind != RELKIND_VIEW)
2014 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2015 errmsg("\"%s\" is not a view",
2016 RelationGetRelationName(targetrelation))));
2019 * Don't allow ALTER TABLE on composite types.
2020 * We want people to use ALTER TYPE for that.
2022 if (relkind == RELKIND_COMPOSITE_TYPE)
2024 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2025 errmsg("\"%s\" is a composite type",
2026 RelationGetRelationName(targetrelation)),
2027 errhint("Use ALTER TYPE instead.")));
2030 RenameRelationInternal(myrelid, newrelname, namespaceId);
2033 * Close rel, but keep exclusive lock!
2035 relation_close(targetrelation, NoLock);
2039 * RenameRelationInternal - change the name of a relation
2041 * XXX - When renaming sequences, we don't bother to modify the
2042 * sequence name that is stored within the sequence itself
2043 * (this would cause problems with MVCC). In the future,
2044 * the sequence name should probably be removed from the
2045 * sequence, AFAIK there's no need for it to be there.
2048 RenameRelationInternal(Oid myrelid, const char *newrelname, Oid namespaceId)
2050 Relation targetrelation;
2051 Relation relrelation; /* for RELATION relation */
2053 Form_pg_class relform;
2056 * Grab an exclusive lock on the target table, index, sequence or
2057 * view, which we will NOT release until end of transaction.
2059 targetrelation = relation_open(myrelid, AccessExclusiveLock);
2062 * Find relation's pg_class tuple, and make sure newrelname isn't in use.
2064 relrelation = heap_open(RelationRelationId, RowExclusiveLock);
2066 reltup = SearchSysCacheCopy(RELOID,
2067 ObjectIdGetDatum(myrelid),
2069 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
2070 elog(ERROR, "cache lookup failed for relation %u", myrelid);
2071 relform = (Form_pg_class) GETSTRUCT(reltup);
2073 if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
2075 (errcode(ERRCODE_DUPLICATE_TABLE),
2076 errmsg("relation \"%s\" already exists",
2080 * Update pg_class tuple with new relname. (Scribbling on reltup is OK
2081 * because it's a copy...)
2083 namestrcpy(&(relform->relname), newrelname);
2085 simple_heap_update(relrelation, &reltup->t_self, reltup);
2087 /* keep the system catalog indexes current */
2088 CatalogUpdateIndexes(relrelation, reltup);
2090 heap_freetuple(reltup);
2091 heap_close(relrelation, RowExclusiveLock);
2094 * Also rename the associated type, if any.
2096 if (OidIsValid(targetrelation->rd_rel->reltype))
2097 RenameTypeInternal(targetrelation->rd_rel->reltype,
2098 newrelname, namespaceId);
2101 * Also rename the associated constraint, if any.
2103 if (targetrelation->rd_rel->relkind == RELKIND_INDEX)
2105 Oid constraintId = get_index_constraint(myrelid);
2107 if (OidIsValid(constraintId))
2108 RenameConstraintById(constraintId, newrelname);
2112 * Close rel, but keep exclusive lock!
2114 relation_close(targetrelation, NoLock);
2118 * Disallow ALTER TABLE (and similar commands) when the current backend has
2119 * any open reference to the target table besides the one just acquired by
2120 * the calling command; this implies there's an open cursor or active plan.
2121 * We need this check because our AccessExclusiveLock doesn't protect us
2122 * against stomping on our own foot, only other people's feet!
2124 * For ALTER TABLE, the only case known to cause serious trouble is ALTER
2125 * COLUMN TYPE, and some changes are obviously pretty benign, so this could
2126 * possibly be relaxed to only error out for certain types of alterations.
2127 * But the use-case for allowing any of these things is not obvious, so we
2128 * won't work hard at it for now.
2130 * We also reject these commands if there are any pending AFTER trigger events
2131 * for the rel. This is certainly necessary for the rewriting variants of
2132 * ALTER TABLE, because they don't preserve tuple TIDs and so the pending
2133 * events would try to fetch the wrong tuples. It might be overly cautious
2134 * in other cases, but again it seems better to err on the side of paranoia.
2136 * REINDEX calls this with "rel" referencing the index to be rebuilt; here
2137 * we are worried about active indexscans on the index. The trigger-event
2138 * check can be skipped, since we are doing no damage to the parent table.
2140 * The statement name (eg, "ALTER TABLE") is passed for use in error messages.
2143 CheckTableNotInUse(Relation rel, const char *stmt)
2145 int expected_refcnt;
2147 expected_refcnt = rel->rd_isnailed ? 2 : 1;
2148 if (rel->rd_refcnt != expected_refcnt)
2150 (errcode(ERRCODE_OBJECT_IN_USE),
2151 /* translator: first %s is a SQL command, eg ALTER TABLE */
2152 errmsg("cannot %s \"%s\" because "
2153 "it is being used by active queries in this session",
2154 stmt, RelationGetRelationName(rel))));
2156 if (rel->rd_rel->relkind != RELKIND_INDEX &&
2157 AfterTriggerPendingOnRel(RelationGetRelid(rel)))
2159 (errcode(ERRCODE_OBJECT_IN_USE),
2160 /* translator: first %s is a SQL command, eg ALTER TABLE */
2161 errmsg("cannot %s \"%s\" because "
2162 "it has pending trigger events",
2163 stmt, RelationGetRelationName(rel))));
2168 * Execute ALTER TABLE, which can be a list of subcommands
2170 * ALTER TABLE is performed in three phases:
2171 * 1. Examine subcommands and perform pre-transformation checking.
2172 * 2. Update system catalogs.
2173 * 3. Scan table(s) to check new constraints, and optionally recopy
2174 * the data into new table(s).
2175 * Phase 3 is not performed unless one or more of the subcommands requires
2176 * it. The intention of this design is to allow multiple independent
2177 * updates of the table schema to be performed with only one pass over the
2180 * ATPrepCmd performs phase 1. A "work queue" entry is created for
2181 * each table to be affected (there may be multiple affected tables if the
2182 * commands traverse a table inheritance hierarchy). Also we do preliminary
2183 * validation of the subcommands, including parse transformation of those
2184 * expressions that need to be evaluated with respect to the old table
2187 * ATRewriteCatalogs performs phase 2 for each affected table. (Note that
2188 * phases 2 and 3 normally do no explicit recursion, since phase 1 already
2189 * did it --- although some subcommands have to recurse in phase 2 instead.)
2190 * Certain subcommands need to be performed before others to avoid
2191 * unnecessary conflicts; for example, DROP COLUMN should come before
2192 * ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
2193 * lists, one for each logical "pass" of phase 2.
2195 * ATRewriteTables performs phase 3 for those tables that need it.
2197 * Thanks to the magic of MVCC, an error anywhere along the way rolls back
2198 * the whole operation; we don't have to do anything special to clean up.
2201 AlterTable(AlterTableStmt *stmt)
2203 Relation rel = relation_openrv(stmt->relation, AccessExclusiveLock);
2205 CheckTableNotInUse(rel, "ALTER TABLE");
2207 /* Check relation type against type specified in the ALTER command */
2208 switch (stmt->relkind)
2212 * For mostly-historical reasons, we allow ALTER TABLE to apply
2213 * to all relation types.
2218 if (rel->rd_rel->relkind != RELKIND_INDEX)
2220 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2221 errmsg("\"%s\" is not an index",
2222 RelationGetRelationName(rel))));
2225 case OBJECT_SEQUENCE:
2226 if (rel->rd_rel->relkind != RELKIND_SEQUENCE)
2228 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2229 errmsg("\"%s\" is not a sequence",
2230 RelationGetRelationName(rel))));
2234 if (rel->rd_rel->relkind != RELKIND_VIEW)
2236 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2237 errmsg("\"%s\" is not a view",
2238 RelationGetRelationName(rel))));
2242 elog(ERROR, "unrecognized object type: %d", (int) stmt->relkind);
2245 ATController(rel, stmt->cmds, interpretInhOption(stmt->relation->inhOpt));
2249 * AlterTableInternal
2251 * ALTER TABLE with target specified by OID
2253 * We do not reject if the relation is already open, because it's quite
2254 * likely that one or more layers of caller have it open. That means it
2255 * is unsafe to use this entry point for alterations that could break
2256 * existing query plans. On the assumption it's not used for such, we
2257 * don't have to reject pending AFTER triggers, either.
2260 AlterTableInternal(Oid relid, List *cmds, bool recurse)
2262 Relation rel = relation_open(relid, AccessExclusiveLock);
2264 ATController(rel, cmds, recurse);
2268 ATController(Relation rel, List *cmds, bool recurse)
2273 /* Phase 1: preliminary examination of commands, create work queue */
2276 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2278 ATPrepCmd(&wqueue, rel, cmd, recurse, false);
2281 /* Close the relation, but keep lock until commit */
2282 relation_close(rel, NoLock);
2284 /* Phase 2: update system catalogs */
2285 ATRewriteCatalogs(&wqueue);
2287 /* Phase 3: scan/rewrite tables as needed */
2288 ATRewriteTables(&wqueue);
2294 * Traffic cop for ALTER TABLE Phase 1 operations, including simple
2295 * recursion and permission checks.
2297 * Caller must have acquired AccessExclusiveLock on relation already.
2298 * This lock should be held until commit.
2301 ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
2302 bool recurse, bool recursing)
2304 AlteredTableInfo *tab;
2307 /* Find or create work queue entry for this table */
2308 tab = ATGetQueueEntry(wqueue, rel);
2311 * Copy the original subcommand for each table. This avoids conflicts
2312 * when different child tables need to make different parse
2313 * transformations (for example, the same column may have different column
2314 * numbers in different children).
2316 cmd = copyObject(cmd);
2319 * Do permissions checking, recursion to child tables if needed, and any
2320 * additional phase-1 processing needed.
2322 switch (cmd->subtype)
2324 case AT_AddColumn: /* ADD COLUMN */
2325 ATSimplePermissions(rel, false);
2326 /* Performs own recursion */
2327 ATPrepAddColumn(wqueue, rel, recurse, cmd);
2328 pass = AT_PASS_ADD_COL;
2330 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
2333 * We allow defaults on views so that INSERT into a view can have
2334 * default-ish behavior. This works because the rewriter
2335 * substitutes default values into INSERTs before it expands
2338 ATSimplePermissions(rel, true);
2339 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2340 /* No command-specific prep needed */
2341 pass = cmd->def ? AT_PASS_ADD_CONSTR : AT_PASS_DROP;
2343 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
2344 ATSimplePermissions(rel, false);
2345 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2346 /* No command-specific prep needed */
2347 pass = AT_PASS_DROP;
2349 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
2350 ATSimplePermissions(rel, false);
2351 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2352 /* No command-specific prep needed */
2353 pass = AT_PASS_ADD_CONSTR;
2355 case AT_SetStatistics: /* ALTER COLUMN STATISTICS */
2356 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2357 /* Performs own permission checks */
2358 ATPrepSetStatistics(rel, cmd->name, cmd->def);
2359 pass = AT_PASS_COL_ATTRS;
2361 case AT_SetStorage: /* ALTER COLUMN STORAGE */
2362 ATSimplePermissions(rel, false);
2363 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2364 /* No command-specific prep needed */
2365 pass = AT_PASS_COL_ATTRS;
2367 case AT_DropColumn: /* DROP COLUMN */
2368 ATSimplePermissions(rel, false);
2369 /* Recursion occurs during execution phase */
2370 /* No command-specific prep needed except saving recurse flag */
2372 cmd->subtype = AT_DropColumnRecurse;
2373 pass = AT_PASS_DROP;
2375 case AT_AddIndex: /* ADD INDEX */
2376 ATSimplePermissions(rel, false);
2377 /* This command never recurses */
2378 /* No command-specific prep needed */
2379 pass = AT_PASS_ADD_INDEX;
2381 case AT_AddConstraint: /* ADD CONSTRAINT */
2382 ATSimplePermissions(rel, false);
2383 /* Recursion occurs during execution phase */
2384 /* No command-specific prep needed except saving recurse flag */
2386 cmd->subtype = AT_AddConstraintRecurse;
2387 pass = AT_PASS_ADD_CONSTR;
2389 case AT_DropConstraint: /* DROP CONSTRAINT */
2390 ATSimplePermissions(rel, false);
2391 /* Recursion occurs during execution phase */
2392 /* No command-specific prep needed except saving recurse flag */
2394 cmd->subtype = AT_DropConstraintRecurse;
2395 pass = AT_PASS_DROP;
2397 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
2398 ATSimplePermissions(rel, false);
2399 /* Performs own recursion */
2400 ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd);
2401 pass = AT_PASS_ALTER_TYPE;
2403 case AT_ChangeOwner: /* ALTER OWNER */
2404 /* This command never recurses */
2405 /* No command-specific prep needed */
2406 pass = AT_PASS_MISC;
2408 case AT_ClusterOn: /* CLUSTER ON */
2409 case AT_DropCluster: /* SET WITHOUT CLUSTER */
2410 ATSimplePermissions(rel, false);
2411 /* These commands never recurse */
2412 /* No command-specific prep needed */
2413 pass = AT_PASS_MISC;
2415 case AT_DropOids: /* SET WITHOUT OIDS */
2416 ATSimplePermissions(rel, false);
2417 /* Performs own recursion */
2418 if (rel->rd_rel->relhasoids)
2420 AlterTableCmd *dropCmd = makeNode(AlterTableCmd);
2422 dropCmd->subtype = AT_DropColumn;
2423 dropCmd->name = pstrdup("oid");
2424 dropCmd->behavior = cmd->behavior;
2425 ATPrepCmd(wqueue, rel, dropCmd, recurse, false);
2427 pass = AT_PASS_DROP;
2429 case AT_SetTableSpace: /* SET TABLESPACE */
2430 ATSimplePermissionsRelationOrIndex(rel);
2431 /* This command never recurses */
2432 ATPrepSetTableSpace(tab, rel, cmd->name);
2433 pass = AT_PASS_MISC; /* doesn't actually matter */
2435 case AT_SetRelOptions: /* SET (...) */
2436 case AT_ResetRelOptions: /* RESET (...) */
2437 ATSimplePermissionsRelationOrIndex(rel);
2438 /* This command never recurses */
2439 /* No command-specific prep needed */
2440 pass = AT_PASS_MISC;
2442 case AT_EnableTrig: /* ENABLE TRIGGER variants */
2443 case AT_EnableAlwaysTrig:
2444 case AT_EnableReplicaTrig:
2445 case AT_EnableTrigAll:
2446 case AT_EnableTrigUser:
2447 case AT_DisableTrig: /* DISABLE TRIGGER variants */
2448 case AT_DisableTrigAll:
2449 case AT_DisableTrigUser:
2450 case AT_EnableRule: /* ENABLE/DISABLE RULE variants */
2451 case AT_EnableAlwaysRule:
2452 case AT_EnableReplicaRule:
2453 case AT_DisableRule:
2454 case AT_AddInherit: /* INHERIT / NO INHERIT */
2455 case AT_DropInherit:
2456 ATSimplePermissions(rel, false);
2457 /* These commands never recurse */
2458 /* No command-specific prep needed */
2459 pass = AT_PASS_MISC;
2462 elog(ERROR, "unrecognized alter table type: %d",
2463 (int) cmd->subtype);
2464 pass = 0; /* keep compiler quiet */
2468 /* Add the subcommand to the appropriate list for phase 2 */
2469 tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
2475 * Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
2476 * dispatched in a "safe" execution order (designed to avoid unnecessary
2480 ATRewriteCatalogs(List **wqueue)
2486 * We process all the tables "in parallel", one pass at a time. This is
2487 * needed because we may have to propagate work from one table to another
2488 * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
2489 * re-adding of the foreign key constraint to the other table). Work can
2490 * only be propagated into later passes, however.
2492 for (pass = 0; pass < AT_NUM_PASSES; pass++)
2494 /* Go through each table that needs to be processed */
2495 foreach(ltab, *wqueue)
2497 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2498 List *subcmds = tab->subcmds[pass];
2506 * Exclusive lock was obtained by phase 1, needn't get it again
2508 rel = relation_open(tab->relid, NoLock);
2510 foreach(lcmd, subcmds)
2511 ATExecCmd(wqueue, tab, rel, (AlterTableCmd *) lfirst(lcmd));
2514 * After the ALTER TYPE pass, do cleanup work (this is not done in
2515 * ATExecAlterColumnType since it should be done only once if
2516 * multiple columns of a table are altered).
2518 if (pass == AT_PASS_ALTER_TYPE)
2519 ATPostAlterTypeCleanup(wqueue, tab);
2521 relation_close(rel, NoLock);
2526 * Check to see if a toast table must be added, if we executed any
2527 * subcommands that might have added a column or changed column storage.
2529 foreach(ltab, *wqueue)
2531 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2533 if (tab->relkind == RELKIND_RELATION &&
2534 (tab->subcmds[AT_PASS_ADD_COL] ||
2535 tab->subcmds[AT_PASS_ALTER_TYPE] ||
2536 tab->subcmds[AT_PASS_COL_ATTRS]))
2537 AlterTableCreateToastTable(tab->relid);
2542 * ATExecCmd: dispatch a subcommand to appropriate execution routine
2545 ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
2548 switch (cmd->subtype)
2550 case AT_AddColumn: /* ADD COLUMN */
2551 ATExecAddColumn(tab, rel, (ColumnDef *) cmd->def);
2553 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
2554 ATExecColumnDefault(rel, cmd->name, cmd->def);
2556 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
2557 ATExecDropNotNull(rel, cmd->name);
2559 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
2560 ATExecSetNotNull(tab, rel, cmd->name);
2562 case AT_SetStatistics: /* ALTER COLUMN STATISTICS */
2563 ATExecSetStatistics(rel, cmd->name, cmd->def);
2565 case AT_SetStorage: /* ALTER COLUMN STORAGE */
2566 ATExecSetStorage(rel, cmd->name, cmd->def);
2568 case AT_DropColumn: /* DROP COLUMN */
2569 ATExecDropColumn(rel, cmd->name, cmd->behavior, false, false);
2571 case AT_DropColumnRecurse: /* DROP COLUMN with recursion */
2572 ATExecDropColumn(rel, cmd->name, cmd->behavior, true, false);
2574 case AT_AddIndex: /* ADD INDEX */
2575 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false);
2577 case AT_ReAddIndex: /* ADD INDEX */
2578 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true);
2580 case AT_AddConstraint: /* ADD CONSTRAINT */
2581 ATExecAddConstraint(wqueue, tab, rel, cmd->def, false);
2583 case AT_AddConstraintRecurse: /* ADD CONSTRAINT with recursion */
2584 ATExecAddConstraint(wqueue, tab, rel, cmd->def, true);
2586 case AT_DropConstraint: /* DROP CONSTRAINT */
2587 ATExecDropConstraint(rel, cmd->name, cmd->behavior, false, false);
2589 case AT_DropConstraintRecurse: /* DROP CONSTRAINT with recursion */
2590 ATExecDropConstraint(rel, cmd->name, cmd->behavior, true, false);
2592 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
2593 ATExecAlterColumnType(tab, rel, cmd->name, (TypeName *) cmd->def);
2595 case AT_ChangeOwner: /* ALTER OWNER */
2596 ATExecChangeOwner(RelationGetRelid(rel),
2597 get_roleid_checked(cmd->name),
2600 case AT_ClusterOn: /* CLUSTER ON */
2601 ATExecClusterOn(rel, cmd->name);
2603 case AT_DropCluster: /* SET WITHOUT CLUSTER */
2604 ATExecDropCluster(rel);
2606 case AT_DropOids: /* SET WITHOUT OIDS */
2609 * Nothing to do here; we'll have generated a DropColumn
2610 * subcommand to do the real work
2613 case AT_SetTableSpace: /* SET TABLESPACE */
2616 * Nothing to do here; Phase 3 does the work
2619 case AT_SetRelOptions: /* SET (...) */
2620 ATExecSetRelOptions(rel, (List *) cmd->def, false);
2622 case AT_ResetRelOptions: /* RESET (...) */
2623 ATExecSetRelOptions(rel, (List *) cmd->def, true);
2626 case AT_EnableTrig: /* ENABLE TRIGGER name */
2627 ATExecEnableDisableTrigger(rel, cmd->name,
2628 TRIGGER_FIRES_ON_ORIGIN, false);
2630 case AT_EnableAlwaysTrig: /* ENABLE ALWAYS TRIGGER name */
2631 ATExecEnableDisableTrigger(rel, cmd->name,
2632 TRIGGER_FIRES_ALWAYS, false);
2634 case AT_EnableReplicaTrig: /* ENABLE REPLICA TRIGGER name */
2635 ATExecEnableDisableTrigger(rel, cmd->name,
2636 TRIGGER_FIRES_ON_REPLICA, false);
2638 case AT_DisableTrig: /* DISABLE TRIGGER name */
2639 ATExecEnableDisableTrigger(rel, cmd->name,
2640 TRIGGER_DISABLED, false);
2642 case AT_EnableTrigAll: /* ENABLE TRIGGER ALL */
2643 ATExecEnableDisableTrigger(rel, NULL,
2644 TRIGGER_FIRES_ON_ORIGIN, false);
2646 case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
2647 ATExecEnableDisableTrigger(rel, NULL,
2648 TRIGGER_DISABLED, false);
2650 case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
2651 ATExecEnableDisableTrigger(rel, NULL,
2652 TRIGGER_FIRES_ON_ORIGIN, true);
2654 case AT_DisableTrigUser: /* DISABLE TRIGGER USER */
2655 ATExecEnableDisableTrigger(rel, NULL,
2656 TRIGGER_DISABLED, true);
2659 case AT_EnableRule: /* ENABLE RULE name */
2660 ATExecEnableDisableRule(rel, cmd->name,
2661 RULE_FIRES_ON_ORIGIN);
2663 case AT_EnableAlwaysRule: /* ENABLE ALWAYS RULE name */
2664 ATExecEnableDisableRule(rel, cmd->name,
2667 case AT_EnableReplicaRule: /* ENABLE REPLICA RULE name */
2668 ATExecEnableDisableRule(rel, cmd->name,
2669 RULE_FIRES_ON_REPLICA);
2671 case AT_DisableRule: /* DISABLE RULE name */
2672 ATExecEnableDisableRule(rel, cmd->name,
2677 ATExecAddInherit(rel, (RangeVar *) cmd->def);
2679 case AT_DropInherit:
2680 ATExecDropInherit(rel, (RangeVar *) cmd->def);
2683 elog(ERROR, "unrecognized alter table type: %d",
2684 (int) cmd->subtype);
2689 * Bump the command counter to ensure the next subcommand in the sequence
2690 * can see the changes so far
2692 CommandCounterIncrement();
2696 * ATRewriteTables: ALTER TABLE phase 3
2699 ATRewriteTables(List **wqueue)
2703 /* Go through each table that needs to be checked or rewritten */
2704 foreach(ltab, *wqueue)
2706 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2709 * We only need to rewrite the table if at least one column needs to
2712 if (tab->newvals != NIL)
2714 /* Build a temporary relation and copy data */
2716 char NewHeapName[NAMEDATALEN];
2719 ObjectAddress object;
2721 OldHeap = heap_open(tab->relid, NoLock);
2724 * We can never allow rewriting of shared or nailed-in-cache
2725 * relations, because we can't support changing their relfilenode
2728 if (OldHeap->rd_rel->relisshared || OldHeap->rd_isnailed)
2730 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2731 errmsg("cannot rewrite system relation \"%s\"",
2732 RelationGetRelationName(OldHeap))));
2735 * Don't allow rewrite on temp tables of other backends ... their
2736 * local buffer manager is not going to cope.
2738 if (isOtherTempNamespace(RelationGetNamespace(OldHeap)))
2740 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2741 errmsg("cannot rewrite temporary tables of other sessions")));
2744 * Select destination tablespace (same as original unless user
2745 * requested a change)
2747 if (tab->newTableSpace)
2748 NewTableSpace = tab->newTableSpace;
2750 NewTableSpace = OldHeap->rd_rel->reltablespace;
2752 heap_close(OldHeap, NoLock);
2755 * Create the new heap, using a temporary name in the same
2756 * namespace as the existing table. NOTE: there is some risk of
2757 * collision with user relnames. Working around this seems more
2758 * trouble than it's worth; in particular, we can't create the new
2759 * heap in a different namespace from the old, or we will have
2760 * problems with the TEMP status of temp tables.
2762 snprintf(NewHeapName, sizeof(NewHeapName),
2763 "pg_temp_%u", tab->relid);
2765 OIDNewHeap = make_new_heap(tab->relid, NewHeapName, NewTableSpace);
2768 * Copy the heap data into the new table with the desired
2769 * modifications, and test the current data within the table
2770 * against new constraints generated by ALTER TABLE commands.
2772 ATRewriteTable(tab, OIDNewHeap);
2775 * Swap the physical files of the old and new heaps. Since we are
2776 * generating a new heap, we can use RecentXmin for the table's
2777 * new relfrozenxid because we rewrote all the tuples on
2778 * ATRewriteTable, so no older Xid remains on the table.
2780 swap_relation_files(tab->relid, OIDNewHeap, RecentXmin);
2782 CommandCounterIncrement();
2784 /* Destroy new heap with old filenode */
2785 object.classId = RelationRelationId;
2786 object.objectId = OIDNewHeap;
2787 object.objectSubId = 0;
2790 * The new relation is local to our transaction and we know
2791 * nothing depends on it, so DROP_RESTRICT should be OK.
2793 performDeletion(&object, DROP_RESTRICT);
2794 /* performDeletion does CommandCounterIncrement at end */
2797 * Rebuild each index on the relation (but not the toast table,
2798 * which is all-new anyway). We do not need
2799 * CommandCounterIncrement() because reindex_relation does it.
2801 reindex_relation(tab->relid, false);
2806 * Test the current data within the table against new constraints
2807 * generated by ALTER TABLE commands, but don't rebuild data.
2809 if (tab->constraints != NIL || tab->new_notnull)
2810 ATRewriteTable(tab, InvalidOid);
2813 * If we had SET TABLESPACE but no reason to reconstruct tuples,
2814 * just do a block-by-block copy.
2816 if (tab->newTableSpace)
2817 ATExecSetTableSpace(tab->relid, tab->newTableSpace);
2822 * Foreign key constraints are checked in a final pass, since (a) it's
2823 * generally best to examine each one separately, and (b) it's at least
2824 * theoretically possible that we have changed both relations of the
2825 * foreign key, and we'd better have finished both rewrites before we try
2826 * to read the tables.
2828 foreach(ltab, *wqueue)
2830 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2831 Relation rel = NULL;
2834 foreach(lcon, tab->constraints)
2836 NewConstraint *con = lfirst(lcon);
2838 if (con->contype == CONSTR_FOREIGN)
2840 FkConstraint *fkconstraint = (FkConstraint *) con->qual;
2845 /* Long since locked, no need for another */
2846 rel = heap_open(tab->relid, NoLock);
2849 refrel = heap_open(con->refrelid, RowShareLock);
2851 validateForeignKeyConstraint(fkconstraint, rel, refrel,
2854 heap_close(refrel, NoLock);
2859 heap_close(rel, NoLock);
2864 * ATRewriteTable: scan or rewrite one table
2866 * OIDNewHeap is InvalidOid if we don't need to rewrite
2869 ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap)
2873 TupleDesc oldTupDesc;
2874 TupleDesc newTupDesc;
2875 bool needscan = false;
2876 List *notnull_attrs;
2882 * Open the relation(s). We have surely already locked the existing
2885 oldrel = heap_open(tab->relid, NoLock);
2886 oldTupDesc = tab->oldDesc;
2887 newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
2889 if (OidIsValid(OIDNewHeap))
2890 newrel = heap_open(OIDNewHeap, AccessExclusiveLock);
2895 * If we need to rewrite the table, the operation has to be propagated to
2896 * tables that use this table's rowtype as a column type.
2898 * (Eventually this will probably become true for scans as well, but at
2899 * the moment a composite type does not enforce any constraints, so it's
2900 * not necessary/appropriate to enforce them just during ALTER.)
2903 find_composite_type_dependencies(oldrel->rd_rel->reltype,
2904 RelationGetRelationName(oldrel),
2908 * Generate the constraint and default execution states
2911 estate = CreateExecutorState();
2913 /* Build the needed expression execution states */
2914 foreach(l, tab->constraints)
2916 NewConstraint *con = lfirst(l);
2918 switch (con->contype)
2922 con->qualstate = (List *)
2923 ExecPrepareExpr((Expr *) con->qual, estate);
2925 case CONSTR_FOREIGN:
2926 /* Nothing to do here */
2929 elog(ERROR, "unrecognized constraint type: %d",
2930 (int) con->contype);
2934 foreach(l, tab->newvals)
2936 NewColumnValue *ex = lfirst(l);
2940 ex->exprstate = ExecPrepareExpr((Expr *) ex->expr, estate);
2943 notnull_attrs = NIL;
2944 if (newrel || tab->new_notnull)
2947 * If we are rebuilding the tuples OR if we added any new NOT NULL
2948 * constraints, check all not-null constraints. This is a bit of
2949 * overkill but it minimizes risk of bugs, and heap_attisnull is a
2950 * pretty cheap test anyway.
2952 for (i = 0; i < newTupDesc->natts; i++)
2954 if (newTupDesc->attrs[i]->attnotnull &&
2955 !newTupDesc->attrs[i]->attisdropped)
2956 notnull_attrs = lappend_int(notnull_attrs, i);
2964 ExprContext *econtext;
2967 TupleTableSlot *oldslot;
2968 TupleTableSlot *newslot;
2971 MemoryContext oldCxt;
2972 List *dropped_attrs = NIL;
2975 econtext = GetPerTupleExprContext(estate);
2978 * Make tuple slots for old and new tuples. Note that even when the
2979 * tuples are the same, the tupDescs might not be (consider ADD COLUMN
2980 * without a default).
2982 oldslot = MakeSingleTupleTableSlot(oldTupDesc);
2983 newslot = MakeSingleTupleTableSlot(newTupDesc);
2985 /* Preallocate values/isnull arrays */
2986 i = Max(newTupDesc->natts, oldTupDesc->natts);
2987 values = (Datum *) palloc(i * sizeof(Datum));
2988 isnull = (bool *) palloc(i * sizeof(bool));
2989 memset(values, 0, i * sizeof(Datum));
2990 memset(isnull, true, i * sizeof(bool));
2993 * Any attributes that are dropped according to the new tuple
2994 * descriptor can be set to NULL. We precompute the list of dropped
2995 * attributes to avoid needing to do so in the per-tuple loop.
2997 for (i = 0; i < newTupDesc->natts; i++)
2999 if (newTupDesc->attrs[i]->attisdropped)
3000 dropped_attrs = lappend_int(dropped_attrs, i);
3004 * Scan through the rows, generating a new row if needed and then
3005 * checking all the constraints.
3007 scan = heap_beginscan(oldrel, SnapshotNow, 0, NULL);
3010 * Switch to per-tuple memory context and reset it for each tuple
3011 * produced, so we don't leak memory.
3013 oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
3015 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
3019 Oid tupOid = InvalidOid;
3021 /* Extract data from old tuple */
3022 heap_deform_tuple(tuple, oldTupDesc, values, isnull);
3023 if (oldTupDesc->tdhasoid)
3024 tupOid = HeapTupleGetOid(tuple);
3026 /* Set dropped attributes to null in new tuple */
3027 foreach(lc, dropped_attrs)
3028 isnull[lfirst_int(lc)] = true;
3031 * Process supplied expressions to replace selected columns.
3032 * Expression inputs come from the old tuple.
3034 ExecStoreTuple(tuple, oldslot, InvalidBuffer, false);
3035 econtext->ecxt_scantuple = oldslot;
3037 foreach(l, tab->newvals)
3039 NewColumnValue *ex = lfirst(l);
3041 values[ex->attnum - 1] = ExecEvalExpr(ex->exprstate,
3043 &isnull[ex->attnum - 1],
3048 * Form the new tuple. Note that we don't explicitly pfree it,
3049 * since the per-tuple memory context will be reset shortly.
3051 tuple = heap_form_tuple(newTupDesc, values, isnull);
3053 /* Preserve OID, if any */
3054 if (newTupDesc->tdhasoid)
3055 HeapTupleSetOid(tuple, tupOid);
3058 /* Now check any constraints on the possibly-changed tuple */
3059 ExecStoreTuple(tuple, newslot, InvalidBuffer, false);
3060 econtext->ecxt_scantuple = newslot;
3062 foreach(l, notnull_attrs)
3064 int attn = lfirst_int(l);
3066 if (heap_attisnull(tuple, attn + 1))
3068 (errcode(ERRCODE_NOT_NULL_VIOLATION),
3069 errmsg("column \"%s\" contains null values",
3070 NameStr(newTupDesc->attrs[attn]->attname))));
3073 foreach(l, tab->constraints)
3075 NewConstraint *con = lfirst(l);
3077 switch (con->contype)
3080 if (!ExecQual(con->qualstate, econtext, true))
3082 (errcode(ERRCODE_CHECK_VIOLATION),
3083 errmsg("check constraint \"%s\" is violated by some row",
3086 case CONSTR_FOREIGN:
3087 /* Nothing to do here */
3090 elog(ERROR, "unrecognized constraint type: %d",
3091 (int) con->contype);
3095 /* Write the tuple out to the new relation */
3097 simple_heap_insert(newrel, tuple);
3099 ResetExprContext(econtext);
3101 CHECK_FOR_INTERRUPTS();
3104 MemoryContextSwitchTo(oldCxt);
3107 ExecDropSingleTupleTableSlot(oldslot);
3108 ExecDropSingleTupleTableSlot(newslot);
3111 FreeExecutorState(estate);
3113 heap_close(oldrel, NoLock);
3115 heap_close(newrel, NoLock);
3119 * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
3121 static AlteredTableInfo *
3122 ATGetQueueEntry(List **wqueue, Relation rel)
3124 Oid relid = RelationGetRelid(rel);
3125 AlteredTableInfo *tab;
3128 foreach(ltab, *wqueue)
3130 tab = (AlteredTableInfo *) lfirst(ltab);
3131 if (tab->relid == relid)
3136 * Not there, so add it. Note that we make a copy of the relation's
3137 * existing descriptor before anything interesting can happen to it.
3139 tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
3141 tab->relkind = rel->rd_rel->relkind;
3142 tab->oldDesc = CreateTupleDescCopy(RelationGetDescr(rel));
3144 *wqueue = lappend(*wqueue, tab);
3150 * ATSimplePermissions
3152 * - Ensure that it is a relation (or possibly a view)
3153 * - Ensure this user is the owner
3154 * - Ensure that it is not a system table
3157 ATSimplePermissions(Relation rel, bool allowView)
3159 if (rel->rd_rel->relkind != RELKIND_RELATION)
3163 if (rel->rd_rel->relkind != RELKIND_VIEW)
3165 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3166 errmsg("\"%s\" is not a table or view",
3167 RelationGetRelationName(rel))));
3171 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3172 errmsg("\"%s\" is not a table",
3173 RelationGetRelationName(rel))));
3176 /* Permissions checks */
3177 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3178 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3179 RelationGetRelationName(rel));
3181 if (!allowSystemTableMods && IsSystemRelation(rel))
3183 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3184 errmsg("permission denied: \"%s\" is a system catalog",
3185 RelationGetRelationName(rel))));
3189 * ATSimplePermissionsRelationOrIndex
3191 * - Ensure that it is a relation or an index
3192 * - Ensure this user is the owner
3193 * - Ensure that it is not a system table
3196 ATSimplePermissionsRelationOrIndex(Relation rel)
3198 if (rel->rd_rel->relkind != RELKIND_RELATION &&
3199 rel->rd_rel->relkind != RELKIND_INDEX)
3201 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3202 errmsg("\"%s\" is not a table or index",
3203 RelationGetRelationName(rel))));
3205 /* Permissions checks */
3206 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3207 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3208 RelationGetRelationName(rel));
3210 if (!allowSystemTableMods && IsSystemRelation(rel))
3212 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3213 errmsg("permission denied: \"%s\" is a system catalog",
3214 RelationGetRelationName(rel))));
3220 * Simple table recursion sufficient for most ALTER TABLE operations.
3221 * All direct and indirect children are processed in an unspecified order.
3222 * Note that if a child inherits from the original table via multiple
3223 * inheritance paths, it will be visited just once.
3226 ATSimpleRecursion(List **wqueue, Relation rel,
3227 AlterTableCmd *cmd, bool recurse)
3230 * Propagate to children if desired. Non-table relations never have
3231 * children, so no need to search in that case.
3233 if (recurse && rel->rd_rel->relkind == RELKIND_RELATION)
3235 Oid relid = RelationGetRelid(rel);
3239 /* this routine is actually in the planner */
3240 children = find_all_inheritors(relid);
3243 * find_all_inheritors does the recursive search of the inheritance
3244 * hierarchy, so all we have to do is process all of the relids in the
3245 * list that it returns.
3247 foreach(child, children)
3249 Oid childrelid = lfirst_oid(child);
3252 if (childrelid == relid)
3254 childrel = relation_open(childrelid, AccessExclusiveLock);
3255 CheckTableNotInUse(childrel, "ALTER TABLE");
3256 ATPrepCmd(wqueue, childrel, cmd, false, true);
3257 relation_close(childrel, NoLock);
3263 * ATOneLevelRecursion
3265 * Here, we visit only direct inheritance children. It is expected that
3266 * the command's prep routine will recurse again to find indirect children.
3267 * When using this technique, a multiply-inheriting child will be visited
3271 ATOneLevelRecursion(List **wqueue, Relation rel,
3274 Oid relid = RelationGetRelid(rel);
3278 /* this routine is actually in the planner */
3279 children = find_inheritance_children(relid);
3281 foreach(child, children)
3283 Oid childrelid = lfirst_oid(child);
3286 childrel = relation_open(childrelid, AccessExclusiveLock);
3287 CheckTableNotInUse(childrel, "ALTER TABLE");
3288 ATPrepCmd(wqueue, childrel, cmd, true, true);
3289 relation_close(childrel, NoLock);
3295 * find_composite_type_dependencies
3297 * Check to see if a composite type is being used as a column in some
3298 * other table (possibly nested several levels deep in composite types!).
3299 * Eventually, we'd like to propagate the check or rewrite operation
3300 * into other such tables, but for now, just error out if we find any.
3302 * Caller should provide either a table name or a type name (not both) to
3303 * report in the error message, if any.
3305 * We assume that functions and views depending on the type are not reasons
3306 * to reject the ALTER. (How safe is this really?)
3309 find_composite_type_dependencies(Oid typeOid,
3310 const char *origTblName,
3311 const char *origTypeName)
3315 SysScanDesc depScan;
3320 * We scan pg_depend to find those things that depend on the rowtype. (We
3321 * assume we can ignore refobjsubid for a rowtype.)
3323 depRel = heap_open(DependRelationId, AccessShareLock);
3325 ScanKeyInit(&key[0],
3326 Anum_pg_depend_refclassid,
3327 BTEqualStrategyNumber, F_OIDEQ,
3328 ObjectIdGetDatum(TypeRelationId));
3329 ScanKeyInit(&key[1],
3330 Anum_pg_depend_refobjid,
3331 BTEqualStrategyNumber, F_OIDEQ,
3332 ObjectIdGetDatum(typeOid));
3334 depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
3335 SnapshotNow, 2, key);
3337 while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
3339 Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
3341 Form_pg_attribute att;
3343 /* Ignore dependees that aren't user columns of relations */
3344 /* (we assume system columns are never of rowtypes) */
3345 if (pg_depend->classid != RelationRelationId ||
3346 pg_depend->objsubid <= 0)
3349 rel = relation_open(pg_depend->objid, AccessShareLock);
3350 att = rel->rd_att->attrs[pg_depend->objsubid - 1];
3352 if (rel->rd_rel->relkind == RELKIND_RELATION)
3356 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3357 errmsg("cannot alter table \"%s\" because column \"%s\".\"%s\" uses its rowtype",
3359 RelationGetRelationName(rel),
3360 NameStr(att->attname))));
3363 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3364 errmsg("cannot alter type \"%s\" because column \"%s\".\"%s\" uses it",
3366 RelationGetRelationName(rel),
3367 NameStr(att->attname))));
3369 else if (OidIsValid(rel->rd_rel->reltype))
3372 * A view or composite type itself isn't a problem, but we must
3373 * recursively check for indirect dependencies via its rowtype.
3375 find_composite_type_dependencies(rel->rd_rel->reltype,
3376 origTblName, origTypeName);
3379 relation_close(rel, AccessShareLock);
3382 systable_endscan(depScan);
3384 relation_close(depRel, AccessShareLock);
3387 * If there's an array type for the rowtype, must check for uses of it,
3390 arrayOid = get_array_type(typeOid);
3391 if (OidIsValid(arrayOid))
3392 find_composite_type_dependencies(arrayOid, origTblName, origTypeName);
3397 * ALTER TABLE ADD COLUMN
3399 * Adds an additional attribute to a relation making the assumption that
3400 * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
3401 * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
3405 ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
3409 * Recurse to add the column to child classes, if requested.
3411 * We must recurse one level at a time, so that multiply-inheriting
3412 * children are visited the right number of times and end up with the
3413 * right attinhcount.
3417 AlterTableCmd *childCmd = copyObject(cmd);
3418 ColumnDef *colDefChild = (ColumnDef *) childCmd->def;
3420 /* Child should see column as singly inherited */
3421 colDefChild->inhcount = 1;
3422 colDefChild->is_local = false;
3424 ATOneLevelRecursion(wqueue, rel, childCmd);
3429 * If we are told not to recurse, there had better not be any child
3430 * tables; else the addition would put them out of step.
3432 if (find_inheritance_children(RelationGetRelid(rel)) != NIL)
3434 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3435 errmsg("column must be added to child tables too")));
3440 ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
3443 Oid myrelid = RelationGetRelid(rel);
3447 HeapTuple attributeTuple;
3448 Form_pg_attribute attribute;
3449 FormData_pg_attribute attributeD;
3453 HeapTuple typeTuple;
3459 attrdesc = heap_open(AttributeRelationId, RowExclusiveLock);
3462 * Are we adding the column to a recursion child? If so, check whether to
3463 * merge with an existing definition for the column.
3465 if (colDef->inhcount > 0)
3469 /* Does child already have a column by this name? */
3470 tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
3471 if (HeapTupleIsValid(tuple))
3473 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
3477 /* Okay if child matches by type */
3478 ctypeId = typenameTypeId(NULL, colDef->typename, &ctypmod);
3479 if (ctypeId != childatt->atttypid ||
3480 ctypmod != childatt->atttypmod)
3482 (errcode(ERRCODE_DATATYPE_MISMATCH),
3483 errmsg("child table \"%s\" has different type for column \"%s\"",
3484 RelationGetRelationName(rel), colDef->colname)));
3486 /* Bump the existing child att's inhcount */
3487 childatt->attinhcount++;
3488 simple_heap_update(attrdesc, &tuple->t_self, tuple);
3489 CatalogUpdateIndexes(attrdesc, tuple);
3491 heap_freetuple(tuple);
3493 /* Inform the user about the merge */
3495 (errmsg("merging definition of column \"%s\" for child \"%s\"",
3496 colDef->colname, RelationGetRelationName(rel))));
3498 heap_close(attrdesc, RowExclusiveLock);
3503 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
3505 reltup = SearchSysCacheCopy(RELOID,
3506 ObjectIdGetDatum(myrelid),
3508 if (!HeapTupleIsValid(reltup))
3509 elog(ERROR, "cache lookup failed for relation %u", myrelid);
3512 * this test is deliberately not attisdropped-aware, since if one tries to
3513 * add a column matching a dropped column name, it's gonna fail anyway.
3515 if (SearchSysCacheExists(ATTNAME,
3516 ObjectIdGetDatum(myrelid),
3517 PointerGetDatum(colDef->colname),
3520 (errcode(ERRCODE_DUPLICATE_COLUMN),
3521 errmsg("column \"%s\" of relation \"%s\" already exists",
3522 colDef->colname, RelationGetRelationName(rel))));
3524 minattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts;
3525 maxatts = minattnum + 1;
3526 if (maxatts > MaxHeapAttributeNumber)
3528 (errcode(ERRCODE_TOO_MANY_COLUMNS),
3529 errmsg("tables can have at most %d columns",
3530 MaxHeapAttributeNumber)));
3533 typeTuple = typenameType(NULL, colDef->typename, &typmod);
3534 tform = (Form_pg_type) GETSTRUCT(typeTuple);
3535 typeOid = HeapTupleGetOid(typeTuple);
3537 /* make sure datatype is legal for a column */
3538 CheckAttributeType(colDef->colname, typeOid);
3540 attributeTuple = heap_addheader(Natts_pg_attribute,
3542 ATTRIBUTE_TUPLE_SIZE,
3543 (void *) &attributeD);
3545 attribute = (Form_pg_attribute) GETSTRUCT(attributeTuple);
3547 attribute->attrelid = myrelid;
3548 namestrcpy(&(attribute->attname), colDef->colname);
3549 attribute->atttypid = typeOid;
3550 attribute->attstattarget = -1;
3551 attribute->attlen = tform->typlen;
3552 attribute->attcacheoff = -1;
3553 attribute->atttypmod = typmod;
3554 attribute->attnum = i;
3555 attribute->attbyval = tform->typbyval;
3556 attribute->attndims = list_length(colDef->typename->arrayBounds);
3557 attribute->attstorage = tform->typstorage;
3558 attribute->attalign = tform->typalign;
3559 attribute->attnotnull = colDef->is_not_null;
3560 attribute->atthasdef = false;
3561 attribute->attisdropped = false;
3562 attribute->attislocal = colDef->is_local;
3563 attribute->attinhcount = colDef->inhcount;
3565 ReleaseSysCache(typeTuple);
3567 simple_heap_insert(attrdesc, attributeTuple);
3569 /* Update indexes on pg_attribute */
3570 CatalogUpdateIndexes(attrdesc, attributeTuple);
3572 heap_close(attrdesc, RowExclusiveLock);
3575 * Update number of attributes in pg_class tuple
3577 ((Form_pg_class) GETSTRUCT(reltup))->relnatts = maxatts;
3579 simple_heap_update(pgclass, &reltup->t_self, reltup);
3581 /* keep catalog indexes current */
3582 CatalogUpdateIndexes(pgclass, reltup);
3584 heap_freetuple(reltup);
3586 heap_close(pgclass, RowExclusiveLock);
3588 /* Make the attribute's catalog entry visible */
3589 CommandCounterIncrement();
3592 * Store the DEFAULT, if any, in the catalogs
3594 if (colDef->raw_default)
3596 RawColumnDefault *rawEnt;
3598 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3599 rawEnt->attnum = attribute->attnum;
3600 rawEnt->raw_default = copyObject(colDef->raw_default);
3603 * This function is intended for CREATE TABLE, so it processes a
3604 * _list_ of defaults, but we just do one.
3606 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL, false, true);
3608 /* Make the additional catalog changes visible */
3609 CommandCounterIncrement();
3613 * Tell Phase 3 to fill in the default expression, if there is one.
3615 * If there is no default, Phase 3 doesn't have to do anything, because
3616 * that effectively means that the default is NULL. The heap tuple access
3617 * routines always check for attnum > # of attributes in tuple, and return
3618 * NULL if so, so without any modification of the tuple data we will get
3619 * the effect of NULL values in the new column.
3621 * An exception occurs when the new column is of a domain type: the domain
3622 * might have a NOT NULL constraint, or a check constraint that indirectly
3623 * rejects nulls. If there are any domain constraints then we construct
3624 * an explicit NULL default value that will be passed through
3625 * CoerceToDomain processing. (This is a tad inefficient, since it causes
3626 * rewriting the table which we really don't have to do, but the present
3627 * design of domain processing doesn't offer any simple way of checking
3628 * the constraints more directly.)
3630 * Note: we use build_column_default, and not just the cooked default
3631 * returned by AddRelationNewConstraints, so that the right thing happens
3632 * when a datatype's default applies.
3634 defval = (Expr *) build_column_default(rel, attribute->attnum);
3636 if (!defval && GetDomainConstraints(typeOid) != NIL)
3641 baseTypeMod = typmod;
3642 baseTypeId = getBaseTypeAndTypmod(typeOid, &baseTypeMod);
3643 defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod);
3644 defval = (Expr *) coerce_to_target_type(NULL,
3649 COERCION_ASSIGNMENT,
3650 COERCE_IMPLICIT_CAST);
3651 if (defval == NULL) /* should not happen */
3652 elog(ERROR, "failed to coerce base type to domain");
3657 NewColumnValue *newval;
3659 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
3660 newval->attnum = attribute->attnum;
3661 newval->expr = defval;
3663 tab->newvals = lappend(tab->newvals, newval);
3667 * If the new column is NOT NULL, tell Phase 3 it needs to test that.
3669 tab->new_notnull |= colDef->is_not_null;
3672 * Add needed dependency entries for the new column.
3674 add_column_datatype_dependency(myrelid, i, attribute->atttypid);
3678 * Install a column's dependency on its datatype.
3681 add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
3683 ObjectAddress myself,
3686 myself.classId = RelationRelationId;
3687 myself.objectId = relid;
3688 myself.objectSubId = attnum;
3689 referenced.classId = TypeRelationId;
3690 referenced.objectId = typid;
3691 referenced.objectSubId = 0;
3692 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
3696 * ALTER TABLE ALTER COLUMN DROP NOT NULL
3699 ATExecDropNotNull(Relation rel, const char *colName)
3705 ListCell *indexoidscan;
3708 * lookup the attribute
3710 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3712 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3714 if (!HeapTupleIsValid(tuple))
3716 (errcode(ERRCODE_UNDEFINED_COLUMN),
3717 errmsg("column \"%s\" of relation \"%s\" does not exist",
3718 colName, RelationGetRelationName(rel))));
3720 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3722 /* Prevent them from altering a system attribute */
3725 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3726 errmsg("cannot alter system column \"%s\"",
3730 * Check that the attribute is not in a primary key
3733 /* Loop over all indexes on the relation */
3734 indexoidlist = RelationGetIndexList(rel);
3736 foreach(indexoidscan, indexoidlist)
3738 Oid indexoid = lfirst_oid(indexoidscan);
3739 HeapTuple indexTuple;
3740 Form_pg_index indexStruct;
3743 indexTuple = SearchSysCache(INDEXRELID,
3744 ObjectIdGetDatum(indexoid),
3746 if (!HeapTupleIsValid(indexTuple))
3747 elog(ERROR, "cache lookup failed for index %u", indexoid);
3748 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
3750 /* If the index is not a primary key, skip the check */
3751 if (indexStruct->indisprimary)
3754 * Loop over each attribute in the primary key and see if it
3755 * matches the to-be-altered attribute
3757 for (i = 0; i < indexStruct->indnatts; i++)
3759 if (indexStruct->indkey.values[i] == attnum)
3761 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3762 errmsg("column \"%s\" is in a primary key",
3767 ReleaseSysCache(indexTuple);
3770 list_free(indexoidlist);
3773 * Okay, actually perform the catalog change ... if needed
3775 if (((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3777 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = FALSE;
3779 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3781 /* keep the system catalog indexes current */
3782 CatalogUpdateIndexes(attr_rel, tuple);
3785 heap_close(attr_rel, RowExclusiveLock);
3789 * ALTER TABLE ALTER COLUMN SET NOT NULL
3792 ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
3793 const char *colName)
3800 * lookup the attribute
3802 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3804 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3806 if (!HeapTupleIsValid(tuple))
3808 (errcode(ERRCODE_UNDEFINED_COLUMN),
3809 errmsg("column \"%s\" of relation \"%s\" does not exist",
3810 colName, RelationGetRelationName(rel))));
3812 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3814 /* Prevent them from altering a system attribute */
3817 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3818 errmsg("cannot alter system column \"%s\"",
3822 * Okay, actually perform the catalog change ... if needed
3824 if (!((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3826 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = TRUE;
3828 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3830 /* keep the system catalog indexes current */
3831 CatalogUpdateIndexes(attr_rel, tuple);
3833 /* Tell Phase 3 it needs to test the constraint */
3834 tab->new_notnull = true;
3837 heap_close(attr_rel, RowExclusiveLock);
3841 * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
3844 ATExecColumnDefault(Relation rel, const char *colName,
3850 * get the number of the attribute
3852 attnum = get_attnum(RelationGetRelid(rel), colName);
3853 if (attnum == InvalidAttrNumber)
3855 (errcode(ERRCODE_UNDEFINED_COLUMN),
3856 errmsg("column \"%s\" of relation \"%s\" does not exist",
3857 colName, RelationGetRelationName(rel))));
3859 /* Prevent them from altering a system attribute */
3862 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3863 errmsg("cannot alter system column \"%s\"",
3867 * Remove any old default for the column. We use RESTRICT here for
3868 * safety, but at present we do not expect anything to depend on the
3871 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false);
3876 RawColumnDefault *rawEnt;
3878 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3879 rawEnt->attnum = attnum;
3880 rawEnt->raw_default = newDefault;
3883 * This function is intended for CREATE TABLE, so it processes a
3884 * _list_ of defaults, but we just do one.
3886 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL, false, true);
3891 * ALTER TABLE ALTER COLUMN SET STATISTICS
3894 ATPrepSetStatistics(Relation rel, const char *colName, Node *flagValue)
3897 * We do our own permission checking because (a) we want to allow SET
3898 * STATISTICS on indexes (for expressional index columns), and (b) we want
3899 * to allow SET STATISTICS on system catalogs without requiring
3900 * allowSystemTableMods to be turned on.
3902 if (rel->rd_rel->relkind != RELKIND_RELATION &&
3903 rel->rd_rel->relkind != RELKIND_INDEX)
3905 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3906 errmsg("\"%s\" is not a table or index",
3907 RelationGetRelationName(rel))));
3909 /* Permissions checks */
3910 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3911 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3912 RelationGetRelationName(rel));
3916 ATExecSetStatistics(Relation rel, const char *colName, Node *newValue)
3919 Relation attrelation;
3921 Form_pg_attribute attrtuple;
3923 Assert(IsA(newValue, Integer));
3924 newtarget = intVal(newValue);
3927 * Limit target to a sane range
3932 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3933 errmsg("statistics target %d is too low",
3936 else if (newtarget > 1000)
3940 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3941 errmsg("lowering statistics target to %d",
3945 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
3947 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3949 if (!HeapTupleIsValid(tuple))
3951 (errcode(ERRCODE_UNDEFINED_COLUMN),
3952 errmsg("column \"%s\" of relation \"%s\" does not exist",
3953 colName, RelationGetRelationName(rel))));
3954 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
3956 if (attrtuple->attnum <= 0)
3958 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3959 errmsg("cannot alter system column \"%s\"",
3962 attrtuple->attstattarget = newtarget;
3964 simple_heap_update(attrelation, &tuple->t_self, tuple);
3966 /* keep system catalog indexes current */
3967 CatalogUpdateIndexes(attrelation, tuple);
3969 heap_freetuple(tuple);
3971 heap_close(attrelation, RowExclusiveLock);
3975 * ALTER TABLE ALTER COLUMN SET STORAGE
3978 ATExecSetStorage(Relation rel, const char *colName, Node *newValue)
3982 Relation attrelation;
3984 Form_pg_attribute attrtuple;
3986 Assert(IsA(newValue, String));
3987 storagemode = strVal(newValue);
3989 if (pg_strcasecmp(storagemode, "plain") == 0)
3991 else if (pg_strcasecmp(storagemode, "external") == 0)
3993 else if (pg_strcasecmp(storagemode, "extended") == 0)
3995 else if (pg_strcasecmp(storagemode, "main") == 0)
4000 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4001 errmsg("invalid storage type \"%s\"",
4003 newstorage = 0; /* keep compiler quiet */
4006 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
4008 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4010 if (!HeapTupleIsValid(tuple))
4012 (errcode(ERRCODE_UNDEFINED_COLUMN),
4013 errmsg("column \"%s\" of relation \"%s\" does not exist",
4014 colName, RelationGetRelationName(rel))));
4015 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
4017 if (attrtuple->attnum <= 0)
4019 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4020 errmsg("cannot alter system column \"%s\"",
4024 * safety check: do not allow toasted storage modes unless column datatype
4027 if (newstorage == 'p' || TypeIsToastable(attrtuple->atttypid))
4028 attrtuple->attstorage = newstorage;
4031 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4032 errmsg("column data type %s can only have storage PLAIN",
4033 format_type_be(attrtuple->atttypid))));
4035 simple_heap_update(attrelation, &tuple->t_self, tuple);
4037 /* keep system catalog indexes current */
4038 CatalogUpdateIndexes(attrelation, tuple);
4040 heap_freetuple(tuple);
4042 heap_close(attrelation, RowExclusiveLock);
4047 * ALTER TABLE DROP COLUMN
4049 * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
4050 * because we have to decide at runtime whether to recurse or not depending
4051 * on whether attinhcount goes to zero or not. (We can't check this in a
4052 * static pre-pass because it won't handle multiple inheritance situations
4053 * correctly.) Since DROP COLUMN doesn't need to create any work queue
4054 * entries for Phase 3, it's okay to recurse internally in this routine
4055 * without considering the work queue.
4058 ATExecDropColumn(Relation rel, const char *colName,
4059 DropBehavior behavior,
4060 bool recurse, bool recursing)
4063 Form_pg_attribute targetatt;
4066 ObjectAddress object;
4068 /* At top level, permission check was done in ATPrepCmd, else do it */
4070 ATSimplePermissions(rel, false);
4073 * get the number of the attribute
4075 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
4076 if (!HeapTupleIsValid(tuple))
4078 (errcode(ERRCODE_UNDEFINED_COLUMN),
4079 errmsg("column \"%s\" of relation \"%s\" does not exist",
4080 colName, RelationGetRelationName(rel))));
4081 targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
4083 attnum = targetatt->attnum;
4085 /* Can't drop a system attribute, except OID */
4086 if (attnum <= 0 && attnum != ObjectIdAttributeNumber)
4088 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4089 errmsg("cannot drop system column \"%s\"",
4092 /* Don't drop inherited columns */
4093 if (targetatt->attinhcount > 0 && !recursing)
4095 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4096 errmsg("cannot drop inherited column \"%s\"",
4099 ReleaseSysCache(tuple);
4102 * Propagate to children as appropriate. Unlike most other ALTER
4103 * routines, we have to do this one level of recursion at a time; we can't
4104 * use find_all_inheritors to do it in one pass.
4106 children = find_inheritance_children(RelationGetRelid(rel));
4113 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
4114 foreach(child, children)
4116 Oid childrelid = lfirst_oid(child);
4118 Form_pg_attribute childatt;
4120 childrel = heap_open(childrelid, AccessExclusiveLock);
4121 CheckTableNotInUse(childrel, "ALTER TABLE");
4123 tuple = SearchSysCacheCopyAttName(childrelid, colName);
4124 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
4125 elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
4126 colName, childrelid);
4127 childatt = (Form_pg_attribute) GETSTRUCT(tuple);
4129 if (childatt->attinhcount <= 0) /* shouldn't happen */
4130 elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
4131 childrelid, colName);
4136 * If the child column has other definition sources, just
4137 * decrement its inheritance count; if not, recurse to delete
4140 if (childatt->attinhcount == 1 && !childatt->attislocal)
4142 /* Time to delete this child column, too */
4143 ATExecDropColumn(childrel, colName, behavior, true, true);
4147 /* Child column must survive my deletion */
4148 childatt->attinhcount--;
4150 simple_heap_update(attr_rel, &tuple->t_self, tuple);
4152 /* keep the system catalog indexes current */
4153 CatalogUpdateIndexes(attr_rel, tuple);
4155 /* Make update visible */
4156 CommandCounterIncrement();
4162 * If we were told to drop ONLY in this table (no recursion),
4163 * we need to mark the inheritors' attributes as locally
4164 * defined rather than inherited.
4166 childatt->attinhcount--;
4167 childatt->attislocal = true;
4169 simple_heap_update(attr_rel, &tuple->t_self, tuple);
4171 /* keep the system catalog indexes current */
4172 CatalogUpdateIndexes(attr_rel, tuple);
4174 /* Make update visible */
4175 CommandCounterIncrement();
4178 heap_freetuple(tuple);
4180 heap_close(childrel, NoLock);
4182 heap_close(attr_rel, RowExclusiveLock);
4186 * Perform the actual column deletion
4188 object.classId = RelationRelationId;
4189 object.objectId = RelationGetRelid(rel);
4190 object.objectSubId = attnum;
4192 performDeletion(&object, behavior);
4195 * If we dropped the OID column, must adjust pg_class.relhasoids
4197 if (attnum == ObjectIdAttributeNumber)
4200 Form_pg_class tuple_class;
4202 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
4204 tuple = SearchSysCacheCopy(RELOID,
4205 ObjectIdGetDatum(RelationGetRelid(rel)),
4207 if (!HeapTupleIsValid(tuple))
4208 elog(ERROR, "cache lookup failed for relation %u",
4209 RelationGetRelid(rel));
4210 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
4212 tuple_class->relhasoids = false;
4213 simple_heap_update(class_rel, &tuple->t_self, tuple);
4215 /* Keep the catalog indexes up to date */
4216 CatalogUpdateIndexes(class_rel, tuple);
4218 heap_close(class_rel, RowExclusiveLock);
4223 * ALTER TABLE ADD INDEX
4225 * There is no such command in the grammar, but parse_utilcmd.c converts
4226 * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands. This lets
4227 * us schedule creation of the index at the appropriate time during ALTER.
4230 ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
4231 IndexStmt *stmt, bool is_rebuild)
4237 Assert(IsA(stmt, IndexStmt));
4239 /* suppress schema rights check when rebuilding existing index */
4240 check_rights = !is_rebuild;
4241 /* skip index build if phase 3 will have to rewrite table anyway */
4242 skip_build = (tab->newvals != NIL);
4243 /* suppress notices when rebuilding existing index */
4246 /* The IndexStmt has already been through transformIndexStmt */
4248 DefineIndex(stmt->relation, /* relation */
4249 stmt->idxname, /* index name */
4250 InvalidOid, /* no predefined OID */
4251 stmt->accessMethod, /* am name */
4253 stmt->indexParams, /* parameters */
4254 (Expr *) stmt->whereClause,
4259 true, /* is_alter_table */
4267 * ALTER TABLE ADD CONSTRAINT
4270 ATExecAddConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
4271 Node *newConstraint, bool recurse)
4273 switch (nodeTag(newConstraint))
4277 Constraint *constr = (Constraint *) newConstraint;
4280 * Currently, we only expect to see CONSTR_CHECK nodes
4281 * arriving here (see the preprocessing done in
4282 * parse_utilcmd.c). Use a switch anyway to make it easier to
4283 * add more code later.
4285 switch (constr->contype)
4288 ATAddCheckConstraint(wqueue, tab, rel,
4289 constr, recurse, false);
4292 elog(ERROR, "unrecognized constraint type: %d",
4293 (int) constr->contype);
4297 case T_FkConstraint:
4299 FkConstraint *fkconstraint = (FkConstraint *) newConstraint;
4302 * Note that we currently never recurse for FK constraints,
4303 * so the "recurse" flag is silently ignored.
4305 * Assign or validate constraint name
4307 if (fkconstraint->constr_name)
4309 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
4310 RelationGetRelid(rel),
4311 RelationGetNamespace(rel),
4312 fkconstraint->constr_name))
4314 (errcode(ERRCODE_DUPLICATE_OBJECT),
4315 errmsg("constraint \"%s\" for relation \"%s\" already exists",
4316 fkconstraint->constr_name,
4317 RelationGetRelationName(rel))));
4320 fkconstraint->constr_name =
4321 ChooseConstraintName(RelationGetRelationName(rel),
4322 strVal(linitial(fkconstraint->fk_attrs)),
4324 RelationGetNamespace(rel),
4327 ATAddForeignKeyConstraint(tab, rel, fkconstraint);
4332 elog(ERROR, "unrecognized node type: %d",
4333 (int) nodeTag(newConstraint));
4338 * Add a check constraint to a single table and its children
4340 * Subroutine for ATExecAddConstraint.
4342 * We must recurse to child tables during execution, rather than using
4343 * ALTER TABLE's normal prep-time recursion. The reason is that all the
4344 * constraints *must* be given the same name, else they won't be seen as
4345 * related later. If the user didn't explicitly specify a name, then
4346 * AddRelationNewConstraints would normally assign different names to the
4347 * child constraints. To fix that, we must capture the name assigned at
4348 * the parent table and pass that down.
4351 ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
4352 Constraint *constr, bool recurse, bool recursing)
4359 /* At top level, permission check was done in ATPrepCmd, else do it */
4361 ATSimplePermissions(rel, false);
4364 * Call AddRelationNewConstraints to do the work, making sure it works on
4365 * a copy of the Constraint so transformExpr can't modify the original.
4366 * It returns a list of cooked constraints.
4368 * If the constraint ends up getting merged with a pre-existing one, it's
4369 * omitted from the returned list, which is what we want: we do not need
4370 * to do any validation work. That can only happen at child tables,
4371 * though, since we disallow merging at the top level.
4373 newcons = AddRelationNewConstraints(rel, NIL,
4374 list_make1(copyObject(constr)),
4375 recursing, !recursing);
4377 /* Add each constraint to Phase 3's queue */
4378 foreach(lcon, newcons)
4380 CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
4381 NewConstraint *newcon;
4383 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
4384 newcon->name = ccon->name;
4385 newcon->contype = ccon->contype;
4386 /* ExecQual wants implicit-AND format */
4387 newcon->qual = (Node *) make_ands_implicit((Expr *) ccon->expr);
4389 tab->constraints = lappend(tab->constraints, newcon);
4391 /* Save the actually assigned name if it was defaulted */
4392 if (constr->name == NULL)
4393 constr->name = ccon->name;
4396 /* At this point we must have a locked-down name to use */
4397 Assert(constr->name != NULL);
4399 /* Advance command counter in case same table is visited multiple times */
4400 CommandCounterIncrement();
4403 * Propagate to children as appropriate. Unlike most other ALTER
4404 * routines, we have to do this one level of recursion at a time; we can't
4405 * use find_all_inheritors to do it in one pass.
4407 children = find_inheritance_children(RelationGetRelid(rel));
4410 * If we are told not to recurse, there had better not be any child
4411 * tables; else the addition would put them out of step.
4413 if (children && !recurse)
4415 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4416 errmsg("constraint must be added to child tables too")));
4418 foreach(child, children)
4420 Oid childrelid = lfirst_oid(child);
4422 AlteredTableInfo *childtab;
4424 childrel = heap_open(childrelid, AccessExclusiveLock);
4425 CheckTableNotInUse(childrel, "ALTER TABLE");
4427 /* Find or create work queue entry for this table */
4428 childtab = ATGetQueueEntry(wqueue, childrel);
4430 /* Recurse to child */
4431 ATAddCheckConstraint(wqueue, childtab, childrel,
4432 constr, recurse, true);
4434 heap_close(childrel, NoLock);
4439 * Add a foreign-key constraint to a single table
4441 * Subroutine for ATExecAddConstraint. Must already hold exclusive
4442 * lock on the rel, and have done appropriate validity/permissions checks
4446 ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
4447 FkConstraint *fkconstraint)
4450 AclResult aclresult;
4451 int16 pkattnum[INDEX_MAX_KEYS];
4452 int16 fkattnum[INDEX_MAX_KEYS];
4453 Oid pktypoid[INDEX_MAX_KEYS];
4454 Oid fktypoid[INDEX_MAX_KEYS];
4455 Oid opclasses[INDEX_MAX_KEYS];
4456 Oid pfeqoperators[INDEX_MAX_KEYS];
4457 Oid ppeqoperators[INDEX_MAX_KEYS];
4458 Oid ffeqoperators[INDEX_MAX_KEYS];
4466 * Grab an exclusive lock on the pk table, so that someone doesn't delete
4467 * rows out from under us. (Although a lesser lock would do for that
4468 * purpose, we'll need exclusive lock anyway to add triggers to the pk
4469 * table; trying to start with a lesser lock will just create a risk of
4472 pkrel = heap_openrv(fkconstraint->pktable, AccessExclusiveLock);
4475 * Validity and permissions checks
4477 * Note: REFERENCES permissions checks are redundant with CREATE TRIGGER,
4478 * but we may as well error out sooner instead of later.
4480 if (pkrel->rd_rel->relkind != RELKIND_RELATION)
4482 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4483 errmsg("referenced relation \"%s\" is not a table",
4484 RelationGetRelationName(pkrel))));
4486 aclresult = pg_class_aclcheck(RelationGetRelid(pkrel), GetUserId(),
4488 if (aclresult != ACLCHECK_OK)
4489 aclcheck_error(aclresult, ACL_KIND_CLASS,
4490 RelationGetRelationName(pkrel));
4492 if (!allowSystemTableMods && IsSystemRelation(pkrel))
4494 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4495 errmsg("permission denied: \"%s\" is a system catalog",
4496 RelationGetRelationName(pkrel))));
4498 aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
4500 if (aclresult != ACLCHECK_OK)
4501 aclcheck_error(aclresult, ACL_KIND_CLASS,
4502 RelationGetRelationName(rel));
4505 * Disallow reference from permanent table to temp table or vice versa.
4506 * (The ban on perm->temp is for fairly obvious reasons. The ban on
4507 * temp->perm is because other backends might need to run the RI triggers
4508 * on the perm table, but they can't reliably see tuples the owning
4509 * backend has created in the temp table, because non-shared buffers are
4510 * used for temp tables.)
4512 if (isTempNamespace(RelationGetNamespace(pkrel)))
4514 if (!isTempNamespace(RelationGetNamespace(rel)))
4516 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4517 errmsg("cannot reference temporary table from permanent table constraint")));
4521 if (isTempNamespace(RelationGetNamespace(rel)))
4523 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4524 errmsg("cannot reference permanent table from temporary table constraint")));
4528 * Look up the referencing attributes to make sure they exist, and record
4529 * their attnums and type OIDs.
4531 MemSet(pkattnum, 0, sizeof(pkattnum));
4532 MemSet(fkattnum, 0, sizeof(fkattnum));
4533 MemSet(pktypoid, 0, sizeof(pktypoid));
4534 MemSet(fktypoid, 0, sizeof(fktypoid));
4535 MemSet(opclasses, 0, sizeof(opclasses));
4536 MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
4537 MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
4538 MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
4540 numfks = transformColumnNameList(RelationGetRelid(rel),
4541 fkconstraint->fk_attrs,
4542 fkattnum, fktypoid);
4545 * If the attribute list for the referenced table was omitted, lookup the
4546 * definition of the primary key and use it. Otherwise, validate the
4547 * supplied attribute list. In either case, discover the index OID and
4548 * index opclasses, and the attnums and type OIDs of the attributes.
4550 if (fkconstraint->pk_attrs == NIL)
4552 numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
4553 &fkconstraint->pk_attrs,
4559 numpks = transformColumnNameList(RelationGetRelid(pkrel),
4560 fkconstraint->pk_attrs,
4561 pkattnum, pktypoid);
4562 /* Look for an index matching the column list */
4563 indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
4568 * Look up the equality operators to use in the constraint.
4570 * Note that we have to be careful about the difference between the actual
4571 * PK column type and the opclass' declared input type, which might be
4572 * only binary-compatible with it. The declared opcintype is the right
4573 * thing to probe pg_amop with.
4575 if (numfks != numpks)
4577 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4578 errmsg("number of referencing and referenced columns for foreign key disagree")));
4580 for (i = 0; i < numpks; i++)
4582 Oid pktype = pktypoid[i];
4583 Oid fktype = fktypoid[i];
4586 Form_pg_opclass cla_tup;
4595 /* We need several fields out of the pg_opclass entry */
4596 cla_ht = SearchSysCache(CLAOID,
4597 ObjectIdGetDatum(opclasses[i]),
4599 if (!HeapTupleIsValid(cla_ht))
4600 elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
4601 cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
4602 amid = cla_tup->opcmethod;
4603 opfamily = cla_tup->opcfamily;
4604 opcintype = cla_tup->opcintype;
4605 ReleaseSysCache(cla_ht);
4608 * Check it's a btree; currently this can never fail since no other
4609 * index AMs support unique indexes. If we ever did have other types
4610 * of unique indexes, we'd need a way to determine which operator
4611 * strategy number is equality. (Is it reasonable to insist that
4612 * every such index AM use btree's number for equality?)
4614 if (amid != BTREE_AM_OID)
4615 elog(ERROR, "only b-tree indexes are supported for foreign keys");
4616 eqstrategy = BTEqualStrategyNumber;
4619 * There had better be a primary equality operator for the index.
4620 * We'll use it for PK = PK comparisons.
4622 ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
4625 if (!OidIsValid(ppeqop))
4626 elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
4627 eqstrategy, opcintype, opcintype, opfamily);
4630 * Are there equality operators that take exactly the FK type? Assume
4631 * we should look through any domain here.
4633 fktyped = getBaseType(fktype);
4635 pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
4637 if (OidIsValid(pfeqop))
4638 ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
4641 ffeqop = InvalidOid; /* keep compiler quiet */
4643 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4646 * Otherwise, look for an implicit cast from the FK type to the
4647 * opcintype, and if found, use the primary equality operator.
4648 * This is a bit tricky because opcintype might be a polymorphic
4649 * type such as ANYARRAY or ANYENUM; so what we have to test is
4650 * whether the two actual column types can be concurrently cast to
4651 * that type. (Otherwise, we'd fail to reject combinations such
4652 * as int[] and point[].)
4654 Oid input_typeids[2];
4655 Oid target_typeids[2];
4657 input_typeids[0] = pktype;
4658 input_typeids[1] = fktype;
4659 target_typeids[0] = opcintype;
4660 target_typeids[1] = opcintype;
4661 if (can_coerce_type(2, input_typeids, target_typeids,
4663 pfeqop = ffeqop = ppeqop;
4666 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4668 (errcode(ERRCODE_DATATYPE_MISMATCH),
4669 errmsg("foreign key constraint \"%s\" "
4670 "cannot be implemented",
4671 fkconstraint->constr_name),
4672 errdetail("Key columns \"%s\" and \"%s\" "
4673 "are of incompatible types: %s and %s.",
4674 strVal(list_nth(fkconstraint->fk_attrs, i)),
4675 strVal(list_nth(fkconstraint->pk_attrs, i)),
4676 format_type_be(fktype),
4677 format_type_be(pktype))));
4679 pfeqoperators[i] = pfeqop;
4680 ppeqoperators[i] = ppeqop;
4681 ffeqoperators[i] = ffeqop;
4685 * Record the FK constraint in pg_constraint.
4687 constrOid = CreateConstraintEntry(fkconstraint->constr_name,
4688 RelationGetNamespace(rel),
4690 fkconstraint->deferrable,
4691 fkconstraint->initdeferred,
4692 RelationGetRelid(rel),
4695 InvalidOid, /* not a domain
4697 RelationGetRelid(pkrel),
4703 fkconstraint->fk_upd_action,
4704 fkconstraint->fk_del_action,
4705 fkconstraint->fk_matchtype,
4707 NULL, /* no check constraint */
4714 * Create the triggers that will enforce the constraint.
4716 createForeignKeyTriggers(rel, fkconstraint, constrOid);
4719 * Tell Phase 3 to check that the constraint is satisfied by existing rows
4720 * (we can skip this during table creation).
4722 if (!fkconstraint->skip_validation)
4724 NewConstraint *newcon;
4726 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
4727 newcon->name = fkconstraint->constr_name;
4728 newcon->contype = CONSTR_FOREIGN;
4729 newcon->refrelid = RelationGetRelid(pkrel);
4730 newcon->conid = constrOid;
4731 newcon->qual = (Node *) fkconstraint;
4733 tab->constraints = lappend(tab->constraints, newcon);
4737 * Close pk table, but keep lock until we've committed.
4739 heap_close(pkrel, NoLock);
4744 * transformColumnNameList - transform list of column names
4746 * Lookup each name and return its attnum and type OID
4749 transformColumnNameList(Oid relId, List *colList,
4750 int16 *attnums, Oid *atttypids)
4758 char *attname = strVal(lfirst(l));
4761 atttuple = SearchSysCacheAttName(relId, attname);
4762 if (!HeapTupleIsValid(atttuple))
4764 (errcode(ERRCODE_UNDEFINED_COLUMN),
4765 errmsg("column \"%s\" referenced in foreign key constraint does not exist",
4767 if (attnum >= INDEX_MAX_KEYS)
4769 (errcode(ERRCODE_TOO_MANY_COLUMNS),
4770 errmsg("cannot have more than %d keys in a foreign key",
4772 attnums[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->attnum;
4773 atttypids[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->atttypid;
4774 ReleaseSysCache(atttuple);
4782 * transformFkeyGetPrimaryKey -
4784 * Look up the names, attnums, and types of the primary key attributes
4785 * for the pkrel. Also return the index OID and index opclasses of the
4786 * index supporting the primary key.
4788 * All parameters except pkrel are output parameters. Also, the function
4789 * return value is the number of attributes in the primary key.
4791 * Used when the column list in the REFERENCES specification is omitted.
4794 transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
4796 int16 *attnums, Oid *atttypids,
4800 ListCell *indexoidscan;
4801 HeapTuple indexTuple = NULL;
4802 Form_pg_index indexStruct = NULL;
4803 Datum indclassDatum;
4805 oidvector *indclass;
4809 * Get the list of index OIDs for the table from the relcache, and look up
4810 * each one in the pg_index syscache until we find one marked primary key
4811 * (hopefully there isn't more than one such).
4813 *indexOid = InvalidOid;
4815 indexoidlist = RelationGetIndexList(pkrel);
4817 foreach(indexoidscan, indexoidlist)
4819 Oid indexoid = lfirst_oid(indexoidscan);
4821 indexTuple = SearchSysCache(INDEXRELID,
4822 ObjectIdGetDatum(indexoid),
4824 if (!HeapTupleIsValid(indexTuple))
4825 elog(ERROR, "cache lookup failed for index %u", indexoid);
4826 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4827 if (indexStruct->indisprimary)
4829 *indexOid = indexoid;
4832 ReleaseSysCache(indexTuple);
4835 list_free(indexoidlist);
4838 * Check that we found it
4840 if (!OidIsValid(*indexOid))
4842 (errcode(ERRCODE_UNDEFINED_OBJECT),
4843 errmsg("there is no primary key for referenced table \"%s\"",
4844 RelationGetRelationName(pkrel))));
4846 /* Must get indclass the hard way */
4847 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4848 Anum_pg_index_indclass, &isnull);
4850 indclass = (oidvector *) DatumGetPointer(indclassDatum);
4853 * Now build the list of PK attributes from the indkey definition (we
4854 * assume a primary key cannot have expressional elements)
4857 for (i = 0; i < indexStruct->indnatts; i++)
4859 int pkattno = indexStruct->indkey.values[i];
4861 attnums[i] = pkattno;
4862 atttypids[i] = attnumTypeId(pkrel, pkattno);
4863 opclasses[i] = indclass->values[i];
4864 *attnamelist = lappend(*attnamelist,
4865 makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
4868 ReleaseSysCache(indexTuple);
4874 * transformFkeyCheckAttrs -
4876 * Make sure that the attributes of a referenced table belong to a unique
4877 * (or primary key) constraint. Return the OID of the index supporting
4878 * the constraint, as well as the opclasses associated with the index
4882 transformFkeyCheckAttrs(Relation pkrel,
4883 int numattrs, int16 *attnums,
4884 Oid *opclasses) /* output parameter */
4886 Oid indexoid = InvalidOid;
4889 ListCell *indexoidscan;
4892 * Get the list of index OIDs for the table from the relcache, and look up
4893 * each one in the pg_index syscache, and match unique indexes to the list
4894 * of attnums we are given.
4896 indexoidlist = RelationGetIndexList(pkrel);
4898 foreach(indexoidscan, indexoidlist)
4900 HeapTuple indexTuple;
4901 Form_pg_index indexStruct;
4905 indexoid = lfirst_oid(indexoidscan);
4906 indexTuple = SearchSysCache(INDEXRELID,
4907 ObjectIdGetDatum(indexoid),
4909 if (!HeapTupleIsValid(indexTuple))
4910 elog(ERROR, "cache lookup failed for index %u", indexoid);
4911 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4914 * Must have the right number of columns; must be unique and not a
4915 * partial index; forget it if there are any expressions, too
4917 if (indexStruct->indnatts == numattrs &&
4918 indexStruct->indisunique &&
4919 heap_attisnull(indexTuple, Anum_pg_index_indpred) &&
4920 heap_attisnull(indexTuple, Anum_pg_index_indexprs))
4922 /* Must get indclass the hard way */
4923 Datum indclassDatum;
4925 oidvector *indclass;
4927 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4928 Anum_pg_index_indclass, &isnull);
4930 indclass = (oidvector *) DatumGetPointer(indclassDatum);
4933 * The given attnum list may match the index columns in any order.
4934 * Check that each list is a subset of the other.
4936 for (i = 0; i < numattrs; i++)
4939 for (j = 0; j < numattrs; j++)
4941 if (attnums[i] == indexStruct->indkey.values[j])
4952 for (i = 0; i < numattrs; i++)
4955 for (j = 0; j < numattrs; j++)
4957 if (attnums[j] == indexStruct->indkey.values[i])
4959 opclasses[j] = indclass->values[i];
4969 ReleaseSysCache(indexTuple);
4976 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4977 errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
4978 RelationGetRelationName(pkrel))));
4980 list_free(indexoidlist);
4986 * Scan the existing rows in a table to verify they meet a proposed FK
4989 * Caller must have opened and locked both relations.
4992 validateForeignKeyConstraint(FkConstraint *fkconstraint,
5002 * Build a trigger call structure; we'll need it either way.
5004 MemSet(&trig, 0, sizeof(trig));
5005 trig.tgoid = InvalidOid;
5006 trig.tgname = fkconstraint->constr_name;
5007 trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
5008 trig.tgisconstraint = TRUE;
5009 trig.tgconstrrelid = RelationGetRelid(pkrel);
5010 trig.tgconstraint = constraintOid;
5011 trig.tgdeferrable = FALSE;
5012 trig.tginitdeferred = FALSE;
5013 /* we needn't fill in tgargs */
5016 * See if we can do it with a single LEFT JOIN query. A FALSE result
5017 * indicates we must proceed with the fire-the-trigger method.
5019 if (RI_Initial_Check(&trig, rel, pkrel))
5023 * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
5024 * if that tuple had just been inserted. If any of those fail, it should
5025 * ereport(ERROR) and that's that.
5027 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
5029 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
5031 FunctionCallInfoData fcinfo;
5032 TriggerData trigdata;
5035 * Make a call to the trigger function
5037 * No parameters are passed, but we do set a context
5039 MemSet(&fcinfo, 0, sizeof(fcinfo));
5042 * We assume RI_FKey_check_ins won't look at flinfo...
5044 trigdata.type = T_TriggerData;
5045 trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
5046 trigdata.tg_relation = rel;
5047 trigdata.tg_trigtuple = tuple;
5048 trigdata.tg_newtuple = NULL;
5049 trigdata.tg_trigger = &trig;
5050 trigdata.tg_trigtuplebuf = scan->rs_cbuf;
5051 trigdata.tg_newtuplebuf = InvalidBuffer;
5053 fcinfo.context = (Node *) &trigdata;
5055 RI_FKey_check_ins(&fcinfo);
5062 CreateFKCheckTrigger(RangeVar *myRel, FkConstraint *fkconstraint,
5063 Oid constraintOid, bool on_insert)
5065 CreateTrigStmt *fk_trigger;
5067 fk_trigger = makeNode(CreateTrigStmt);
5068 fk_trigger->trigname = fkconstraint->constr_name;
5069 fk_trigger->relation = myRel;
5070 fk_trigger->before = false;
5071 fk_trigger->row = true;
5073 /* Either ON INSERT or ON UPDATE */
5076 fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
5077 fk_trigger->actions[0] = 'i';
5081 fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
5082 fk_trigger->actions[0] = 'u';
5084 fk_trigger->actions[1] = '\0';
5086 fk_trigger->isconstraint = true;
5087 fk_trigger->deferrable = fkconstraint->deferrable;
5088 fk_trigger->initdeferred = fkconstraint->initdeferred;
5089 fk_trigger->constrrel = fkconstraint->pktable;
5090 fk_trigger->args = NIL;
5092 (void) CreateTrigger(fk_trigger, constraintOid);
5094 /* Make changes-so-far visible */
5095 CommandCounterIncrement();
5099 * Create the triggers that implement an FK constraint.
5102 createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
5106 CreateTrigStmt *fk_trigger;
5109 * Reconstruct a RangeVar for my relation (not passed in, unfortunately).
5111 myRel = makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
5112 pstrdup(RelationGetRelationName(rel)));
5114 /* Make changes-so-far visible */
5115 CommandCounterIncrement();
5118 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the CHECK
5119 * action for both INSERTs and UPDATEs on the referencing table.
5121 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, true);
5122 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, false);
5125 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
5126 * DELETE action on the referenced table.
5128 fk_trigger = makeNode(CreateTrigStmt);
5129 fk_trigger->trigname = fkconstraint->constr_name;
5130 fk_trigger->relation = fkconstraint->pktable;
5131 fk_trigger->before = false;
5132 fk_trigger->row = true;
5133 fk_trigger->actions[0] = 'd';
5134 fk_trigger->actions[1] = '\0';
5136 fk_trigger->isconstraint = true;
5137 fk_trigger->constrrel = myRel;
5138 switch (fkconstraint->fk_del_action)
5140 case FKCONSTR_ACTION_NOACTION:
5141 fk_trigger->deferrable = fkconstraint->deferrable;
5142 fk_trigger->initdeferred = fkconstraint->initdeferred;
5143 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
5145 case FKCONSTR_ACTION_RESTRICT:
5146 fk_trigger->deferrable = false;
5147 fk_trigger->initdeferred = false;
5148 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
5150 case FKCONSTR_ACTION_CASCADE:
5151 fk_trigger->deferrable = false;
5152 fk_trigger->initdeferred = false;
5153 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
5155 case FKCONSTR_ACTION_SETNULL:
5156 fk_trigger->deferrable = false;
5157 fk_trigger->initdeferred = false;
5158 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
5160 case FKCONSTR_ACTION_SETDEFAULT:
5161 fk_trigger->deferrable = false;
5162 fk_trigger->initdeferred = false;
5163 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
5166 elog(ERROR, "unrecognized FK action type: %d",
5167 (int) fkconstraint->fk_del_action);
5170 fk_trigger->args = NIL;
5172 (void) CreateTrigger(fk_trigger, constraintOid);
5174 /* Make changes-so-far visible */
5175 CommandCounterIncrement();
5178 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
5179 * UPDATE action on the referenced table.
5181 fk_trigger = makeNode(CreateTrigStmt);
5182 fk_trigger->trigname = fkconstraint->constr_name;
5183 fk_trigger->relation = fkconstraint->pktable;
5184 fk_trigger->before = false;
5185 fk_trigger->row = true;
5186 fk_trigger->actions[0] = 'u';
5187 fk_trigger->actions[1] = '\0';
5188 fk_trigger->isconstraint = true;
5189 fk_trigger->constrrel = myRel;
5190 switch (fkconstraint->fk_upd_action)
5192 case FKCONSTR_ACTION_NOACTION:
5193 fk_trigger->deferrable = fkconstraint->deferrable;
5194 fk_trigger->initdeferred = fkconstraint->initdeferred;
5195 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
5197 case FKCONSTR_ACTION_RESTRICT:
5198 fk_trigger->deferrable = false;
5199 fk_trigger->initdeferred = false;
5200 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
5202 case FKCONSTR_ACTION_CASCADE:
5203 fk_trigger->deferrable = false;
5204 fk_trigger->initdeferred = false;
5205 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
5207 case FKCONSTR_ACTION_SETNULL:
5208 fk_trigger->deferrable = false;
5209 fk_trigger->initdeferred = false;
5210 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
5212 case FKCONSTR_ACTION_SETDEFAULT:
5213 fk_trigger->deferrable = false;
5214 fk_trigger->initdeferred = false;
5215 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
5218 elog(ERROR, "unrecognized FK action type: %d",
5219 (int) fkconstraint->fk_upd_action);
5222 fk_trigger->args = NIL;
5224 (void) CreateTrigger(fk_trigger, constraintOid);
5228 * ALTER TABLE DROP CONSTRAINT
5230 * Like DROP COLUMN, we can't use the normal ALTER TABLE recursion mechanism.
5233 ATExecDropConstraint(Relation rel, const char *constrName,
5234 DropBehavior behavior,
5235 bool recurse, bool recursing)
5240 Form_pg_constraint con;
5245 bool is_check_constraint = false;
5247 /* At top level, permission check was done in ATPrepCmd, else do it */
5249 ATSimplePermissions(rel, false);
5251 conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
5254 * Find and drop the target constraint
5257 Anum_pg_constraint_conrelid,
5258 BTEqualStrategyNumber, F_OIDEQ,
5259 ObjectIdGetDatum(RelationGetRelid(rel)));
5260 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
5261 true, SnapshotNow, 1, &key);
5263 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
5265 ObjectAddress conobj;
5267 con = (Form_pg_constraint) GETSTRUCT(tuple);
5269 if (strcmp(NameStr(con->conname), constrName) != 0)
5272 /* Don't drop inherited constraints */
5273 if (con->coninhcount > 0 && !recursing)
5275 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5276 errmsg("cannot drop inherited constraint \"%s\" of relation \"%s\"",
5277 constrName, RelationGetRelationName(rel))));
5279 /* Right now only CHECK constraints can be inherited */
5280 if (con->contype == CONSTRAINT_CHECK)
5281 is_check_constraint = true;
5284 * Perform the actual constraint deletion
5286 conobj.classId = ConstraintRelationId;
5287 conobj.objectId = HeapTupleGetOid(tuple);
5288 conobj.objectSubId = 0;
5290 performDeletion(&conobj, behavior);
5295 systable_endscan(scan);
5299 (errcode(ERRCODE_UNDEFINED_OBJECT),
5300 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
5301 constrName, RelationGetRelationName(rel))));
5304 * Propagate to children as appropriate. Unlike most other ALTER
5305 * routines, we have to do this one level of recursion at a time; we can't
5306 * use find_all_inheritors to do it in one pass.
5308 if (is_check_constraint)
5309 children = find_inheritance_children(RelationGetRelid(rel));
5313 foreach(child, children)
5315 Oid childrelid = lfirst_oid(child);
5318 childrel = heap_open(childrelid, AccessExclusiveLock);
5319 CheckTableNotInUse(childrel, "ALTER TABLE");
5322 Anum_pg_constraint_conrelid,
5323 BTEqualStrategyNumber, F_OIDEQ,
5324 ObjectIdGetDatum(childrelid));
5325 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
5326 true, SnapshotNow, 1, &key);
5330 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
5332 HeapTuple copy_tuple;
5334 con = (Form_pg_constraint) GETSTRUCT(tuple);
5336 /* Right now only CHECK constraints can be inherited */
5337 if (con->contype != CONSTRAINT_CHECK)
5340 if (strcmp(NameStr(con->conname), constrName) != 0)
5345 if (con->coninhcount <= 0) /* shouldn't happen */
5346 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
5347 childrelid, constrName);
5349 copy_tuple = heap_copytuple(tuple);
5350 con = (Form_pg_constraint) GETSTRUCT(copy_tuple);
5355 * If the child constraint has other definition sources,
5356 * just decrement its inheritance count; if not, recurse
5359 if (con->coninhcount == 1 && !con->conislocal)
5361 /* Time to delete this child constraint, too */
5362 ATExecDropConstraint(childrel, constrName, behavior,
5367 /* Child constraint must survive my deletion */
5369 simple_heap_update(conrel, ©_tuple->t_self, copy_tuple);
5370 CatalogUpdateIndexes(conrel, copy_tuple);
5372 /* Make update visible */
5373 CommandCounterIncrement();
5379 * If we were told to drop ONLY in this table (no
5380 * recursion), we need to mark the inheritors' constraints
5381 * as locally defined rather than inherited.
5384 con->conislocal = true;
5386 simple_heap_update(conrel, ©_tuple->t_self, copy_tuple);
5387 CatalogUpdateIndexes(conrel, copy_tuple);
5389 /* Make update visible */
5390 CommandCounterIncrement();
5393 heap_freetuple(copy_tuple);
5396 systable_endscan(scan);
5400 (errcode(ERRCODE_UNDEFINED_OBJECT),
5401 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
5403 RelationGetRelationName(childrel))));
5405 heap_close(childrel, NoLock);
5408 heap_close(conrel, RowExclusiveLock);
5415 ATPrepAlterColumnType(List **wqueue,
5416 AlteredTableInfo *tab, Relation rel,
5417 bool recurse, bool recursing,
5420 char *colName = cmd->name;
5421 TypeName *typename = (TypeName *) cmd->def;
5423 Form_pg_attribute attTup;
5428 NewColumnValue *newval;
5429 ParseState *pstate = make_parsestate(NULL);
5431 /* lookup the attribute so we can check inheritance status */
5432 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
5433 if (!HeapTupleIsValid(tuple))
5435 (errcode(ERRCODE_UNDEFINED_COLUMN),
5436 errmsg("column \"%s\" of relation \"%s\" does not exist",
5437 colName, RelationGetRelationName(rel))));
5438 attTup = (Form_pg_attribute) GETSTRUCT(tuple);
5439 attnum = attTup->attnum;
5441 /* Can't alter a system attribute */
5444 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5445 errmsg("cannot alter system column \"%s\"",
5448 /* Don't alter inherited columns */
5449 if (attTup->attinhcount > 0 && !recursing)
5451 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5452 errmsg("cannot alter inherited column \"%s\"",
5455 /* Look up the target type */
5456 targettype = typenameTypeId(NULL, typename, &targettypmod);
5458 /* make sure datatype is legal for a column */
5459 CheckAttributeType(colName, targettype);
5462 * Set up an expression to transform the old data value to the new type.
5463 * If a USING option was given, transform and use that expression, else
5464 * just take the old value and try to coerce it. We do this first so that
5465 * type incompatibility can be detected before we waste effort, and
5466 * because we need the expression to be parsed against the original table
5473 /* Expression must be able to access vars of old table */
5474 rte = addRangeTableEntryForRelation(pstate,
5479 addRTEtoQuery(pstate, rte, false, true, true);
5481 transform = transformExpr(pstate, cmd->transform);
5483 /* It can't return a set */
5484 if (expression_returns_set(transform))
5486 (errcode(ERRCODE_DATATYPE_MISMATCH),
5487 errmsg("transform expression must not return a set")));
5489 /* No subplans or aggregates, either... */
5490 if (pstate->p_hasSubLinks)
5492 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5493 errmsg("cannot use subquery in transform expression")));
5494 if (pstate->p_hasAggs)
5496 (errcode(ERRCODE_GROUPING_ERROR),
5497 errmsg("cannot use aggregate function in transform expression")));
5501 transform = (Node *) makeVar(1, attnum,
5502 attTup->atttypid, attTup->atttypmod,
5506 transform = coerce_to_target_type(pstate,
5507 transform, exprType(transform),
5508 targettype, targettypmod,
5509 COERCION_ASSIGNMENT,
5510 COERCE_IMPLICIT_CAST);
5511 if (transform == NULL)
5513 (errcode(ERRCODE_DATATYPE_MISMATCH),
5514 errmsg("column \"%s\" cannot be cast to type \"%s\"",
5515 colName, TypeNameToString(typename))));
5518 * Add a work queue item to make ATRewriteTable update the column
5521 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
5522 newval->attnum = attnum;
5523 newval->expr = (Expr *) transform;
5525 tab->newvals = lappend(tab->newvals, newval);
5527 ReleaseSysCache(tuple);
5530 * The recursion case is handled by ATSimpleRecursion. However, if we are
5531 * told not to recurse, there had better not be any child tables; else the
5532 * alter would put them out of step.
5535 ATSimpleRecursion(wqueue, rel, cmd, recurse);
5536 else if (!recursing &&
5537 find_inheritance_children(RelationGetRelid(rel)) != NIL)
5539 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5540 errmsg("type of inherited column \"%s\" must be changed in child tables too",
5545 ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
5546 const char *colName, TypeName *typename)
5549 Form_pg_attribute attTup;
5551 HeapTuple typeTuple;
5556 Relation attrelation;
5562 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
5564 /* Look up the target column */
5565 heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5566 if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
5568 (errcode(ERRCODE_UNDEFINED_COLUMN),
5569 errmsg("column \"%s\" of relation \"%s\" does not exist",
5570 colName, RelationGetRelationName(rel))));
5571 attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
5572 attnum = attTup->attnum;
5574 /* Check for multiple ALTER TYPE on same column --- can't cope */
5575 if (attTup->atttypid != tab->oldDesc->attrs[attnum - 1]->atttypid ||
5576 attTup->atttypmod != tab->oldDesc->attrs[attnum - 1]->atttypmod)
5578 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5579 errmsg("cannot alter type of column \"%s\" twice",
5582 /* Look up the target type (should not fail, since prep found it) */
5583 typeTuple = typenameType(NULL, typename, &targettypmod);
5584 tform = (Form_pg_type) GETSTRUCT(typeTuple);
5585 targettype = HeapTupleGetOid(typeTuple);
5588 * If there is a default expression for the column, get it and ensure we
5589 * can coerce it to the new datatype. (We must do this before changing
5590 * the column type, because build_column_default itself will try to
5591 * coerce, and will not issue the error message we want if it fails.)
5593 * We remove any implicit coercion steps at the top level of the old
5594 * default expression; this has been agreed to satisfy the principle of
5595 * least surprise. (The conversion to the new column type should act like
5596 * it started from what the user sees as the stored expression, and the
5597 * implicit coercions aren't going to be shown.)
5599 if (attTup->atthasdef)
5601 defaultexpr = build_column_default(rel, attnum);
5602 Assert(defaultexpr);
5603 defaultexpr = strip_implicit_coercions(defaultexpr);
5604 defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
5605 defaultexpr, exprType(defaultexpr),
5606 targettype, targettypmod,
5607 COERCION_ASSIGNMENT,
5608 COERCE_IMPLICIT_CAST);
5609 if (defaultexpr == NULL)
5611 (errcode(ERRCODE_DATATYPE_MISMATCH),
5612 errmsg("default for column \"%s\" cannot be cast to type \"%s\"",
5613 colName, TypeNameToString(typename))));
5619 * Find everything that depends on the column (constraints, indexes, etc),
5620 * and record enough information to let us recreate the objects.
5622 * The actual recreation does not happen here, but only after we have
5623 * performed all the individual ALTER TYPE operations. We have to save
5624 * the info before executing ALTER TYPE, though, else the deparser will
5627 * There could be multiple entries for the same object, so we must check
5628 * to ensure we process each one only once. Note: we assume that an index
5629 * that implements a constraint will not show a direct dependency on the
5632 depRel = heap_open(DependRelationId, RowExclusiveLock);
5634 ScanKeyInit(&key[0],
5635 Anum_pg_depend_refclassid,
5636 BTEqualStrategyNumber, F_OIDEQ,
5637 ObjectIdGetDatum(RelationRelationId));
5638 ScanKeyInit(&key[1],
5639 Anum_pg_depend_refobjid,
5640 BTEqualStrategyNumber, F_OIDEQ,
5641 ObjectIdGetDatum(RelationGetRelid(rel)));
5642 ScanKeyInit(&key[2],
5643 Anum_pg_depend_refobjsubid,
5644 BTEqualStrategyNumber, F_INT4EQ,
5645 Int32GetDatum((int32) attnum));
5647 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
5648 SnapshotNow, 3, key);
5650 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5652 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5653 ObjectAddress foundObject;
5655 /* We don't expect any PIN dependencies on columns */
5656 if (foundDep->deptype == DEPENDENCY_PIN)
5657 elog(ERROR, "cannot alter type of a pinned column");
5659 foundObject.classId = foundDep->classid;
5660 foundObject.objectId = foundDep->objid;
5661 foundObject.objectSubId = foundDep->objsubid;
5663 switch (getObjectClass(&foundObject))
5667 char relKind = get_rel_relkind(foundObject.objectId);
5669 if (relKind == RELKIND_INDEX)
5671 Assert(foundObject.objectSubId == 0);
5672 if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
5674 tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
5675 foundObject.objectId);
5676 tab->changedIndexDefs = lappend(tab->changedIndexDefs,
5677 pg_get_indexdef_string(foundObject.objectId));
5680 else if (relKind == RELKIND_SEQUENCE)
5683 * This must be a SERIAL column's sequence. We need
5684 * not do anything to it.
5686 Assert(foundObject.objectSubId == 0);
5690 /* Not expecting any other direct dependencies... */
5691 elog(ERROR, "unexpected object depending on column: %s",
5692 getObjectDescription(&foundObject));
5697 case OCLASS_CONSTRAINT:
5698 Assert(foundObject.objectSubId == 0);
5699 if (!list_member_oid(tab->changedConstraintOids,
5700 foundObject.objectId))
5702 char *defstring = pg_get_constraintdef_string(foundObject.objectId);
5705 * Put NORMAL dependencies at the front of the list and
5706 * AUTO dependencies at the back. This makes sure that
5707 * foreign-key constraints depending on this column will
5708 * be dropped before unique or primary-key constraints of
5709 * the column; which we must have because the FK
5710 * constraints depend on the indexes belonging to the
5711 * unique constraints.
5713 if (foundDep->deptype == DEPENDENCY_NORMAL)
5715 tab->changedConstraintOids =
5716 lcons_oid(foundObject.objectId,
5717 tab->changedConstraintOids);
5718 tab->changedConstraintDefs =
5720 tab->changedConstraintDefs);
5724 tab->changedConstraintOids =
5725 lappend_oid(tab->changedConstraintOids,
5726 foundObject.objectId);
5727 tab->changedConstraintDefs =
5728 lappend(tab->changedConstraintDefs,
5734 case OCLASS_REWRITE:
5735 /* XXX someday see if we can cope with revising views */
5737 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5738 errmsg("cannot alter type of a column used by a view or rule"),
5739 errdetail("%s depends on column \"%s\"",
5740 getObjectDescription(&foundObject),
5744 case OCLASS_DEFAULT:
5747 * Ignore the column's default expression, since we will fix
5750 Assert(defaultexpr);
5756 case OCLASS_CONVERSION:
5757 case OCLASS_LANGUAGE:
5758 case OCLASS_OPERATOR:
5759 case OCLASS_OPCLASS:
5760 case OCLASS_OPFAMILY:
5761 case OCLASS_TRIGGER:
5763 case OCLASS_TSPARSER:
5765 case OCLASS_TSTEMPLATE:
5766 case OCLASS_TSCONFIG:
5769 * We don't expect any of these sorts of objects to depend on
5772 elog(ERROR, "unexpected object depending on column: %s",
5773 getObjectDescription(&foundObject));
5777 elog(ERROR, "unrecognized object class: %u",
5778 foundObject.classId);
5782 systable_endscan(scan);
5785 * Now scan for dependencies of this column on other things. The only
5786 * thing we should find is the dependency on the column datatype, which we
5789 ScanKeyInit(&key[0],
5790 Anum_pg_depend_classid,
5791 BTEqualStrategyNumber, F_OIDEQ,
5792 ObjectIdGetDatum(RelationRelationId));
5793 ScanKeyInit(&key[1],
5794 Anum_pg_depend_objid,
5795 BTEqualStrategyNumber, F_OIDEQ,
5796 ObjectIdGetDatum(RelationGetRelid(rel)));
5797 ScanKeyInit(&key[2],
5798 Anum_pg_depend_objsubid,
5799 BTEqualStrategyNumber, F_INT4EQ,
5800 Int32GetDatum((int32) attnum));
5802 scan = systable_beginscan(depRel, DependDependerIndexId, true,
5803 SnapshotNow, 3, key);
5805 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5807 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5809 if (foundDep->deptype != DEPENDENCY_NORMAL)
5810 elog(ERROR, "found unexpected dependency type '%c'",
5812 if (foundDep->refclassid != TypeRelationId ||
5813 foundDep->refobjid != attTup->atttypid)
5814 elog(ERROR, "found unexpected dependency for column");
5816 simple_heap_delete(depRel, &depTup->t_self);
5819 systable_endscan(scan);
5821 heap_close(depRel, RowExclusiveLock);
5824 * Here we go --- change the recorded column type. (Note heapTup is a
5825 * copy of the syscache entry, so okay to scribble on.)
5827 attTup->atttypid = targettype;
5828 attTup->atttypmod = targettypmod;
5829 attTup->attndims = list_length(typename->arrayBounds);
5830 attTup->attlen = tform->typlen;
5831 attTup->attbyval = tform->typbyval;
5832 attTup->attalign = tform->typalign;
5833 attTup->attstorage = tform->typstorage;
5835 ReleaseSysCache(typeTuple);
5837 simple_heap_update(attrelation, &heapTup->t_self, heapTup);
5839 /* keep system catalog indexes current */
5840 CatalogUpdateIndexes(attrelation, heapTup);
5842 heap_close(attrelation, RowExclusiveLock);
5844 /* Install dependency on new datatype */
5845 add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
5848 * Drop any pg_statistic entry for the column, since it's now wrong type
5850 RemoveStatistics(RelationGetRelid(rel), attnum);
5853 * Update the default, if present, by brute force --- remove and re-add
5854 * the default. Probably unsafe to take shortcuts, since the new version
5855 * may well have additional dependencies. (It's okay to do this now,
5856 * rather than after other ALTER TYPE commands, since the default won't
5857 * depend on other column types.)
5861 /* Must make new row visible since it will be updated again */
5862 CommandCounterIncrement();
5865 * We use RESTRICT here for safety, but at present we do not expect
5866 * anything to depend on the default.
5868 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true);
5870 StoreAttrDefault(rel, attnum, defaultexpr);
5874 heap_freetuple(heapTup);
5878 * Cleanup after we've finished all the ALTER TYPE operations for a
5879 * particular relation. We have to drop and recreate all the indexes
5880 * and constraints that depend on the altered columns.
5883 ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab)
5889 * Re-parse the index and constraint definitions, and attach them to the
5890 * appropriate work queue entries. We do this before dropping because in
5891 * the case of a FOREIGN KEY constraint, we might not yet have exclusive
5892 * lock on the table the constraint is attached to, and we need to get
5893 * that before dropping. It's safe because the parser won't actually look
5894 * at the catalogs to detect the existing entry.
5896 foreach(l, tab->changedIndexDefs)
5897 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
5898 foreach(l, tab->changedConstraintDefs)
5899 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
5902 * Now we can drop the existing constraints and indexes --- constraints
5903 * first, since some of them might depend on the indexes. In fact, we
5904 * have to delete FOREIGN KEY constraints before UNIQUE constraints, but
5905 * we already ordered the constraint list to ensure that would happen. It
5906 * should be okay to use DROP_RESTRICT here, since nothing else should be
5907 * depending on these objects.
5909 foreach(l, tab->changedConstraintOids)
5911 obj.classId = ConstraintRelationId;
5912 obj.objectId = lfirst_oid(l);
5913 obj.objectSubId = 0;
5914 performDeletion(&obj, DROP_RESTRICT);
5917 foreach(l, tab->changedIndexOids)
5919 obj.classId = RelationRelationId;
5920 obj.objectId = lfirst_oid(l);
5921 obj.objectSubId = 0;
5922 performDeletion(&obj, DROP_RESTRICT);
5926 * The objects will get recreated during subsequent passes over the work
5932 ATPostAlterTypeParse(char *cmd, List **wqueue)
5934 List *raw_parsetree_list;
5935 List *querytree_list;
5936 ListCell *list_item;
5939 * We expect that we will get only ALTER TABLE and CREATE INDEX
5940 * statements. Hence, there is no need to pass them through
5941 * parse_analyze() or the rewriter, but instead we need to pass them
5942 * through parse_utilcmd.c to make them ready for execution.
5944 raw_parsetree_list = raw_parser(cmd);
5945 querytree_list = NIL;
5946 foreach(list_item, raw_parsetree_list)
5948 Node *stmt = (Node *) lfirst(list_item);
5950 if (IsA(stmt, IndexStmt))
5951 querytree_list = lappend(querytree_list,
5952 transformIndexStmt((IndexStmt *) stmt,
5954 else if (IsA(stmt, AlterTableStmt))
5955 querytree_list = list_concat(querytree_list,
5956 transformAlterTableStmt((AlterTableStmt *) stmt,
5959 querytree_list = lappend(querytree_list, stmt);
5963 * Attach each generated command to the proper place in the work queue.
5964 * Note this could result in creation of entirely new work-queue entries.
5966 foreach(list_item, querytree_list)
5968 Node *stm = (Node *) lfirst(list_item);
5970 AlteredTableInfo *tab;
5972 switch (nodeTag(stm))
5976 IndexStmt *stmt = (IndexStmt *) stm;
5977 AlterTableCmd *newcmd;
5979 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
5980 tab = ATGetQueueEntry(wqueue, rel);
5981 newcmd = makeNode(AlterTableCmd);
5982 newcmd->subtype = AT_ReAddIndex;
5983 newcmd->def = (Node *) stmt;
5984 tab->subcmds[AT_PASS_OLD_INDEX] =
5985 lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
5986 relation_close(rel, NoLock);
5989 case T_AlterTableStmt:
5991 AlterTableStmt *stmt = (AlterTableStmt *) stm;
5994 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
5995 tab = ATGetQueueEntry(wqueue, rel);
5996 foreach(lcmd, stmt->cmds)
5998 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
6000 switch (cmd->subtype)
6003 cmd->subtype = AT_ReAddIndex;
6004 tab->subcmds[AT_PASS_OLD_INDEX] =
6005 lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
6007 case AT_AddConstraint:
6008 tab->subcmds[AT_PASS_OLD_CONSTR] =
6009 lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
6012 elog(ERROR, "unexpected statement type: %d",
6013 (int) cmd->subtype);
6016 relation_close(rel, NoLock);
6020 elog(ERROR, "unexpected statement type: %d",
6021 (int) nodeTag(stm));
6030 * recursing is true if we are recursing from a table to its indexes,
6031 * sequences, or toast table. We don't allow the ownership of those things to
6032 * be changed separately from the parent table. Also, we can skip permission
6033 * checks (this is necessary not just an optimization, else we'd fail to
6034 * handle toast tables properly).
6036 * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
6037 * free-standing composite type.
6040 ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing)
6042 Relation target_rel;
6045 Form_pg_class tuple_class;
6048 * Get exclusive lock till end of transaction on the target table. Use
6049 * relation_open so that we can work on indexes and sequences.
6051 target_rel = relation_open(relationOid, AccessExclusiveLock);
6053 /* Get its pg_class tuple, too */
6054 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
6056 tuple = SearchSysCache(RELOID,
6057 ObjectIdGetDatum(relationOid),
6059 if (!HeapTupleIsValid(tuple))
6060 elog(ERROR, "cache lookup failed for relation %u", relationOid);
6061 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
6063 /* Can we change the ownership of this tuple? */
6064 switch (tuple_class->relkind)
6066 case RELKIND_RELATION:
6068 /* ok to change owner */
6074 * Because ALTER INDEX OWNER used to be allowed, and in fact
6075 * is generated by old versions of pg_dump, we give a warning
6076 * and do nothing rather than erroring out. Also, to avoid
6077 * unnecessary chatter while restoring those old dumps, say
6078 * nothing at all if the command would be a no-op anyway.
6080 if (tuple_class->relowner != newOwnerId)
6082 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6083 errmsg("cannot change owner of index \"%s\"",
6084 NameStr(tuple_class->relname)),
6085 errhint("Change the ownership of the index's table, instead.")));
6086 /* quick hack to exit via the no-op path */
6087 newOwnerId = tuple_class->relowner;
6090 case RELKIND_SEQUENCE:
6092 tuple_class->relowner != newOwnerId)
6094 /* if it's an owned sequence, disallow changing it by itself */
6098 if (sequenceIsOwned(relationOid, &tableId, &colId))
6100 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6101 errmsg("cannot change owner of sequence \"%s\"",
6102 NameStr(tuple_class->relname)),
6103 errdetail("Sequence \"%s\" is linked to table \"%s\".",
6104 NameStr(tuple_class->relname),
6105 get_rel_name(tableId))));
6108 case RELKIND_COMPOSITE_TYPE:
6112 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6113 errmsg("\"%s\" is a composite type",
6114 NameStr(tuple_class->relname)),
6115 errhint("Use ALTER TYPE instead.")));
6117 case RELKIND_TOASTVALUE:
6123 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6124 errmsg("\"%s\" is not a table, view, or sequence",
6125 NameStr(tuple_class->relname))));
6129 * If the new owner is the same as the existing owner, consider the
6130 * command to have succeeded. This is for dump restoration purposes.
6132 if (tuple_class->relowner != newOwnerId)
6134 Datum repl_val[Natts_pg_class];
6135 char repl_null[Natts_pg_class];
6136 char repl_repl[Natts_pg_class];
6142 /* skip permission checks when recursing to index or toast table */
6145 /* Superusers can always do it */
6148 Oid namespaceOid = tuple_class->relnamespace;
6149 AclResult aclresult;
6151 /* Otherwise, must be owner of the existing object */
6152 if (!pg_class_ownercheck(relationOid, GetUserId()))
6153 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
6154 RelationGetRelationName(target_rel));
6156 /* Must be able to become new owner */
6157 check_is_member_of_role(GetUserId(), newOwnerId);
6159 /* New owner must have CREATE privilege on namespace */
6160 aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
6162 if (aclresult != ACLCHECK_OK)
6163 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
6164 get_namespace_name(namespaceOid));
6168 memset(repl_null, ' ', sizeof(repl_null));
6169 memset(repl_repl, ' ', sizeof(repl_repl));
6171 repl_repl[Anum_pg_class_relowner - 1] = 'r';
6172 repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
6175 * Determine the modified ACL for the new owner. This is only
6176 * necessary when the ACL is non-null.
6178 aclDatum = SysCacheGetAttr(RELOID, tuple,
6179 Anum_pg_class_relacl,
6183 newAcl = aclnewowner(DatumGetAclP(aclDatum),
6184 tuple_class->relowner, newOwnerId);
6185 repl_repl[Anum_pg_class_relacl - 1] = 'r';
6186 repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
6189 newtuple = heap_modifytuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
6191 simple_heap_update(class_rel, &newtuple->t_self, newtuple);
6192 CatalogUpdateIndexes(class_rel, newtuple);
6194 heap_freetuple(newtuple);
6197 * Update owner dependency reference, if any. A composite type has
6198 * none, because it's tracked for the pg_type entry instead of here;
6199 * indexes and TOAST tables don't have their own entries either.
6201 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
6202 tuple_class->relkind != RELKIND_INDEX &&
6203 tuple_class->relkind != RELKIND_TOASTVALUE)
6204 changeDependencyOnOwner(RelationRelationId, relationOid,
6208 * Also change the ownership of the table's rowtype, if it has one
6210 if (tuple_class->relkind != RELKIND_INDEX)
6211 AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId,
6212 tuple_class->relkind == RELKIND_COMPOSITE_TYPE);
6215 * If we are operating on a table, also change the ownership of any
6216 * indexes and sequences that belong to the table, as well as the
6217 * table's toast table (if it has one)
6219 if (tuple_class->relkind == RELKIND_RELATION ||
6220 tuple_class->relkind == RELKIND_TOASTVALUE)
6222 List *index_oid_list;
6225 /* Find all the indexes belonging to this relation */
6226 index_oid_list = RelationGetIndexList(target_rel);
6228 /* For each index, recursively change its ownership */
6229 foreach(i, index_oid_list)
6230 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true);
6232 list_free(index_oid_list);
6235 if (tuple_class->relkind == RELKIND_RELATION)
6237 /* If it has a toast table, recurse to change its ownership */
6238 if (tuple_class->reltoastrelid != InvalidOid)
6239 ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
6242 /* If it has dependent sequences, recurse to change them too */
6243 change_owner_recurse_to_sequences(relationOid, newOwnerId);
6247 ReleaseSysCache(tuple);
6248 heap_close(class_rel, RowExclusiveLock);
6249 relation_close(target_rel, NoLock);
6253 * change_owner_recurse_to_sequences
6255 * Helper function for ATExecChangeOwner. Examines pg_depend searching
6256 * for sequences that are dependent on serial columns, and changes their
6260 change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId)
6268 * SERIAL sequences are those having an auto dependency on one of the
6269 * table's columns (we don't care *which* column, exactly).
6271 depRel = heap_open(DependRelationId, AccessShareLock);
6273 ScanKeyInit(&key[0],
6274 Anum_pg_depend_refclassid,
6275 BTEqualStrategyNumber, F_OIDEQ,
6276 ObjectIdGetDatum(RelationRelationId));
6277 ScanKeyInit(&key[1],
6278 Anum_pg_depend_refobjid,
6279 BTEqualStrategyNumber, F_OIDEQ,
6280 ObjectIdGetDatum(relationOid));
6281 /* we leave refobjsubid unspecified */
6283 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
6284 SnapshotNow, 2, key);
6286 while (HeapTupleIsValid(tup = systable_getnext(scan)))
6288 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
6291 /* skip dependencies other than auto dependencies on columns */
6292 if (depForm->refobjsubid == 0 ||
6293 depForm->classid != RelationRelationId ||
6294 depForm->objsubid != 0 ||
6295 depForm->deptype != DEPENDENCY_AUTO)
6298 /* Use relation_open just in case it's an index */
6299 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
6301 /* skip non-sequence relations */
6302 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
6304 /* No need to keep the lock */
6305 relation_close(seqRel, AccessExclusiveLock);
6309 /* We don't need to close the sequence while we alter it. */
6310 ATExecChangeOwner(depForm->objid, newOwnerId, true);
6312 /* Now we can close it. Keep the lock till end of transaction. */
6313 relation_close(seqRel, NoLock);
6316 systable_endscan(scan);
6318 relation_close(depRel, AccessShareLock);
6322 * ALTER TABLE CLUSTER ON
6324 * The only thing we have to do is to change the indisclustered bits.
6327 ATExecClusterOn(Relation rel, const char *indexName)
6331 indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
6333 if (!OidIsValid(indexOid))
6335 (errcode(ERRCODE_UNDEFINED_OBJECT),
6336 errmsg("index \"%s\" for table \"%s\" does not exist",
6337 indexName, RelationGetRelationName(rel))));
6339 /* Check index is valid to cluster on */
6340 check_index_is_clusterable(rel, indexOid, false);
6342 /* And do the work */
6343 mark_index_clustered(rel, indexOid);
6347 * ALTER TABLE SET WITHOUT CLUSTER
6349 * We have to find any indexes on the table that have indisclustered bit
6350 * set and turn it off.
6353 ATExecDropCluster(Relation rel)
6355 mark_index_clustered(rel, InvalidOid);
6359 * ALTER TABLE SET TABLESPACE
6362 ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, char *tablespacename)
6365 AclResult aclresult;
6367 /* Check that the tablespace exists */
6368 tablespaceId = get_tablespace_oid(tablespacename);
6369 if (!OidIsValid(tablespaceId))
6371 (errcode(ERRCODE_UNDEFINED_OBJECT),
6372 errmsg("tablespace \"%s\" does not exist", tablespacename)));
6374 /* Check its permissions */
6375 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(), ACL_CREATE);
6376 if (aclresult != ACLCHECK_OK)
6377 aclcheck_error(aclresult, ACL_KIND_TABLESPACE, tablespacename);
6379 /* Save info for Phase 3 to do the real work */
6380 if (OidIsValid(tab->newTableSpace))
6382 (errcode(ERRCODE_SYNTAX_ERROR),
6383 errmsg("cannot have multiple SET TABLESPACE subcommands")));
6384 tab->newTableSpace = tablespaceId;
6388 * ALTER TABLE/INDEX SET (...) or RESET (...)
6391 ATExecSetRelOptions(Relation rel, List *defList, bool isReset)
6400 Datum repl_val[Natts_pg_class];
6401 char repl_null[Natts_pg_class];
6402 char repl_repl[Natts_pg_class];
6405 return; /* nothing to do */
6407 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
6409 /* Get the old reloptions */
6410 relid = RelationGetRelid(rel);
6411 tuple = SearchSysCache(RELOID,
6412 ObjectIdGetDatum(relid),
6414 if (!HeapTupleIsValid(tuple))
6415 elog(ERROR, "cache lookup failed for relation %u", relid);
6417 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions, &isnull);
6419 /* Generate new proposed reloptions (text array) */
6420 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
6421 defList, false, isReset);
6424 switch (rel->rd_rel->relkind)
6426 case RELKIND_RELATION:
6427 case RELKIND_TOASTVALUE:
6428 (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
6431 (void) index_reloptions(rel->rd_am->amoptions, newOptions, true);
6435 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6436 errmsg("\"%s\" is not a table, index, or TOAST table",
6437 RelationGetRelationName(rel))));
6442 * All we need do here is update the pg_class row; the new options will be
6443 * propagated into relcaches during post-commit cache inval.
6445 memset(repl_val, 0, sizeof(repl_val));
6446 memset(repl_null, ' ', sizeof(repl_null));
6447 memset(repl_repl, ' ', sizeof(repl_repl));
6449 if (newOptions != (Datum) 0)
6450 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
6452 repl_null[Anum_pg_class_reloptions - 1] = 'n';
6454 repl_repl[Anum_pg_class_reloptions - 1] = 'r';
6456 newtuple = heap_modifytuple(tuple, RelationGetDescr(pgclass),
6457 repl_val, repl_null, repl_repl);
6459 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
6461 CatalogUpdateIndexes(pgclass, newtuple);
6463 heap_freetuple(newtuple);
6465 ReleaseSysCache(tuple);
6467 heap_close(pgclass, RowExclusiveLock);
6471 * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
6472 * rewriting to be done, so we just want to copy the data as fast as possible.
6475 ATExecSetTableSpace(Oid tableOid, Oid newTableSpace)
6481 RelFileNode newrnode;
6482 SMgrRelation dstrel;
6485 Form_pg_class rd_rel;
6488 * Need lock here in case we are recursing to toast table or index
6490 rel = relation_open(tableOid, AccessExclusiveLock);
6493 * We can never allow moving of shared or nailed-in-cache relations,
6494 * because we can't support changing their reltablespace values.
6496 if (rel->rd_rel->relisshared || rel->rd_isnailed)
6498 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6499 errmsg("cannot move system relation \"%s\"",
6500 RelationGetRelationName(rel))));
6502 /* Can't move a non-shared relation into pg_global */
6503 if (newTableSpace == GLOBALTABLESPACE_OID)
6505 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6506 errmsg("only shared relations can be placed in pg_global tablespace")));
6509 * Don't allow moving temp tables of other backends ... their local buffer
6510 * manager is not going to cope.
6512 if (isOtherTempNamespace(RelationGetNamespace(rel)))
6514 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6515 errmsg("cannot move temporary tables of other sessions")));
6518 * No work if no change in tablespace.
6520 oldTableSpace = rel->rd_rel->reltablespace;
6521 if (newTableSpace == oldTableSpace ||
6522 (newTableSpace == MyDatabaseTableSpace && oldTableSpace == 0))
6524 relation_close(rel, NoLock);
6528 reltoastrelid = rel->rd_rel->reltoastrelid;
6529 reltoastidxid = rel->rd_rel->reltoastidxid;
6531 /* Get a modifiable copy of the relation's pg_class row */
6532 pg_class = heap_open(RelationRelationId, RowExclusiveLock);
6534 tuple = SearchSysCacheCopy(RELOID,
6535 ObjectIdGetDatum(tableOid),
6537 if (!HeapTupleIsValid(tuple))
6538 elog(ERROR, "cache lookup failed for relation %u", tableOid);
6539 rd_rel = (Form_pg_class) GETSTRUCT(tuple);
6541 /* create another storage file. Is it a little ugly ? */
6542 /* NOTE: any conflict in relfilenode value will be caught here */
6543 newrnode = rel->rd_node;
6544 newrnode.spcNode = newTableSpace;
6546 dstrel = smgropen(newrnode);
6547 smgrcreate(dstrel, rel->rd_istemp, false);
6549 /* copy relation data to the new physical file */
6550 copy_relation_data(rel, dstrel);
6552 /* schedule unlinking old physical file */
6553 RelationOpenSmgr(rel);
6554 smgrscheduleunlink(rel->rd_smgr, rel->rd_istemp);
6557 * Now drop smgr references. The source was already dropped by
6558 * smgrscheduleunlink.
6562 /* update the pg_class row */
6563 rd_rel->reltablespace = (newTableSpace == MyDatabaseTableSpace) ? InvalidOid : newTableSpace;
6564 simple_heap_update(pg_class, &tuple->t_self, tuple);
6565 CatalogUpdateIndexes(pg_class, tuple);
6567 heap_freetuple(tuple);
6569 heap_close(pg_class, RowExclusiveLock);
6571 relation_close(rel, NoLock);
6573 /* Make sure the reltablespace change is visible */
6574 CommandCounterIncrement();
6576 /* Move associated toast relation and/or index, too */
6577 if (OidIsValid(reltoastrelid))
6578 ATExecSetTableSpace(reltoastrelid, newTableSpace);
6579 if (OidIsValid(reltoastidxid))
6580 ATExecSetTableSpace(reltoastidxid, newTableSpace);
6584 * Copy data, block by block
6587 copy_relation_data(Relation rel, SMgrRelation dst)
6591 BlockNumber nblocks;
6594 Page page = (Page) buf;
6597 * Since we copy the file directly without looking at the shared buffers,
6598 * we'd better first flush out any pages of the source relation that are
6599 * in shared buffers. We assume no new changes will be made while we are
6600 * holding exclusive lock on the rel.
6602 FlushRelationBuffers(rel);
6605 * We need to log the copied data in WAL iff WAL archiving is enabled AND
6606 * it's not a temp rel.
6608 use_wal = XLogArchivingActive() && !rel->rd_istemp;
6610 nblocks = RelationGetNumberOfBlocks(rel);
6611 /* RelationGetNumberOfBlocks will certainly have opened rd_smgr */
6614 for (blkno = 0; blkno < nblocks; blkno++)
6616 smgrread(src, blkno, buf);
6620 log_newpage(&dst->smgr_rnode, blkno, page);
6623 * Now write the page. We say isTemp = true even if it's not a temp
6624 * rel, because there's no need for smgr to schedule an fsync for this
6625 * write; we'll do it ourselves below.
6627 smgrextend(dst, blkno, buf, true);
6631 * If the rel isn't temp, we must fsync it down to disk before it's safe
6632 * to commit the transaction. (For a temp rel we don't care since the rel
6633 * will be uninteresting after a crash anyway.)
6635 * It's obvious that we must do this when not WAL-logging the copy. It's
6636 * less obvious that we have to do it even if we did WAL-log the copied
6637 * pages. The reason is that since we're copying outside shared buffers, a
6638 * CHECKPOINT occurring during the copy has no way to flush the previously
6639 * written data to disk (indeed it won't know the new rel even exists). A
6640 * crash later on would replay WAL from the checkpoint, therefore it
6641 * wouldn't replay our earlier WAL entries. If we do not fsync those pages
6642 * here, they might still not be on disk when the crash occurs.
6644 if (!rel->rd_istemp)
6649 * ALTER TABLE ENABLE/DISABLE TRIGGER
6651 * We just pass this off to trigger.c.
6654 ATExecEnableDisableTrigger(Relation rel, char *trigname,
6655 char fires_when, bool skip_system)
6657 EnableDisableTrigger(rel, trigname, fires_when, skip_system);
6661 * ALTER TABLE ENABLE/DISABLE RULE
6663 * We just pass this off to rewriteDefine.c.
6666 ATExecEnableDisableRule(Relation rel, char *trigname,
6669 EnableDisableRule(rel, trigname, fires_when);
6673 * ALTER TABLE INHERIT
6675 * Add a parent to the child's parents. This verifies that all the columns and
6676 * check constraints of the parent appear in the child and that they have the
6677 * same data types and expressions.
6680 ATExecAddInherit(Relation child_rel, RangeVar *parent)
6682 Relation parent_rel,
6686 HeapTuple inheritsTuple;
6691 * AccessShareLock on the parent is what's obtained during normal CREATE
6692 * TABLE ... INHERITS ..., so should be enough here.
6694 parent_rel = heap_openrv(parent, AccessShareLock);
6697 * Must be owner of both parent and child -- child was checked by
6698 * ATSimplePermissions call in ATPrepCmd
6700 ATSimplePermissions(parent_rel, false);
6702 /* Permanent rels cannot inherit from temporary ones */
6703 if (!isTempNamespace(RelationGetNamespace(child_rel)) &&
6704 isTempNamespace(RelationGetNamespace(parent_rel)))
6706 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6707 errmsg("cannot inherit from temporary relation \"%s\"",
6708 RelationGetRelationName(parent_rel))));
6711 * Check for duplicates in the list of parents, and determine the highest
6712 * inhseqno already present; we'll use the next one for the new parent.
6713 * (Note: get RowExclusiveLock because we will write pg_inherits below.)
6715 * Note: we do not reject the case where the child already inherits from
6716 * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
6718 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
6720 Anum_pg_inherits_inhrelid,
6721 BTEqualStrategyNumber, F_OIDEQ,
6722 ObjectIdGetDatum(RelationGetRelid(child_rel)));
6723 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
6724 true, SnapshotNow, 1, &key);
6726 /* inhseqno sequences start at 1 */
6728 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
6730 Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
6732 if (inh->inhparent == RelationGetRelid(parent_rel))
6734 (errcode(ERRCODE_DUPLICATE_TABLE),
6735 errmsg("relation \"%s\" would be inherited from more than once",
6736 RelationGetRelationName(parent_rel))));
6737 if (inh->inhseqno > inhseqno)
6738 inhseqno = inh->inhseqno;
6740 systable_endscan(scan);
6743 * Prevent circularity by seeing if proposed parent inherits from child.
6744 * (In particular, this disallows making a rel inherit from itself.)
6746 * This is not completely bulletproof because of race conditions: in
6747 * multi-level inheritance trees, someone else could concurrently be
6748 * making another inheritance link that closes the loop but does not join
6749 * either of the rels we have locked. Preventing that seems to require
6750 * exclusive locks on the entire inheritance tree, which is a cure worse
6751 * than the disease. find_all_inheritors() will cope with circularity
6752 * anyway, so don't sweat it too much.
6754 children = find_all_inheritors(RelationGetRelid(child_rel));
6756 if (list_member_oid(children, RelationGetRelid(parent_rel)))
6758 (errcode(ERRCODE_DUPLICATE_TABLE),
6759 errmsg("circular inheritance not allowed"),
6760 errdetail("\"%s\" is already a child of \"%s\".",
6762 RelationGetRelationName(child_rel))));
6764 /* If parent has OIDs then child must have OIDs */
6765 if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
6767 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6768 errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
6769 RelationGetRelationName(child_rel),
6770 RelationGetRelationName(parent_rel))));
6772 /* Match up the columns and bump attinhcount as needed */
6773 MergeAttributesIntoExisting(child_rel, parent_rel);
6775 /* Match up the constraints and bump coninhcount as needed */
6776 MergeConstraintsIntoExisting(child_rel, parent_rel);
6779 * OK, it looks valid. Make the catalog entries that show inheritance.
6781 StoreCatalogInheritance1(RelationGetRelid(child_rel),
6782 RelationGetRelid(parent_rel),
6786 /* Now we're done with pg_inherits */
6787 heap_close(catalogRelation, RowExclusiveLock);
6789 /* keep our lock on the parent relation until commit */
6790 heap_close(parent_rel, NoLock);
6794 * Obtain the source-text form of the constraint expression for a check
6795 * constraint, given its pg_constraint tuple
6798 decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
6800 Form_pg_constraint con;
6805 con = (Form_pg_constraint) GETSTRUCT(contup);
6806 attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
6808 elog(ERROR, "null conbin for constraint %u", HeapTupleGetOid(contup));
6810 expr = DirectFunctionCall2(pg_get_expr, attr,
6811 ObjectIdGetDatum(con->conrelid));
6812 return TextDatumGetCString(expr);
6816 * Determine whether two check constraints are functionally equivalent
6818 * The test we apply is to see whether they reverse-compile to the same
6819 * source string. This insulates us from issues like whether attributes
6820 * have the same physical column numbers in parent and child relations.
6823 constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
6825 Form_pg_constraint acon = (Form_pg_constraint) GETSTRUCT(a);
6826 Form_pg_constraint bcon = (Form_pg_constraint) GETSTRUCT(b);
6828 if (acon->condeferrable != bcon->condeferrable ||
6829 acon->condeferred != bcon->condeferred ||
6830 strcmp(decompile_conbin(a, tupleDesc),
6831 decompile_conbin(b, tupleDesc)) != 0)
6838 * Check columns in child table match up with columns in parent, and increment
6839 * their attinhcount.
6841 * Called by ATExecAddInherit
6843 * Currently all parent columns must be found in child. Missing columns are an
6844 * error. One day we might consider creating new columns like CREATE TABLE
6845 * does. However, that is widely unpopular --- in the common use case of
6846 * partitioned tables it's a foot-gun.
6848 * The data type must match exactly. If the parent column is NOT NULL then
6849 * the child must be as well. Defaults are not compared, however.
6852 MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel)
6855 AttrNumber parent_attno;
6857 TupleDesc tupleDesc;
6858 TupleConstr *constr;
6861 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
6863 tupleDesc = RelationGetDescr(parent_rel);
6864 parent_natts = tupleDesc->natts;
6865 constr = tupleDesc->constr;
6867 for (parent_attno = 1; parent_attno <= parent_natts; parent_attno++)
6869 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
6870 char *attributeName = NameStr(attribute->attname);
6872 /* Ignore dropped columns in the parent. */
6873 if (attribute->attisdropped)
6876 /* Find same column in child (matching on column name). */
6877 tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel),
6879 if (HeapTupleIsValid(tuple))
6881 /* Check they are same type and typmod */
6882 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
6884 if (attribute->atttypid != childatt->atttypid ||
6885 attribute->atttypmod != childatt->atttypmod)
6887 (errcode(ERRCODE_DATATYPE_MISMATCH),
6888 errmsg("child table \"%s\" has different type for column \"%s\"",
6889 RelationGetRelationName(child_rel),
6892 if (attribute->attnotnull && !childatt->attnotnull)
6894 (errcode(ERRCODE_DATATYPE_MISMATCH),
6895 errmsg("column \"%s\" in child table must be marked NOT NULL",
6899 * OK, bump the child column's inheritance count. (If we fail
6900 * later on, this change will just roll back.)
6902 childatt->attinhcount++;
6903 simple_heap_update(attrrel, &tuple->t_self, tuple);
6904 CatalogUpdateIndexes(attrrel, tuple);
6905 heap_freetuple(tuple);
6910 (errcode(ERRCODE_DATATYPE_MISMATCH),
6911 errmsg("child table is missing column \"%s\"",
6916 heap_close(attrrel, RowExclusiveLock);
6920 * Check constraints in child table match up with constraints in parent,
6921 * and increment their coninhcount.
6923 * Called by ATExecAddInherit
6925 * Currently all constraints in parent must be present in the child. One day we
6926 * may consider adding new constraints like CREATE TABLE does. We may also want
6927 * to allow an optional flag on parent table constraints indicating they are
6928 * intended to ONLY apply to the master table, not to the children. That would
6929 * make it possible to ensure no records are mistakenly inserted into the
6930 * master in partitioned tables rather than the appropriate child.
6932 * XXX This is O(N^2) which may be an issue with tables with hundreds of
6933 * constraints. As long as tables have more like 10 constraints it shouldn't be
6934 * a problem though. Even 100 constraints ought not be the end of the world.
6937 MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
6939 Relation catalog_relation;
6940 TupleDesc tuple_desc;
6941 SysScanDesc parent_scan;
6942 ScanKeyData parent_key;
6943 HeapTuple parent_tuple;
6945 catalog_relation = heap_open(ConstraintRelationId, RowExclusiveLock);
6946 tuple_desc = RelationGetDescr(catalog_relation);
6948 /* Outer loop scans through the parent's constraint definitions */
6949 ScanKeyInit(&parent_key,
6950 Anum_pg_constraint_conrelid,
6951 BTEqualStrategyNumber, F_OIDEQ,
6952 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
6953 parent_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
6954 true, SnapshotNow, 1, &parent_key);
6956 while (HeapTupleIsValid(parent_tuple = systable_getnext(parent_scan)))
6958 Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(parent_tuple);
6959 SysScanDesc child_scan;
6960 ScanKeyData child_key;
6961 HeapTuple child_tuple;
6964 if (parent_con->contype != CONSTRAINT_CHECK)
6967 /* Search for a child constraint matching this one */
6968 ScanKeyInit(&child_key,
6969 Anum_pg_constraint_conrelid,
6970 BTEqualStrategyNumber, F_OIDEQ,
6971 ObjectIdGetDatum(RelationGetRelid(child_rel)));
6972 child_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
6973 true, SnapshotNow, 1, &child_key);
6975 while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
6977 Form_pg_constraint child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
6978 HeapTuple child_copy;
6980 if (child_con->contype != CONSTRAINT_CHECK)
6983 if (strcmp(NameStr(parent_con->conname),
6984 NameStr(child_con->conname)) != 0)
6987 if (!constraints_equivalent(parent_tuple, child_tuple, tuple_desc))
6989 (errcode(ERRCODE_DATATYPE_MISMATCH),
6990 errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
6991 RelationGetRelationName(child_rel),
6992 NameStr(parent_con->conname))));
6995 * OK, bump the child constraint's inheritance count. (If we fail
6996 * later on, this change will just roll back.)
6998 child_copy = heap_copytuple(child_tuple);
6999 child_con = (Form_pg_constraint) GETSTRUCT(child_copy);
7000 child_con->coninhcount++;
7001 simple_heap_update(catalog_relation, &child_copy->t_self, child_copy);
7002 CatalogUpdateIndexes(catalog_relation, child_copy);
7003 heap_freetuple(child_copy);
7009 systable_endscan(child_scan);
7013 (errcode(ERRCODE_DATATYPE_MISMATCH),
7014 errmsg("child table is missing constraint \"%s\"",
7015 NameStr(parent_con->conname))));
7018 systable_endscan(parent_scan);
7019 heap_close(catalog_relation, RowExclusiveLock);
7023 * ALTER TABLE NO INHERIT
7025 * Drop a parent from the child's parents. This just adjusts the attinhcount
7026 * and attislocal of the columns and removes the pg_inherit and pg_depend
7029 * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
7030 * up attislocal stays true, which means if a child is ever removed from a
7031 * parent then its columns will never be automatically dropped which may
7032 * surprise. But at least we'll never surprise by dropping columns someone
7033 * isn't expecting to be dropped which would actually mean data loss.
7035 * coninhcount and conislocal for inherited constraints are adjusted in
7036 * exactly the same way.
7039 ATExecDropInherit(Relation rel, RangeVar *parent)
7041 Relation parent_rel;
7042 Relation catalogRelation;
7045 HeapTuple inheritsTuple,
7053 * AccessShareLock on the parent is probably enough, seeing that DROP
7054 * TABLE doesn't lock parent tables at all. We need some lock since we'll
7055 * be inspecting the parent's schema.
7057 parent_rel = heap_openrv(parent, AccessShareLock);
7060 * We don't bother to check ownership of the parent table --- ownership of
7061 * the child is presumed enough rights.
7065 * Find and destroy the pg_inherits entry linking the two, or error out if
7068 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
7069 ScanKeyInit(&key[0],
7070 Anum_pg_inherits_inhrelid,
7071 BTEqualStrategyNumber, F_OIDEQ,
7072 ObjectIdGetDatum(RelationGetRelid(rel)));
7073 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
7074 true, SnapshotNow, 1, key);
7076 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
7080 inhparent = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
7081 if (inhparent == RelationGetRelid(parent_rel))
7083 simple_heap_delete(catalogRelation, &inheritsTuple->t_self);
7089 systable_endscan(scan);
7090 heap_close(catalogRelation, RowExclusiveLock);
7094 (errcode(ERRCODE_UNDEFINED_TABLE),
7095 errmsg("relation \"%s\" is not a parent of relation \"%s\"",
7096 RelationGetRelationName(parent_rel),
7097 RelationGetRelationName(rel))));
7100 * Search through child columns looking for ones matching parent rel
7102 catalogRelation = heap_open(AttributeRelationId, RowExclusiveLock);
7103 ScanKeyInit(&key[0],
7104 Anum_pg_attribute_attrelid,
7105 BTEqualStrategyNumber, F_OIDEQ,
7106 ObjectIdGetDatum(RelationGetRelid(rel)));
7107 scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
7108 true, SnapshotNow, 1, key);
7109 while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
7111 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
7113 /* Ignore if dropped or not inherited */
7114 if (att->attisdropped)
7116 if (att->attinhcount <= 0)
7119 if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
7120 NameStr(att->attname)))
7122 /* Decrement inhcount and possibly set islocal to true */
7123 HeapTuple copyTuple = heap_copytuple(attributeTuple);
7124 Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
7126 copy_att->attinhcount--;
7127 if (copy_att->attinhcount == 0)
7128 copy_att->attislocal = true;
7130 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
7131 CatalogUpdateIndexes(catalogRelation, copyTuple);
7132 heap_freetuple(copyTuple);
7135 systable_endscan(scan);
7136 heap_close(catalogRelation, RowExclusiveLock);
7139 * Likewise, find inherited check constraints and disinherit them.
7140 * To do this, we first need a list of the names of the parent's check
7141 * constraints. (We cheat a bit by only checking for name matches,
7142 * assuming that the expressions will match.)
7144 catalogRelation = heap_open(ConstraintRelationId, RowExclusiveLock);
7145 ScanKeyInit(&key[0],
7146 Anum_pg_constraint_conrelid,
7147 BTEqualStrategyNumber, F_OIDEQ,
7148 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
7149 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
7150 true, SnapshotNow, 1, key);
7154 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
7156 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
7158 if (con->contype == CONSTRAINT_CHECK)
7159 connames = lappend(connames, pstrdup(NameStr(con->conname)));
7162 systable_endscan(scan);
7164 /* Now scan the child's constraints */
7165 ScanKeyInit(&key[0],
7166 Anum_pg_constraint_conrelid,
7167 BTEqualStrategyNumber, F_OIDEQ,
7168 ObjectIdGetDatum(RelationGetRelid(rel)));
7169 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
7170 true, SnapshotNow, 1, key);
7172 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
7174 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
7178 if (con->contype != CONSTRAINT_CHECK)
7182 foreach (lc, connames)
7184 if (strcmp(NameStr(con->conname), (char *) lfirst(lc)) == 0)
7193 /* Decrement inhcount and possibly set islocal to true */
7194 HeapTuple copyTuple = heap_copytuple(constraintTuple);
7195 Form_pg_constraint copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
7196 if (copy_con->coninhcount <= 0) /* shouldn't happen */
7197 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
7198 RelationGetRelid(rel), NameStr(copy_con->conname));
7200 copy_con->coninhcount--;
7201 if (copy_con->coninhcount == 0)
7202 copy_con->conislocal = true;
7204 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
7205 CatalogUpdateIndexes(catalogRelation, copyTuple);
7206 heap_freetuple(copyTuple);
7210 systable_endscan(scan);
7211 heap_close(catalogRelation, RowExclusiveLock);
7214 * Drop the dependency
7216 * There's no convenient way to do this, so go trawling through pg_depend
7218 catalogRelation = heap_open(DependRelationId, RowExclusiveLock);
7220 ScanKeyInit(&key[0],
7221 Anum_pg_depend_classid,
7222 BTEqualStrategyNumber, F_OIDEQ,
7223 ObjectIdGetDatum(RelationRelationId));
7224 ScanKeyInit(&key[1],
7225 Anum_pg_depend_objid,
7226 BTEqualStrategyNumber, F_OIDEQ,
7227 ObjectIdGetDatum(RelationGetRelid(rel)));
7228 ScanKeyInit(&key[2],
7229 Anum_pg_depend_objsubid,
7230 BTEqualStrategyNumber, F_INT4EQ,
7233 scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
7234 SnapshotNow, 3, key);
7236 while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
7238 Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
7240 if (dep->refclassid == RelationRelationId &&
7241 dep->refobjid == RelationGetRelid(parent_rel) &&
7242 dep->refobjsubid == 0 &&
7243 dep->deptype == DEPENDENCY_NORMAL)
7244 simple_heap_delete(catalogRelation, &depTuple->t_self);
7247 systable_endscan(scan);
7248 heap_close(catalogRelation, RowExclusiveLock);
7250 /* keep our lock on the parent relation until commit */
7251 heap_close(parent_rel, NoLock);
7256 * Execute ALTER TABLE SET SCHEMA
7258 * Note: caller must have checked ownership of the relation already
7261 AlterTableNamespace(RangeVar *relation, const char *newschema,
7262 ObjectType stmttype)
7270 rel = relation_openrv(relation, AccessExclusiveLock);
7272 relid = RelationGetRelid(rel);
7273 oldNspOid = RelationGetNamespace(rel);
7275 /* Check relation type against type specified in the ALTER command */
7280 * For mostly-historical reasons, we allow ALTER TABLE to apply
7281 * to all relation types.
7285 case OBJECT_SEQUENCE:
7286 if (rel->rd_rel->relkind != RELKIND_SEQUENCE)
7288 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7289 errmsg("\"%s\" is not a sequence",
7290 RelationGetRelationName(rel))));
7294 if (rel->rd_rel->relkind != RELKIND_VIEW)
7296 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7297 errmsg("\"%s\" is not a view",
7298 RelationGetRelationName(rel))));
7302 elog(ERROR, "unrecognized object type: %d", (int) stmttype);
7305 /* Can we change the schema of this tuple? */
7306 switch (rel->rd_rel->relkind)
7308 case RELKIND_RELATION:
7310 /* ok to change schema */
7312 case RELKIND_SEQUENCE:
7314 /* if it's an owned sequence, disallow moving it by itself */
7318 if (sequenceIsOwned(relid, &tableId, &colId))
7320 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7321 errmsg("cannot move an owned sequence into another schema"),
7322 errdetail("Sequence \"%s\" is linked to table \"%s\".",
7323 RelationGetRelationName(rel),
7324 get_rel_name(tableId))));
7327 case RELKIND_COMPOSITE_TYPE:
7329 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7330 errmsg("\"%s\" is a composite type",
7331 RelationGetRelationName(rel)),
7332 errhint("Use ALTER TYPE instead.")));
7335 case RELKIND_TOASTVALUE:
7339 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7340 errmsg("\"%s\" is not a table, view, or sequence",
7341 RelationGetRelationName(rel))));
7344 /* get schema OID and check its permissions */
7345 nspOid = LookupCreationNamespace(newschema);
7347 if (oldNspOid == nspOid)
7349 (errcode(ERRCODE_DUPLICATE_TABLE),
7350 errmsg("relation \"%s\" is already in schema \"%s\"",
7351 RelationGetRelationName(rel),
7354 /* disallow renaming into or out of temp schemas */
7355 if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
7357 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7358 errmsg("cannot move objects into or out of temporary schemas")));
7360 /* same for TOAST schema */
7361 if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
7363 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7364 errmsg("cannot move objects into or out of TOAST schema")));
7366 /* OK, modify the pg_class row and pg_depend entry */
7367 classRel = heap_open(RelationRelationId, RowExclusiveLock);
7369 AlterRelationNamespaceInternal(classRel, relid, oldNspOid, nspOid, true);
7371 /* Fix the table's rowtype too */
7372 AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid, false, false);
7374 /* Fix other dependent stuff */
7375 if (rel->rd_rel->relkind == RELKIND_RELATION)
7377 AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid);
7378 AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid, newschema);
7379 AlterConstraintNamespaces(relid, oldNspOid, nspOid, false);
7382 heap_close(classRel, RowExclusiveLock);
7384 /* close rel, but keep lock until commit */
7385 relation_close(rel, NoLock);
7389 * The guts of relocating a relation to another namespace: fix the pg_class
7390 * entry, and the pg_depend entry if any. Caller must already have
7391 * opened and write-locked pg_class.
7394 AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
7395 Oid oldNspOid, Oid newNspOid,
7396 bool hasDependEntry)
7399 Form_pg_class classForm;
7401 classTup = SearchSysCacheCopy(RELOID,
7402 ObjectIdGetDatum(relOid),
7404 if (!HeapTupleIsValid(classTup))
7405 elog(ERROR, "cache lookup failed for relation %u", relOid);
7406 classForm = (Form_pg_class) GETSTRUCT(classTup);
7408 Assert(classForm->relnamespace == oldNspOid);
7410 /* check for duplicate name (more friendly than unique-index failure) */
7411 if (get_relname_relid(NameStr(classForm->relname),
7412 newNspOid) != InvalidOid)
7414 (errcode(ERRCODE_DUPLICATE_TABLE),
7415 errmsg("relation \"%s\" already exists in schema \"%s\"",
7416 NameStr(classForm->relname),
7417 get_namespace_name(newNspOid))));
7419 /* classTup is a copy, so OK to scribble on */
7420 classForm->relnamespace = newNspOid;
7422 simple_heap_update(classRel, &classTup->t_self, classTup);
7423 CatalogUpdateIndexes(classRel, classTup);
7425 /* Update dependency on schema if caller said so */
7426 if (hasDependEntry &&
7427 changeDependencyFor(RelationRelationId, relOid,
7428 NamespaceRelationId, oldNspOid, newNspOid) != 1)
7429 elog(ERROR, "failed to change schema dependency for relation \"%s\"",
7430 NameStr(classForm->relname));
7432 heap_freetuple(classTup);
7436 * Move all indexes for the specified relation to another namespace.
7438 * Note: we assume adequate permission checking was done by the caller,
7439 * and that the caller has a suitable lock on the owning relation.
7442 AlterIndexNamespaces(Relation classRel, Relation rel,
7443 Oid oldNspOid, Oid newNspOid)
7448 indexList = RelationGetIndexList(rel);
7450 foreach(l, indexList)
7452 Oid indexOid = lfirst_oid(l);
7455 * Note: currently, the index will not have its own dependency on the
7456 * namespace, so we don't need to do changeDependencyFor(). There's no
7457 * rowtype in pg_type, either.
7459 AlterRelationNamespaceInternal(classRel, indexOid,
7460 oldNspOid, newNspOid,
7464 list_free(indexList);
7468 * Move all SERIAL-column sequences of the specified relation to another
7471 * Note: we assume adequate permission checking was done by the caller,
7472 * and that the caller has a suitable lock on the owning relation.
7475 AlterSeqNamespaces(Relation classRel, Relation rel,
7476 Oid oldNspOid, Oid newNspOid, const char *newNspName)
7484 * SERIAL sequences are those having an auto dependency on one of the
7485 * table's columns (we don't care *which* column, exactly).
7487 depRel = heap_open(DependRelationId, AccessShareLock);
7489 ScanKeyInit(&key[0],
7490 Anum_pg_depend_refclassid,
7491 BTEqualStrategyNumber, F_OIDEQ,
7492 ObjectIdGetDatum(RelationRelationId));
7493 ScanKeyInit(&key[1],
7494 Anum_pg_depend_refobjid,
7495 BTEqualStrategyNumber, F_OIDEQ,
7496 ObjectIdGetDatum(RelationGetRelid(rel)));
7497 /* we leave refobjsubid unspecified */
7499 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
7500 SnapshotNow, 2, key);
7502 while (HeapTupleIsValid(tup = systable_getnext(scan)))
7504 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
7507 /* skip dependencies other than auto dependencies on columns */
7508 if (depForm->refobjsubid == 0 ||
7509 depForm->classid != RelationRelationId ||
7510 depForm->objsubid != 0 ||
7511 depForm->deptype != DEPENDENCY_AUTO)
7514 /* Use relation_open just in case it's an index */
7515 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
7517 /* skip non-sequence relations */
7518 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
7520 /* No need to keep the lock */
7521 relation_close(seqRel, AccessExclusiveLock);
7525 /* Fix the pg_class and pg_depend entries */
7526 AlterRelationNamespaceInternal(classRel, depForm->objid,
7527 oldNspOid, newNspOid,
7531 * Sequences have entries in pg_type. We need to be careful to move
7532 * them to the new namespace, too.
7534 AlterTypeNamespaceInternal(RelationGetForm(seqRel)->reltype,
7535 newNspOid, false, false);
7537 /* Now we can close it. Keep the lock till end of transaction. */
7538 relation_close(seqRel, NoLock);
7541 systable_endscan(scan);
7543 relation_close(depRel, AccessShareLock);
7548 * This code supports
7549 * CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
7551 * Because we only support this for TEMP tables, it's sufficient to remember
7552 * the state in a backend-local data structure.
7556 * Register a newly-created relation's ON COMMIT action.
7559 register_on_commit_action(Oid relid, OnCommitAction action)
7562 MemoryContext oldcxt;
7565 * We needn't bother registering the relation unless there is an ON COMMIT
7566 * action we need to take.
7568 if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
7571 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
7573 oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
7575 oc->oncommit = action;
7576 oc->creating_subid = GetCurrentSubTransactionId();
7577 oc->deleting_subid = InvalidSubTransactionId;
7579 on_commits = lcons(oc, on_commits);
7581 MemoryContextSwitchTo(oldcxt);
7585 * Unregister any ON COMMIT action when a relation is deleted.
7587 * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
7590 remove_on_commit_action(Oid relid)
7594 foreach(l, on_commits)
7596 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
7598 if (oc->relid == relid)
7600 oc->deleting_subid = GetCurrentSubTransactionId();
7607 * Perform ON COMMIT actions.
7609 * This is invoked just before actually committing, since it's possible
7610 * to encounter errors.
7613 PreCommit_on_commit_actions(void)
7616 List *oids_to_truncate = NIL;
7618 foreach(l, on_commits)
7620 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
7622 /* Ignore entry if already dropped in this xact */
7623 if (oc->deleting_subid != InvalidSubTransactionId)
7626 switch (oc->oncommit)
7629 case ONCOMMIT_PRESERVE_ROWS:
7630 /* Do nothing (there shouldn't be such entries, actually) */
7632 case ONCOMMIT_DELETE_ROWS:
7633 oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
7637 ObjectAddress object;
7639 object.classId = RelationRelationId;
7640 object.objectId = oc->relid;
7641 object.objectSubId = 0;
7642 performDeletion(&object, DROP_CASCADE);
7645 * Note that table deletion will call
7646 * remove_on_commit_action, so the entry should get marked
7649 Assert(oc->deleting_subid != InvalidSubTransactionId);
7654 if (oids_to_truncate != NIL)
7656 heap_truncate(oids_to_truncate);
7657 CommandCounterIncrement(); /* XXX needed? */
7662 * Post-commit or post-abort cleanup for ON COMMIT management.
7664 * All we do here is remove no-longer-needed OnCommitItem entries.
7666 * During commit, remove entries that were deleted during this transaction;
7667 * during abort, remove those created during this transaction.
7670 AtEOXact_on_commit_actions(bool isCommit)
7673 ListCell *prev_item;
7676 cur_item = list_head(on_commits);
7678 while (cur_item != NULL)
7680 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
7682 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
7683 oc->creating_subid != InvalidSubTransactionId)
7685 /* cur_item must be removed */
7686 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
7689 cur_item = lnext(prev_item);
7691 cur_item = list_head(on_commits);
7695 /* cur_item must be preserved */
7696 oc->creating_subid = InvalidSubTransactionId;
7697 oc->deleting_subid = InvalidSubTransactionId;
7698 prev_item = cur_item;
7699 cur_item = lnext(prev_item);
7705 * Post-subcommit or post-subabort cleanup for ON COMMIT management.
7707 * During subabort, we can immediately remove entries created during this
7708 * subtransaction. During subcommit, just relabel entries marked during
7709 * this subtransaction as being the parent's responsibility.
7712 AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
7713 SubTransactionId parentSubid)
7716 ListCell *prev_item;
7719 cur_item = list_head(on_commits);
7721 while (cur_item != NULL)
7723 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
7725 if (!isCommit && oc->creating_subid == mySubid)
7727 /* cur_item must be removed */
7728 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
7731 cur_item = lnext(prev_item);
7733 cur_item = list_head(on_commits);
7737 /* cur_item must be preserved */
7738 if (oc->creating_subid == mySubid)
7739 oc->creating_subid = parentSubid;
7740 if (oc->deleting_subid == mySubid)
7741 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
7742 prev_item = cur_item;
7743 cur_item = lnext(prev_item);