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.255 2008/05/19 04:14:24 tgl Exp $
13 *-------------------------------------------------------------------------
17 #include "access/genam.h"
18 #include "access/heapam.h"
19 #include "access/reloptions.h"
20 #include "access/sysattr.h"
21 #include "access/xact.h"
22 #include "catalog/catalog.h"
23 #include "catalog/dependency.h"
24 #include "catalog/heap.h"
25 #include "catalog/index.h"
26 #include "catalog/indexing.h"
27 #include "catalog/namespace.h"
28 #include "catalog/pg_constraint.h"
29 #include "catalog/pg_depend.h"
30 #include "catalog/pg_inherits.h"
31 #include "catalog/pg_namespace.h"
32 #include "catalog/pg_opclass.h"
33 #include "catalog/pg_tablespace.h"
34 #include "catalog/pg_trigger.h"
35 #include "catalog/pg_type.h"
36 #include "catalog/pg_type_fn.h"
37 #include "catalog/toasting.h"
38 #include "commands/cluster.h"
39 #include "commands/defrem.h"
40 #include "commands/sequence.h"
41 #include "commands/tablecmds.h"
42 #include "commands/tablespace.h"
43 #include "commands/trigger.h"
44 #include "commands/typecmds.h"
45 #include "executor/executor.h"
46 #include "miscadmin.h"
47 #include "nodes/makefuncs.h"
48 #include "nodes/parsenodes.h"
49 #include "optimizer/clauses.h"
50 #include "optimizer/plancat.h"
51 #include "optimizer/prep.h"
52 #include "parser/gramparse.h"
53 #include "parser/parse_clause.h"
54 #include "parser/parse_coerce.h"
55 #include "parser/parse_expr.h"
56 #include "parser/parse_oper.h"
57 #include "parser/parse_relation.h"
58 #include "parser/parse_type.h"
59 #include "parser/parse_utilcmd.h"
60 #include "parser/parser.h"
61 #include "rewrite/rewriteDefine.h"
62 #include "rewrite/rewriteHandler.h"
63 #include "storage/bufmgr.h"
64 #include "storage/smgr.h"
65 #include "utils/acl.h"
66 #include "utils/builtins.h"
67 #include "utils/fmgroids.h"
68 #include "utils/inval.h"
69 #include "utils/lsyscache.h"
70 #include "utils/memutils.h"
71 #include "utils/relcache.h"
72 #include "utils/snapmgr.h"
73 #include "utils/syscache.h"
74 #include "utils/tqual.h"
78 * ON COMMIT action list
80 typedef struct OnCommitItem
82 Oid relid; /* relid of relation */
83 OnCommitAction oncommit; /* what to do at end of xact */
86 * If this entry was created during the current transaction,
87 * creating_subid is the ID of the creating subxact; if created in a prior
88 * transaction, creating_subid is zero. If deleted during the current
89 * transaction, deleting_subid is the ID of the deleting subxact; if no
90 * deletion request is pending, deleting_subid is zero.
92 SubTransactionId creating_subid;
93 SubTransactionId deleting_subid;
96 static List *on_commits = NIL;
100 * State information for ALTER TABLE
102 * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
103 * structs, one for each table modified by the operation (the named table
104 * plus any child tables that are affected). We save lists of subcommands
105 * to apply to this table (possibly modified by parse transformation steps);
106 * these lists will be executed in Phase 2. If a Phase 3 step is needed,
107 * necessary information is stored in the constraints and newvals lists.
109 * Phase 2 is divided into multiple passes; subcommands are executed in
110 * a pass determined by subcommand type.
113 #define AT_PASS_DROP 0 /* DROP (all flavors) */
114 #define AT_PASS_ALTER_TYPE 1 /* ALTER COLUMN TYPE */
115 #define AT_PASS_OLD_INDEX 2 /* re-add existing indexes */
116 #define AT_PASS_OLD_CONSTR 3 /* re-add existing constraints */
117 #define AT_PASS_COL_ATTRS 4 /* set other column attributes */
118 /* We could support a RENAME COLUMN pass here, but not currently used */
119 #define AT_PASS_ADD_COL 5 /* ADD COLUMN */
120 #define AT_PASS_ADD_INDEX 6 /* ADD indexes */
121 #define AT_PASS_ADD_CONSTR 7 /* ADD constraints, defaults */
122 #define AT_PASS_MISC 8 /* other stuff */
123 #define AT_NUM_PASSES 9
125 typedef struct AlteredTableInfo
127 /* Information saved before any work commences: */
128 Oid relid; /* Relation to work on */
129 char relkind; /* Its relkind */
130 TupleDesc oldDesc; /* Pre-modification tuple descriptor */
131 /* Information saved by Phase 1 for Phase 2: */
132 List *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
133 /* Information saved by Phases 1/2 for Phase 3: */
134 List *constraints; /* List of NewConstraint */
135 List *newvals; /* List of NewColumnValue */
136 bool new_notnull; /* T if we added new NOT NULL constraints */
137 Oid newTableSpace; /* new tablespace; 0 means no change */
138 /* Objects to rebuild after completing ALTER TYPE operations */
139 List *changedConstraintOids; /* OIDs of constraints to rebuild */
140 List *changedConstraintDefs; /* string definitions of same */
141 List *changedIndexOids; /* OIDs of indexes to rebuild */
142 List *changedIndexDefs; /* string definitions of same */
145 /* Struct describing one new constraint to check in Phase 3 scan */
146 /* Note: new NOT NULL constraints are handled elsewhere */
147 typedef struct NewConstraint
149 char *name; /* Constraint name, or NULL if none */
150 ConstrType contype; /* CHECK or FOREIGN */
151 Oid refrelid; /* PK rel, if FOREIGN */
152 Oid conid; /* OID of pg_constraint entry, if FOREIGN */
153 Node *qual; /* Check expr or FkConstraint struct */
154 List *qualstate; /* Execution state for CHECK */
158 * Struct describing one new column value that needs to be computed during
159 * Phase 3 copy (this could be either a new column with a non-null default, or
160 * a column that we're changing the type of). Columns without such an entry
161 * are just copied from the old table during ATRewriteTable. Note that the
162 * expr is an expression over *old* table values.
164 typedef struct NewColumnValue
166 AttrNumber attnum; /* which column */
167 Expr *expr; /* expression to compute */
168 ExprState *exprstate; /* execution state */
172 static void truncate_check_rel(Relation rel);
173 static List *MergeAttributes(List *schema, List *supers, bool istemp,
174 List **supOids, List **supconstr, int *supOidCount);
175 static bool MergeCheckConstraint(List *constraints, char *name, Node *expr);
176 static bool change_varattnos_walker(Node *node, const AttrNumber *newattno);
177 static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel);
178 static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
179 static void StoreCatalogInheritance(Oid relationId, List *supers);
180 static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
181 int16 seqNumber, Relation inhRelation);
182 static int findAttrByName(const char *attributeName, List *schema);
183 static void setRelhassubclassInRelation(Oid relationId, bool relhassubclass);
184 static void AlterIndexNamespaces(Relation classRel, Relation rel,
185 Oid oldNspOid, Oid newNspOid);
186 static void AlterSeqNamespaces(Relation classRel, Relation rel,
187 Oid oldNspOid, Oid newNspOid,
188 const char *newNspName);
189 static int transformColumnNameList(Oid relId, List *colList,
190 int16 *attnums, Oid *atttypids);
191 static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
193 int16 *attnums, Oid *atttypids,
195 static Oid transformFkeyCheckAttrs(Relation pkrel,
196 int numattrs, int16 *attnums,
198 static void validateForeignKeyConstraint(FkConstraint *fkconstraint,
199 Relation rel, Relation pkrel, Oid constraintOid);
200 static void createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
202 static void ATController(Relation rel, List *cmds, bool recurse);
203 static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
204 bool recurse, bool recursing);
205 static void ATRewriteCatalogs(List **wqueue);
206 static void ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
208 static void ATRewriteTables(List **wqueue);
209 static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap);
210 static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
211 static void ATSimplePermissions(Relation rel, bool allowView);
212 static void ATSimplePermissionsRelationOrIndex(Relation rel);
213 static void ATSimpleRecursion(List **wqueue, Relation rel,
214 AlterTableCmd *cmd, bool recurse);
215 static void ATOneLevelRecursion(List **wqueue, Relation rel,
217 static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
219 static void ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
221 static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
222 static void ATExecDropNotNull(Relation rel, const char *colName);
223 static void ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
224 const char *colName);
225 static void ATExecColumnDefault(Relation rel, const char *colName,
227 static void ATPrepSetStatistics(Relation rel, const char *colName,
229 static void ATExecSetStatistics(Relation rel, const char *colName,
231 static void ATExecSetStorage(Relation rel, const char *colName,
233 static void ATExecDropColumn(Relation rel, const char *colName,
234 DropBehavior behavior,
235 bool recurse, bool recursing);
236 static void ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
237 IndexStmt *stmt, bool is_rebuild);
238 static void ATExecAddConstraint(List **wqueue,
239 AlteredTableInfo *tab, Relation rel,
240 Node *newConstraint, bool recurse);
241 static void ATAddCheckConstraint(List **wqueue,
242 AlteredTableInfo *tab, Relation rel,
244 bool recurse, bool recursing);
245 static void ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
246 FkConstraint *fkconstraint);
247 static void ATExecDropConstraint(Relation rel, const char *constrName,
248 DropBehavior behavior,
249 bool recurse, bool recursing);
250 static void ATPrepAlterColumnType(List **wqueue,
251 AlteredTableInfo *tab, Relation rel,
252 bool recurse, bool recursing,
254 static void ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
255 const char *colName, TypeName *typename);
256 static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab);
257 static void ATPostAlterTypeParse(char *cmd, List **wqueue);
258 static void change_owner_recurse_to_sequences(Oid relationOid,
260 static void ATExecClusterOn(Relation rel, const char *indexName);
261 static void ATExecDropCluster(Relation rel);
262 static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
263 char *tablespacename);
264 static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace);
265 static void ATExecSetRelOptions(Relation rel, List *defList, bool isReset);
266 static void ATExecEnableDisableTrigger(Relation rel, char *trigname,
267 char fires_when, bool skip_system);
268 static void ATExecEnableDisableRule(Relation rel, char *rulename,
270 static void ATExecAddInherit(Relation rel, RangeVar *parent);
271 static void ATExecDropInherit(Relation rel, RangeVar *parent);
272 static void copy_relation_data(Relation rel, SMgrRelation dst);
275 /* ----------------------------------------------------------------
277 * Creates a new relation.
279 * If successful, returns the OID of the new relation.
280 * ----------------------------------------------------------------
283 DefineRelation(CreateStmt *stmt, char relkind)
285 char relname[NAMEDATALEN];
287 List *schema = stmt->tableElts;
291 TupleDesc descriptor;
293 List *old_constraints;
297 List *cookedDefaults;
303 * Truncate relname to appropriate length (probably a waste of time, as
304 * parser should have done this already).
306 StrNCpy(relname, stmt->relation->relname, NAMEDATALEN);
309 * Check consistency of arguments
311 if (stmt->oncommit != ONCOMMIT_NOOP && !stmt->relation->istemp)
313 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
314 errmsg("ON COMMIT can only be used on temporary tables")));
317 * Look up the namespace in which we are supposed to create the relation.
318 * Check we have permission to create there. Skip check if bootstrapping,
319 * since permissions machinery may not be working yet.
321 namespaceId = RangeVarGetCreationNamespace(stmt->relation);
323 if (!IsBootstrapProcessingMode())
327 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
329 if (aclresult != ACLCHECK_OK)
330 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
331 get_namespace_name(namespaceId));
335 * Select tablespace to use. If not specified, use default tablespace
336 * (which may in turn default to database's default).
338 if (stmt->tablespacename)
340 tablespaceId = get_tablespace_oid(stmt->tablespacename);
341 if (!OidIsValid(tablespaceId))
343 (errcode(ERRCODE_UNDEFINED_OBJECT),
344 errmsg("tablespace \"%s\" does not exist",
345 stmt->tablespacename)));
349 tablespaceId = GetDefaultTablespace(stmt->relation->istemp);
350 /* note InvalidOid is OK in this case */
353 /* Check permissions except when using database's default */
354 if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
358 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
360 if (aclresult != ACLCHECK_OK)
361 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
362 get_tablespace_name(tablespaceId));
366 * Parse and validate reloptions, if any.
368 reloptions = transformRelOptions((Datum) 0, stmt->options, true, false);
370 (void) heap_reloptions(relkind, reloptions, true);
373 * Look up inheritance ancestors and generate relation schema, including
374 * inherited attributes.
376 schema = MergeAttributes(schema, stmt->inhRelations,
377 stmt->relation->istemp,
378 &inheritOids, &old_constraints, &parentOidCount);
381 * Create a tuple descriptor from the relation schema. Note that this
382 * deals with column names, types, and NOT NULL constraints, but not
383 * default values or CHECK constraints; we handle those below.
385 descriptor = BuildDescForRelation(schema);
387 localHasOids = interpretOidsOption(stmt->options);
388 descriptor->tdhasoid = (localHasOids || parentOidCount > 0);
391 * Find columns with default values and prepare for insertion of the
392 * defaults. Pre-cooked (that is, inherited) defaults go into a list of
393 * CookedConstraint structs that we'll pass to heap_create_with_catalog,
394 * while raw defaults go into a list of RawColumnDefault structs that
395 * will be processed by AddRelationNewConstraints. (We can't deal with
396 * raw expressions until we can do transformExpr.)
398 * We can set the atthasdef flags now in the tuple descriptor; this just
399 * saves StoreAttrDefault from having to do an immediate update of the
403 cookedDefaults = NIL;
406 foreach(listptr, schema)
408 ColumnDef *colDef = lfirst(listptr);
412 if (colDef->raw_default != NULL)
414 RawColumnDefault *rawEnt;
416 Assert(colDef->cooked_default == NULL);
418 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
419 rawEnt->attnum = attnum;
420 rawEnt->raw_default = colDef->raw_default;
421 rawDefaults = lappend(rawDefaults, rawEnt);
422 descriptor->attrs[attnum - 1]->atthasdef = true;
424 else if (colDef->cooked_default != NULL)
426 CookedConstraint *cooked;
428 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
429 cooked->contype = CONSTR_DEFAULT;
431 cooked->attnum = attnum;
432 cooked->expr = stringToNode(colDef->cooked_default);
433 cooked->is_local = true; /* not used for defaults */
434 cooked->inhcount = 0; /* ditto */
435 cookedDefaults = lappend(cookedDefaults, cooked);
436 descriptor->attrs[attnum - 1]->atthasdef = true;
441 * Create the relation. Inherited defaults and constraints are passed
442 * in for immediate handling --- since they don't need parsing, they
443 * can be stored immediately.
445 relationId = heap_create_with_catalog(relname,
451 list_concat(cookedDefaults,
459 allowSystemTableMods);
461 StoreCatalogInheritance(relationId, inheritOids);
464 * We must bump the command counter to make the newly-created relation
465 * tuple visible for opening.
467 CommandCounterIncrement();
470 * Open the new relation and acquire exclusive lock on it. This isn't
471 * really necessary for locking out other backends (since they can't see
472 * the new rel anyway until we commit), but it keeps the lock manager from
473 * complaining about deadlock risks.
475 rel = relation_open(relationId, AccessExclusiveLock);
478 * Now add any newly specified column default values and CHECK constraints
479 * to the new relation. These are passed to us in the form of raw
480 * parsetrees; we need to transform them to executable expression trees
481 * before they can be added. The most convenient way to do that is to
482 * apply the parser's transformExpr routine, but transformExpr doesn't
483 * work unless we have a pre-existing relation. So, the transformation has
484 * to be postponed to this final step of CREATE TABLE.
486 if (rawDefaults || stmt->constraints)
487 AddRelationNewConstraints(rel, rawDefaults, stmt->constraints,
491 * Clean up. We keep lock on new relation (although it shouldn't be
492 * visible to anyone else anyway, until commit).
494 relation_close(rel, NoLock);
501 * Deletes a relation.
504 RemoveRelation(const RangeVar *relation, DropBehavior behavior)
507 ObjectAddress object;
509 relOid = RangeVarGetRelid(relation, false);
511 object.classId = RelationRelationId;
512 object.objectId = relOid;
513 object.objectSubId = 0;
515 performDeletion(&object, behavior);
520 * Executes a TRUNCATE command.
522 * This is a multi-relation truncate. We first open and grab exclusive
523 * lock on all relations involved, checking permissions and otherwise
524 * verifying that the relation is OK for truncation. In CASCADE mode,
525 * relations having FK references to the targeted relations are automatically
526 * added to the group; in RESTRICT mode, we check that all FK references are
527 * internal to the group that's being truncated. Finally all the relations
528 * are truncated and reindexed.
531 ExecuteTruncate(TruncateStmt *stmt)
535 List *seq_relids = NIL;
537 ResultRelInfo *resultRelInfos;
538 ResultRelInfo *resultRelInfo;
542 * Open, exclusive-lock, and check all the explicitly-specified relations
544 foreach(cell, stmt->relations)
546 RangeVar *rv = lfirst(cell);
549 rel = heap_openrv(rv, AccessExclusiveLock);
550 truncate_check_rel(rel);
551 rels = lappend(rels, rel);
552 relids = lappend_oid(relids, RelationGetRelid(rel));
556 * In CASCADE mode, suck in all referencing relations as well. This
557 * requires multiple iterations to find indirectly-dependent relations. At
558 * each phase, we need to exclusive-lock new rels before looking for their
559 * dependencies, else we might miss something. Also, we check each rel as
560 * soon as we open it, to avoid a faux pas such as holding lock for a long
561 * time on a rel we have no permissions for.
563 if (stmt->behavior == DROP_CASCADE)
569 newrelids = heap_truncate_find_FKs(relids);
570 if (newrelids == NIL)
571 break; /* nothing else to add */
573 foreach(cell, newrelids)
575 Oid relid = lfirst_oid(cell);
578 rel = heap_open(relid, AccessExclusiveLock);
580 (errmsg("truncate cascades to table \"%s\"",
581 RelationGetRelationName(rel))));
582 truncate_check_rel(rel);
583 rels = lappend(rels, rel);
584 relids = lappend_oid(relids, relid);
590 * Check foreign key references. In CASCADE mode, this should be
591 * unnecessary since we just pulled in all the references; but as a
592 * cross-check, do it anyway if in an Assert-enabled build.
594 #ifdef USE_ASSERT_CHECKING
595 heap_truncate_check_FKs(rels, false);
597 if (stmt->behavior == DROP_RESTRICT)
598 heap_truncate_check_FKs(rels, false);
602 * If we are asked to restart sequences, find all the sequences,
603 * lock them (we only need AccessShareLock because that's all that
604 * ALTER SEQUENCE takes), and check permissions. We want to do this
605 * early since it's pointless to do all the truncation work only to fail
606 * on sequence permissions.
608 if (stmt->restart_seqs)
612 Relation rel = (Relation) lfirst(cell);
613 List *seqlist = getOwnedSequences(RelationGetRelid(rel));
616 foreach(seqcell, seqlist)
618 Oid seq_relid = lfirst_oid(seqcell);
621 seq_rel = relation_open(seq_relid, AccessShareLock);
623 /* This check must match AlterSequence! */
624 if (!pg_class_ownercheck(seq_relid, GetUserId()))
625 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
626 RelationGetRelationName(seq_rel));
628 seq_relids = lappend_oid(seq_relids, seq_relid);
630 relation_close(seq_rel, NoLock);
635 /* Prepare to catch AFTER triggers. */
636 AfterTriggerBeginQuery();
639 * To fire triggers, we'll need an EState as well as a ResultRelInfo
642 estate = CreateExecutorState();
643 resultRelInfos = (ResultRelInfo *)
644 palloc(list_length(rels) * sizeof(ResultRelInfo));
645 resultRelInfo = resultRelInfos;
648 Relation rel = (Relation) lfirst(cell);
650 InitResultRelInfo(resultRelInfo,
652 0, /* dummy rangetable index */
653 CMD_DELETE, /* don't need any index info */
657 estate->es_result_relations = resultRelInfos;
658 estate->es_num_result_relations = list_length(rels);
661 * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
662 * truncating (this is because one of them might throw an error).
663 * Also, if we were to allow them to prevent statement execution,
664 * that would need to be handled here.
666 resultRelInfo = resultRelInfos;
669 estate->es_result_relation_info = resultRelInfo;
670 ExecBSTruncateTriggers(estate, resultRelInfo);
675 * OK, truncate each table.
679 Relation rel = (Relation) lfirst(cell);
684 * Create a new empty storage file for the relation, and assign it as
685 * the relfilenode value. The old storage file is scheduled for
686 * deletion at commit.
688 setNewRelfilenode(rel, RecentXmin);
690 heap_relid = RelationGetRelid(rel);
691 toast_relid = rel->rd_rel->reltoastrelid;
694 * The same for the toast table, if any.
696 if (OidIsValid(toast_relid))
698 rel = relation_open(toast_relid, AccessExclusiveLock);
699 setNewRelfilenode(rel, RecentXmin);
700 heap_close(rel, NoLock);
704 * Reconstruct the indexes to match, and we're done.
706 reindex_relation(heap_relid, true);
710 * Process all AFTER STATEMENT TRUNCATE triggers.
712 resultRelInfo = resultRelInfos;
715 estate->es_result_relation_info = resultRelInfo;
716 ExecASTruncateTriggers(estate, resultRelInfo);
720 /* Handle queued AFTER triggers */
721 AfterTriggerEndQuery(estate);
723 /* We can clean up the EState now */
724 FreeExecutorState(estate);
726 /* And close the rels (can't do this while EState still holds refs) */
729 Relation rel = (Relation) lfirst(cell);
731 heap_close(rel, NoLock);
735 * Lastly, restart any owned sequences if we were asked to. This is done
736 * last because it's nontransactional: restarts will not roll back if
737 * we abort later. Hence it's important to postpone them as long as
738 * possible. (This is also a big reason why we locked and
739 * permission-checked the sequences beforehand.)
741 if (stmt->restart_seqs)
743 List *options = list_make1(makeDefElem("restart", NULL));
745 foreach(cell, seq_relids)
747 Oid seq_relid = lfirst_oid(cell);
749 AlterSequenceInternal(seq_relid, options);
755 * Check that a given rel is safe to truncate. Subroutine for ExecuteTruncate
758 truncate_check_rel(Relation rel)
760 /* Only allow truncate on regular tables */
761 if (rel->rd_rel->relkind != RELKIND_RELATION)
763 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
764 errmsg("\"%s\" is not a table",
765 RelationGetRelationName(rel))));
767 /* Permissions checks */
768 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
769 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
770 RelationGetRelationName(rel));
772 if (!allowSystemTableMods && IsSystemRelation(rel))
774 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
775 errmsg("permission denied: \"%s\" is a system catalog",
776 RelationGetRelationName(rel))));
779 * We can never allow truncation of shared or nailed-in-cache relations,
780 * because we can't support changing their relfilenode values.
782 if (rel->rd_rel->relisshared || rel->rd_isnailed)
784 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
785 errmsg("cannot truncate system relation \"%s\"",
786 RelationGetRelationName(rel))));
789 * Don't allow truncate on temp tables of other backends ... their local
790 * buffer manager is not going to cope.
792 if (isOtherTempNamespace(RelationGetNamespace(rel)))
794 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
795 errmsg("cannot truncate temporary tables of other sessions")));
798 * Also check for active uses of the relation in the current transaction,
799 * including open scans and pending AFTER trigger events.
801 CheckTableNotInUse(rel, "TRUNCATE");
806 * Returns new schema given initial schema and superclasses.
809 * 'schema' is the column/attribute definition for the table. (It's a list
810 * of ColumnDef's.) It is destructively changed.
811 * 'supers' is a list of names (as RangeVar nodes) of parent relations.
812 * 'istemp' is TRUE if we are creating a temp relation.
815 * 'supOids' receives a list of the OIDs of the parent relations.
816 * 'supconstr' receives a list of constraints belonging to the parents,
817 * updated as necessary to be valid for the child.
818 * 'supOidCount' is set to the number of parents that have OID columns.
821 * Completed schema list.
824 * The order in which the attributes are inherited is very important.
825 * Intuitively, the inherited attributes should come first. If a table
826 * inherits from multiple parents, the order of those attributes are
827 * according to the order of the parents specified in CREATE TABLE.
831 * create table person (name text, age int4, location point);
832 * create table emp (salary int4, manager text) inherits(person);
833 * create table student (gpa float8) inherits (person);
834 * create table stud_emp (percent int4) inherits (emp, student);
836 * The order of the attributes of stud_emp is:
838 * person {1:name, 2:age, 3:location}
840 * {6:gpa} student emp {4:salary, 5:manager}
842 * stud_emp {7:percent}
844 * If the same attribute name appears multiple times, then it appears
845 * in the result table in the proper location for its first appearance.
847 * Constraints (including NOT NULL constraints) for the child table
848 * are the union of all relevant constraints, from both the child schema
851 * The default value for a child column is defined as:
852 * (1) If the child schema specifies a default, that value is used.
853 * (2) If neither the child nor any parent specifies a default, then
854 * the column will not have a default.
855 * (3) If conflicting defaults are inherited from different parents
856 * (and not overridden by the child), an error is raised.
857 * (4) Otherwise the inherited default is used.
858 * Rule (3) is new in Postgres 7.1; in earlier releases you got a
859 * rather arbitrary choice of which parent default to use.
863 MergeAttributes(List *schema, List *supers, bool istemp,
864 List **supOids, List **supconstr, int *supOidCount)
867 List *inhSchema = NIL;
868 List *parentOids = NIL;
869 List *constraints = NIL;
870 int parentsWithOids = 0;
871 bool have_bogus_defaults = false;
872 char *bogus_marker = "Bogus!"; /* marks conflicting defaults */
876 * Check for and reject tables with too many columns. We perform this
877 * check relatively early for two reasons: (a) we don't run the risk of
878 * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
879 * okay if we're processing <= 1600 columns, but could take minutes to
880 * execute if the user attempts to create a table with hundreds of
881 * thousands of columns.
883 * Note that we also need to check that any we do not exceed this figure
884 * after including columns from inherited relations.
886 if (list_length(schema) > MaxHeapAttributeNumber)
888 (errcode(ERRCODE_TOO_MANY_COLUMNS),
889 errmsg("tables can have at most %d columns",
890 MaxHeapAttributeNumber)));
893 * Check for duplicate names in the explicit list of attributes.
895 * Although we might consider merging such entries in the same way that we
896 * handle name conflicts for inherited attributes, it seems to make more
897 * sense to assume such conflicts are errors.
899 foreach(entry, schema)
901 ColumnDef *coldef = lfirst(entry);
904 for_each_cell(rest, lnext(entry))
906 ColumnDef *restdef = lfirst(rest);
908 if (strcmp(coldef->colname, restdef->colname) == 0)
910 (errcode(ERRCODE_DUPLICATE_COLUMN),
911 errmsg("column \"%s\" specified more than once",
917 * Scan the parents left-to-right, and merge their attributes to form a
918 * list of inherited attributes (inhSchema). Also check to see if we need
919 * to inherit an OID column.
922 foreach(entry, supers)
924 RangeVar *parent = (RangeVar *) lfirst(entry);
928 AttrNumber *newattno;
929 AttrNumber parent_attno;
931 relation = heap_openrv(parent, AccessShareLock);
933 if (relation->rd_rel->relkind != RELKIND_RELATION)
935 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
936 errmsg("inherited relation \"%s\" is not a table",
938 /* Permanent rels cannot inherit from temporary ones */
939 if (!istemp && isTempNamespace(RelationGetNamespace(relation)))
941 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
942 errmsg("cannot inherit from temporary relation \"%s\"",
946 * We should have an UNDER permission flag for this, but for now,
947 * demand that creator of a child table own the parent.
949 if (!pg_class_ownercheck(RelationGetRelid(relation), GetUserId()))
950 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
951 RelationGetRelationName(relation));
954 * Reject duplications in the list of parents.
956 if (list_member_oid(parentOids, RelationGetRelid(relation)))
958 (errcode(ERRCODE_DUPLICATE_TABLE),
959 errmsg("relation \"%s\" would be inherited from more than once",
962 parentOids = lappend_oid(parentOids, RelationGetRelid(relation));
964 if (relation->rd_rel->relhasoids)
967 tupleDesc = RelationGetDescr(relation);
968 constr = tupleDesc->constr;
971 * newattno[] will contain the child-table attribute numbers for the
972 * attributes of this parent table. (They are not the same for
973 * parents after the first one, nor if we have dropped columns.)
975 newattno = (AttrNumber *)
976 palloc(tupleDesc->natts * sizeof(AttrNumber));
978 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
981 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
982 char *attributeName = NameStr(attribute->attname);
987 * Ignore dropped columns in the parent.
989 if (attribute->attisdropped)
992 * change_varattnos_of_a_node asserts that this is greater
993 * than zero, so if anything tries to use it, we should find
996 newattno[parent_attno - 1] = 0;
1001 * Does it conflict with some previously inherited column?
1003 exist_attno = findAttrByName(attributeName, inhSchema);
1004 if (exist_attno > 0)
1010 * Yes, try to merge the two column definitions. They must
1011 * have the same type and typmod.
1014 (errmsg("merging multiple inherited definitions of column \"%s\"",
1016 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1017 defTypeId = typenameTypeId(NULL, def->typename, &deftypmod);
1018 if (defTypeId != attribute->atttypid ||
1019 deftypmod != attribute->atttypmod)
1021 (errcode(ERRCODE_DATATYPE_MISMATCH),
1022 errmsg("inherited column \"%s\" has a type conflict",
1024 errdetail("%s versus %s",
1025 TypeNameToString(def->typename),
1026 format_type_be(attribute->atttypid))));
1028 /* Merge of NOT NULL constraints = OR 'em together */
1029 def->is_not_null |= attribute->attnotnull;
1030 /* Default and other constraints are handled below */
1031 newattno[parent_attno - 1] = exist_attno;
1036 * No, create a new inherited column
1038 def = makeNode(ColumnDef);
1039 def->colname = pstrdup(attributeName);
1040 def->typename = makeTypeNameFromOid(attribute->atttypid,
1041 attribute->atttypmod);
1043 def->is_local = false;
1044 def->is_not_null = attribute->attnotnull;
1045 def->raw_default = NULL;
1046 def->cooked_default = NULL;
1047 def->constraints = NIL;
1048 inhSchema = lappend(inhSchema, def);
1049 newattno[parent_attno - 1] = ++child_attno;
1053 * Copy default if any
1055 if (attribute->atthasdef)
1057 char *this_default = NULL;
1058 AttrDefault *attrdef;
1061 /* Find default in constraint structure */
1062 Assert(constr != NULL);
1063 attrdef = constr->defval;
1064 for (i = 0; i < constr->num_defval; i++)
1066 if (attrdef[i].adnum == parent_attno)
1068 this_default = attrdef[i].adbin;
1072 Assert(this_default != NULL);
1075 * If default expr could contain any vars, we'd need to fix
1076 * 'em, but it can't; so default is ready to apply to child.
1078 * If we already had a default from some prior parent, check
1079 * to see if they are the same. If so, no problem; if not,
1080 * mark the column as having a bogus default. Below, we will
1081 * complain if the bogus default isn't overridden by the child
1084 Assert(def->raw_default == NULL);
1085 if (def->cooked_default == NULL)
1086 def->cooked_default = pstrdup(this_default);
1087 else if (strcmp(def->cooked_default, this_default) != 0)
1089 def->cooked_default = bogus_marker;
1090 have_bogus_defaults = true;
1096 * Now copy the CHECK constraints of this parent, adjusting attnos
1097 * using the completed newattno[] map. Identically named constraints
1098 * are merged if possible, else we throw error.
1100 if (constr && constr->num_check > 0)
1102 ConstrCheck *check = constr->check;
1105 for (i = 0; i < constr->num_check; i++)
1107 char *name = check[i].ccname;
1110 /* adjust varattnos of ccbin here */
1111 expr = stringToNode(check[i].ccbin);
1112 change_varattnos_of_a_node(expr, newattno);
1114 /* check for duplicate */
1115 if (!MergeCheckConstraint(constraints, name, expr))
1117 /* nope, this is a new one */
1118 CookedConstraint *cooked;
1120 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1121 cooked->contype = CONSTR_CHECK;
1122 cooked->name = pstrdup(name);
1123 cooked->attnum = 0; /* not used for constraints */
1124 cooked->expr = expr;
1125 cooked->is_local = false;
1126 cooked->inhcount = 1;
1127 constraints = lappend(constraints, cooked);
1135 * Close the parent rel, but keep our AccessShareLock on it until xact
1136 * commit. That will prevent someone else from deleting or ALTERing
1137 * the parent before the child is committed.
1139 heap_close(relation, NoLock);
1143 * If we had no inherited attributes, the result schema is just the
1144 * explicitly declared columns. Otherwise, we need to merge the declared
1145 * columns into the inherited schema list.
1147 if (inhSchema != NIL)
1149 foreach(entry, schema)
1151 ColumnDef *newdef = lfirst(entry);
1152 char *attributeName = newdef->colname;
1156 * Does it conflict with some previously inherited column?
1158 exist_attno = findAttrByName(attributeName, inhSchema);
1159 if (exist_attno > 0)
1168 * Yes, try to merge the two column definitions. They must
1169 * have the same type and typmod.
1172 (errmsg("merging column \"%s\" with inherited definition",
1174 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1175 defTypeId = typenameTypeId(NULL, def->typename, &deftypmod);
1176 newTypeId = typenameTypeId(NULL, newdef->typename, &newtypmod);
1177 if (defTypeId != newTypeId || deftypmod != newtypmod)
1179 (errcode(ERRCODE_DATATYPE_MISMATCH),
1180 errmsg("column \"%s\" has a type conflict",
1182 errdetail("%s versus %s",
1183 TypeNameToString(def->typename),
1184 TypeNameToString(newdef->typename))));
1185 /* Mark the column as locally defined */
1186 def->is_local = true;
1187 /* Merge of NOT NULL constraints = OR 'em together */
1188 def->is_not_null |= newdef->is_not_null;
1189 /* If new def has a default, override previous default */
1190 if (newdef->raw_default != NULL)
1192 def->raw_default = newdef->raw_default;
1193 def->cooked_default = newdef->cooked_default;
1199 * No, attach new column to result schema
1201 inhSchema = lappend(inhSchema, newdef);
1208 * Check that we haven't exceeded the legal # of columns after merging
1209 * in inherited columns.
1211 if (list_length(schema) > MaxHeapAttributeNumber)
1213 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1214 errmsg("tables can have at most %d columns",
1215 MaxHeapAttributeNumber)));
1219 * If we found any conflicting parent default values, check to make sure
1220 * they were overridden by the child.
1222 if (have_bogus_defaults)
1224 foreach(entry, schema)
1226 ColumnDef *def = lfirst(entry);
1228 if (def->cooked_default == bogus_marker)
1230 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
1231 errmsg("column \"%s\" inherits conflicting default values",
1233 errhint("To resolve the conflict, specify a default explicitly.")));
1237 *supOids = parentOids;
1238 *supconstr = constraints;
1239 *supOidCount = parentsWithOids;
1245 * MergeCheckConstraint
1246 * Try to merge an inherited CHECK constraint with previous ones
1248 * If we inherit identically-named constraints from multiple parents, we must
1249 * merge them, or throw an error if they don't have identical definitions.
1251 * constraints is a list of CookedConstraint structs for previous constraints.
1253 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
1254 * got a so-far-unique name, or throws error if conflict.
1257 MergeCheckConstraint(List *constraints, char *name, Node *expr)
1261 foreach(lc, constraints)
1263 CookedConstraint *ccon = (CookedConstraint *) lfirst(lc);
1265 Assert(ccon->contype == CONSTR_CHECK);
1267 /* Non-matching names never conflict */
1268 if (strcmp(ccon->name, name) != 0)
1271 if (equal(expr, ccon->expr))
1279 (errcode(ERRCODE_DUPLICATE_OBJECT),
1280 errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
1289 * Replace varattno values in an expression tree according to the given
1290 * map array, that is, varattno N is replaced by newattno[N-1]. It is
1291 * caller's responsibility to ensure that the array is long enough to
1292 * define values for all user varattnos present in the tree. System column
1293 * attnos remain unchanged.
1295 * Note that the passed node tree is modified in-place!
1298 change_varattnos_of_a_node(Node *node, const AttrNumber *newattno)
1300 /* no setup needed, so away we go */
1301 (void) change_varattnos_walker(node, newattno);
1305 change_varattnos_walker(Node *node, const AttrNumber *newattno)
1311 Var *var = (Var *) node;
1313 if (var->varlevelsup == 0 && var->varno == 1 &&
1317 * ??? the following may be a problem when the node is multiply
1318 * referenced though stringToNode() doesn't create such a node
1321 Assert(newattno[var->varattno - 1] > 0);
1322 var->varattno = var->varoattno = newattno[var->varattno - 1];
1326 return expression_tree_walker(node, change_varattnos_walker,
1331 * Generate a map for change_varattnos_of_a_node from old and new TupleDesc's,
1332 * matching according to column name.
1335 varattnos_map(TupleDesc old, TupleDesc new)
1341 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * old->natts);
1342 for (i = 1; i <= old->natts; i++)
1344 if (old->attrs[i - 1]->attisdropped)
1345 continue; /* leave the entry as zero */
1347 for (j = 1; j <= new->natts; j++)
1349 if (strcmp(NameStr(old->attrs[i - 1]->attname),
1350 NameStr(new->attrs[j - 1]->attname)) == 0)
1361 * Generate a map for change_varattnos_of_a_node from a TupleDesc and a list
1365 varattnos_map_schema(TupleDesc old, List *schema)
1370 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * old->natts);
1371 for (i = 1; i <= old->natts; i++)
1373 if (old->attrs[i - 1]->attisdropped)
1374 continue; /* leave the entry as zero */
1376 attmap[i - 1] = findAttrByName(NameStr(old->attrs[i - 1]->attname),
1384 * StoreCatalogInheritance
1385 * Updates the system catalogs with proper inheritance information.
1387 * supers is a list of the OIDs of the new relation's direct ancestors.
1390 StoreCatalogInheritance(Oid relationId, List *supers)
1399 AssertArg(OidIsValid(relationId));
1405 * Store INHERITS information in pg_inherits using direct ancestors only.
1406 * Also enter dependencies on the direct ancestors, and make sure they are
1407 * marked with relhassubclass = true.
1409 * (Once upon a time, both direct and indirect ancestors were found here
1410 * and then entered into pg_ipl. Since that catalog doesn't exist
1411 * anymore, there's no need to look for indirect ancestors.)
1413 relation = heap_open(InheritsRelationId, RowExclusiveLock);
1416 foreach(entry, supers)
1418 Oid parentOid = lfirst_oid(entry);
1420 StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation);
1424 heap_close(relation, RowExclusiveLock);
1428 * Make catalog entries showing relationId as being an inheritance child
1429 * of parentOid. inhRelation is the already-opened pg_inherits catalog.
1432 StoreCatalogInheritance1(Oid relationId, Oid parentOid,
1433 int16 seqNumber, Relation inhRelation)
1435 TupleDesc desc = RelationGetDescr(inhRelation);
1436 Datum datum[Natts_pg_inherits];
1437 char nullarr[Natts_pg_inherits];
1438 ObjectAddress childobject,
1443 * Make the pg_inherits entry
1445 datum[0] = ObjectIdGetDatum(relationId); /* inhrelid */
1446 datum[1] = ObjectIdGetDatum(parentOid); /* inhparent */
1447 datum[2] = Int16GetDatum(seqNumber); /* inhseqno */
1453 tuple = heap_formtuple(desc, datum, nullarr);
1455 simple_heap_insert(inhRelation, tuple);
1457 CatalogUpdateIndexes(inhRelation, tuple);
1459 heap_freetuple(tuple);
1462 * Store a dependency too
1464 parentobject.classId = RelationRelationId;
1465 parentobject.objectId = parentOid;
1466 parentobject.objectSubId = 0;
1467 childobject.classId = RelationRelationId;
1468 childobject.objectId = relationId;
1469 childobject.objectSubId = 0;
1471 recordDependencyOn(&childobject, &parentobject, DEPENDENCY_NORMAL);
1474 * Mark the parent as having subclasses.
1476 setRelhassubclassInRelation(parentOid, true);
1480 * Look for an existing schema entry with the given name.
1482 * Returns the index (starting with 1) if attribute already exists in schema,
1486 findAttrByName(const char *attributeName, List *schema)
1493 ColumnDef *def = lfirst(s);
1495 if (strcmp(attributeName, def->colname) == 0)
1504 * Update a relation's pg_class.relhassubclass entry to the given value
1507 setRelhassubclassInRelation(Oid relationId, bool relhassubclass)
1509 Relation relationRelation;
1511 Form_pg_class classtuple;
1514 * Fetch a modifiable copy of the tuple, modify it, update pg_class.
1516 * If the tuple already has the right relhassubclass setting, we don't
1517 * need to update it, but we still need to issue an SI inval message.
1519 relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
1520 tuple = SearchSysCacheCopy(RELOID,
1521 ObjectIdGetDatum(relationId),
1523 if (!HeapTupleIsValid(tuple))
1524 elog(ERROR, "cache lookup failed for relation %u", relationId);
1525 classtuple = (Form_pg_class) GETSTRUCT(tuple);
1527 if (classtuple->relhassubclass != relhassubclass)
1529 classtuple->relhassubclass = relhassubclass;
1530 simple_heap_update(relationRelation, &tuple->t_self, tuple);
1532 /* keep the catalog indexes up to date */
1533 CatalogUpdateIndexes(relationRelation, tuple);
1537 /* no need to change tuple, but force relcache rebuild anyway */
1538 CacheInvalidateRelcacheByTuple(tuple);
1541 heap_freetuple(tuple);
1542 heap_close(relationRelation, RowExclusiveLock);
1547 * renameatt - changes the name of a attribute in a relation
1549 * Attname attribute is changed in attribute catalog.
1550 * No record of the previous attname is kept (correct?).
1552 * get proper relrelation from relation catalog (if not arg)
1553 * scan attribute catalog
1554 * for name conflict (within rel)
1555 * for original attribute (if not arg)
1556 * modify attname in attribute tuple
1557 * insert modified attribute in attribute catalog
1558 * delete original attribute from attribute catalog
1561 renameatt(Oid myrelid,
1562 const char *oldattname,
1563 const char *newattname,
1567 Relation targetrelation;
1568 Relation attrelation;
1570 Form_pg_attribute attform;
1573 ListCell *indexoidscan;
1576 * Grab an exclusive lock on the target table, which we will NOT release
1577 * until end of transaction.
1579 targetrelation = relation_open(myrelid, AccessExclusiveLock);
1582 * permissions checking. this would normally be done in utility.c, but
1583 * this particular routine is recursive.
1585 * normally, only the owner of a class can change its schema.
1587 if (!pg_class_ownercheck(myrelid, GetUserId()))
1588 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1589 RelationGetRelationName(targetrelation));
1590 if (!allowSystemTableMods && IsSystemRelation(targetrelation))
1592 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1593 errmsg("permission denied: \"%s\" is a system catalog",
1594 RelationGetRelationName(targetrelation))));
1597 * if the 'recurse' flag is set then we are supposed to rename this
1598 * attribute in all classes that inherit from 'relname' (as well as in
1601 * any permissions or problems with duplicate attributes will cause the
1602 * whole transaction to abort, which is what we want -- all or nothing.
1609 /* this routine is actually in the planner */
1610 children = find_all_inheritors(myrelid);
1613 * find_all_inheritors does the recursive search of the inheritance
1614 * hierarchy, so all we have to do is process all of the relids in the
1615 * list that it returns.
1617 foreach(child, children)
1619 Oid childrelid = lfirst_oid(child);
1621 if (childrelid == myrelid)
1623 /* note we need not recurse again */
1624 renameatt(childrelid, oldattname, newattname, false, true);
1630 * If we are told not to recurse, there had better not be any child
1631 * tables; else the rename would put them out of step.
1634 find_inheritance_children(myrelid) != NIL)
1636 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1637 errmsg("inherited column \"%s\" must be renamed in child tables too",
1641 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
1643 atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
1644 if (!HeapTupleIsValid(atttup))
1646 (errcode(ERRCODE_UNDEFINED_COLUMN),
1647 errmsg("column \"%s\" does not exist",
1649 attform = (Form_pg_attribute) GETSTRUCT(atttup);
1651 attnum = attform->attnum;
1654 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1655 errmsg("cannot rename system column \"%s\"",
1659 * if the attribute is inherited, forbid the renaming, unless we are
1660 * already inside a recursive rename.
1662 if (attform->attinhcount > 0 && !recursing)
1664 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1665 errmsg("cannot rename inherited column \"%s\"",
1668 /* should not already exist */
1669 /* this test is deliberately not attisdropped-aware */
1670 if (SearchSysCacheExists(ATTNAME,
1671 ObjectIdGetDatum(myrelid),
1672 PointerGetDatum(newattname),
1675 (errcode(ERRCODE_DUPLICATE_COLUMN),
1676 errmsg("column \"%s\" of relation \"%s\" already exists",
1677 newattname, RelationGetRelationName(targetrelation))));
1679 namestrcpy(&(attform->attname), newattname);
1681 simple_heap_update(attrelation, &atttup->t_self, atttup);
1683 /* keep system catalog indexes current */
1684 CatalogUpdateIndexes(attrelation, atttup);
1686 heap_freetuple(atttup);
1689 * Update column names of indexes that refer to the column being renamed.
1691 indexoidlist = RelationGetIndexList(targetrelation);
1693 foreach(indexoidscan, indexoidlist)
1695 Oid indexoid = lfirst_oid(indexoidscan);
1697 Form_pg_index indexform;
1701 * Scan through index columns to see if there's any simple index
1702 * entries for this attribute. We ignore expressional entries.
1704 indextup = SearchSysCache(INDEXRELID,
1705 ObjectIdGetDatum(indexoid),
1707 if (!HeapTupleIsValid(indextup))
1708 elog(ERROR, "cache lookup failed for index %u", indexoid);
1709 indexform = (Form_pg_index) GETSTRUCT(indextup);
1711 for (i = 0; i < indexform->indnatts; i++)
1713 if (attnum != indexform->indkey.values[i])
1717 * Found one, rename it.
1719 atttup = SearchSysCacheCopy(ATTNUM,
1720 ObjectIdGetDatum(indexoid),
1721 Int16GetDatum(i + 1),
1723 if (!HeapTupleIsValid(atttup))
1724 continue; /* should we raise an error? */
1727 * Update the (copied) attribute tuple.
1729 namestrcpy(&(((Form_pg_attribute) GETSTRUCT(atttup))->attname),
1732 simple_heap_update(attrelation, &atttup->t_self, atttup);
1734 /* keep system catalog indexes current */
1735 CatalogUpdateIndexes(attrelation, atttup);
1737 heap_freetuple(atttup);
1740 ReleaseSysCache(indextup);
1743 list_free(indexoidlist);
1745 heap_close(attrelation, RowExclusiveLock);
1747 relation_close(targetrelation, NoLock); /* close rel but keep lock */
1752 * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW RENAME
1754 * Caller has already done permissions checks.
1757 RenameRelation(Oid myrelid, const char *newrelname, ObjectType reltype)
1759 Relation targetrelation;
1764 * Grab an exclusive lock on the target table, index, sequence or view,
1765 * which we will NOT release until end of transaction.
1767 targetrelation = relation_open(myrelid, AccessExclusiveLock);
1769 namespaceId = RelationGetNamespace(targetrelation);
1770 relkind = targetrelation->rd_rel->relkind;
1773 * For compatibility with prior releases, we don't complain if ALTER TABLE
1774 * or ALTER INDEX is used to rename a sequence or view.
1776 if (reltype == OBJECT_SEQUENCE && relkind != RELKIND_SEQUENCE)
1778 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1779 errmsg("\"%s\" is not a sequence",
1780 RelationGetRelationName(targetrelation))));
1782 if (reltype == OBJECT_VIEW && relkind != RELKIND_VIEW)
1784 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1785 errmsg("\"%s\" is not a view",
1786 RelationGetRelationName(targetrelation))));
1789 * Don't allow ALTER TABLE on composite types.
1790 * We want people to use ALTER TYPE for that.
1792 if (relkind == RELKIND_COMPOSITE_TYPE)
1794 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1795 errmsg("\"%s\" is a composite type",
1796 RelationGetRelationName(targetrelation)),
1797 errhint("Use ALTER TYPE instead.")));
1800 RenameRelationInternal(myrelid, newrelname, namespaceId);
1803 * Close rel, but keep exclusive lock!
1805 relation_close(targetrelation, NoLock);
1809 * RenameRelationInternal - change the name of a relation
1811 * XXX - When renaming sequences, we don't bother to modify the
1812 * sequence name that is stored within the sequence itself
1813 * (this would cause problems with MVCC). In the future,
1814 * the sequence name should probably be removed from the
1815 * sequence, AFAIK there's no need for it to be there.
1818 RenameRelationInternal(Oid myrelid, const char *newrelname, Oid namespaceId)
1820 Relation targetrelation;
1821 Relation relrelation; /* for RELATION relation */
1823 Form_pg_class relform;
1826 * Grab an exclusive lock on the target table, index, sequence or
1827 * view, which we will NOT release until end of transaction.
1829 targetrelation = relation_open(myrelid, AccessExclusiveLock);
1832 * Find relation's pg_class tuple, and make sure newrelname isn't in use.
1834 relrelation = heap_open(RelationRelationId, RowExclusiveLock);
1836 reltup = SearchSysCacheCopy(RELOID,
1837 ObjectIdGetDatum(myrelid),
1839 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
1840 elog(ERROR, "cache lookup failed for relation %u", myrelid);
1841 relform = (Form_pg_class) GETSTRUCT(reltup);
1843 if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
1845 (errcode(ERRCODE_DUPLICATE_TABLE),
1846 errmsg("relation \"%s\" already exists",
1850 * Update pg_class tuple with new relname. (Scribbling on reltup is OK
1851 * because it's a copy...)
1853 namestrcpy(&(relform->relname), newrelname);
1855 simple_heap_update(relrelation, &reltup->t_self, reltup);
1857 /* keep the system catalog indexes current */
1858 CatalogUpdateIndexes(relrelation, reltup);
1860 heap_freetuple(reltup);
1861 heap_close(relrelation, RowExclusiveLock);
1864 * Also rename the associated type, if any.
1866 if (OidIsValid(targetrelation->rd_rel->reltype))
1867 RenameTypeInternal(targetrelation->rd_rel->reltype,
1868 newrelname, namespaceId);
1871 * Also rename the associated constraint, if any.
1873 if (targetrelation->rd_rel->relkind == RELKIND_INDEX)
1875 Oid constraintId = get_index_constraint(myrelid);
1877 if (OidIsValid(constraintId))
1878 RenameConstraintById(constraintId, newrelname);
1882 * Close rel, but keep exclusive lock!
1884 relation_close(targetrelation, NoLock);
1888 * Disallow ALTER TABLE (and similar commands) when the current backend has
1889 * any open reference to the target table besides the one just acquired by
1890 * the calling command; this implies there's an open cursor or active plan.
1891 * We need this check because our AccessExclusiveLock doesn't protect us
1892 * against stomping on our own foot, only other people's feet!
1894 * For ALTER TABLE, the only case known to cause serious trouble is ALTER
1895 * COLUMN TYPE, and some changes are obviously pretty benign, so this could
1896 * possibly be relaxed to only error out for certain types of alterations.
1897 * But the use-case for allowing any of these things is not obvious, so we
1898 * won't work hard at it for now.
1900 * We also reject these commands if there are any pending AFTER trigger events
1901 * for the rel. This is certainly necessary for the rewriting variants of
1902 * ALTER TABLE, because they don't preserve tuple TIDs and so the pending
1903 * events would try to fetch the wrong tuples. It might be overly cautious
1904 * in other cases, but again it seems better to err on the side of paranoia.
1906 * REINDEX calls this with "rel" referencing the index to be rebuilt; here
1907 * we are worried about active indexscans on the index. The trigger-event
1908 * check can be skipped, since we are doing no damage to the parent table.
1910 * The statement name (eg, "ALTER TABLE") is passed for use in error messages.
1913 CheckTableNotInUse(Relation rel, const char *stmt)
1915 int expected_refcnt;
1917 expected_refcnt = rel->rd_isnailed ? 2 : 1;
1918 if (rel->rd_refcnt != expected_refcnt)
1920 (errcode(ERRCODE_OBJECT_IN_USE),
1921 /* translator: first %s is a SQL command, eg ALTER TABLE */
1922 errmsg("cannot %s \"%s\" because "
1923 "it is being used by active queries in this session",
1924 stmt, RelationGetRelationName(rel))));
1926 if (rel->rd_rel->relkind != RELKIND_INDEX &&
1927 AfterTriggerPendingOnRel(RelationGetRelid(rel)))
1929 (errcode(ERRCODE_OBJECT_IN_USE),
1930 /* translator: first %s is a SQL command, eg ALTER TABLE */
1931 errmsg("cannot %s \"%s\" because "
1932 "it has pending trigger events",
1933 stmt, RelationGetRelationName(rel))));
1938 * Execute ALTER TABLE, which can be a list of subcommands
1940 * ALTER TABLE is performed in three phases:
1941 * 1. Examine subcommands and perform pre-transformation checking.
1942 * 2. Update system catalogs.
1943 * 3. Scan table(s) to check new constraints, and optionally recopy
1944 * the data into new table(s).
1945 * Phase 3 is not performed unless one or more of the subcommands requires
1946 * it. The intention of this design is to allow multiple independent
1947 * updates of the table schema to be performed with only one pass over the
1950 * ATPrepCmd performs phase 1. A "work queue" entry is created for
1951 * each table to be affected (there may be multiple affected tables if the
1952 * commands traverse a table inheritance hierarchy). Also we do preliminary
1953 * validation of the subcommands, including parse transformation of those
1954 * expressions that need to be evaluated with respect to the old table
1957 * ATRewriteCatalogs performs phase 2 for each affected table. (Note that
1958 * phases 2 and 3 normally do no explicit recursion, since phase 1 already
1959 * did it --- although some subcommands have to recurse in phase 2 instead.)
1960 * Certain subcommands need to be performed before others to avoid
1961 * unnecessary conflicts; for example, DROP COLUMN should come before
1962 * ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
1963 * lists, one for each logical "pass" of phase 2.
1965 * ATRewriteTables performs phase 3 for those tables that need it.
1967 * Thanks to the magic of MVCC, an error anywhere along the way rolls back
1968 * the whole operation; we don't have to do anything special to clean up.
1971 AlterTable(AlterTableStmt *stmt)
1973 Relation rel = relation_openrv(stmt->relation, AccessExclusiveLock);
1975 CheckTableNotInUse(rel, "ALTER TABLE");
1977 ATController(rel, stmt->cmds, interpretInhOption(stmt->relation->inhOpt));
1981 * AlterTableInternal
1983 * ALTER TABLE with target specified by OID
1985 * We do not reject if the relation is already open, because it's quite
1986 * likely that one or more layers of caller have it open. That means it
1987 * is unsafe to use this entry point for alterations that could break
1988 * existing query plans. On the assumption it's not used for such, we
1989 * don't have to reject pending AFTER triggers, either.
1992 AlterTableInternal(Oid relid, List *cmds, bool recurse)
1994 Relation rel = relation_open(relid, AccessExclusiveLock);
1996 ATController(rel, cmds, recurse);
2000 ATController(Relation rel, List *cmds, bool recurse)
2005 /* Phase 1: preliminary examination of commands, create work queue */
2008 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2010 ATPrepCmd(&wqueue, rel, cmd, recurse, false);
2013 /* Close the relation, but keep lock until commit */
2014 relation_close(rel, NoLock);
2016 /* Phase 2: update system catalogs */
2017 ATRewriteCatalogs(&wqueue);
2019 /* Phase 3: scan/rewrite tables as needed */
2020 ATRewriteTables(&wqueue);
2026 * Traffic cop for ALTER TABLE Phase 1 operations, including simple
2027 * recursion and permission checks.
2029 * Caller must have acquired AccessExclusiveLock on relation already.
2030 * This lock should be held until commit.
2033 ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
2034 bool recurse, bool recursing)
2036 AlteredTableInfo *tab;
2039 /* Find or create work queue entry for this table */
2040 tab = ATGetQueueEntry(wqueue, rel);
2043 * Copy the original subcommand for each table. This avoids conflicts
2044 * when different child tables need to make different parse
2045 * transformations (for example, the same column may have different column
2046 * numbers in different children).
2048 cmd = copyObject(cmd);
2051 * Do permissions checking, recursion to child tables if needed, and any
2052 * additional phase-1 processing needed.
2054 switch (cmd->subtype)
2056 case AT_AddColumn: /* ADD COLUMN */
2057 ATSimplePermissions(rel, false);
2058 /* Performs own recursion */
2059 ATPrepAddColumn(wqueue, rel, recurse, cmd);
2060 pass = AT_PASS_ADD_COL;
2062 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
2065 * We allow defaults on views so that INSERT into a view can have
2066 * default-ish behavior. This works because the rewriter
2067 * substitutes default values into INSERTs before it expands
2070 ATSimplePermissions(rel, true);
2071 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2072 /* No command-specific prep needed */
2073 pass = cmd->def ? AT_PASS_ADD_CONSTR : AT_PASS_DROP;
2075 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
2076 ATSimplePermissions(rel, false);
2077 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2078 /* No command-specific prep needed */
2079 pass = AT_PASS_DROP;
2081 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
2082 ATSimplePermissions(rel, false);
2083 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2084 /* No command-specific prep needed */
2085 pass = AT_PASS_ADD_CONSTR;
2087 case AT_SetStatistics: /* ALTER COLUMN STATISTICS */
2088 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2089 /* Performs own permission checks */
2090 ATPrepSetStatistics(rel, cmd->name, cmd->def);
2091 pass = AT_PASS_COL_ATTRS;
2093 case AT_SetStorage: /* ALTER COLUMN STORAGE */
2094 ATSimplePermissions(rel, false);
2095 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2096 /* No command-specific prep needed */
2097 pass = AT_PASS_COL_ATTRS;
2099 case AT_DropColumn: /* DROP COLUMN */
2100 ATSimplePermissions(rel, false);
2101 /* Recursion occurs during execution phase */
2102 /* No command-specific prep needed except saving recurse flag */
2104 cmd->subtype = AT_DropColumnRecurse;
2105 pass = AT_PASS_DROP;
2107 case AT_AddIndex: /* ADD INDEX */
2108 ATSimplePermissions(rel, false);
2109 /* This command never recurses */
2110 /* No command-specific prep needed */
2111 pass = AT_PASS_ADD_INDEX;
2113 case AT_AddConstraint: /* ADD CONSTRAINT */
2114 ATSimplePermissions(rel, false);
2115 /* Recursion occurs during execution phase */
2116 /* No command-specific prep needed except saving recurse flag */
2118 cmd->subtype = AT_AddConstraintRecurse;
2119 pass = AT_PASS_ADD_CONSTR;
2121 case AT_DropConstraint: /* DROP CONSTRAINT */
2122 ATSimplePermissions(rel, false);
2123 /* Recursion occurs during execution phase */
2124 /* No command-specific prep needed except saving recurse flag */
2126 cmd->subtype = AT_DropConstraintRecurse;
2127 pass = AT_PASS_DROP;
2129 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
2130 ATSimplePermissions(rel, false);
2131 /* Performs own recursion */
2132 ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd);
2133 pass = AT_PASS_ALTER_TYPE;
2135 case AT_ChangeOwner: /* ALTER OWNER */
2136 /* This command never recurses */
2137 /* No command-specific prep needed */
2138 pass = AT_PASS_MISC;
2140 case AT_ClusterOn: /* CLUSTER ON */
2141 case AT_DropCluster: /* SET WITHOUT CLUSTER */
2142 ATSimplePermissions(rel, false);
2143 /* These commands never recurse */
2144 /* No command-specific prep needed */
2145 pass = AT_PASS_MISC;
2147 case AT_DropOids: /* SET WITHOUT OIDS */
2148 ATSimplePermissions(rel, false);
2149 /* Performs own recursion */
2150 if (rel->rd_rel->relhasoids)
2152 AlterTableCmd *dropCmd = makeNode(AlterTableCmd);
2154 dropCmd->subtype = AT_DropColumn;
2155 dropCmd->name = pstrdup("oid");
2156 dropCmd->behavior = cmd->behavior;
2157 ATPrepCmd(wqueue, rel, dropCmd, recurse, false);
2159 pass = AT_PASS_DROP;
2161 case AT_SetTableSpace: /* SET TABLESPACE */
2162 ATSimplePermissionsRelationOrIndex(rel);
2163 /* This command never recurses */
2164 ATPrepSetTableSpace(tab, rel, cmd->name);
2165 pass = AT_PASS_MISC; /* doesn't actually matter */
2167 case AT_SetRelOptions: /* SET (...) */
2168 case AT_ResetRelOptions: /* RESET (...) */
2169 ATSimplePermissionsRelationOrIndex(rel);
2170 /* This command never recurses */
2171 /* No command-specific prep needed */
2172 pass = AT_PASS_MISC;
2174 case AT_EnableTrig: /* ENABLE TRIGGER variants */
2175 case AT_EnableAlwaysTrig:
2176 case AT_EnableReplicaTrig:
2177 case AT_EnableTrigAll:
2178 case AT_EnableTrigUser:
2179 case AT_DisableTrig: /* DISABLE TRIGGER variants */
2180 case AT_DisableTrigAll:
2181 case AT_DisableTrigUser:
2182 case AT_EnableRule: /* ENABLE/DISABLE RULE variants */
2183 case AT_EnableAlwaysRule:
2184 case AT_EnableReplicaRule:
2185 case AT_DisableRule:
2186 case AT_AddInherit: /* INHERIT / NO INHERIT */
2187 case AT_DropInherit:
2188 ATSimplePermissions(rel, false);
2189 /* These commands never recurse */
2190 /* No command-specific prep needed */
2191 pass = AT_PASS_MISC;
2194 elog(ERROR, "unrecognized alter table type: %d",
2195 (int) cmd->subtype);
2196 pass = 0; /* keep compiler quiet */
2200 /* Add the subcommand to the appropriate list for phase 2 */
2201 tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
2207 * Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
2208 * dispatched in a "safe" execution order (designed to avoid unnecessary
2212 ATRewriteCatalogs(List **wqueue)
2218 * We process all the tables "in parallel", one pass at a time. This is
2219 * needed because we may have to propagate work from one table to another
2220 * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
2221 * re-adding of the foreign key constraint to the other table). Work can
2222 * only be propagated into later passes, however.
2224 for (pass = 0; pass < AT_NUM_PASSES; pass++)
2226 /* Go through each table that needs to be processed */
2227 foreach(ltab, *wqueue)
2229 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2230 List *subcmds = tab->subcmds[pass];
2238 * Exclusive lock was obtained by phase 1, needn't get it again
2240 rel = relation_open(tab->relid, NoLock);
2242 foreach(lcmd, subcmds)
2243 ATExecCmd(wqueue, tab, rel, (AlterTableCmd *) lfirst(lcmd));
2246 * After the ALTER TYPE pass, do cleanup work (this is not done in
2247 * ATExecAlterColumnType since it should be done only once if
2248 * multiple columns of a table are altered).
2250 if (pass == AT_PASS_ALTER_TYPE)
2251 ATPostAlterTypeCleanup(wqueue, tab);
2253 relation_close(rel, NoLock);
2258 * Check to see if a toast table must be added, if we executed any
2259 * subcommands that might have added a column or changed column storage.
2261 foreach(ltab, *wqueue)
2263 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2265 if (tab->relkind == RELKIND_RELATION &&
2266 (tab->subcmds[AT_PASS_ADD_COL] ||
2267 tab->subcmds[AT_PASS_ALTER_TYPE] ||
2268 tab->subcmds[AT_PASS_COL_ATTRS]))
2269 AlterTableCreateToastTable(tab->relid);
2274 * ATExecCmd: dispatch a subcommand to appropriate execution routine
2277 ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
2280 switch (cmd->subtype)
2282 case AT_AddColumn: /* ADD COLUMN */
2283 ATExecAddColumn(tab, rel, (ColumnDef *) cmd->def);
2285 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
2286 ATExecColumnDefault(rel, cmd->name, cmd->def);
2288 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
2289 ATExecDropNotNull(rel, cmd->name);
2291 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
2292 ATExecSetNotNull(tab, rel, cmd->name);
2294 case AT_SetStatistics: /* ALTER COLUMN STATISTICS */
2295 ATExecSetStatistics(rel, cmd->name, cmd->def);
2297 case AT_SetStorage: /* ALTER COLUMN STORAGE */
2298 ATExecSetStorage(rel, cmd->name, cmd->def);
2300 case AT_DropColumn: /* DROP COLUMN */
2301 ATExecDropColumn(rel, cmd->name, cmd->behavior, false, false);
2303 case AT_DropColumnRecurse: /* DROP COLUMN with recursion */
2304 ATExecDropColumn(rel, cmd->name, cmd->behavior, true, false);
2306 case AT_AddIndex: /* ADD INDEX */
2307 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false);
2309 case AT_ReAddIndex: /* ADD INDEX */
2310 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true);
2312 case AT_AddConstraint: /* ADD CONSTRAINT */
2313 ATExecAddConstraint(wqueue, tab, rel, cmd->def, false);
2315 case AT_AddConstraintRecurse: /* ADD CONSTRAINT with recursion */
2316 ATExecAddConstraint(wqueue, tab, rel, cmd->def, true);
2318 case AT_DropConstraint: /* DROP CONSTRAINT */
2319 ATExecDropConstraint(rel, cmd->name, cmd->behavior, false, false);
2321 case AT_DropConstraintRecurse: /* DROP CONSTRAINT with recursion */
2322 ATExecDropConstraint(rel, cmd->name, cmd->behavior, true, false);
2324 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
2325 ATExecAlterColumnType(tab, rel, cmd->name, (TypeName *) cmd->def);
2327 case AT_ChangeOwner: /* ALTER OWNER */
2328 ATExecChangeOwner(RelationGetRelid(rel),
2329 get_roleid_checked(cmd->name),
2332 case AT_ClusterOn: /* CLUSTER ON */
2333 ATExecClusterOn(rel, cmd->name);
2335 case AT_DropCluster: /* SET WITHOUT CLUSTER */
2336 ATExecDropCluster(rel);
2338 case AT_DropOids: /* SET WITHOUT OIDS */
2341 * Nothing to do here; we'll have generated a DropColumn
2342 * subcommand to do the real work
2345 case AT_SetTableSpace: /* SET TABLESPACE */
2348 * Nothing to do here; Phase 3 does the work
2351 case AT_SetRelOptions: /* SET (...) */
2352 ATExecSetRelOptions(rel, (List *) cmd->def, false);
2354 case AT_ResetRelOptions: /* RESET (...) */
2355 ATExecSetRelOptions(rel, (List *) cmd->def, true);
2358 case AT_EnableTrig: /* ENABLE TRIGGER name */
2359 ATExecEnableDisableTrigger(rel, cmd->name,
2360 TRIGGER_FIRES_ON_ORIGIN, false);
2362 case AT_EnableAlwaysTrig: /* ENABLE ALWAYS TRIGGER name */
2363 ATExecEnableDisableTrigger(rel, cmd->name,
2364 TRIGGER_FIRES_ALWAYS, false);
2366 case AT_EnableReplicaTrig: /* ENABLE REPLICA TRIGGER name */
2367 ATExecEnableDisableTrigger(rel, cmd->name,
2368 TRIGGER_FIRES_ON_REPLICA, false);
2370 case AT_DisableTrig: /* DISABLE TRIGGER name */
2371 ATExecEnableDisableTrigger(rel, cmd->name,
2372 TRIGGER_DISABLED, false);
2374 case AT_EnableTrigAll: /* ENABLE TRIGGER ALL */
2375 ATExecEnableDisableTrigger(rel, NULL,
2376 TRIGGER_FIRES_ON_ORIGIN, false);
2378 case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
2379 ATExecEnableDisableTrigger(rel, NULL,
2380 TRIGGER_DISABLED, false);
2382 case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
2383 ATExecEnableDisableTrigger(rel, NULL,
2384 TRIGGER_FIRES_ON_ORIGIN, true);
2386 case AT_DisableTrigUser: /* DISABLE TRIGGER USER */
2387 ATExecEnableDisableTrigger(rel, NULL,
2388 TRIGGER_DISABLED, true);
2391 case AT_EnableRule: /* ENABLE RULE name */
2392 ATExecEnableDisableRule(rel, cmd->name,
2393 RULE_FIRES_ON_ORIGIN);
2395 case AT_EnableAlwaysRule: /* ENABLE ALWAYS RULE name */
2396 ATExecEnableDisableRule(rel, cmd->name,
2399 case AT_EnableReplicaRule: /* ENABLE REPLICA RULE name */
2400 ATExecEnableDisableRule(rel, cmd->name,
2401 RULE_FIRES_ON_REPLICA);
2403 case AT_DisableRule: /* DISABLE RULE name */
2404 ATExecEnableDisableRule(rel, cmd->name,
2409 ATExecAddInherit(rel, (RangeVar *) cmd->def);
2411 case AT_DropInherit:
2412 ATExecDropInherit(rel, (RangeVar *) cmd->def);
2415 elog(ERROR, "unrecognized alter table type: %d",
2416 (int) cmd->subtype);
2421 * Bump the command counter to ensure the next subcommand in the sequence
2422 * can see the changes so far
2424 CommandCounterIncrement();
2428 * ATRewriteTables: ALTER TABLE phase 3
2431 ATRewriteTables(List **wqueue)
2435 /* Go through each table that needs to be checked or rewritten */
2436 foreach(ltab, *wqueue)
2438 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2441 * We only need to rewrite the table if at least one column needs to
2444 if (tab->newvals != NIL)
2446 /* Build a temporary relation and copy data */
2448 char NewHeapName[NAMEDATALEN];
2451 ObjectAddress object;
2453 OldHeap = heap_open(tab->relid, NoLock);
2456 * We can never allow rewriting of shared or nailed-in-cache
2457 * relations, because we can't support changing their relfilenode
2460 if (OldHeap->rd_rel->relisshared || OldHeap->rd_isnailed)
2462 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2463 errmsg("cannot rewrite system relation \"%s\"",
2464 RelationGetRelationName(OldHeap))));
2467 * Don't allow rewrite on temp tables of other backends ... their
2468 * local buffer manager is not going to cope.
2470 if (isOtherTempNamespace(RelationGetNamespace(OldHeap)))
2472 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2473 errmsg("cannot rewrite temporary tables of other sessions")));
2476 * Select destination tablespace (same as original unless user
2477 * requested a change)
2479 if (tab->newTableSpace)
2480 NewTableSpace = tab->newTableSpace;
2482 NewTableSpace = OldHeap->rd_rel->reltablespace;
2484 heap_close(OldHeap, NoLock);
2487 * Create the new heap, using a temporary name in the same
2488 * namespace as the existing table. NOTE: there is some risk of
2489 * collision with user relnames. Working around this seems more
2490 * trouble than it's worth; in particular, we can't create the new
2491 * heap in a different namespace from the old, or we will have
2492 * problems with the TEMP status of temp tables.
2494 snprintf(NewHeapName, sizeof(NewHeapName),
2495 "pg_temp_%u", tab->relid);
2497 OIDNewHeap = make_new_heap(tab->relid, NewHeapName, NewTableSpace);
2500 * Copy the heap data into the new table with the desired
2501 * modifications, and test the current data within the table
2502 * against new constraints generated by ALTER TABLE commands.
2504 ATRewriteTable(tab, OIDNewHeap);
2507 * Swap the physical files of the old and new heaps. Since we are
2508 * generating a new heap, we can use RecentXmin for the table's
2509 * new relfrozenxid because we rewrote all the tuples on
2510 * ATRewriteTable, so no older Xid remains on the table.
2512 swap_relation_files(tab->relid, OIDNewHeap, RecentXmin);
2514 CommandCounterIncrement();
2516 /* Destroy new heap with old filenode */
2517 object.classId = RelationRelationId;
2518 object.objectId = OIDNewHeap;
2519 object.objectSubId = 0;
2522 * The new relation is local to our transaction and we know
2523 * nothing depends on it, so DROP_RESTRICT should be OK.
2525 performDeletion(&object, DROP_RESTRICT);
2526 /* performDeletion does CommandCounterIncrement at end */
2529 * Rebuild each index on the relation (but not the toast table,
2530 * which is all-new anyway). We do not need
2531 * CommandCounterIncrement() because reindex_relation does it.
2533 reindex_relation(tab->relid, false);
2538 * Test the current data within the table against new constraints
2539 * generated by ALTER TABLE commands, but don't rebuild data.
2541 if (tab->constraints != NIL || tab->new_notnull)
2542 ATRewriteTable(tab, InvalidOid);
2545 * If we had SET TABLESPACE but no reason to reconstruct tuples,
2546 * just do a block-by-block copy.
2548 if (tab->newTableSpace)
2549 ATExecSetTableSpace(tab->relid, tab->newTableSpace);
2554 * Foreign key constraints are checked in a final pass, since (a) it's
2555 * generally best to examine each one separately, and (b) it's at least
2556 * theoretically possible that we have changed both relations of the
2557 * foreign key, and we'd better have finished both rewrites before we try
2558 * to read the tables.
2560 foreach(ltab, *wqueue)
2562 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2563 Relation rel = NULL;
2566 foreach(lcon, tab->constraints)
2568 NewConstraint *con = lfirst(lcon);
2570 if (con->contype == CONSTR_FOREIGN)
2572 FkConstraint *fkconstraint = (FkConstraint *) con->qual;
2577 /* Long since locked, no need for another */
2578 rel = heap_open(tab->relid, NoLock);
2581 refrel = heap_open(con->refrelid, RowShareLock);
2583 validateForeignKeyConstraint(fkconstraint, rel, refrel,
2586 heap_close(refrel, NoLock);
2591 heap_close(rel, NoLock);
2596 * ATRewriteTable: scan or rewrite one table
2598 * OIDNewHeap is InvalidOid if we don't need to rewrite
2601 ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap)
2605 TupleDesc oldTupDesc;
2606 TupleDesc newTupDesc;
2607 bool needscan = false;
2608 List *notnull_attrs;
2614 * Open the relation(s). We have surely already locked the existing
2617 oldrel = heap_open(tab->relid, NoLock);
2618 oldTupDesc = tab->oldDesc;
2619 newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
2621 if (OidIsValid(OIDNewHeap))
2622 newrel = heap_open(OIDNewHeap, AccessExclusiveLock);
2627 * If we need to rewrite the table, the operation has to be propagated to
2628 * tables that use this table's rowtype as a column type.
2630 * (Eventually this will probably become true for scans as well, but at
2631 * the moment a composite type does not enforce any constraints, so it's
2632 * not necessary/appropriate to enforce them just during ALTER.)
2635 find_composite_type_dependencies(oldrel->rd_rel->reltype,
2636 RelationGetRelationName(oldrel),
2640 * Generate the constraint and default execution states
2643 estate = CreateExecutorState();
2645 /* Build the needed expression execution states */
2646 foreach(l, tab->constraints)
2648 NewConstraint *con = lfirst(l);
2650 switch (con->contype)
2654 con->qualstate = (List *)
2655 ExecPrepareExpr((Expr *) con->qual, estate);
2657 case CONSTR_FOREIGN:
2658 /* Nothing to do here */
2661 elog(ERROR, "unrecognized constraint type: %d",
2662 (int) con->contype);
2666 foreach(l, tab->newvals)
2668 NewColumnValue *ex = lfirst(l);
2672 ex->exprstate = ExecPrepareExpr((Expr *) ex->expr, estate);
2675 notnull_attrs = NIL;
2676 if (newrel || tab->new_notnull)
2679 * If we are rebuilding the tuples OR if we added any new NOT NULL
2680 * constraints, check all not-null constraints. This is a bit of
2681 * overkill but it minimizes risk of bugs, and heap_attisnull is a
2682 * pretty cheap test anyway.
2684 for (i = 0; i < newTupDesc->natts; i++)
2686 if (newTupDesc->attrs[i]->attnotnull &&
2687 !newTupDesc->attrs[i]->attisdropped)
2688 notnull_attrs = lappend_int(notnull_attrs, i);
2696 ExprContext *econtext;
2699 TupleTableSlot *oldslot;
2700 TupleTableSlot *newslot;
2703 MemoryContext oldCxt;
2704 List *dropped_attrs = NIL;
2707 econtext = GetPerTupleExprContext(estate);
2710 * Make tuple slots for old and new tuples. Note that even when the
2711 * tuples are the same, the tupDescs might not be (consider ADD COLUMN
2712 * without a default).
2714 oldslot = MakeSingleTupleTableSlot(oldTupDesc);
2715 newslot = MakeSingleTupleTableSlot(newTupDesc);
2717 /* Preallocate values/isnull arrays */
2718 i = Max(newTupDesc->natts, oldTupDesc->natts);
2719 values = (Datum *) palloc(i * sizeof(Datum));
2720 isnull = (bool *) palloc(i * sizeof(bool));
2721 memset(values, 0, i * sizeof(Datum));
2722 memset(isnull, true, i * sizeof(bool));
2725 * Any attributes that are dropped according to the new tuple
2726 * descriptor can be set to NULL. We precompute the list of dropped
2727 * attributes to avoid needing to do so in the per-tuple loop.
2729 for (i = 0; i < newTupDesc->natts; i++)
2731 if (newTupDesc->attrs[i]->attisdropped)
2732 dropped_attrs = lappend_int(dropped_attrs, i);
2736 * Scan through the rows, generating a new row if needed and then
2737 * checking all the constraints.
2739 scan = heap_beginscan(oldrel, SnapshotNow, 0, NULL);
2742 * Switch to per-tuple memory context and reset it for each tuple
2743 * produced, so we don't leak memory.
2745 oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
2747 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2751 Oid tupOid = InvalidOid;
2753 /* Extract data from old tuple */
2754 heap_deform_tuple(tuple, oldTupDesc, values, isnull);
2755 if (oldTupDesc->tdhasoid)
2756 tupOid = HeapTupleGetOid(tuple);
2758 /* Set dropped attributes to null in new tuple */
2759 foreach(lc, dropped_attrs)
2760 isnull[lfirst_int(lc)] = true;
2763 * Process supplied expressions to replace selected columns.
2764 * Expression inputs come from the old tuple.
2766 ExecStoreTuple(tuple, oldslot, InvalidBuffer, false);
2767 econtext->ecxt_scantuple = oldslot;
2769 foreach(l, tab->newvals)
2771 NewColumnValue *ex = lfirst(l);
2773 values[ex->attnum - 1] = ExecEvalExpr(ex->exprstate,
2775 &isnull[ex->attnum - 1],
2780 * Form the new tuple. Note that we don't explicitly pfree it,
2781 * since the per-tuple memory context will be reset shortly.
2783 tuple = heap_form_tuple(newTupDesc, values, isnull);
2785 /* Preserve OID, if any */
2786 if (newTupDesc->tdhasoid)
2787 HeapTupleSetOid(tuple, tupOid);
2790 /* Now check any constraints on the possibly-changed tuple */
2791 ExecStoreTuple(tuple, newslot, InvalidBuffer, false);
2792 econtext->ecxt_scantuple = newslot;
2794 foreach(l, notnull_attrs)
2796 int attn = lfirst_int(l);
2798 if (heap_attisnull(tuple, attn + 1))
2800 (errcode(ERRCODE_NOT_NULL_VIOLATION),
2801 errmsg("column \"%s\" contains null values",
2802 NameStr(newTupDesc->attrs[attn]->attname))));
2805 foreach(l, tab->constraints)
2807 NewConstraint *con = lfirst(l);
2809 switch (con->contype)
2812 if (!ExecQual(con->qualstate, econtext, true))
2814 (errcode(ERRCODE_CHECK_VIOLATION),
2815 errmsg("check constraint \"%s\" is violated by some row",
2818 case CONSTR_FOREIGN:
2819 /* Nothing to do here */
2822 elog(ERROR, "unrecognized constraint type: %d",
2823 (int) con->contype);
2827 /* Write the tuple out to the new relation */
2829 simple_heap_insert(newrel, tuple);
2831 ResetExprContext(econtext);
2833 CHECK_FOR_INTERRUPTS();
2836 MemoryContextSwitchTo(oldCxt);
2839 ExecDropSingleTupleTableSlot(oldslot);
2840 ExecDropSingleTupleTableSlot(newslot);
2843 FreeExecutorState(estate);
2845 heap_close(oldrel, NoLock);
2847 heap_close(newrel, NoLock);
2851 * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
2853 static AlteredTableInfo *
2854 ATGetQueueEntry(List **wqueue, Relation rel)
2856 Oid relid = RelationGetRelid(rel);
2857 AlteredTableInfo *tab;
2860 foreach(ltab, *wqueue)
2862 tab = (AlteredTableInfo *) lfirst(ltab);
2863 if (tab->relid == relid)
2868 * Not there, so add it. Note that we make a copy of the relation's
2869 * existing descriptor before anything interesting can happen to it.
2871 tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
2873 tab->relkind = rel->rd_rel->relkind;
2874 tab->oldDesc = CreateTupleDescCopy(RelationGetDescr(rel));
2876 *wqueue = lappend(*wqueue, tab);
2882 * ATSimplePermissions
2884 * - Ensure that it is a relation (or possibly a view)
2885 * - Ensure this user is the owner
2886 * - Ensure that it is not a system table
2889 ATSimplePermissions(Relation rel, bool allowView)
2891 if (rel->rd_rel->relkind != RELKIND_RELATION)
2895 if (rel->rd_rel->relkind != RELKIND_VIEW)
2897 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2898 errmsg("\"%s\" is not a table or view",
2899 RelationGetRelationName(rel))));
2903 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2904 errmsg("\"%s\" is not a table",
2905 RelationGetRelationName(rel))));
2908 /* Permissions checks */
2909 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
2910 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
2911 RelationGetRelationName(rel));
2913 if (!allowSystemTableMods && IsSystemRelation(rel))
2915 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2916 errmsg("permission denied: \"%s\" is a system catalog",
2917 RelationGetRelationName(rel))));
2921 * ATSimplePermissionsRelationOrIndex
2923 * - Ensure that it is a relation or an index
2924 * - Ensure this user is the owner
2925 * - Ensure that it is not a system table
2928 ATSimplePermissionsRelationOrIndex(Relation rel)
2930 if (rel->rd_rel->relkind != RELKIND_RELATION &&
2931 rel->rd_rel->relkind != RELKIND_INDEX)
2933 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2934 errmsg("\"%s\" is not a table or index",
2935 RelationGetRelationName(rel))));
2937 /* Permissions checks */
2938 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
2939 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
2940 RelationGetRelationName(rel));
2942 if (!allowSystemTableMods && IsSystemRelation(rel))
2944 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2945 errmsg("permission denied: \"%s\" is a system catalog",
2946 RelationGetRelationName(rel))));
2952 * Simple table recursion sufficient for most ALTER TABLE operations.
2953 * All direct and indirect children are processed in an unspecified order.
2954 * Note that if a child inherits from the original table via multiple
2955 * inheritance paths, it will be visited just once.
2958 ATSimpleRecursion(List **wqueue, Relation rel,
2959 AlterTableCmd *cmd, bool recurse)
2962 * Propagate to children if desired. Non-table relations never have
2963 * children, so no need to search in that case.
2965 if (recurse && rel->rd_rel->relkind == RELKIND_RELATION)
2967 Oid relid = RelationGetRelid(rel);
2971 /* this routine is actually in the planner */
2972 children = find_all_inheritors(relid);
2975 * find_all_inheritors does the recursive search of the inheritance
2976 * hierarchy, so all we have to do is process all of the relids in the
2977 * list that it returns.
2979 foreach(child, children)
2981 Oid childrelid = lfirst_oid(child);
2984 if (childrelid == relid)
2986 childrel = relation_open(childrelid, AccessExclusiveLock);
2987 CheckTableNotInUse(childrel, "ALTER TABLE");
2988 ATPrepCmd(wqueue, childrel, cmd, false, true);
2989 relation_close(childrel, NoLock);
2995 * ATOneLevelRecursion
2997 * Here, we visit only direct inheritance children. It is expected that
2998 * the command's prep routine will recurse again to find indirect children.
2999 * When using this technique, a multiply-inheriting child will be visited
3003 ATOneLevelRecursion(List **wqueue, Relation rel,
3006 Oid relid = RelationGetRelid(rel);
3010 /* this routine is actually in the planner */
3011 children = find_inheritance_children(relid);
3013 foreach(child, children)
3015 Oid childrelid = lfirst_oid(child);
3018 childrel = relation_open(childrelid, AccessExclusiveLock);
3019 CheckTableNotInUse(childrel, "ALTER TABLE");
3020 ATPrepCmd(wqueue, childrel, cmd, true, true);
3021 relation_close(childrel, NoLock);
3027 * find_composite_type_dependencies
3029 * Check to see if a composite type is being used as a column in some
3030 * other table (possibly nested several levels deep in composite types!).
3031 * Eventually, we'd like to propagate the check or rewrite operation
3032 * into other such tables, but for now, just error out if we find any.
3034 * Caller should provide either a table name or a type name (not both) to
3035 * report in the error message, if any.
3037 * We assume that functions and views depending on the type are not reasons
3038 * to reject the ALTER. (How safe is this really?)
3041 find_composite_type_dependencies(Oid typeOid,
3042 const char *origTblName,
3043 const char *origTypeName)
3047 SysScanDesc depScan;
3052 * We scan pg_depend to find those things that depend on the rowtype. (We
3053 * assume we can ignore refobjsubid for a rowtype.)
3055 depRel = heap_open(DependRelationId, AccessShareLock);
3057 ScanKeyInit(&key[0],
3058 Anum_pg_depend_refclassid,
3059 BTEqualStrategyNumber, F_OIDEQ,
3060 ObjectIdGetDatum(TypeRelationId));
3061 ScanKeyInit(&key[1],
3062 Anum_pg_depend_refobjid,
3063 BTEqualStrategyNumber, F_OIDEQ,
3064 ObjectIdGetDatum(typeOid));
3066 depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
3067 SnapshotNow, 2, key);
3069 while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
3071 Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
3073 Form_pg_attribute att;
3075 /* Ignore dependees that aren't user columns of relations */
3076 /* (we assume system columns are never of rowtypes) */
3077 if (pg_depend->classid != RelationRelationId ||
3078 pg_depend->objsubid <= 0)
3081 rel = relation_open(pg_depend->objid, AccessShareLock);
3082 att = rel->rd_att->attrs[pg_depend->objsubid - 1];
3084 if (rel->rd_rel->relkind == RELKIND_RELATION)
3088 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3089 errmsg("cannot alter table \"%s\" because column \"%s\".\"%s\" uses its rowtype",
3091 RelationGetRelationName(rel),
3092 NameStr(att->attname))));
3095 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3096 errmsg("cannot alter type \"%s\" because column \"%s\".\"%s\" uses it",
3098 RelationGetRelationName(rel),
3099 NameStr(att->attname))));
3101 else if (OidIsValid(rel->rd_rel->reltype))
3104 * A view or composite type itself isn't a problem, but we must
3105 * recursively check for indirect dependencies via its rowtype.
3107 find_composite_type_dependencies(rel->rd_rel->reltype,
3108 origTblName, origTypeName);
3111 relation_close(rel, AccessShareLock);
3114 systable_endscan(depScan);
3116 relation_close(depRel, AccessShareLock);
3119 * If there's an array type for the rowtype, must check for uses of it,
3122 arrayOid = get_array_type(typeOid);
3123 if (OidIsValid(arrayOid))
3124 find_composite_type_dependencies(arrayOid, origTblName, origTypeName);
3129 * ALTER TABLE ADD COLUMN
3131 * Adds an additional attribute to a relation making the assumption that
3132 * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
3133 * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
3137 ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
3141 * Recurse to add the column to child classes, if requested.
3143 * We must recurse one level at a time, so that multiply-inheriting
3144 * children are visited the right number of times and end up with the
3145 * right attinhcount.
3149 AlterTableCmd *childCmd = copyObject(cmd);
3150 ColumnDef *colDefChild = (ColumnDef *) childCmd->def;
3152 /* Child should see column as singly inherited */
3153 colDefChild->inhcount = 1;
3154 colDefChild->is_local = false;
3156 ATOneLevelRecursion(wqueue, rel, childCmd);
3161 * If we are told not to recurse, there had better not be any child
3162 * tables; else the addition would put them out of step.
3164 if (find_inheritance_children(RelationGetRelid(rel)) != NIL)
3166 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3167 errmsg("column must be added to child tables too")));
3172 ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
3175 Oid myrelid = RelationGetRelid(rel);
3179 HeapTuple attributeTuple;
3180 Form_pg_attribute attribute;
3181 FormData_pg_attribute attributeD;
3185 HeapTuple typeTuple;
3191 attrdesc = heap_open(AttributeRelationId, RowExclusiveLock);
3194 * Are we adding the column to a recursion child? If so, check whether to
3195 * merge with an existing definition for the column.
3197 if (colDef->inhcount > 0)
3201 /* Does child already have a column by this name? */
3202 tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
3203 if (HeapTupleIsValid(tuple))
3205 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
3209 /* Okay if child matches by type */
3210 ctypeId = typenameTypeId(NULL, colDef->typename, &ctypmod);
3211 if (ctypeId != childatt->atttypid ||
3212 ctypmod != childatt->atttypmod)
3214 (errcode(ERRCODE_DATATYPE_MISMATCH),
3215 errmsg("child table \"%s\" has different type for column \"%s\"",
3216 RelationGetRelationName(rel), colDef->colname)));
3218 /* Bump the existing child att's inhcount */
3219 childatt->attinhcount++;
3220 simple_heap_update(attrdesc, &tuple->t_self, tuple);
3221 CatalogUpdateIndexes(attrdesc, tuple);
3223 heap_freetuple(tuple);
3225 /* Inform the user about the merge */
3227 (errmsg("merging definition of column \"%s\" for child \"%s\"",
3228 colDef->colname, RelationGetRelationName(rel))));
3230 heap_close(attrdesc, RowExclusiveLock);
3235 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
3237 reltup = SearchSysCacheCopy(RELOID,
3238 ObjectIdGetDatum(myrelid),
3240 if (!HeapTupleIsValid(reltup))
3241 elog(ERROR, "cache lookup failed for relation %u", myrelid);
3244 * this test is deliberately not attisdropped-aware, since if one tries to
3245 * add a column matching a dropped column name, it's gonna fail anyway.
3247 if (SearchSysCacheExists(ATTNAME,
3248 ObjectIdGetDatum(myrelid),
3249 PointerGetDatum(colDef->colname),
3252 (errcode(ERRCODE_DUPLICATE_COLUMN),
3253 errmsg("column \"%s\" of relation \"%s\" already exists",
3254 colDef->colname, RelationGetRelationName(rel))));
3256 minattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts;
3257 maxatts = minattnum + 1;
3258 if (maxatts > MaxHeapAttributeNumber)
3260 (errcode(ERRCODE_TOO_MANY_COLUMNS),
3261 errmsg("tables can have at most %d columns",
3262 MaxHeapAttributeNumber)));
3265 typeTuple = typenameType(NULL, colDef->typename, &typmod);
3266 tform = (Form_pg_type) GETSTRUCT(typeTuple);
3267 typeOid = HeapTupleGetOid(typeTuple);
3269 /* make sure datatype is legal for a column */
3270 CheckAttributeType(colDef->colname, typeOid);
3272 attributeTuple = heap_addheader(Natts_pg_attribute,
3274 ATTRIBUTE_TUPLE_SIZE,
3275 (void *) &attributeD);
3277 attribute = (Form_pg_attribute) GETSTRUCT(attributeTuple);
3279 attribute->attrelid = myrelid;
3280 namestrcpy(&(attribute->attname), colDef->colname);
3281 attribute->atttypid = typeOid;
3282 attribute->attstattarget = -1;
3283 attribute->attlen = tform->typlen;
3284 attribute->attcacheoff = -1;
3285 attribute->atttypmod = typmod;
3286 attribute->attnum = i;
3287 attribute->attbyval = tform->typbyval;
3288 attribute->attndims = list_length(colDef->typename->arrayBounds);
3289 attribute->attstorage = tform->typstorage;
3290 attribute->attalign = tform->typalign;
3291 attribute->attnotnull = colDef->is_not_null;
3292 attribute->atthasdef = false;
3293 attribute->attisdropped = false;
3294 attribute->attislocal = colDef->is_local;
3295 attribute->attinhcount = colDef->inhcount;
3297 ReleaseSysCache(typeTuple);
3299 simple_heap_insert(attrdesc, attributeTuple);
3301 /* Update indexes on pg_attribute */
3302 CatalogUpdateIndexes(attrdesc, attributeTuple);
3304 heap_close(attrdesc, RowExclusiveLock);
3307 * Update number of attributes in pg_class tuple
3309 ((Form_pg_class) GETSTRUCT(reltup))->relnatts = maxatts;
3311 simple_heap_update(pgclass, &reltup->t_self, reltup);
3313 /* keep catalog indexes current */
3314 CatalogUpdateIndexes(pgclass, reltup);
3316 heap_freetuple(reltup);
3318 heap_close(pgclass, RowExclusiveLock);
3320 /* Make the attribute's catalog entry visible */
3321 CommandCounterIncrement();
3324 * Store the DEFAULT, if any, in the catalogs
3326 if (colDef->raw_default)
3328 RawColumnDefault *rawEnt;
3330 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3331 rawEnt->attnum = attribute->attnum;
3332 rawEnt->raw_default = copyObject(colDef->raw_default);
3335 * This function is intended for CREATE TABLE, so it processes a
3336 * _list_ of defaults, but we just do one.
3338 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL, false, true);
3340 /* Make the additional catalog changes visible */
3341 CommandCounterIncrement();
3345 * Tell Phase 3 to fill in the default expression, if there is one.
3347 * If there is no default, Phase 3 doesn't have to do anything, because
3348 * that effectively means that the default is NULL. The heap tuple access
3349 * routines always check for attnum > # of attributes in tuple, and return
3350 * NULL if so, so without any modification of the tuple data we will get
3351 * the effect of NULL values in the new column.
3353 * An exception occurs when the new column is of a domain type: the domain
3354 * might have a NOT NULL constraint, or a check constraint that indirectly
3355 * rejects nulls. If there are any domain constraints then we construct
3356 * an explicit NULL default value that will be passed through
3357 * CoerceToDomain processing. (This is a tad inefficient, since it causes
3358 * rewriting the table which we really don't have to do, but the present
3359 * design of domain processing doesn't offer any simple way of checking
3360 * the constraints more directly.)
3362 * Note: we use build_column_default, and not just the cooked default
3363 * returned by AddRelationNewConstraints, so that the right thing happens
3364 * when a datatype's default applies.
3366 defval = (Expr *) build_column_default(rel, attribute->attnum);
3368 if (!defval && GetDomainConstraints(typeOid) != NIL)
3373 baseTypeMod = typmod;
3374 baseTypeId = getBaseTypeAndTypmod(typeOid, &baseTypeMod);
3375 defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod);
3376 defval = (Expr *) coerce_to_target_type(NULL,
3381 COERCION_ASSIGNMENT,
3382 COERCE_IMPLICIT_CAST);
3383 if (defval == NULL) /* should not happen */
3384 elog(ERROR, "failed to coerce base type to domain");
3389 NewColumnValue *newval;
3391 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
3392 newval->attnum = attribute->attnum;
3393 newval->expr = defval;
3395 tab->newvals = lappend(tab->newvals, newval);
3399 * If the new column is NOT NULL, tell Phase 3 it needs to test that.
3401 tab->new_notnull |= colDef->is_not_null;
3404 * Add needed dependency entries for the new column.
3406 add_column_datatype_dependency(myrelid, i, attribute->atttypid);
3410 * Install a column's dependency on its datatype.
3413 add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
3415 ObjectAddress myself,
3418 myself.classId = RelationRelationId;
3419 myself.objectId = relid;
3420 myself.objectSubId = attnum;
3421 referenced.classId = TypeRelationId;
3422 referenced.objectId = typid;
3423 referenced.objectSubId = 0;
3424 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
3428 * ALTER TABLE ALTER COLUMN DROP NOT NULL
3431 ATExecDropNotNull(Relation rel, const char *colName)
3437 ListCell *indexoidscan;
3440 * lookup the attribute
3442 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3444 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3446 if (!HeapTupleIsValid(tuple))
3448 (errcode(ERRCODE_UNDEFINED_COLUMN),
3449 errmsg("column \"%s\" of relation \"%s\" does not exist",
3450 colName, RelationGetRelationName(rel))));
3452 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3454 /* Prevent them from altering a system attribute */
3457 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3458 errmsg("cannot alter system column \"%s\"",
3462 * Check that the attribute is not in a primary key
3465 /* Loop over all indexes on the relation */
3466 indexoidlist = RelationGetIndexList(rel);
3468 foreach(indexoidscan, indexoidlist)
3470 Oid indexoid = lfirst_oid(indexoidscan);
3471 HeapTuple indexTuple;
3472 Form_pg_index indexStruct;
3475 indexTuple = SearchSysCache(INDEXRELID,
3476 ObjectIdGetDatum(indexoid),
3478 if (!HeapTupleIsValid(indexTuple))
3479 elog(ERROR, "cache lookup failed for index %u", indexoid);
3480 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
3482 /* If the index is not a primary key, skip the check */
3483 if (indexStruct->indisprimary)
3486 * Loop over each attribute in the primary key and see if it
3487 * matches the to-be-altered attribute
3489 for (i = 0; i < indexStruct->indnatts; i++)
3491 if (indexStruct->indkey.values[i] == attnum)
3493 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3494 errmsg("column \"%s\" is in a primary key",
3499 ReleaseSysCache(indexTuple);
3502 list_free(indexoidlist);
3505 * Okay, actually perform the catalog change ... if needed
3507 if (((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3509 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = FALSE;
3511 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3513 /* keep the system catalog indexes current */
3514 CatalogUpdateIndexes(attr_rel, tuple);
3517 heap_close(attr_rel, RowExclusiveLock);
3521 * ALTER TABLE ALTER COLUMN SET NOT NULL
3524 ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
3525 const char *colName)
3532 * lookup the attribute
3534 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3536 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3538 if (!HeapTupleIsValid(tuple))
3540 (errcode(ERRCODE_UNDEFINED_COLUMN),
3541 errmsg("column \"%s\" of relation \"%s\" does not exist",
3542 colName, RelationGetRelationName(rel))));
3544 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3546 /* Prevent them from altering a system attribute */
3549 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3550 errmsg("cannot alter system column \"%s\"",
3554 * Okay, actually perform the catalog change ... if needed
3556 if (!((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3558 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = TRUE;
3560 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3562 /* keep the system catalog indexes current */
3563 CatalogUpdateIndexes(attr_rel, tuple);
3565 /* Tell Phase 3 it needs to test the constraint */
3566 tab->new_notnull = true;
3569 heap_close(attr_rel, RowExclusiveLock);
3573 * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
3576 ATExecColumnDefault(Relation rel, const char *colName,
3582 * get the number of the attribute
3584 attnum = get_attnum(RelationGetRelid(rel), colName);
3585 if (attnum == InvalidAttrNumber)
3587 (errcode(ERRCODE_UNDEFINED_COLUMN),
3588 errmsg("column \"%s\" of relation \"%s\" does not exist",
3589 colName, RelationGetRelationName(rel))));
3591 /* Prevent them from altering a system attribute */
3594 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3595 errmsg("cannot alter system column \"%s\"",
3599 * Remove any old default for the column. We use RESTRICT here for
3600 * safety, but at present we do not expect anything to depend on the
3603 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false);
3608 RawColumnDefault *rawEnt;
3610 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3611 rawEnt->attnum = attnum;
3612 rawEnt->raw_default = newDefault;
3615 * This function is intended for CREATE TABLE, so it processes a
3616 * _list_ of defaults, but we just do one.
3618 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL, false, true);
3623 * ALTER TABLE ALTER COLUMN SET STATISTICS
3626 ATPrepSetStatistics(Relation rel, const char *colName, Node *flagValue)
3629 * We do our own permission checking because (a) we want to allow SET
3630 * STATISTICS on indexes (for expressional index columns), and (b) we want
3631 * to allow SET STATISTICS on system catalogs without requiring
3632 * allowSystemTableMods to be turned on.
3634 if (rel->rd_rel->relkind != RELKIND_RELATION &&
3635 rel->rd_rel->relkind != RELKIND_INDEX)
3637 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3638 errmsg("\"%s\" is not a table or index",
3639 RelationGetRelationName(rel))));
3641 /* Permissions checks */
3642 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3643 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3644 RelationGetRelationName(rel));
3648 ATExecSetStatistics(Relation rel, const char *colName, Node *newValue)
3651 Relation attrelation;
3653 Form_pg_attribute attrtuple;
3655 Assert(IsA(newValue, Integer));
3656 newtarget = intVal(newValue);
3659 * Limit target to a sane range
3664 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3665 errmsg("statistics target %d is too low",
3668 else if (newtarget > 1000)
3672 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3673 errmsg("lowering statistics target to %d",
3677 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
3679 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3681 if (!HeapTupleIsValid(tuple))
3683 (errcode(ERRCODE_UNDEFINED_COLUMN),
3684 errmsg("column \"%s\" of relation \"%s\" does not exist",
3685 colName, RelationGetRelationName(rel))));
3686 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
3688 if (attrtuple->attnum <= 0)
3690 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3691 errmsg("cannot alter system column \"%s\"",
3694 attrtuple->attstattarget = newtarget;
3696 simple_heap_update(attrelation, &tuple->t_self, tuple);
3698 /* keep system catalog indexes current */
3699 CatalogUpdateIndexes(attrelation, tuple);
3701 heap_freetuple(tuple);
3703 heap_close(attrelation, RowExclusiveLock);
3707 * ALTER TABLE ALTER COLUMN SET STORAGE
3710 ATExecSetStorage(Relation rel, const char *colName, Node *newValue)
3714 Relation attrelation;
3716 Form_pg_attribute attrtuple;
3718 Assert(IsA(newValue, String));
3719 storagemode = strVal(newValue);
3721 if (pg_strcasecmp(storagemode, "plain") == 0)
3723 else if (pg_strcasecmp(storagemode, "external") == 0)
3725 else if (pg_strcasecmp(storagemode, "extended") == 0)
3727 else if (pg_strcasecmp(storagemode, "main") == 0)
3732 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3733 errmsg("invalid storage type \"%s\"",
3735 newstorage = 0; /* keep compiler quiet */
3738 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
3740 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3742 if (!HeapTupleIsValid(tuple))
3744 (errcode(ERRCODE_UNDEFINED_COLUMN),
3745 errmsg("column \"%s\" of relation \"%s\" does not exist",
3746 colName, RelationGetRelationName(rel))));
3747 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
3749 if (attrtuple->attnum <= 0)
3751 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3752 errmsg("cannot alter system column \"%s\"",
3756 * safety check: do not allow toasted storage modes unless column datatype
3759 if (newstorage == 'p' || TypeIsToastable(attrtuple->atttypid))
3760 attrtuple->attstorage = newstorage;
3763 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3764 errmsg("column data type %s can only have storage PLAIN",
3765 format_type_be(attrtuple->atttypid))));
3767 simple_heap_update(attrelation, &tuple->t_self, tuple);
3769 /* keep system catalog indexes current */
3770 CatalogUpdateIndexes(attrelation, tuple);
3772 heap_freetuple(tuple);
3774 heap_close(attrelation, RowExclusiveLock);
3779 * ALTER TABLE DROP COLUMN
3781 * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
3782 * because we have to decide at runtime whether to recurse or not depending
3783 * on whether attinhcount goes to zero or not. (We can't check this in a
3784 * static pre-pass because it won't handle multiple inheritance situations
3785 * correctly.) Since DROP COLUMN doesn't need to create any work queue
3786 * entries for Phase 3, it's okay to recurse internally in this routine
3787 * without considering the work queue.
3790 ATExecDropColumn(Relation rel, const char *colName,
3791 DropBehavior behavior,
3792 bool recurse, bool recursing)
3795 Form_pg_attribute targetatt;
3798 ObjectAddress object;
3800 /* At top level, permission check was done in ATPrepCmd, else do it */
3802 ATSimplePermissions(rel, false);
3805 * get the number of the attribute
3807 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
3808 if (!HeapTupleIsValid(tuple))
3810 (errcode(ERRCODE_UNDEFINED_COLUMN),
3811 errmsg("column \"%s\" of relation \"%s\" does not exist",
3812 colName, RelationGetRelationName(rel))));
3813 targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
3815 attnum = targetatt->attnum;
3817 /* Can't drop a system attribute, except OID */
3818 if (attnum <= 0 && attnum != ObjectIdAttributeNumber)
3820 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3821 errmsg("cannot drop system column \"%s\"",
3824 /* Don't drop inherited columns */
3825 if (targetatt->attinhcount > 0 && !recursing)
3827 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3828 errmsg("cannot drop inherited column \"%s\"",
3831 ReleaseSysCache(tuple);
3834 * Propagate to children as appropriate. Unlike most other ALTER
3835 * routines, we have to do this one level of recursion at a time; we can't
3836 * use find_all_inheritors to do it in one pass.
3838 children = find_inheritance_children(RelationGetRelid(rel));
3845 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3846 foreach(child, children)
3848 Oid childrelid = lfirst_oid(child);
3850 Form_pg_attribute childatt;
3852 childrel = heap_open(childrelid, AccessExclusiveLock);
3853 CheckTableNotInUse(childrel, "ALTER TABLE");
3855 tuple = SearchSysCacheCopyAttName(childrelid, colName);
3856 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
3857 elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
3858 colName, childrelid);
3859 childatt = (Form_pg_attribute) GETSTRUCT(tuple);
3861 if (childatt->attinhcount <= 0) /* shouldn't happen */
3862 elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
3863 childrelid, colName);
3868 * If the child column has other definition sources, just
3869 * decrement its inheritance count; if not, recurse to delete
3872 if (childatt->attinhcount == 1 && !childatt->attislocal)
3874 /* Time to delete this child column, too */
3875 ATExecDropColumn(childrel, colName, behavior, true, true);
3879 /* Child column must survive my deletion */
3880 childatt->attinhcount--;
3882 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3884 /* keep the system catalog indexes current */
3885 CatalogUpdateIndexes(attr_rel, tuple);
3887 /* Make update visible */
3888 CommandCounterIncrement();
3894 * If we were told to drop ONLY in this table (no recursion),
3895 * we need to mark the inheritors' attributes as locally
3896 * defined rather than inherited.
3898 childatt->attinhcount--;
3899 childatt->attislocal = true;
3901 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3903 /* keep the system catalog indexes current */
3904 CatalogUpdateIndexes(attr_rel, tuple);
3906 /* Make update visible */
3907 CommandCounterIncrement();
3910 heap_freetuple(tuple);
3912 heap_close(childrel, NoLock);
3914 heap_close(attr_rel, RowExclusiveLock);
3918 * Perform the actual column deletion
3920 object.classId = RelationRelationId;
3921 object.objectId = RelationGetRelid(rel);
3922 object.objectSubId = attnum;
3924 performDeletion(&object, behavior);
3927 * If we dropped the OID column, must adjust pg_class.relhasoids
3929 if (attnum == ObjectIdAttributeNumber)
3932 Form_pg_class tuple_class;
3934 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
3936 tuple = SearchSysCacheCopy(RELOID,
3937 ObjectIdGetDatum(RelationGetRelid(rel)),
3939 if (!HeapTupleIsValid(tuple))
3940 elog(ERROR, "cache lookup failed for relation %u",
3941 RelationGetRelid(rel));
3942 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
3944 tuple_class->relhasoids = false;
3945 simple_heap_update(class_rel, &tuple->t_self, tuple);
3947 /* Keep the catalog indexes up to date */
3948 CatalogUpdateIndexes(class_rel, tuple);
3950 heap_close(class_rel, RowExclusiveLock);
3955 * ALTER TABLE ADD INDEX
3957 * There is no such command in the grammar, but parse_utilcmd.c converts
3958 * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands. This lets
3959 * us schedule creation of the index at the appropriate time during ALTER.
3962 ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
3963 IndexStmt *stmt, bool is_rebuild)
3969 Assert(IsA(stmt, IndexStmt));
3971 /* suppress schema rights check when rebuilding existing index */
3972 check_rights = !is_rebuild;
3973 /* skip index build if phase 3 will have to rewrite table anyway */
3974 skip_build = (tab->newvals != NIL);
3975 /* suppress notices when rebuilding existing index */
3978 /* The IndexStmt has already been through transformIndexStmt */
3980 DefineIndex(stmt->relation, /* relation */
3981 stmt->idxname, /* index name */
3982 InvalidOid, /* no predefined OID */
3983 stmt->accessMethod, /* am name */
3985 stmt->indexParams, /* parameters */
3986 (Expr *) stmt->whereClause,
3991 true, /* is_alter_table */
3999 * ALTER TABLE ADD CONSTRAINT
4002 ATExecAddConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
4003 Node *newConstraint, bool recurse)
4005 switch (nodeTag(newConstraint))
4009 Constraint *constr = (Constraint *) newConstraint;
4012 * Currently, we only expect to see CONSTR_CHECK nodes
4013 * arriving here (see the preprocessing done in
4014 * parse_utilcmd.c). Use a switch anyway to make it easier to
4015 * add more code later.
4017 switch (constr->contype)
4020 ATAddCheckConstraint(wqueue, tab, rel,
4021 constr, recurse, false);
4024 elog(ERROR, "unrecognized constraint type: %d",
4025 (int) constr->contype);
4029 case T_FkConstraint:
4031 FkConstraint *fkconstraint = (FkConstraint *) newConstraint;
4034 * Note that we currently never recurse for FK constraints,
4035 * so the "recurse" flag is silently ignored.
4037 * Assign or validate constraint name
4039 if (fkconstraint->constr_name)
4041 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
4042 RelationGetRelid(rel),
4043 RelationGetNamespace(rel),
4044 fkconstraint->constr_name))
4046 (errcode(ERRCODE_DUPLICATE_OBJECT),
4047 errmsg("constraint \"%s\" for relation \"%s\" already exists",
4048 fkconstraint->constr_name,
4049 RelationGetRelationName(rel))));
4052 fkconstraint->constr_name =
4053 ChooseConstraintName(RelationGetRelationName(rel),
4054 strVal(linitial(fkconstraint->fk_attrs)),
4056 RelationGetNamespace(rel),
4059 ATAddForeignKeyConstraint(tab, rel, fkconstraint);
4064 elog(ERROR, "unrecognized node type: %d",
4065 (int) nodeTag(newConstraint));
4070 * Add a check constraint to a single table and its children
4072 * Subroutine for ATExecAddConstraint.
4074 * We must recurse to child tables during execution, rather than using
4075 * ALTER TABLE's normal prep-time recursion. The reason is that all the
4076 * constraints *must* be given the same name, else they won't be seen as
4077 * related later. If the user didn't explicitly specify a name, then
4078 * AddRelationNewConstraints would normally assign different names to the
4079 * child constraints. To fix that, we must capture the name assigned at
4080 * the parent table and pass that down.
4083 ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
4084 Constraint *constr, bool recurse, bool recursing)
4091 /* At top level, permission check was done in ATPrepCmd, else do it */
4093 ATSimplePermissions(rel, false);
4096 * Call AddRelationNewConstraints to do the work, making sure it works on
4097 * a copy of the Constraint so transformExpr can't modify the original.
4098 * It returns a list of cooked constraints.
4100 * If the constraint ends up getting merged with a pre-existing one, it's
4101 * omitted from the returned list, which is what we want: we do not need
4102 * to do any validation work. That can only happen at child tables,
4103 * though, since we disallow merging at the top level.
4105 newcons = AddRelationNewConstraints(rel, NIL,
4106 list_make1(copyObject(constr)),
4107 recursing, !recursing);
4109 /* Add each constraint to Phase 3's queue */
4110 foreach(lcon, newcons)
4112 CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
4113 NewConstraint *newcon;
4115 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
4116 newcon->name = ccon->name;
4117 newcon->contype = ccon->contype;
4118 /* ExecQual wants implicit-AND format */
4119 newcon->qual = (Node *) make_ands_implicit((Expr *) ccon->expr);
4121 tab->constraints = lappend(tab->constraints, newcon);
4123 /* Save the actually assigned name if it was defaulted */
4124 if (constr->name == NULL)
4125 constr->name = ccon->name;
4128 /* At this point we must have a locked-down name to use */
4129 Assert(constr->name != NULL);
4131 /* Advance command counter in case same table is visited multiple times */
4132 CommandCounterIncrement();
4135 * Propagate to children as appropriate. Unlike most other ALTER
4136 * routines, we have to do this one level of recursion at a time; we can't
4137 * use find_all_inheritors to do it in one pass.
4139 children = find_inheritance_children(RelationGetRelid(rel));
4142 * If we are told not to recurse, there had better not be any child
4143 * tables; else the addition would put them out of step.
4145 if (children && !recurse)
4147 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4148 errmsg("constraint must be added to child tables too")));
4150 foreach(child, children)
4152 Oid childrelid = lfirst_oid(child);
4154 AlteredTableInfo *childtab;
4156 childrel = heap_open(childrelid, AccessExclusiveLock);
4157 CheckTableNotInUse(childrel, "ALTER TABLE");
4159 /* Find or create work queue entry for this table */
4160 childtab = ATGetQueueEntry(wqueue, childrel);
4162 /* Recurse to child */
4163 ATAddCheckConstraint(wqueue, childtab, childrel,
4164 constr, recurse, true);
4166 heap_close(childrel, NoLock);
4171 * Add a foreign-key constraint to a single table
4173 * Subroutine for ATExecAddConstraint. Must already hold exclusive
4174 * lock on the rel, and have done appropriate validity/permissions checks
4178 ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
4179 FkConstraint *fkconstraint)
4182 AclResult aclresult;
4183 int16 pkattnum[INDEX_MAX_KEYS];
4184 int16 fkattnum[INDEX_MAX_KEYS];
4185 Oid pktypoid[INDEX_MAX_KEYS];
4186 Oid fktypoid[INDEX_MAX_KEYS];
4187 Oid opclasses[INDEX_MAX_KEYS];
4188 Oid pfeqoperators[INDEX_MAX_KEYS];
4189 Oid ppeqoperators[INDEX_MAX_KEYS];
4190 Oid ffeqoperators[INDEX_MAX_KEYS];
4198 * Grab an exclusive lock on the pk table, so that someone doesn't delete
4199 * rows out from under us. (Although a lesser lock would do for that
4200 * purpose, we'll need exclusive lock anyway to add triggers to the pk
4201 * table; trying to start with a lesser lock will just create a risk of
4204 pkrel = heap_openrv(fkconstraint->pktable, AccessExclusiveLock);
4207 * Validity and permissions checks
4209 * Note: REFERENCES permissions checks are redundant with CREATE TRIGGER,
4210 * but we may as well error out sooner instead of later.
4212 if (pkrel->rd_rel->relkind != RELKIND_RELATION)
4214 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4215 errmsg("referenced relation \"%s\" is not a table",
4216 RelationGetRelationName(pkrel))));
4218 aclresult = pg_class_aclcheck(RelationGetRelid(pkrel), GetUserId(),
4220 if (aclresult != ACLCHECK_OK)
4221 aclcheck_error(aclresult, ACL_KIND_CLASS,
4222 RelationGetRelationName(pkrel));
4224 if (!allowSystemTableMods && IsSystemRelation(pkrel))
4226 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4227 errmsg("permission denied: \"%s\" is a system catalog",
4228 RelationGetRelationName(pkrel))));
4230 aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
4232 if (aclresult != ACLCHECK_OK)
4233 aclcheck_error(aclresult, ACL_KIND_CLASS,
4234 RelationGetRelationName(rel));
4237 * Disallow reference from permanent table to temp table or vice versa.
4238 * (The ban on perm->temp is for fairly obvious reasons. The ban on
4239 * temp->perm is because other backends might need to run the RI triggers
4240 * on the perm table, but they can't reliably see tuples the owning
4241 * backend has created in the temp table, because non-shared buffers are
4242 * used for temp tables.)
4244 if (isTempNamespace(RelationGetNamespace(pkrel)))
4246 if (!isTempNamespace(RelationGetNamespace(rel)))
4248 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4249 errmsg("cannot reference temporary table from permanent table constraint")));
4253 if (isTempNamespace(RelationGetNamespace(rel)))
4255 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4256 errmsg("cannot reference permanent table from temporary table constraint")));
4260 * Look up the referencing attributes to make sure they exist, and record
4261 * their attnums and type OIDs.
4263 MemSet(pkattnum, 0, sizeof(pkattnum));
4264 MemSet(fkattnum, 0, sizeof(fkattnum));
4265 MemSet(pktypoid, 0, sizeof(pktypoid));
4266 MemSet(fktypoid, 0, sizeof(fktypoid));
4267 MemSet(opclasses, 0, sizeof(opclasses));
4268 MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
4269 MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
4270 MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
4272 numfks = transformColumnNameList(RelationGetRelid(rel),
4273 fkconstraint->fk_attrs,
4274 fkattnum, fktypoid);
4277 * If the attribute list for the referenced table was omitted, lookup the
4278 * definition of the primary key and use it. Otherwise, validate the
4279 * supplied attribute list. In either case, discover the index OID and
4280 * index opclasses, and the attnums and type OIDs of the attributes.
4282 if (fkconstraint->pk_attrs == NIL)
4284 numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
4285 &fkconstraint->pk_attrs,
4291 numpks = transformColumnNameList(RelationGetRelid(pkrel),
4292 fkconstraint->pk_attrs,
4293 pkattnum, pktypoid);
4294 /* Look for an index matching the column list */
4295 indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
4300 * Look up the equality operators to use in the constraint.
4302 * Note that we have to be careful about the difference between the actual
4303 * PK column type and the opclass' declared input type, which might be
4304 * only binary-compatible with it. The declared opcintype is the right
4305 * thing to probe pg_amop with.
4307 if (numfks != numpks)
4309 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4310 errmsg("number of referencing and referenced columns for foreign key disagree")));
4312 for (i = 0; i < numpks; i++)
4314 Oid pktype = pktypoid[i];
4315 Oid fktype = fktypoid[i];
4318 Form_pg_opclass cla_tup;
4327 /* We need several fields out of the pg_opclass entry */
4328 cla_ht = SearchSysCache(CLAOID,
4329 ObjectIdGetDatum(opclasses[i]),
4331 if (!HeapTupleIsValid(cla_ht))
4332 elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
4333 cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
4334 amid = cla_tup->opcmethod;
4335 opfamily = cla_tup->opcfamily;
4336 opcintype = cla_tup->opcintype;
4337 ReleaseSysCache(cla_ht);
4340 * Check it's a btree; currently this can never fail since no other
4341 * index AMs support unique indexes. If we ever did have other types
4342 * of unique indexes, we'd need a way to determine which operator
4343 * strategy number is equality. (Is it reasonable to insist that
4344 * every such index AM use btree's number for equality?)
4346 if (amid != BTREE_AM_OID)
4347 elog(ERROR, "only b-tree indexes are supported for foreign keys");
4348 eqstrategy = BTEqualStrategyNumber;
4351 * There had better be a primary equality operator for the index.
4352 * We'll use it for PK = PK comparisons.
4354 ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
4357 if (!OidIsValid(ppeqop))
4358 elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
4359 eqstrategy, opcintype, opcintype, opfamily);
4362 * Are there equality operators that take exactly the FK type? Assume
4363 * we should look through any domain here.
4365 fktyped = getBaseType(fktype);
4367 pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
4369 if (OidIsValid(pfeqop))
4370 ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
4373 ffeqop = InvalidOid; /* keep compiler quiet */
4375 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4378 * Otherwise, look for an implicit cast from the FK type to the
4379 * opcintype, and if found, use the primary equality operator.
4380 * This is a bit tricky because opcintype might be a polymorphic
4381 * type such as ANYARRAY or ANYENUM; so what we have to test is
4382 * whether the two actual column types can be concurrently cast to
4383 * that type. (Otherwise, we'd fail to reject combinations such
4384 * as int[] and point[].)
4386 Oid input_typeids[2];
4387 Oid target_typeids[2];
4389 input_typeids[0] = pktype;
4390 input_typeids[1] = fktype;
4391 target_typeids[0] = opcintype;
4392 target_typeids[1] = opcintype;
4393 if (can_coerce_type(2, input_typeids, target_typeids,
4395 pfeqop = ffeqop = ppeqop;
4398 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4400 (errcode(ERRCODE_DATATYPE_MISMATCH),
4401 errmsg("foreign key constraint \"%s\" "
4402 "cannot be implemented",
4403 fkconstraint->constr_name),
4404 errdetail("Key columns \"%s\" and \"%s\" "
4405 "are of incompatible types: %s and %s.",
4406 strVal(list_nth(fkconstraint->fk_attrs, i)),
4407 strVal(list_nth(fkconstraint->pk_attrs, i)),
4408 format_type_be(fktype),
4409 format_type_be(pktype))));
4411 pfeqoperators[i] = pfeqop;
4412 ppeqoperators[i] = ppeqop;
4413 ffeqoperators[i] = ffeqop;
4417 * Record the FK constraint in pg_constraint.
4419 constrOid = CreateConstraintEntry(fkconstraint->constr_name,
4420 RelationGetNamespace(rel),
4422 fkconstraint->deferrable,
4423 fkconstraint->initdeferred,
4424 RelationGetRelid(rel),
4427 InvalidOid, /* not a domain
4429 RelationGetRelid(pkrel),
4435 fkconstraint->fk_upd_action,
4436 fkconstraint->fk_del_action,
4437 fkconstraint->fk_matchtype,
4439 NULL, /* no check constraint */
4446 * Create the triggers that will enforce the constraint.
4448 createForeignKeyTriggers(rel, fkconstraint, constrOid);
4451 * Tell Phase 3 to check that the constraint is satisfied by existing rows
4452 * (we can skip this during table creation).
4454 if (!fkconstraint->skip_validation)
4456 NewConstraint *newcon;
4458 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
4459 newcon->name = fkconstraint->constr_name;
4460 newcon->contype = CONSTR_FOREIGN;
4461 newcon->refrelid = RelationGetRelid(pkrel);
4462 newcon->conid = constrOid;
4463 newcon->qual = (Node *) fkconstraint;
4465 tab->constraints = lappend(tab->constraints, newcon);
4469 * Close pk table, but keep lock until we've committed.
4471 heap_close(pkrel, NoLock);
4476 * transformColumnNameList - transform list of column names
4478 * Lookup each name and return its attnum and type OID
4481 transformColumnNameList(Oid relId, List *colList,
4482 int16 *attnums, Oid *atttypids)
4490 char *attname = strVal(lfirst(l));
4493 atttuple = SearchSysCacheAttName(relId, attname);
4494 if (!HeapTupleIsValid(atttuple))
4496 (errcode(ERRCODE_UNDEFINED_COLUMN),
4497 errmsg("column \"%s\" referenced in foreign key constraint does not exist",
4499 if (attnum >= INDEX_MAX_KEYS)
4501 (errcode(ERRCODE_TOO_MANY_COLUMNS),
4502 errmsg("cannot have more than %d keys in a foreign key",
4504 attnums[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->attnum;
4505 atttypids[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->atttypid;
4506 ReleaseSysCache(atttuple);
4514 * transformFkeyGetPrimaryKey -
4516 * Look up the names, attnums, and types of the primary key attributes
4517 * for the pkrel. Also return the index OID and index opclasses of the
4518 * index supporting the primary key.
4520 * All parameters except pkrel are output parameters. Also, the function
4521 * return value is the number of attributes in the primary key.
4523 * Used when the column list in the REFERENCES specification is omitted.
4526 transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
4528 int16 *attnums, Oid *atttypids,
4532 ListCell *indexoidscan;
4533 HeapTuple indexTuple = NULL;
4534 Form_pg_index indexStruct = NULL;
4535 Datum indclassDatum;
4537 oidvector *indclass;
4541 * Get the list of index OIDs for the table from the relcache, and look up
4542 * each one in the pg_index syscache until we find one marked primary key
4543 * (hopefully there isn't more than one such).
4545 *indexOid = InvalidOid;
4547 indexoidlist = RelationGetIndexList(pkrel);
4549 foreach(indexoidscan, indexoidlist)
4551 Oid indexoid = lfirst_oid(indexoidscan);
4553 indexTuple = SearchSysCache(INDEXRELID,
4554 ObjectIdGetDatum(indexoid),
4556 if (!HeapTupleIsValid(indexTuple))
4557 elog(ERROR, "cache lookup failed for index %u", indexoid);
4558 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4559 if (indexStruct->indisprimary)
4561 *indexOid = indexoid;
4564 ReleaseSysCache(indexTuple);
4567 list_free(indexoidlist);
4570 * Check that we found it
4572 if (!OidIsValid(*indexOid))
4574 (errcode(ERRCODE_UNDEFINED_OBJECT),
4575 errmsg("there is no primary key for referenced table \"%s\"",
4576 RelationGetRelationName(pkrel))));
4578 /* Must get indclass the hard way */
4579 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4580 Anum_pg_index_indclass, &isnull);
4582 indclass = (oidvector *) DatumGetPointer(indclassDatum);
4585 * Now build the list of PK attributes from the indkey definition (we
4586 * assume a primary key cannot have expressional elements)
4589 for (i = 0; i < indexStruct->indnatts; i++)
4591 int pkattno = indexStruct->indkey.values[i];
4593 attnums[i] = pkattno;
4594 atttypids[i] = attnumTypeId(pkrel, pkattno);
4595 opclasses[i] = indclass->values[i];
4596 *attnamelist = lappend(*attnamelist,
4597 makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
4600 ReleaseSysCache(indexTuple);
4606 * transformFkeyCheckAttrs -
4608 * Make sure that the attributes of a referenced table belong to a unique
4609 * (or primary key) constraint. Return the OID of the index supporting
4610 * the constraint, as well as the opclasses associated with the index
4614 transformFkeyCheckAttrs(Relation pkrel,
4615 int numattrs, int16 *attnums,
4616 Oid *opclasses) /* output parameter */
4618 Oid indexoid = InvalidOid;
4621 ListCell *indexoidscan;
4624 * Get the list of index OIDs for the table from the relcache, and look up
4625 * each one in the pg_index syscache, and match unique indexes to the list
4626 * of attnums we are given.
4628 indexoidlist = RelationGetIndexList(pkrel);
4630 foreach(indexoidscan, indexoidlist)
4632 HeapTuple indexTuple;
4633 Form_pg_index indexStruct;
4637 indexoid = lfirst_oid(indexoidscan);
4638 indexTuple = SearchSysCache(INDEXRELID,
4639 ObjectIdGetDatum(indexoid),
4641 if (!HeapTupleIsValid(indexTuple))
4642 elog(ERROR, "cache lookup failed for index %u", indexoid);
4643 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4646 * Must have the right number of columns; must be unique and not a
4647 * partial index; forget it if there are any expressions, too
4649 if (indexStruct->indnatts == numattrs &&
4650 indexStruct->indisunique &&
4651 heap_attisnull(indexTuple, Anum_pg_index_indpred) &&
4652 heap_attisnull(indexTuple, Anum_pg_index_indexprs))
4654 /* Must get indclass the hard way */
4655 Datum indclassDatum;
4657 oidvector *indclass;
4659 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4660 Anum_pg_index_indclass, &isnull);
4662 indclass = (oidvector *) DatumGetPointer(indclassDatum);
4665 * The given attnum list may match the index columns in any order.
4666 * Check that each list is a subset of the other.
4668 for (i = 0; i < numattrs; i++)
4671 for (j = 0; j < numattrs; j++)
4673 if (attnums[i] == indexStruct->indkey.values[j])
4684 for (i = 0; i < numattrs; i++)
4687 for (j = 0; j < numattrs; j++)
4689 if (attnums[j] == indexStruct->indkey.values[i])
4691 opclasses[j] = indclass->values[i];
4701 ReleaseSysCache(indexTuple);
4708 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4709 errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
4710 RelationGetRelationName(pkrel))));
4712 list_free(indexoidlist);
4718 * Scan the existing rows in a table to verify they meet a proposed FK
4721 * Caller must have opened and locked both relations.
4724 validateForeignKeyConstraint(FkConstraint *fkconstraint,
4734 * Build a trigger call structure; we'll need it either way.
4736 MemSet(&trig, 0, sizeof(trig));
4737 trig.tgoid = InvalidOid;
4738 trig.tgname = fkconstraint->constr_name;
4739 trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
4740 trig.tgisconstraint = TRUE;
4741 trig.tgconstrrelid = RelationGetRelid(pkrel);
4742 trig.tgconstraint = constraintOid;
4743 trig.tgdeferrable = FALSE;
4744 trig.tginitdeferred = FALSE;
4745 /* we needn't fill in tgargs */
4748 * See if we can do it with a single LEFT JOIN query. A FALSE result
4749 * indicates we must proceed with the fire-the-trigger method.
4751 if (RI_Initial_Check(&trig, rel, pkrel))
4755 * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
4756 * if that tuple had just been inserted. If any of those fail, it should
4757 * ereport(ERROR) and that's that.
4759 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
4761 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
4763 FunctionCallInfoData fcinfo;
4764 TriggerData trigdata;
4767 * Make a call to the trigger function
4769 * No parameters are passed, but we do set a context
4771 MemSet(&fcinfo, 0, sizeof(fcinfo));
4774 * We assume RI_FKey_check_ins won't look at flinfo...
4776 trigdata.type = T_TriggerData;
4777 trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
4778 trigdata.tg_relation = rel;
4779 trigdata.tg_trigtuple = tuple;
4780 trigdata.tg_newtuple = NULL;
4781 trigdata.tg_trigger = &trig;
4782 trigdata.tg_trigtuplebuf = scan->rs_cbuf;
4783 trigdata.tg_newtuplebuf = InvalidBuffer;
4785 fcinfo.context = (Node *) &trigdata;
4787 RI_FKey_check_ins(&fcinfo);
4794 CreateFKCheckTrigger(RangeVar *myRel, FkConstraint *fkconstraint,
4795 Oid constraintOid, bool on_insert)
4797 CreateTrigStmt *fk_trigger;
4799 fk_trigger = makeNode(CreateTrigStmt);
4800 fk_trigger->trigname = fkconstraint->constr_name;
4801 fk_trigger->relation = myRel;
4802 fk_trigger->before = false;
4803 fk_trigger->row = true;
4805 /* Either ON INSERT or ON UPDATE */
4808 fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
4809 fk_trigger->actions[0] = 'i';
4813 fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
4814 fk_trigger->actions[0] = 'u';
4816 fk_trigger->actions[1] = '\0';
4818 fk_trigger->isconstraint = true;
4819 fk_trigger->deferrable = fkconstraint->deferrable;
4820 fk_trigger->initdeferred = fkconstraint->initdeferred;
4821 fk_trigger->constrrel = fkconstraint->pktable;
4822 fk_trigger->args = NIL;
4824 (void) CreateTrigger(fk_trigger, constraintOid);
4826 /* Make changes-so-far visible */
4827 CommandCounterIncrement();
4831 * Create the triggers that implement an FK constraint.
4834 createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
4838 CreateTrigStmt *fk_trigger;
4841 * Reconstruct a RangeVar for my relation (not passed in, unfortunately).
4843 myRel = makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
4844 pstrdup(RelationGetRelationName(rel)));
4846 /* Make changes-so-far visible */
4847 CommandCounterIncrement();
4850 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the CHECK
4851 * action for both INSERTs and UPDATEs on the referencing table.
4853 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, true);
4854 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, false);
4857 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
4858 * DELETE action on the referenced table.
4860 fk_trigger = makeNode(CreateTrigStmt);
4861 fk_trigger->trigname = fkconstraint->constr_name;
4862 fk_trigger->relation = fkconstraint->pktable;
4863 fk_trigger->before = false;
4864 fk_trigger->row = true;
4865 fk_trigger->actions[0] = 'd';
4866 fk_trigger->actions[1] = '\0';
4868 fk_trigger->isconstraint = true;
4869 fk_trigger->constrrel = myRel;
4870 switch (fkconstraint->fk_del_action)
4872 case FKCONSTR_ACTION_NOACTION:
4873 fk_trigger->deferrable = fkconstraint->deferrable;
4874 fk_trigger->initdeferred = fkconstraint->initdeferred;
4875 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
4877 case FKCONSTR_ACTION_RESTRICT:
4878 fk_trigger->deferrable = false;
4879 fk_trigger->initdeferred = false;
4880 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
4882 case FKCONSTR_ACTION_CASCADE:
4883 fk_trigger->deferrable = false;
4884 fk_trigger->initdeferred = false;
4885 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
4887 case FKCONSTR_ACTION_SETNULL:
4888 fk_trigger->deferrable = false;
4889 fk_trigger->initdeferred = false;
4890 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
4892 case FKCONSTR_ACTION_SETDEFAULT:
4893 fk_trigger->deferrable = false;
4894 fk_trigger->initdeferred = false;
4895 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
4898 elog(ERROR, "unrecognized FK action type: %d",
4899 (int) fkconstraint->fk_del_action);
4902 fk_trigger->args = NIL;
4904 (void) CreateTrigger(fk_trigger, constraintOid);
4906 /* Make changes-so-far visible */
4907 CommandCounterIncrement();
4910 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
4911 * UPDATE action on the referenced table.
4913 fk_trigger = makeNode(CreateTrigStmt);
4914 fk_trigger->trigname = fkconstraint->constr_name;
4915 fk_trigger->relation = fkconstraint->pktable;
4916 fk_trigger->before = false;
4917 fk_trigger->row = true;
4918 fk_trigger->actions[0] = 'u';
4919 fk_trigger->actions[1] = '\0';
4920 fk_trigger->isconstraint = true;
4921 fk_trigger->constrrel = myRel;
4922 switch (fkconstraint->fk_upd_action)
4924 case FKCONSTR_ACTION_NOACTION:
4925 fk_trigger->deferrable = fkconstraint->deferrable;
4926 fk_trigger->initdeferred = fkconstraint->initdeferred;
4927 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
4929 case FKCONSTR_ACTION_RESTRICT:
4930 fk_trigger->deferrable = false;
4931 fk_trigger->initdeferred = false;
4932 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
4934 case FKCONSTR_ACTION_CASCADE:
4935 fk_trigger->deferrable = false;
4936 fk_trigger->initdeferred = false;
4937 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
4939 case FKCONSTR_ACTION_SETNULL:
4940 fk_trigger->deferrable = false;
4941 fk_trigger->initdeferred = false;
4942 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
4944 case FKCONSTR_ACTION_SETDEFAULT:
4945 fk_trigger->deferrable = false;
4946 fk_trigger->initdeferred = false;
4947 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
4950 elog(ERROR, "unrecognized FK action type: %d",
4951 (int) fkconstraint->fk_upd_action);
4954 fk_trigger->args = NIL;
4956 (void) CreateTrigger(fk_trigger, constraintOid);
4960 * ALTER TABLE DROP CONSTRAINT
4962 * Like DROP COLUMN, we can't use the normal ALTER TABLE recursion mechanism.
4965 ATExecDropConstraint(Relation rel, const char *constrName,
4966 DropBehavior behavior,
4967 bool recurse, bool recursing)
4972 Form_pg_constraint con;
4977 bool is_check_constraint = false;
4979 /* At top level, permission check was done in ATPrepCmd, else do it */
4981 ATSimplePermissions(rel, false);
4983 conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
4986 * Find and drop the target constraint
4989 Anum_pg_constraint_conrelid,
4990 BTEqualStrategyNumber, F_OIDEQ,
4991 ObjectIdGetDatum(RelationGetRelid(rel)));
4992 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
4993 true, SnapshotNow, 1, &key);
4995 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
4997 ObjectAddress conobj;
4999 con = (Form_pg_constraint) GETSTRUCT(tuple);
5001 if (strcmp(NameStr(con->conname), constrName) != 0)
5004 /* Don't drop inherited constraints */
5005 if (con->coninhcount > 0 && !recursing)
5007 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5008 errmsg("cannot drop inherited constraint \"%s\" of relation \"%s\"",
5009 constrName, RelationGetRelationName(rel))));
5011 /* Right now only CHECK constraints can be inherited */
5012 if (con->contype == CONSTRAINT_CHECK)
5013 is_check_constraint = true;
5016 * Perform the actual constraint deletion
5018 conobj.classId = ConstraintRelationId;
5019 conobj.objectId = HeapTupleGetOid(tuple);
5020 conobj.objectSubId = 0;
5022 performDeletion(&conobj, behavior);
5027 systable_endscan(scan);
5031 (errcode(ERRCODE_UNDEFINED_OBJECT),
5032 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
5033 constrName, RelationGetRelationName(rel))));
5036 * Propagate to children as appropriate. Unlike most other ALTER
5037 * routines, we have to do this one level of recursion at a time; we can't
5038 * use find_all_inheritors to do it in one pass.
5040 if (is_check_constraint)
5041 children = find_inheritance_children(RelationGetRelid(rel));
5045 foreach(child, children)
5047 Oid childrelid = lfirst_oid(child);
5050 childrel = heap_open(childrelid, AccessExclusiveLock);
5051 CheckTableNotInUse(childrel, "ALTER TABLE");
5054 Anum_pg_constraint_conrelid,
5055 BTEqualStrategyNumber, F_OIDEQ,
5056 ObjectIdGetDatum(childrelid));
5057 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
5058 true, SnapshotNow, 1, &key);
5062 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
5064 HeapTuple copy_tuple;
5066 con = (Form_pg_constraint) GETSTRUCT(tuple);
5068 /* Right now only CHECK constraints can be inherited */
5069 if (con->contype != CONSTRAINT_CHECK)
5072 if (strcmp(NameStr(con->conname), constrName) != 0)
5077 if (con->coninhcount <= 0) /* shouldn't happen */
5078 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
5079 childrelid, constrName);
5081 copy_tuple = heap_copytuple(tuple);
5082 con = (Form_pg_constraint) GETSTRUCT(copy_tuple);
5087 * If the child constraint has other definition sources,
5088 * just decrement its inheritance count; if not, recurse
5091 if (con->coninhcount == 1 && !con->conislocal)
5093 /* Time to delete this child constraint, too */
5094 ATExecDropConstraint(childrel, constrName, behavior,
5099 /* Child constraint must survive my deletion */
5101 simple_heap_update(conrel, ©_tuple->t_self, copy_tuple);
5102 CatalogUpdateIndexes(conrel, copy_tuple);
5104 /* Make update visible */
5105 CommandCounterIncrement();
5111 * If we were told to drop ONLY in this table (no
5112 * recursion), we need to mark the inheritors' constraints
5113 * as locally defined rather than inherited.
5116 con->conislocal = true;
5118 simple_heap_update(conrel, ©_tuple->t_self, copy_tuple);
5119 CatalogUpdateIndexes(conrel, copy_tuple);
5121 /* Make update visible */
5122 CommandCounterIncrement();
5125 heap_freetuple(copy_tuple);
5128 systable_endscan(scan);
5132 (errcode(ERRCODE_UNDEFINED_OBJECT),
5133 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
5135 RelationGetRelationName(childrel))));
5137 heap_close(childrel, NoLock);
5140 heap_close(conrel, RowExclusiveLock);
5147 ATPrepAlterColumnType(List **wqueue,
5148 AlteredTableInfo *tab, Relation rel,
5149 bool recurse, bool recursing,
5152 char *colName = cmd->name;
5153 TypeName *typename = (TypeName *) cmd->def;
5155 Form_pg_attribute attTup;
5160 NewColumnValue *newval;
5161 ParseState *pstate = make_parsestate(NULL);
5163 /* lookup the attribute so we can check inheritance status */
5164 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
5165 if (!HeapTupleIsValid(tuple))
5167 (errcode(ERRCODE_UNDEFINED_COLUMN),
5168 errmsg("column \"%s\" of relation \"%s\" does not exist",
5169 colName, RelationGetRelationName(rel))));
5170 attTup = (Form_pg_attribute) GETSTRUCT(tuple);
5171 attnum = attTup->attnum;
5173 /* Can't alter a system attribute */
5176 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5177 errmsg("cannot alter system column \"%s\"",
5180 /* Don't alter inherited columns */
5181 if (attTup->attinhcount > 0 && !recursing)
5183 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5184 errmsg("cannot alter inherited column \"%s\"",
5187 /* Look up the target type */
5188 targettype = typenameTypeId(NULL, typename, &targettypmod);
5190 /* make sure datatype is legal for a column */
5191 CheckAttributeType(colName, targettype);
5194 * Set up an expression to transform the old data value to the new type.
5195 * If a USING option was given, transform and use that expression, else
5196 * just take the old value and try to coerce it. We do this first so that
5197 * type incompatibility can be detected before we waste effort, and
5198 * because we need the expression to be parsed against the original table
5205 /* Expression must be able to access vars of old table */
5206 rte = addRangeTableEntryForRelation(pstate,
5211 addRTEtoQuery(pstate, rte, false, true, true);
5213 transform = transformExpr(pstate, cmd->transform);
5215 /* It can't return a set */
5216 if (expression_returns_set(transform))
5218 (errcode(ERRCODE_DATATYPE_MISMATCH),
5219 errmsg("transform expression must not return a set")));
5221 /* No subplans or aggregates, either... */
5222 if (pstate->p_hasSubLinks)
5224 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5225 errmsg("cannot use subquery in transform expression")));
5226 if (pstate->p_hasAggs)
5228 (errcode(ERRCODE_GROUPING_ERROR),
5229 errmsg("cannot use aggregate function in transform expression")));
5233 transform = (Node *) makeVar(1, attnum,
5234 attTup->atttypid, attTup->atttypmod,
5238 transform = coerce_to_target_type(pstate,
5239 transform, exprType(transform),
5240 targettype, targettypmod,
5241 COERCION_ASSIGNMENT,
5242 COERCE_IMPLICIT_CAST);
5243 if (transform == NULL)
5245 (errcode(ERRCODE_DATATYPE_MISMATCH),
5246 errmsg("column \"%s\" cannot be cast to type \"%s\"",
5247 colName, TypeNameToString(typename))));
5250 * Add a work queue item to make ATRewriteTable update the column
5253 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
5254 newval->attnum = attnum;
5255 newval->expr = (Expr *) transform;
5257 tab->newvals = lappend(tab->newvals, newval);
5259 ReleaseSysCache(tuple);
5262 * The recursion case is handled by ATSimpleRecursion. However, if we are
5263 * told not to recurse, there had better not be any child tables; else the
5264 * alter would put them out of step.
5267 ATSimpleRecursion(wqueue, rel, cmd, recurse);
5268 else if (!recursing &&
5269 find_inheritance_children(RelationGetRelid(rel)) != NIL)
5271 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5272 errmsg("type of inherited column \"%s\" must be changed in child tables too",
5277 ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
5278 const char *colName, TypeName *typename)
5281 Form_pg_attribute attTup;
5283 HeapTuple typeTuple;
5288 Relation attrelation;
5294 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
5296 /* Look up the target column */
5297 heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5298 if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
5300 (errcode(ERRCODE_UNDEFINED_COLUMN),
5301 errmsg("column \"%s\" of relation \"%s\" does not exist",
5302 colName, RelationGetRelationName(rel))));
5303 attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
5304 attnum = attTup->attnum;
5306 /* Check for multiple ALTER TYPE on same column --- can't cope */
5307 if (attTup->atttypid != tab->oldDesc->attrs[attnum - 1]->atttypid ||
5308 attTup->atttypmod != tab->oldDesc->attrs[attnum - 1]->atttypmod)
5310 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5311 errmsg("cannot alter type of column \"%s\" twice",
5314 /* Look up the target type (should not fail, since prep found it) */
5315 typeTuple = typenameType(NULL, typename, &targettypmod);
5316 tform = (Form_pg_type) GETSTRUCT(typeTuple);
5317 targettype = HeapTupleGetOid(typeTuple);
5320 * If there is a default expression for the column, get it and ensure we
5321 * can coerce it to the new datatype. (We must do this before changing
5322 * the column type, because build_column_default itself will try to
5323 * coerce, and will not issue the error message we want if it fails.)
5325 * We remove any implicit coercion steps at the top level of the old
5326 * default expression; this has been agreed to satisfy the principle of
5327 * least surprise. (The conversion to the new column type should act like
5328 * it started from what the user sees as the stored expression, and the
5329 * implicit coercions aren't going to be shown.)
5331 if (attTup->atthasdef)
5333 defaultexpr = build_column_default(rel, attnum);
5334 Assert(defaultexpr);
5335 defaultexpr = strip_implicit_coercions(defaultexpr);
5336 defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
5337 defaultexpr, exprType(defaultexpr),
5338 targettype, targettypmod,
5339 COERCION_ASSIGNMENT,
5340 COERCE_IMPLICIT_CAST);
5341 if (defaultexpr == NULL)
5343 (errcode(ERRCODE_DATATYPE_MISMATCH),
5344 errmsg("default for column \"%s\" cannot be cast to type \"%s\"",
5345 colName, TypeNameToString(typename))));
5351 * Find everything that depends on the column (constraints, indexes, etc),
5352 * and record enough information to let us recreate the objects.
5354 * The actual recreation does not happen here, but only after we have
5355 * performed all the individual ALTER TYPE operations. We have to save
5356 * the info before executing ALTER TYPE, though, else the deparser will
5359 * There could be multiple entries for the same object, so we must check
5360 * to ensure we process each one only once. Note: we assume that an index
5361 * that implements a constraint will not show a direct dependency on the
5364 depRel = heap_open(DependRelationId, RowExclusiveLock);
5366 ScanKeyInit(&key[0],
5367 Anum_pg_depend_refclassid,
5368 BTEqualStrategyNumber, F_OIDEQ,
5369 ObjectIdGetDatum(RelationRelationId));
5370 ScanKeyInit(&key[1],
5371 Anum_pg_depend_refobjid,
5372 BTEqualStrategyNumber, F_OIDEQ,
5373 ObjectIdGetDatum(RelationGetRelid(rel)));
5374 ScanKeyInit(&key[2],
5375 Anum_pg_depend_refobjsubid,
5376 BTEqualStrategyNumber, F_INT4EQ,
5377 Int32GetDatum((int32) attnum));
5379 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
5380 SnapshotNow, 3, key);
5382 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5384 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5385 ObjectAddress foundObject;
5387 /* We don't expect any PIN dependencies on columns */
5388 if (foundDep->deptype == DEPENDENCY_PIN)
5389 elog(ERROR, "cannot alter type of a pinned column");
5391 foundObject.classId = foundDep->classid;
5392 foundObject.objectId = foundDep->objid;
5393 foundObject.objectSubId = foundDep->objsubid;
5395 switch (getObjectClass(&foundObject))
5399 char relKind = get_rel_relkind(foundObject.objectId);
5401 if (relKind == RELKIND_INDEX)
5403 Assert(foundObject.objectSubId == 0);
5404 if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
5406 tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
5407 foundObject.objectId);
5408 tab->changedIndexDefs = lappend(tab->changedIndexDefs,
5409 pg_get_indexdef_string(foundObject.objectId));
5412 else if (relKind == RELKIND_SEQUENCE)
5415 * This must be a SERIAL column's sequence. We need
5416 * not do anything to it.
5418 Assert(foundObject.objectSubId == 0);
5422 /* Not expecting any other direct dependencies... */
5423 elog(ERROR, "unexpected object depending on column: %s",
5424 getObjectDescription(&foundObject));
5429 case OCLASS_CONSTRAINT:
5430 Assert(foundObject.objectSubId == 0);
5431 if (!list_member_oid(tab->changedConstraintOids,
5432 foundObject.objectId))
5434 char *defstring = pg_get_constraintdef_string(foundObject.objectId);
5437 * Put NORMAL dependencies at the front of the list and
5438 * AUTO dependencies at the back. This makes sure that
5439 * foreign-key constraints depending on this column will
5440 * be dropped before unique or primary-key constraints of
5441 * the column; which we must have because the FK
5442 * constraints depend on the indexes belonging to the
5443 * unique constraints.
5445 if (foundDep->deptype == DEPENDENCY_NORMAL)
5447 tab->changedConstraintOids =
5448 lcons_oid(foundObject.objectId,
5449 tab->changedConstraintOids);
5450 tab->changedConstraintDefs =
5452 tab->changedConstraintDefs);
5456 tab->changedConstraintOids =
5457 lappend_oid(tab->changedConstraintOids,
5458 foundObject.objectId);
5459 tab->changedConstraintDefs =
5460 lappend(tab->changedConstraintDefs,
5466 case OCLASS_REWRITE:
5467 /* XXX someday see if we can cope with revising views */
5469 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5470 errmsg("cannot alter type of a column used by a view or rule"),
5471 errdetail("%s depends on column \"%s\"",
5472 getObjectDescription(&foundObject),
5476 case OCLASS_DEFAULT:
5479 * Ignore the column's default expression, since we will fix
5482 Assert(defaultexpr);
5488 case OCLASS_CONVERSION:
5489 case OCLASS_LANGUAGE:
5490 case OCLASS_OPERATOR:
5491 case OCLASS_OPCLASS:
5492 case OCLASS_OPFAMILY:
5493 case OCLASS_TRIGGER:
5495 case OCLASS_TSPARSER:
5497 case OCLASS_TSTEMPLATE:
5498 case OCLASS_TSCONFIG:
5501 * We don't expect any of these sorts of objects to depend on
5504 elog(ERROR, "unexpected object depending on column: %s",
5505 getObjectDescription(&foundObject));
5509 elog(ERROR, "unrecognized object class: %u",
5510 foundObject.classId);
5514 systable_endscan(scan);
5517 * Now scan for dependencies of this column on other things. The only
5518 * thing we should find is the dependency on the column datatype, which we
5521 ScanKeyInit(&key[0],
5522 Anum_pg_depend_classid,
5523 BTEqualStrategyNumber, F_OIDEQ,
5524 ObjectIdGetDatum(RelationRelationId));
5525 ScanKeyInit(&key[1],
5526 Anum_pg_depend_objid,
5527 BTEqualStrategyNumber, F_OIDEQ,
5528 ObjectIdGetDatum(RelationGetRelid(rel)));
5529 ScanKeyInit(&key[2],
5530 Anum_pg_depend_objsubid,
5531 BTEqualStrategyNumber, F_INT4EQ,
5532 Int32GetDatum((int32) attnum));
5534 scan = systable_beginscan(depRel, DependDependerIndexId, true,
5535 SnapshotNow, 3, key);
5537 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5539 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5541 if (foundDep->deptype != DEPENDENCY_NORMAL)
5542 elog(ERROR, "found unexpected dependency type '%c'",
5544 if (foundDep->refclassid != TypeRelationId ||
5545 foundDep->refobjid != attTup->atttypid)
5546 elog(ERROR, "found unexpected dependency for column");
5548 simple_heap_delete(depRel, &depTup->t_self);
5551 systable_endscan(scan);
5553 heap_close(depRel, RowExclusiveLock);
5556 * Here we go --- change the recorded column type. (Note heapTup is a
5557 * copy of the syscache entry, so okay to scribble on.)
5559 attTup->atttypid = targettype;
5560 attTup->atttypmod = targettypmod;
5561 attTup->attndims = list_length(typename->arrayBounds);
5562 attTup->attlen = tform->typlen;
5563 attTup->attbyval = tform->typbyval;
5564 attTup->attalign = tform->typalign;
5565 attTup->attstorage = tform->typstorage;
5567 ReleaseSysCache(typeTuple);
5569 simple_heap_update(attrelation, &heapTup->t_self, heapTup);
5571 /* keep system catalog indexes current */
5572 CatalogUpdateIndexes(attrelation, heapTup);
5574 heap_close(attrelation, RowExclusiveLock);
5576 /* Install dependency on new datatype */
5577 add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
5580 * Drop any pg_statistic entry for the column, since it's now wrong type
5582 RemoveStatistics(RelationGetRelid(rel), attnum);
5585 * Update the default, if present, by brute force --- remove and re-add
5586 * the default. Probably unsafe to take shortcuts, since the new version
5587 * may well have additional dependencies. (It's okay to do this now,
5588 * rather than after other ALTER TYPE commands, since the default won't
5589 * depend on other column types.)
5593 /* Must make new row visible since it will be updated again */
5594 CommandCounterIncrement();
5597 * We use RESTRICT here for safety, but at present we do not expect
5598 * anything to depend on the default.
5600 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true);
5602 StoreAttrDefault(rel, attnum, defaultexpr);
5606 heap_freetuple(heapTup);
5610 * Cleanup after we've finished all the ALTER TYPE operations for a
5611 * particular relation. We have to drop and recreate all the indexes
5612 * and constraints that depend on the altered columns.
5615 ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab)
5621 * Re-parse the index and constraint definitions, and attach them to the
5622 * appropriate work queue entries. We do this before dropping because in
5623 * the case of a FOREIGN KEY constraint, we might not yet have exclusive
5624 * lock on the table the constraint is attached to, and we need to get
5625 * that before dropping. It's safe because the parser won't actually look
5626 * at the catalogs to detect the existing entry.
5628 foreach(l, tab->changedIndexDefs)
5629 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
5630 foreach(l, tab->changedConstraintDefs)
5631 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
5634 * Now we can drop the existing constraints and indexes --- constraints
5635 * first, since some of them might depend on the indexes. In fact, we
5636 * have to delete FOREIGN KEY constraints before UNIQUE constraints, but
5637 * we already ordered the constraint list to ensure that would happen. It
5638 * should be okay to use DROP_RESTRICT here, since nothing else should be
5639 * depending on these objects.
5641 foreach(l, tab->changedConstraintOids)
5643 obj.classId = ConstraintRelationId;
5644 obj.objectId = lfirst_oid(l);
5645 obj.objectSubId = 0;
5646 performDeletion(&obj, DROP_RESTRICT);
5649 foreach(l, tab->changedIndexOids)
5651 obj.classId = RelationRelationId;
5652 obj.objectId = lfirst_oid(l);
5653 obj.objectSubId = 0;
5654 performDeletion(&obj, DROP_RESTRICT);
5658 * The objects will get recreated during subsequent passes over the work
5664 ATPostAlterTypeParse(char *cmd, List **wqueue)
5666 List *raw_parsetree_list;
5667 List *querytree_list;
5668 ListCell *list_item;
5671 * We expect that we will get only ALTER TABLE and CREATE INDEX
5672 * statements. Hence, there is no need to pass them through
5673 * parse_analyze() or the rewriter, but instead we need to pass them
5674 * through parse_utilcmd.c to make them ready for execution.
5676 raw_parsetree_list = raw_parser(cmd);
5677 querytree_list = NIL;
5678 foreach(list_item, raw_parsetree_list)
5680 Node *stmt = (Node *) lfirst(list_item);
5682 if (IsA(stmt, IndexStmt))
5683 querytree_list = lappend(querytree_list,
5684 transformIndexStmt((IndexStmt *) stmt,
5686 else if (IsA(stmt, AlterTableStmt))
5687 querytree_list = list_concat(querytree_list,
5688 transformAlterTableStmt((AlterTableStmt *) stmt,
5691 querytree_list = lappend(querytree_list, stmt);
5695 * Attach each generated command to the proper place in the work queue.
5696 * Note this could result in creation of entirely new work-queue entries.
5698 foreach(list_item, querytree_list)
5700 Node *stm = (Node *) lfirst(list_item);
5702 AlteredTableInfo *tab;
5704 switch (nodeTag(stm))
5708 IndexStmt *stmt = (IndexStmt *) stm;
5709 AlterTableCmd *newcmd;
5711 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
5712 tab = ATGetQueueEntry(wqueue, rel);
5713 newcmd = makeNode(AlterTableCmd);
5714 newcmd->subtype = AT_ReAddIndex;
5715 newcmd->def = (Node *) stmt;
5716 tab->subcmds[AT_PASS_OLD_INDEX] =
5717 lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
5718 relation_close(rel, NoLock);
5721 case T_AlterTableStmt:
5723 AlterTableStmt *stmt = (AlterTableStmt *) stm;
5726 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
5727 tab = ATGetQueueEntry(wqueue, rel);
5728 foreach(lcmd, stmt->cmds)
5730 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
5732 switch (cmd->subtype)
5735 cmd->subtype = AT_ReAddIndex;
5736 tab->subcmds[AT_PASS_OLD_INDEX] =
5737 lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
5739 case AT_AddConstraint:
5740 tab->subcmds[AT_PASS_OLD_CONSTR] =
5741 lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
5744 elog(ERROR, "unexpected statement type: %d",
5745 (int) cmd->subtype);
5748 relation_close(rel, NoLock);
5752 elog(ERROR, "unexpected statement type: %d",
5753 (int) nodeTag(stm));
5762 * recursing is true if we are recursing from a table to its indexes,
5763 * sequences, or toast table. We don't allow the ownership of those things to
5764 * be changed separately from the parent table. Also, we can skip permission
5765 * checks (this is necessary not just an optimization, else we'd fail to
5766 * handle toast tables properly).
5768 * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
5769 * free-standing composite type.
5772 ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing)
5774 Relation target_rel;
5777 Form_pg_class tuple_class;
5780 * Get exclusive lock till end of transaction on the target table. Use
5781 * relation_open so that we can work on indexes and sequences.
5783 target_rel = relation_open(relationOid, AccessExclusiveLock);
5785 /* Get its pg_class tuple, too */
5786 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
5788 tuple = SearchSysCache(RELOID,
5789 ObjectIdGetDatum(relationOid),
5791 if (!HeapTupleIsValid(tuple))
5792 elog(ERROR, "cache lookup failed for relation %u", relationOid);
5793 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
5795 /* Can we change the ownership of this tuple? */
5796 switch (tuple_class->relkind)
5798 case RELKIND_RELATION:
5800 /* ok to change owner */
5806 * Because ALTER INDEX OWNER used to be allowed, and in fact
5807 * is generated by old versions of pg_dump, we give a warning
5808 * and do nothing rather than erroring out. Also, to avoid
5809 * unnecessary chatter while restoring those old dumps, say
5810 * nothing at all if the command would be a no-op anyway.
5812 if (tuple_class->relowner != newOwnerId)
5814 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5815 errmsg("cannot change owner of index \"%s\"",
5816 NameStr(tuple_class->relname)),
5817 errhint("Change the ownership of the index's table, instead.")));
5818 /* quick hack to exit via the no-op path */
5819 newOwnerId = tuple_class->relowner;
5822 case RELKIND_SEQUENCE:
5824 tuple_class->relowner != newOwnerId)
5826 /* if it's an owned sequence, disallow changing it by itself */
5830 if (sequenceIsOwned(relationOid, &tableId, &colId))
5832 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5833 errmsg("cannot change owner of sequence \"%s\"",
5834 NameStr(tuple_class->relname)),
5835 errdetail("Sequence \"%s\" is linked to table \"%s\".",
5836 NameStr(tuple_class->relname),
5837 get_rel_name(tableId))));
5840 case RELKIND_COMPOSITE_TYPE:
5844 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5845 errmsg("\"%s\" is a composite type",
5846 NameStr(tuple_class->relname)),
5847 errhint("Use ALTER TYPE instead.")));
5849 case RELKIND_TOASTVALUE:
5855 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5856 errmsg("\"%s\" is not a table, view, or sequence",
5857 NameStr(tuple_class->relname))));
5861 * If the new owner is the same as the existing owner, consider the
5862 * command to have succeeded. This is for dump restoration purposes.
5864 if (tuple_class->relowner != newOwnerId)
5866 Datum repl_val[Natts_pg_class];
5867 char repl_null[Natts_pg_class];
5868 char repl_repl[Natts_pg_class];
5874 /* skip permission checks when recursing to index or toast table */
5877 /* Superusers can always do it */
5880 Oid namespaceOid = tuple_class->relnamespace;
5881 AclResult aclresult;
5883 /* Otherwise, must be owner of the existing object */
5884 if (!pg_class_ownercheck(relationOid, GetUserId()))
5885 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
5886 RelationGetRelationName(target_rel));
5888 /* Must be able to become new owner */
5889 check_is_member_of_role(GetUserId(), newOwnerId);
5891 /* New owner must have CREATE privilege on namespace */
5892 aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
5894 if (aclresult != ACLCHECK_OK)
5895 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
5896 get_namespace_name(namespaceOid));
5900 memset(repl_null, ' ', sizeof(repl_null));
5901 memset(repl_repl, ' ', sizeof(repl_repl));
5903 repl_repl[Anum_pg_class_relowner - 1] = 'r';
5904 repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
5907 * Determine the modified ACL for the new owner. This is only
5908 * necessary when the ACL is non-null.
5910 aclDatum = SysCacheGetAttr(RELOID, tuple,
5911 Anum_pg_class_relacl,
5915 newAcl = aclnewowner(DatumGetAclP(aclDatum),
5916 tuple_class->relowner, newOwnerId);
5917 repl_repl[Anum_pg_class_relacl - 1] = 'r';
5918 repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
5921 newtuple = heap_modifytuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
5923 simple_heap_update(class_rel, &newtuple->t_self, newtuple);
5924 CatalogUpdateIndexes(class_rel, newtuple);
5926 heap_freetuple(newtuple);
5929 * Update owner dependency reference, if any. A composite type has
5930 * none, because it's tracked for the pg_type entry instead of here;
5931 * indexes and TOAST tables don't have their own entries either.
5933 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
5934 tuple_class->relkind != RELKIND_INDEX &&
5935 tuple_class->relkind != RELKIND_TOASTVALUE)
5936 changeDependencyOnOwner(RelationRelationId, relationOid,
5940 * Also change the ownership of the table's rowtype, if it has one
5942 if (tuple_class->relkind != RELKIND_INDEX)
5943 AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId,
5944 tuple_class->relkind == RELKIND_COMPOSITE_TYPE);
5947 * If we are operating on a table, also change the ownership of any
5948 * indexes and sequences that belong to the table, as well as the
5949 * table's toast table (if it has one)
5951 if (tuple_class->relkind == RELKIND_RELATION ||
5952 tuple_class->relkind == RELKIND_TOASTVALUE)
5954 List *index_oid_list;
5957 /* Find all the indexes belonging to this relation */
5958 index_oid_list = RelationGetIndexList(target_rel);
5960 /* For each index, recursively change its ownership */
5961 foreach(i, index_oid_list)
5962 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true);
5964 list_free(index_oid_list);
5967 if (tuple_class->relkind == RELKIND_RELATION)
5969 /* If it has a toast table, recurse to change its ownership */
5970 if (tuple_class->reltoastrelid != InvalidOid)
5971 ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
5974 /* If it has dependent sequences, recurse to change them too */
5975 change_owner_recurse_to_sequences(relationOid, newOwnerId);
5979 ReleaseSysCache(tuple);
5980 heap_close(class_rel, RowExclusiveLock);
5981 relation_close(target_rel, NoLock);
5985 * change_owner_recurse_to_sequences
5987 * Helper function for ATExecChangeOwner. Examines pg_depend searching
5988 * for sequences that are dependent on serial columns, and changes their
5992 change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId)
6000 * SERIAL sequences are those having an auto dependency on one of the
6001 * table's columns (we don't care *which* column, exactly).
6003 depRel = heap_open(DependRelationId, AccessShareLock);
6005 ScanKeyInit(&key[0],
6006 Anum_pg_depend_refclassid,
6007 BTEqualStrategyNumber, F_OIDEQ,
6008 ObjectIdGetDatum(RelationRelationId));
6009 ScanKeyInit(&key[1],
6010 Anum_pg_depend_refobjid,
6011 BTEqualStrategyNumber, F_OIDEQ,
6012 ObjectIdGetDatum(relationOid));
6013 /* we leave refobjsubid unspecified */
6015 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
6016 SnapshotNow, 2, key);
6018 while (HeapTupleIsValid(tup = systable_getnext(scan)))
6020 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
6023 /* skip dependencies other than auto dependencies on columns */
6024 if (depForm->refobjsubid == 0 ||
6025 depForm->classid != RelationRelationId ||
6026 depForm->objsubid != 0 ||
6027 depForm->deptype != DEPENDENCY_AUTO)
6030 /* Use relation_open just in case it's an index */
6031 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
6033 /* skip non-sequence relations */
6034 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
6036 /* No need to keep the lock */
6037 relation_close(seqRel, AccessExclusiveLock);
6041 /* We don't need to close the sequence while we alter it. */
6042 ATExecChangeOwner(depForm->objid, newOwnerId, true);
6044 /* Now we can close it. Keep the lock till end of transaction. */
6045 relation_close(seqRel, NoLock);
6048 systable_endscan(scan);
6050 relation_close(depRel, AccessShareLock);
6054 * ALTER TABLE CLUSTER ON
6056 * The only thing we have to do is to change the indisclustered bits.
6059 ATExecClusterOn(Relation rel, const char *indexName)
6063 indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
6065 if (!OidIsValid(indexOid))
6067 (errcode(ERRCODE_UNDEFINED_OBJECT),
6068 errmsg("index \"%s\" for table \"%s\" does not exist",
6069 indexName, RelationGetRelationName(rel))));
6071 /* Check index is valid to cluster on */
6072 check_index_is_clusterable(rel, indexOid, false);
6074 /* And do the work */
6075 mark_index_clustered(rel, indexOid);
6079 * ALTER TABLE SET WITHOUT CLUSTER
6081 * We have to find any indexes on the table that have indisclustered bit
6082 * set and turn it off.
6085 ATExecDropCluster(Relation rel)
6087 mark_index_clustered(rel, InvalidOid);
6091 * ALTER TABLE SET TABLESPACE
6094 ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, char *tablespacename)
6097 AclResult aclresult;
6099 /* Check that the tablespace exists */
6100 tablespaceId = get_tablespace_oid(tablespacename);
6101 if (!OidIsValid(tablespaceId))
6103 (errcode(ERRCODE_UNDEFINED_OBJECT),
6104 errmsg("tablespace \"%s\" does not exist", tablespacename)));
6106 /* Check its permissions */
6107 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(), ACL_CREATE);
6108 if (aclresult != ACLCHECK_OK)
6109 aclcheck_error(aclresult, ACL_KIND_TABLESPACE, tablespacename);
6111 /* Save info for Phase 3 to do the real work */
6112 if (OidIsValid(tab->newTableSpace))
6114 (errcode(ERRCODE_SYNTAX_ERROR),
6115 errmsg("cannot have multiple SET TABLESPACE subcommands")));
6116 tab->newTableSpace = tablespaceId;
6120 * ALTER TABLE/INDEX SET (...) or RESET (...)
6123 ATExecSetRelOptions(Relation rel, List *defList, bool isReset)
6132 Datum repl_val[Natts_pg_class];
6133 char repl_null[Natts_pg_class];
6134 char repl_repl[Natts_pg_class];
6137 return; /* nothing to do */
6139 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
6141 /* Get the old reloptions */
6142 relid = RelationGetRelid(rel);
6143 tuple = SearchSysCache(RELOID,
6144 ObjectIdGetDatum(relid),
6146 if (!HeapTupleIsValid(tuple))
6147 elog(ERROR, "cache lookup failed for relation %u", relid);
6149 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions, &isnull);
6151 /* Generate new proposed reloptions (text array) */
6152 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
6153 defList, false, isReset);
6156 switch (rel->rd_rel->relkind)
6158 case RELKIND_RELATION:
6159 case RELKIND_TOASTVALUE:
6160 (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
6163 (void) index_reloptions(rel->rd_am->amoptions, newOptions, true);
6167 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6168 errmsg("\"%s\" is not a table, index, or TOAST table",
6169 RelationGetRelationName(rel))));
6174 * All we need do here is update the pg_class row; the new options will be
6175 * propagated into relcaches during post-commit cache inval.
6177 memset(repl_val, 0, sizeof(repl_val));
6178 memset(repl_null, ' ', sizeof(repl_null));
6179 memset(repl_repl, ' ', sizeof(repl_repl));
6181 if (newOptions != (Datum) 0)
6182 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
6184 repl_null[Anum_pg_class_reloptions - 1] = 'n';
6186 repl_repl[Anum_pg_class_reloptions - 1] = 'r';
6188 newtuple = heap_modifytuple(tuple, RelationGetDescr(pgclass),
6189 repl_val, repl_null, repl_repl);
6191 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
6193 CatalogUpdateIndexes(pgclass, newtuple);
6195 heap_freetuple(newtuple);
6197 ReleaseSysCache(tuple);
6199 heap_close(pgclass, RowExclusiveLock);
6203 * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
6204 * rewriting to be done, so we just want to copy the data as fast as possible.
6207 ATExecSetTableSpace(Oid tableOid, Oid newTableSpace)
6213 RelFileNode newrnode;
6214 SMgrRelation dstrel;
6217 Form_pg_class rd_rel;
6220 * Need lock here in case we are recursing to toast table or index
6222 rel = relation_open(tableOid, AccessExclusiveLock);
6225 * We can never allow moving of shared or nailed-in-cache relations,
6226 * because we can't support changing their reltablespace values.
6228 if (rel->rd_rel->relisshared || rel->rd_isnailed)
6230 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6231 errmsg("cannot move system relation \"%s\"",
6232 RelationGetRelationName(rel))));
6234 /* Can't move a non-shared relation into pg_global */
6235 if (newTableSpace == GLOBALTABLESPACE_OID)
6237 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6238 errmsg("only shared relations can be placed in pg_global tablespace")));
6241 * Don't allow moving temp tables of other backends ... their local buffer
6242 * manager is not going to cope.
6244 if (isOtherTempNamespace(RelationGetNamespace(rel)))
6246 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6247 errmsg("cannot move temporary tables of other sessions")));
6250 * No work if no change in tablespace.
6252 oldTableSpace = rel->rd_rel->reltablespace;
6253 if (newTableSpace == oldTableSpace ||
6254 (newTableSpace == MyDatabaseTableSpace && oldTableSpace == 0))
6256 relation_close(rel, NoLock);
6260 reltoastrelid = rel->rd_rel->reltoastrelid;
6261 reltoastidxid = rel->rd_rel->reltoastidxid;
6263 /* Get a modifiable copy of the relation's pg_class row */
6264 pg_class = heap_open(RelationRelationId, RowExclusiveLock);
6266 tuple = SearchSysCacheCopy(RELOID,
6267 ObjectIdGetDatum(tableOid),
6269 if (!HeapTupleIsValid(tuple))
6270 elog(ERROR, "cache lookup failed for relation %u", tableOid);
6271 rd_rel = (Form_pg_class) GETSTRUCT(tuple);
6273 /* create another storage file. Is it a little ugly ? */
6274 /* NOTE: any conflict in relfilenode value will be caught here */
6275 newrnode = rel->rd_node;
6276 newrnode.spcNode = newTableSpace;
6278 dstrel = smgropen(newrnode);
6279 smgrcreate(dstrel, rel->rd_istemp, false);
6281 /* copy relation data to the new physical file */
6282 copy_relation_data(rel, dstrel);
6284 /* schedule unlinking old physical file */
6285 RelationOpenSmgr(rel);
6286 smgrscheduleunlink(rel->rd_smgr, rel->rd_istemp);
6289 * Now drop smgr references. The source was already dropped by
6290 * smgrscheduleunlink.
6294 /* update the pg_class row */
6295 rd_rel->reltablespace = (newTableSpace == MyDatabaseTableSpace) ? InvalidOid : newTableSpace;
6296 simple_heap_update(pg_class, &tuple->t_self, tuple);
6297 CatalogUpdateIndexes(pg_class, tuple);
6299 heap_freetuple(tuple);
6301 heap_close(pg_class, RowExclusiveLock);
6303 relation_close(rel, NoLock);
6305 /* Make sure the reltablespace change is visible */
6306 CommandCounterIncrement();
6308 /* Move associated toast relation and/or index, too */
6309 if (OidIsValid(reltoastrelid))
6310 ATExecSetTableSpace(reltoastrelid, newTableSpace);
6311 if (OidIsValid(reltoastidxid))
6312 ATExecSetTableSpace(reltoastidxid, newTableSpace);
6316 * Copy data, block by block
6319 copy_relation_data(Relation rel, SMgrRelation dst)
6323 BlockNumber nblocks;
6326 Page page = (Page) buf;
6329 * Since we copy the file directly without looking at the shared buffers,
6330 * we'd better first flush out any pages of the source relation that are
6331 * in shared buffers. We assume no new changes will be made while we are
6332 * holding exclusive lock on the rel.
6334 FlushRelationBuffers(rel);
6337 * We need to log the copied data in WAL iff WAL archiving is enabled AND
6338 * it's not a temp rel.
6340 use_wal = XLogArchivingActive() && !rel->rd_istemp;
6342 nblocks = RelationGetNumberOfBlocks(rel);
6343 /* RelationGetNumberOfBlocks will certainly have opened rd_smgr */
6346 for (blkno = 0; blkno < nblocks; blkno++)
6348 smgrread(src, blkno, buf);
6352 log_newpage(&dst->smgr_rnode, blkno, page);
6355 * Now write the page. We say isTemp = true even if it's not a temp
6356 * rel, because there's no need for smgr to schedule an fsync for this
6357 * write; we'll do it ourselves below.
6359 smgrextend(dst, blkno, buf, true);
6363 * If the rel isn't temp, we must fsync it down to disk before it's safe
6364 * to commit the transaction. (For a temp rel we don't care since the rel
6365 * will be uninteresting after a crash anyway.)
6367 * It's obvious that we must do this when not WAL-logging the copy. It's
6368 * less obvious that we have to do it even if we did WAL-log the copied
6369 * pages. The reason is that since we're copying outside shared buffers, a
6370 * CHECKPOINT occurring during the copy has no way to flush the previously
6371 * written data to disk (indeed it won't know the new rel even exists). A
6372 * crash later on would replay WAL from the checkpoint, therefore it
6373 * wouldn't replay our earlier WAL entries. If we do not fsync those pages
6374 * here, they might still not be on disk when the crash occurs.
6376 if (!rel->rd_istemp)
6381 * ALTER TABLE ENABLE/DISABLE TRIGGER
6383 * We just pass this off to trigger.c.
6386 ATExecEnableDisableTrigger(Relation rel, char *trigname,
6387 char fires_when, bool skip_system)
6389 EnableDisableTrigger(rel, trigname, fires_when, skip_system);
6393 * ALTER TABLE ENABLE/DISABLE RULE
6395 * We just pass this off to rewriteDefine.c.
6398 ATExecEnableDisableRule(Relation rel, char *trigname,
6401 EnableDisableRule(rel, trigname, fires_when);
6405 * ALTER TABLE INHERIT
6407 * Add a parent to the child's parents. This verifies that all the columns and
6408 * check constraints of the parent appear in the child and that they have the
6409 * same data types and expressions.
6412 ATExecAddInherit(Relation child_rel, RangeVar *parent)
6414 Relation parent_rel,
6418 HeapTuple inheritsTuple;
6423 * AccessShareLock on the parent is what's obtained during normal CREATE
6424 * TABLE ... INHERITS ..., so should be enough here.
6426 parent_rel = heap_openrv(parent, AccessShareLock);
6429 * Must be owner of both parent and child -- child was checked by
6430 * ATSimplePermissions call in ATPrepCmd
6432 ATSimplePermissions(parent_rel, false);
6434 /* Permanent rels cannot inherit from temporary ones */
6435 if (!isTempNamespace(RelationGetNamespace(child_rel)) &&
6436 isTempNamespace(RelationGetNamespace(parent_rel)))
6438 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6439 errmsg("cannot inherit from temporary relation \"%s\"",
6440 RelationGetRelationName(parent_rel))));
6443 * Check for duplicates in the list of parents, and determine the highest
6444 * inhseqno already present; we'll use the next one for the new parent.
6445 * (Note: get RowExclusiveLock because we will write pg_inherits below.)
6447 * Note: we do not reject the case where the child already inherits from
6448 * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
6450 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
6452 Anum_pg_inherits_inhrelid,
6453 BTEqualStrategyNumber, F_OIDEQ,
6454 ObjectIdGetDatum(RelationGetRelid(child_rel)));
6455 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
6456 true, SnapshotNow, 1, &key);
6458 /* inhseqno sequences start at 1 */
6460 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
6462 Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
6464 if (inh->inhparent == RelationGetRelid(parent_rel))
6466 (errcode(ERRCODE_DUPLICATE_TABLE),
6467 errmsg("relation \"%s\" would be inherited from more than once",
6468 RelationGetRelationName(parent_rel))));
6469 if (inh->inhseqno > inhseqno)
6470 inhseqno = inh->inhseqno;
6472 systable_endscan(scan);
6475 * Prevent circularity by seeing if proposed parent inherits from child.
6476 * (In particular, this disallows making a rel inherit from itself.)
6478 * This is not completely bulletproof because of race conditions: in
6479 * multi-level inheritance trees, someone else could concurrently be
6480 * making another inheritance link that closes the loop but does not join
6481 * either of the rels we have locked. Preventing that seems to require
6482 * exclusive locks on the entire inheritance tree, which is a cure worse
6483 * than the disease. find_all_inheritors() will cope with circularity
6484 * anyway, so don't sweat it too much.
6486 children = find_all_inheritors(RelationGetRelid(child_rel));
6488 if (list_member_oid(children, RelationGetRelid(parent_rel)))
6490 (errcode(ERRCODE_DUPLICATE_TABLE),
6491 errmsg("circular inheritance not allowed"),
6492 errdetail("\"%s\" is already a child of \"%s\".",
6494 RelationGetRelationName(child_rel))));
6496 /* If parent has OIDs then child must have OIDs */
6497 if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
6499 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6500 errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
6501 RelationGetRelationName(child_rel),
6502 RelationGetRelationName(parent_rel))));
6504 /* Match up the columns and bump attinhcount as needed */
6505 MergeAttributesIntoExisting(child_rel, parent_rel);
6507 /* Match up the constraints and bump coninhcount as needed */
6508 MergeConstraintsIntoExisting(child_rel, parent_rel);
6511 * OK, it looks valid. Make the catalog entries that show inheritance.
6513 StoreCatalogInheritance1(RelationGetRelid(child_rel),
6514 RelationGetRelid(parent_rel),
6518 /* Now we're done with pg_inherits */
6519 heap_close(catalogRelation, RowExclusiveLock);
6521 /* keep our lock on the parent relation until commit */
6522 heap_close(parent_rel, NoLock);
6526 * Obtain the source-text form of the constraint expression for a check
6527 * constraint, given its pg_constraint tuple
6530 decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
6532 Form_pg_constraint con;
6537 con = (Form_pg_constraint) GETSTRUCT(contup);
6538 attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
6540 elog(ERROR, "null conbin for constraint %u", HeapTupleGetOid(contup));
6542 expr = DirectFunctionCall2(pg_get_expr, attr,
6543 ObjectIdGetDatum(con->conrelid));
6544 return TextDatumGetCString(expr);
6548 * Determine whether two check constraints are functionally equivalent
6550 * The test we apply is to see whether they reverse-compile to the same
6551 * source string. This insulates us from issues like whether attributes
6552 * have the same physical column numbers in parent and child relations.
6555 constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
6557 Form_pg_constraint acon = (Form_pg_constraint) GETSTRUCT(a);
6558 Form_pg_constraint bcon = (Form_pg_constraint) GETSTRUCT(b);
6560 if (acon->condeferrable != bcon->condeferrable ||
6561 acon->condeferred != bcon->condeferred ||
6562 strcmp(decompile_conbin(a, tupleDesc),
6563 decompile_conbin(b, tupleDesc)) != 0)
6570 * Check columns in child table match up with columns in parent, and increment
6571 * their attinhcount.
6573 * Called by ATExecAddInherit
6575 * Currently all parent columns must be found in child. Missing columns are an
6576 * error. One day we might consider creating new columns like CREATE TABLE
6577 * does. However, that is widely unpopular --- in the common use case of
6578 * partitioned tables it's a foot-gun.
6580 * The data type must match exactly. If the parent column is NOT NULL then
6581 * the child must be as well. Defaults are not compared, however.
6584 MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel)
6587 AttrNumber parent_attno;
6589 TupleDesc tupleDesc;
6590 TupleConstr *constr;
6593 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
6595 tupleDesc = RelationGetDescr(parent_rel);
6596 parent_natts = tupleDesc->natts;
6597 constr = tupleDesc->constr;
6599 for (parent_attno = 1; parent_attno <= parent_natts; parent_attno++)
6601 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
6602 char *attributeName = NameStr(attribute->attname);
6604 /* Ignore dropped columns in the parent. */
6605 if (attribute->attisdropped)
6608 /* Find same column in child (matching on column name). */
6609 tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel),
6611 if (HeapTupleIsValid(tuple))
6613 /* Check they are same type and typmod */
6614 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
6616 if (attribute->atttypid != childatt->atttypid ||
6617 attribute->atttypmod != childatt->atttypmod)
6619 (errcode(ERRCODE_DATATYPE_MISMATCH),
6620 errmsg("child table \"%s\" has different type for column \"%s\"",
6621 RelationGetRelationName(child_rel),
6624 if (attribute->attnotnull && !childatt->attnotnull)
6626 (errcode(ERRCODE_DATATYPE_MISMATCH),
6627 errmsg("column \"%s\" in child table must be marked NOT NULL",
6631 * OK, bump the child column's inheritance count. (If we fail
6632 * later on, this change will just roll back.)
6634 childatt->attinhcount++;
6635 simple_heap_update(attrrel, &tuple->t_self, tuple);
6636 CatalogUpdateIndexes(attrrel, tuple);
6637 heap_freetuple(tuple);
6642 (errcode(ERRCODE_DATATYPE_MISMATCH),
6643 errmsg("child table is missing column \"%s\"",
6648 heap_close(attrrel, RowExclusiveLock);
6652 * Check constraints in child table match up with constraints in parent,
6653 * and increment their coninhcount.
6655 * Called by ATExecAddInherit
6657 * Currently all constraints in parent must be present in the child. One day we
6658 * may consider adding new constraints like CREATE TABLE does. We may also want
6659 * to allow an optional flag on parent table constraints indicating they are
6660 * intended to ONLY apply to the master table, not to the children. That would
6661 * make it possible to ensure no records are mistakenly inserted into the
6662 * master in partitioned tables rather than the appropriate child.
6664 * XXX This is O(N^2) which may be an issue with tables with hundreds of
6665 * constraints. As long as tables have more like 10 constraints it shouldn't be
6666 * a problem though. Even 100 constraints ought not be the end of the world.
6669 MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
6671 Relation catalog_relation;
6672 TupleDesc tuple_desc;
6673 SysScanDesc parent_scan;
6674 ScanKeyData parent_key;
6675 HeapTuple parent_tuple;
6677 catalog_relation = heap_open(ConstraintRelationId, RowExclusiveLock);
6678 tuple_desc = RelationGetDescr(catalog_relation);
6680 /* Outer loop scans through the parent's constraint definitions */
6681 ScanKeyInit(&parent_key,
6682 Anum_pg_constraint_conrelid,
6683 BTEqualStrategyNumber, F_OIDEQ,
6684 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
6685 parent_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
6686 true, SnapshotNow, 1, &parent_key);
6688 while (HeapTupleIsValid(parent_tuple = systable_getnext(parent_scan)))
6690 Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(parent_tuple);
6691 SysScanDesc child_scan;
6692 ScanKeyData child_key;
6693 HeapTuple child_tuple;
6696 if (parent_con->contype != CONSTRAINT_CHECK)
6699 /* Search for a child constraint matching this one */
6700 ScanKeyInit(&child_key,
6701 Anum_pg_constraint_conrelid,
6702 BTEqualStrategyNumber, F_OIDEQ,
6703 ObjectIdGetDatum(RelationGetRelid(child_rel)));
6704 child_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
6705 true, SnapshotNow, 1, &child_key);
6707 while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
6709 Form_pg_constraint child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
6710 HeapTuple child_copy;
6712 if (child_con->contype != CONSTRAINT_CHECK)
6715 if (strcmp(NameStr(parent_con->conname),
6716 NameStr(child_con->conname)) != 0)
6719 if (!constraints_equivalent(parent_tuple, child_tuple, tuple_desc))
6721 (errcode(ERRCODE_DATATYPE_MISMATCH),
6722 errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
6723 RelationGetRelationName(child_rel),
6724 NameStr(parent_con->conname))));
6727 * OK, bump the child constraint's inheritance count. (If we fail
6728 * later on, this change will just roll back.)
6730 child_copy = heap_copytuple(child_tuple);
6731 child_con = (Form_pg_constraint) GETSTRUCT(child_copy);
6732 child_con->coninhcount++;
6733 simple_heap_update(catalog_relation, &child_copy->t_self, child_copy);
6734 CatalogUpdateIndexes(catalog_relation, child_copy);
6735 heap_freetuple(child_copy);
6741 systable_endscan(child_scan);
6745 (errcode(ERRCODE_DATATYPE_MISMATCH),
6746 errmsg("child table is missing constraint \"%s\"",
6747 NameStr(parent_con->conname))));
6750 systable_endscan(parent_scan);
6751 heap_close(catalog_relation, RowExclusiveLock);
6755 * ALTER TABLE NO INHERIT
6757 * Drop a parent from the child's parents. This just adjusts the attinhcount
6758 * and attislocal of the columns and removes the pg_inherit and pg_depend
6761 * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
6762 * up attislocal stays true, which means if a child is ever removed from a
6763 * parent then its columns will never be automatically dropped which may
6764 * surprise. But at least we'll never surprise by dropping columns someone
6765 * isn't expecting to be dropped which would actually mean data loss.
6767 * coninhcount and conislocal for inherited constraints are adjusted in
6768 * exactly the same way.
6771 ATExecDropInherit(Relation rel, RangeVar *parent)
6773 Relation parent_rel;
6774 Relation catalogRelation;
6777 HeapTuple inheritsTuple,
6785 * AccessShareLock on the parent is probably enough, seeing that DROP
6786 * TABLE doesn't lock parent tables at all. We need some lock since we'll
6787 * be inspecting the parent's schema.
6789 parent_rel = heap_openrv(parent, AccessShareLock);
6792 * We don't bother to check ownership of the parent table --- ownership of
6793 * the child is presumed enough rights.
6797 * Find and destroy the pg_inherits entry linking the two, or error out if
6800 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
6801 ScanKeyInit(&key[0],
6802 Anum_pg_inherits_inhrelid,
6803 BTEqualStrategyNumber, F_OIDEQ,
6804 ObjectIdGetDatum(RelationGetRelid(rel)));
6805 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
6806 true, SnapshotNow, 1, key);
6808 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
6812 inhparent = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
6813 if (inhparent == RelationGetRelid(parent_rel))
6815 simple_heap_delete(catalogRelation, &inheritsTuple->t_self);
6821 systable_endscan(scan);
6822 heap_close(catalogRelation, RowExclusiveLock);
6826 (errcode(ERRCODE_UNDEFINED_TABLE),
6827 errmsg("relation \"%s\" is not a parent of relation \"%s\"",
6828 RelationGetRelationName(parent_rel),
6829 RelationGetRelationName(rel))));
6832 * Search through child columns looking for ones matching parent rel
6834 catalogRelation = heap_open(AttributeRelationId, RowExclusiveLock);
6835 ScanKeyInit(&key[0],
6836 Anum_pg_attribute_attrelid,
6837 BTEqualStrategyNumber, F_OIDEQ,
6838 ObjectIdGetDatum(RelationGetRelid(rel)));
6839 scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
6840 true, SnapshotNow, 1, key);
6841 while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
6843 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
6845 /* Ignore if dropped or not inherited */
6846 if (att->attisdropped)
6848 if (att->attinhcount <= 0)
6851 if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
6852 NameStr(att->attname)))
6854 /* Decrement inhcount and possibly set islocal to true */
6855 HeapTuple copyTuple = heap_copytuple(attributeTuple);
6856 Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
6858 copy_att->attinhcount--;
6859 if (copy_att->attinhcount == 0)
6860 copy_att->attislocal = true;
6862 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
6863 CatalogUpdateIndexes(catalogRelation, copyTuple);
6864 heap_freetuple(copyTuple);
6867 systable_endscan(scan);
6868 heap_close(catalogRelation, RowExclusiveLock);
6871 * Likewise, find inherited check constraints and disinherit them.
6872 * To do this, we first need a list of the names of the parent's check
6873 * constraints. (We cheat a bit by only checking for name matches,
6874 * assuming that the expressions will match.)
6876 catalogRelation = heap_open(ConstraintRelationId, RowExclusiveLock);
6877 ScanKeyInit(&key[0],
6878 Anum_pg_constraint_conrelid,
6879 BTEqualStrategyNumber, F_OIDEQ,
6880 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
6881 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
6882 true, SnapshotNow, 1, key);
6886 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
6888 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
6890 if (con->contype == CONSTRAINT_CHECK)
6891 connames = lappend(connames, pstrdup(NameStr(con->conname)));
6894 systable_endscan(scan);
6896 /* Now scan the child's constraints */
6897 ScanKeyInit(&key[0],
6898 Anum_pg_constraint_conrelid,
6899 BTEqualStrategyNumber, F_OIDEQ,
6900 ObjectIdGetDatum(RelationGetRelid(rel)));
6901 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
6902 true, SnapshotNow, 1, key);
6904 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
6906 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
6910 if (con->contype != CONSTRAINT_CHECK)
6914 foreach (lc, connames)
6916 if (strcmp(NameStr(con->conname), (char *) lfirst(lc)) == 0)
6925 /* Decrement inhcount and possibly set islocal to true */
6926 HeapTuple copyTuple = heap_copytuple(constraintTuple);
6927 Form_pg_constraint copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
6928 if (copy_con->coninhcount <= 0) /* shouldn't happen */
6929 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
6930 RelationGetRelid(rel), NameStr(copy_con->conname));
6932 copy_con->coninhcount--;
6933 if (copy_con->coninhcount == 0)
6934 copy_con->conislocal = true;
6936 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
6937 CatalogUpdateIndexes(catalogRelation, copyTuple);
6938 heap_freetuple(copyTuple);
6942 systable_endscan(scan);
6943 heap_close(catalogRelation, RowExclusiveLock);
6946 * Drop the dependency
6948 * There's no convenient way to do this, so go trawling through pg_depend
6950 catalogRelation = heap_open(DependRelationId, RowExclusiveLock);
6952 ScanKeyInit(&key[0],
6953 Anum_pg_depend_classid,
6954 BTEqualStrategyNumber, F_OIDEQ,
6955 ObjectIdGetDatum(RelationRelationId));
6956 ScanKeyInit(&key[1],
6957 Anum_pg_depend_objid,
6958 BTEqualStrategyNumber, F_OIDEQ,
6959 ObjectIdGetDatum(RelationGetRelid(rel)));
6960 ScanKeyInit(&key[2],
6961 Anum_pg_depend_objsubid,
6962 BTEqualStrategyNumber, F_INT4EQ,
6965 scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
6966 SnapshotNow, 3, key);
6968 while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
6970 Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
6972 if (dep->refclassid == RelationRelationId &&
6973 dep->refobjid == RelationGetRelid(parent_rel) &&
6974 dep->refobjsubid == 0 &&
6975 dep->deptype == DEPENDENCY_NORMAL)
6976 simple_heap_delete(catalogRelation, &depTuple->t_self);
6979 systable_endscan(scan);
6980 heap_close(catalogRelation, RowExclusiveLock);
6982 /* keep our lock on the parent relation until commit */
6983 heap_close(parent_rel, NoLock);
6988 * Execute ALTER TABLE SET SCHEMA
6990 * Note: caller must have checked ownership of the relation already
6993 AlterTableNamespace(RangeVar *relation, const char *newschema)
7001 rel = relation_openrv(relation, AccessExclusiveLock);
7003 relid = RelationGetRelid(rel);
7004 oldNspOid = RelationGetNamespace(rel);
7006 /* Can we change the schema of this tuple? */
7007 switch (rel->rd_rel->relkind)
7009 case RELKIND_RELATION:
7011 /* ok to change schema */
7013 case RELKIND_SEQUENCE:
7015 /* if it's an owned sequence, disallow moving it by itself */
7019 if (sequenceIsOwned(relid, &tableId, &colId))
7021 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7022 errmsg("cannot move an owned sequence into another schema"),
7023 errdetail("Sequence \"%s\" is linked to table \"%s\".",
7024 RelationGetRelationName(rel),
7025 get_rel_name(tableId))));
7028 case RELKIND_COMPOSITE_TYPE:
7030 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7031 errmsg("\"%s\" is a composite type",
7032 RelationGetRelationName(rel)),
7033 errhint("Use ALTER TYPE instead.")));
7036 case RELKIND_TOASTVALUE:
7040 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7041 errmsg("\"%s\" is not a table, view, or sequence",
7042 RelationGetRelationName(rel))));
7045 /* get schema OID and check its permissions */
7046 nspOid = LookupCreationNamespace(newschema);
7048 if (oldNspOid == nspOid)
7050 (errcode(ERRCODE_DUPLICATE_TABLE),
7051 errmsg("relation \"%s\" is already in schema \"%s\"",
7052 RelationGetRelationName(rel),
7055 /* disallow renaming into or out of temp schemas */
7056 if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
7058 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7059 errmsg("cannot move objects into or out of temporary schemas")));
7061 /* same for TOAST schema */
7062 if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
7064 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7065 errmsg("cannot move objects into or out of TOAST schema")));
7067 /* OK, modify the pg_class row and pg_depend entry */
7068 classRel = heap_open(RelationRelationId, RowExclusiveLock);
7070 AlterRelationNamespaceInternal(classRel, relid, oldNspOid, nspOid, true);
7072 /* Fix the table's rowtype too */
7073 AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid, false, false);
7075 /* Fix other dependent stuff */
7076 if (rel->rd_rel->relkind == RELKIND_RELATION)
7078 AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid);
7079 AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid, newschema);
7080 AlterConstraintNamespaces(relid, oldNspOid, nspOid, false);
7083 heap_close(classRel, RowExclusiveLock);
7085 /* close rel, but keep lock until commit */
7086 relation_close(rel, NoLock);
7090 * The guts of relocating a relation to another namespace: fix the pg_class
7091 * entry, and the pg_depend entry if any. Caller must already have
7092 * opened and write-locked pg_class.
7095 AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
7096 Oid oldNspOid, Oid newNspOid,
7097 bool hasDependEntry)
7100 Form_pg_class classForm;
7102 classTup = SearchSysCacheCopy(RELOID,
7103 ObjectIdGetDatum(relOid),
7105 if (!HeapTupleIsValid(classTup))
7106 elog(ERROR, "cache lookup failed for relation %u", relOid);
7107 classForm = (Form_pg_class) GETSTRUCT(classTup);
7109 Assert(classForm->relnamespace == oldNspOid);
7111 /* check for duplicate name (more friendly than unique-index failure) */
7112 if (get_relname_relid(NameStr(classForm->relname),
7113 newNspOid) != InvalidOid)
7115 (errcode(ERRCODE_DUPLICATE_TABLE),
7116 errmsg("relation \"%s\" already exists in schema \"%s\"",
7117 NameStr(classForm->relname),
7118 get_namespace_name(newNspOid))));
7120 /* classTup is a copy, so OK to scribble on */
7121 classForm->relnamespace = newNspOid;
7123 simple_heap_update(classRel, &classTup->t_self, classTup);
7124 CatalogUpdateIndexes(classRel, classTup);
7126 /* Update dependency on schema if caller said so */
7127 if (hasDependEntry &&
7128 changeDependencyFor(RelationRelationId, relOid,
7129 NamespaceRelationId, oldNspOid, newNspOid) != 1)
7130 elog(ERROR, "failed to change schema dependency for relation \"%s\"",
7131 NameStr(classForm->relname));
7133 heap_freetuple(classTup);
7137 * Move all indexes for the specified relation to another namespace.
7139 * Note: we assume adequate permission checking was done by the caller,
7140 * and that the caller has a suitable lock on the owning relation.
7143 AlterIndexNamespaces(Relation classRel, Relation rel,
7144 Oid oldNspOid, Oid newNspOid)
7149 indexList = RelationGetIndexList(rel);
7151 foreach(l, indexList)
7153 Oid indexOid = lfirst_oid(l);
7156 * Note: currently, the index will not have its own dependency on the
7157 * namespace, so we don't need to do changeDependencyFor(). There's no
7158 * rowtype in pg_type, either.
7160 AlterRelationNamespaceInternal(classRel, indexOid,
7161 oldNspOid, newNspOid,
7165 list_free(indexList);
7169 * Move all SERIAL-column sequences of the specified relation to another
7172 * Note: we assume adequate permission checking was done by the caller,
7173 * and that the caller has a suitable lock on the owning relation.
7176 AlterSeqNamespaces(Relation classRel, Relation rel,
7177 Oid oldNspOid, Oid newNspOid, const char *newNspName)
7185 * SERIAL sequences are those having an auto dependency on one of the
7186 * table's columns (we don't care *which* column, exactly).
7188 depRel = heap_open(DependRelationId, AccessShareLock);
7190 ScanKeyInit(&key[0],
7191 Anum_pg_depend_refclassid,
7192 BTEqualStrategyNumber, F_OIDEQ,
7193 ObjectIdGetDatum(RelationRelationId));
7194 ScanKeyInit(&key[1],
7195 Anum_pg_depend_refobjid,
7196 BTEqualStrategyNumber, F_OIDEQ,
7197 ObjectIdGetDatum(RelationGetRelid(rel)));
7198 /* we leave refobjsubid unspecified */
7200 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
7201 SnapshotNow, 2, key);
7203 while (HeapTupleIsValid(tup = systable_getnext(scan)))
7205 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
7208 /* skip dependencies other than auto dependencies on columns */
7209 if (depForm->refobjsubid == 0 ||
7210 depForm->classid != RelationRelationId ||
7211 depForm->objsubid != 0 ||
7212 depForm->deptype != DEPENDENCY_AUTO)
7215 /* Use relation_open just in case it's an index */
7216 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
7218 /* skip non-sequence relations */
7219 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
7221 /* No need to keep the lock */
7222 relation_close(seqRel, AccessExclusiveLock);
7226 /* Fix the pg_class and pg_depend entries */
7227 AlterRelationNamespaceInternal(classRel, depForm->objid,
7228 oldNspOid, newNspOid,
7232 * Sequences have entries in pg_type. We need to be careful to move
7233 * them to the new namespace, too.
7235 AlterTypeNamespaceInternal(RelationGetForm(seqRel)->reltype,
7236 newNspOid, false, false);
7238 /* Now we can close it. Keep the lock till end of transaction. */
7239 relation_close(seqRel, NoLock);
7242 systable_endscan(scan);
7244 relation_close(depRel, AccessShareLock);
7249 * This code supports
7250 * CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
7252 * Because we only support this for TEMP tables, it's sufficient to remember
7253 * the state in a backend-local data structure.
7257 * Register a newly-created relation's ON COMMIT action.
7260 register_on_commit_action(Oid relid, OnCommitAction action)
7263 MemoryContext oldcxt;
7266 * We needn't bother registering the relation unless there is an ON COMMIT
7267 * action we need to take.
7269 if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
7272 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
7274 oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
7276 oc->oncommit = action;
7277 oc->creating_subid = GetCurrentSubTransactionId();
7278 oc->deleting_subid = InvalidSubTransactionId;
7280 on_commits = lcons(oc, on_commits);
7282 MemoryContextSwitchTo(oldcxt);
7286 * Unregister any ON COMMIT action when a relation is deleted.
7288 * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
7291 remove_on_commit_action(Oid relid)
7295 foreach(l, on_commits)
7297 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
7299 if (oc->relid == relid)
7301 oc->deleting_subid = GetCurrentSubTransactionId();
7308 * Perform ON COMMIT actions.
7310 * This is invoked just before actually committing, since it's possible
7311 * to encounter errors.
7314 PreCommit_on_commit_actions(void)
7317 List *oids_to_truncate = NIL;
7319 foreach(l, on_commits)
7321 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
7323 /* Ignore entry if already dropped in this xact */
7324 if (oc->deleting_subid != InvalidSubTransactionId)
7327 switch (oc->oncommit)
7330 case ONCOMMIT_PRESERVE_ROWS:
7331 /* Do nothing (there shouldn't be such entries, actually) */
7333 case ONCOMMIT_DELETE_ROWS:
7334 oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
7338 ObjectAddress object;
7340 object.classId = RelationRelationId;
7341 object.objectId = oc->relid;
7342 object.objectSubId = 0;
7343 performDeletion(&object, DROP_CASCADE);
7346 * Note that table deletion will call
7347 * remove_on_commit_action, so the entry should get marked
7350 Assert(oc->deleting_subid != InvalidSubTransactionId);
7355 if (oids_to_truncate != NIL)
7357 heap_truncate(oids_to_truncate);
7358 CommandCounterIncrement(); /* XXX needed? */
7363 * Post-commit or post-abort cleanup for ON COMMIT management.
7365 * All we do here is remove no-longer-needed OnCommitItem entries.
7367 * During commit, remove entries that were deleted during this transaction;
7368 * during abort, remove those created during this transaction.
7371 AtEOXact_on_commit_actions(bool isCommit)
7374 ListCell *prev_item;
7377 cur_item = list_head(on_commits);
7379 while (cur_item != NULL)
7381 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
7383 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
7384 oc->creating_subid != InvalidSubTransactionId)
7386 /* cur_item must be removed */
7387 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
7390 cur_item = lnext(prev_item);
7392 cur_item = list_head(on_commits);
7396 /* cur_item must be preserved */
7397 oc->creating_subid = InvalidSubTransactionId;
7398 oc->deleting_subid = InvalidSubTransactionId;
7399 prev_item = cur_item;
7400 cur_item = lnext(prev_item);
7406 * Post-subcommit or post-subabort cleanup for ON COMMIT management.
7408 * During subabort, we can immediately remove entries created during this
7409 * subtransaction. During subcommit, just relabel entries marked during
7410 * this subtransaction as being the parent's responsibility.
7413 AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
7414 SubTransactionId parentSubid)
7417 ListCell *prev_item;
7420 cur_item = list_head(on_commits);
7422 while (cur_item != NULL)
7424 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
7426 if (!isCommit && oc->creating_subid == mySubid)
7428 /* cur_item must be removed */
7429 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
7432 cur_item = lnext(prev_item);
7434 cur_item = list_head(on_commits);
7438 /* cur_item must be preserved */
7439 if (oc->creating_subid == mySubid)
7440 oc->creating_subid = parentSubid;
7441 if (oc->deleting_subid == mySubid)
7442 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
7443 prev_item = cur_item;
7444 cur_item = lnext(prev_item);