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.251 2008/04/24 20:17:50 tgl Exp $
13 *-------------------------------------------------------------------------
17 #include "access/genam.h"
18 #include "access/heapam.h"
19 #include "access/reloptions.h"
20 #include "access/xact.h"
21 #include "catalog/catalog.h"
22 #include "catalog/dependency.h"
23 #include "catalog/heap.h"
24 #include "catalog/index.h"
25 #include "catalog/indexing.h"
26 #include "catalog/namespace.h"
27 #include "catalog/pg_constraint.h"
28 #include "catalog/pg_depend.h"
29 #include "catalog/pg_inherits.h"
30 #include "catalog/pg_namespace.h"
31 #include "catalog/pg_opclass.h"
32 #include "catalog/pg_tablespace.h"
33 #include "catalog/pg_trigger.h"
34 #include "catalog/pg_type.h"
35 #include "catalog/pg_type_fn.h"
36 #include "catalog/toasting.h"
37 #include "commands/cluster.h"
38 #include "commands/defrem.h"
39 #include "commands/tablecmds.h"
40 #include "commands/tablespace.h"
41 #include "commands/trigger.h"
42 #include "commands/typecmds.h"
43 #include "executor/executor.h"
44 #include "miscadmin.h"
45 #include "nodes/makefuncs.h"
46 #include "nodes/parsenodes.h"
47 #include "optimizer/clauses.h"
48 #include "optimizer/plancat.h"
49 #include "optimizer/prep.h"
50 #include "parser/gramparse.h"
51 #include "parser/parse_clause.h"
52 #include "parser/parse_coerce.h"
53 #include "parser/parse_expr.h"
54 #include "parser/parse_oper.h"
55 #include "parser/parse_relation.h"
56 #include "parser/parse_type.h"
57 #include "parser/parse_utilcmd.h"
58 #include "parser/parser.h"
59 #include "rewrite/rewriteDefine.h"
60 #include "rewrite/rewriteHandler.h"
61 #include "storage/smgr.h"
62 #include "utils/acl.h"
63 #include "utils/builtins.h"
64 #include "utils/fmgroids.h"
65 #include "utils/inval.h"
66 #include "utils/lsyscache.h"
67 #include "utils/memutils.h"
68 #include "utils/relcache.h"
69 #include "utils/snapmgr.h"
70 #include "utils/syscache.h"
71 #include "utils/tqual.h"
75 * ON COMMIT action list
77 typedef struct OnCommitItem
79 Oid relid; /* relid of relation */
80 OnCommitAction oncommit; /* what to do at end of xact */
83 * If this entry was created during the current transaction,
84 * creating_subid is the ID of the creating subxact; if created in a prior
85 * transaction, creating_subid is zero. If deleted during the current
86 * transaction, deleting_subid is the ID of the deleting subxact; if no
87 * deletion request is pending, deleting_subid is zero.
89 SubTransactionId creating_subid;
90 SubTransactionId deleting_subid;
93 static List *on_commits = NIL;
97 * State information for ALTER TABLE
99 * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
100 * structs, one for each table modified by the operation (the named table
101 * plus any child tables that are affected). We save lists of subcommands
102 * to apply to this table (possibly modified by parse transformation steps);
103 * these lists will be executed in Phase 2. If a Phase 3 step is needed,
104 * necessary information is stored in the constraints and newvals lists.
106 * Phase 2 is divided into multiple passes; subcommands are executed in
107 * a pass determined by subcommand type.
110 #define AT_PASS_DROP 0 /* DROP (all flavors) */
111 #define AT_PASS_ALTER_TYPE 1 /* ALTER COLUMN TYPE */
112 #define AT_PASS_OLD_INDEX 2 /* re-add existing indexes */
113 #define AT_PASS_OLD_CONSTR 3 /* re-add existing constraints */
114 #define AT_PASS_COL_ATTRS 4 /* set other column attributes */
115 /* We could support a RENAME COLUMN pass here, but not currently used */
116 #define AT_PASS_ADD_COL 5 /* ADD COLUMN */
117 #define AT_PASS_ADD_INDEX 6 /* ADD indexes */
118 #define AT_PASS_ADD_CONSTR 7 /* ADD constraints, defaults */
119 #define AT_PASS_MISC 8 /* other stuff */
120 #define AT_NUM_PASSES 9
122 typedef struct AlteredTableInfo
124 /* Information saved before any work commences: */
125 Oid relid; /* Relation to work on */
126 char relkind; /* Its relkind */
127 TupleDesc oldDesc; /* Pre-modification tuple descriptor */
128 /* Information saved by Phase 1 for Phase 2: */
129 List *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
130 /* Information saved by Phases 1/2 for Phase 3: */
131 List *constraints; /* List of NewConstraint */
132 List *newvals; /* List of NewColumnValue */
133 bool new_notnull; /* T if we added new NOT NULL constraints */
134 Oid newTableSpace; /* new tablespace; 0 means no change */
135 /* Objects to rebuild after completing ALTER TYPE operations */
136 List *changedConstraintOids; /* OIDs of constraints to rebuild */
137 List *changedConstraintDefs; /* string definitions of same */
138 List *changedIndexOids; /* OIDs of indexes to rebuild */
139 List *changedIndexDefs; /* string definitions of same */
142 /* Struct describing one new constraint to check in Phase 3 scan */
143 /* Note: new NOT NULL constraints are handled elsewhere */
144 typedef struct NewConstraint
146 char *name; /* Constraint name, or NULL if none */
147 ConstrType contype; /* CHECK or FOREIGN */
148 Oid refrelid; /* PK rel, if FOREIGN */
149 Oid conid; /* OID of pg_constraint entry, if FOREIGN */
150 Node *qual; /* Check expr or FkConstraint struct */
151 List *qualstate; /* Execution state for CHECK */
155 * Struct describing one new column value that needs to be computed during
156 * Phase 3 copy (this could be either a new column with a non-null default, or
157 * a column that we're changing the type of). Columns without such an entry
158 * are just copied from the old table during ATRewriteTable. Note that the
159 * expr is an expression over *old* table values.
161 typedef struct NewColumnValue
163 AttrNumber attnum; /* which column */
164 Expr *expr; /* expression to compute */
165 ExprState *exprstate; /* execution state */
169 static void truncate_check_rel(Relation rel);
170 static List *MergeAttributes(List *schema, List *supers, bool istemp,
171 List **supOids, List **supconstr, int *supOidCount);
172 static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
173 static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel);
174 static void add_nonduplicate_constraint(Constraint *cdef,
175 ConstrCheck *check, int *ncheck);
176 static bool change_varattnos_walker(Node *node, const AttrNumber *newattno);
177 static void StoreCatalogInheritance(Oid relationId, List *supers);
178 static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
179 int16 seqNumber, Relation inhRelation);
180 static int findAttrByName(const char *attributeName, List *schema);
181 static void setRelhassubclassInRelation(Oid relationId, bool relhassubclass);
182 static void AlterIndexNamespaces(Relation classRel, Relation rel,
183 Oid oldNspOid, Oid newNspOid);
184 static void AlterSeqNamespaces(Relation classRel, Relation rel,
185 Oid oldNspOid, Oid newNspOid,
186 const char *newNspName);
187 static int transformColumnNameList(Oid relId, List *colList,
188 int16 *attnums, Oid *atttypids);
189 static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
191 int16 *attnums, Oid *atttypids,
193 static Oid transformFkeyCheckAttrs(Relation pkrel,
194 int numattrs, int16 *attnums,
196 static void validateForeignKeyConstraint(FkConstraint *fkconstraint,
197 Relation rel, Relation pkrel, Oid constraintOid);
198 static void createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
200 static void ATController(Relation rel, List *cmds, bool recurse);
201 static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
202 bool recurse, bool recursing);
203 static void ATRewriteCatalogs(List **wqueue);
204 static void ATExecCmd(AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd);
205 static void ATRewriteTables(List **wqueue);
206 static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap);
207 static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
208 static void ATSimplePermissions(Relation rel, bool allowView);
209 static void ATSimplePermissionsRelationOrIndex(Relation rel);
210 static void ATSimpleRecursion(List **wqueue, Relation rel,
211 AlterTableCmd *cmd, bool recurse);
212 static void ATOneLevelRecursion(List **wqueue, Relation rel,
214 static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
216 static void ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
218 static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
219 static void ATExecDropNotNull(Relation rel, const char *colName);
220 static void ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
221 const char *colName);
222 static void ATExecColumnDefault(Relation rel, const char *colName,
224 static void ATPrepSetStatistics(Relation rel, const char *colName,
226 static void ATExecSetStatistics(Relation rel, const char *colName,
228 static void ATExecSetStorage(Relation rel, const char *colName,
230 static void ATExecDropColumn(Relation rel, const char *colName,
231 DropBehavior behavior,
232 bool recurse, bool recursing);
233 static void ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
234 IndexStmt *stmt, bool is_rebuild);
235 static void ATExecAddConstraint(AlteredTableInfo *tab, Relation rel,
236 Node *newConstraint);
237 static void ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
238 FkConstraint *fkconstraint);
239 static void ATPrepDropConstraint(List **wqueue, Relation rel,
240 bool recurse, AlterTableCmd *cmd);
241 static void ATExecDropConstraint(Relation rel, const char *constrName,
242 DropBehavior behavior, bool quiet);
243 static void ATPrepAlterColumnType(List **wqueue,
244 AlteredTableInfo *tab, Relation rel,
245 bool recurse, bool recursing,
247 static void ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
248 const char *colName, TypeName *typename);
249 static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab);
250 static void ATPostAlterTypeParse(char *cmd, List **wqueue);
251 static void change_owner_recurse_to_sequences(Oid relationOid,
253 static void ATExecClusterOn(Relation rel, const char *indexName);
254 static void ATExecDropCluster(Relation rel);
255 static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
256 char *tablespacename);
257 static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace);
258 static void ATExecSetRelOptions(Relation rel, List *defList, bool isReset);
259 static void ATExecEnableDisableTrigger(Relation rel, char *trigname,
260 char fires_when, bool skip_system);
261 static void ATExecEnableDisableRule(Relation rel, char *rulename,
263 static void ATExecAddInherit(Relation rel, RangeVar *parent);
264 static void ATExecDropInherit(Relation rel, RangeVar *parent);
265 static void copy_relation_data(Relation rel, SMgrRelation dst);
268 /* ----------------------------------------------------------------
270 * Creates a new relation.
272 * If successful, returns the OID of the new relation.
273 * ----------------------------------------------------------------
276 DefineRelation(CreateStmt *stmt, char relkind)
278 char relname[NAMEDATALEN];
280 List *schema = stmt->tableElts;
284 TupleDesc descriptor;
286 List *old_constraints;
295 * Truncate relname to appropriate length (probably a waste of time, as
296 * parser should have done this already).
298 StrNCpy(relname, stmt->relation->relname, NAMEDATALEN);
301 * Check consistency of arguments
303 if (stmt->oncommit != ONCOMMIT_NOOP && !stmt->relation->istemp)
305 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
306 errmsg("ON COMMIT can only be used on temporary tables")));
309 * Look up the namespace in which we are supposed to create the relation.
310 * Check we have permission to create there. Skip check if bootstrapping,
311 * since permissions machinery may not be working yet.
313 namespaceId = RangeVarGetCreationNamespace(stmt->relation);
315 if (!IsBootstrapProcessingMode())
319 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
321 if (aclresult != ACLCHECK_OK)
322 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
323 get_namespace_name(namespaceId));
327 * Select tablespace to use. If not specified, use default tablespace
328 * (which may in turn default to database's default).
330 if (stmt->tablespacename)
332 tablespaceId = get_tablespace_oid(stmt->tablespacename);
333 if (!OidIsValid(tablespaceId))
335 (errcode(ERRCODE_UNDEFINED_OBJECT),
336 errmsg("tablespace \"%s\" does not exist",
337 stmt->tablespacename)));
341 tablespaceId = GetDefaultTablespace(stmt->relation->istemp);
342 /* note InvalidOid is OK in this case */
345 /* Check permissions except when using database's default */
346 if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
350 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
352 if (aclresult != ACLCHECK_OK)
353 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
354 get_tablespace_name(tablespaceId));
358 * Parse and validate reloptions, if any.
360 reloptions = transformRelOptions((Datum) 0, stmt->options, true, false);
362 (void) heap_reloptions(relkind, reloptions, true);
365 * Look up inheritance ancestors and generate relation schema, including
366 * inherited attributes.
368 schema = MergeAttributes(schema, stmt->inhRelations,
369 stmt->relation->istemp,
370 &inheritOids, &old_constraints, &parentOidCount);
373 * Create a relation descriptor from the relation schema and create the
374 * relation. Note that in this stage only inherited (pre-cooked) defaults
375 * and constraints will be included into the new relation.
376 * (BuildDescForRelation takes care of the inherited defaults, but we have
377 * to copy inherited constraints here.)
379 descriptor = BuildDescForRelation(schema);
381 localHasOids = interpretOidsOption(stmt->options);
382 descriptor->tdhasoid = (localHasOids || parentOidCount > 0);
384 if (old_constraints || stmt->constraints)
389 /* make array that's certainly big enough */
390 check = (ConstrCheck *)
391 palloc((list_length(old_constraints) +
392 list_length(stmt->constraints)) * sizeof(ConstrCheck));
393 /* deal with constraints from MergeAttributes */
394 foreach(listptr, old_constraints)
396 Constraint *cdef = (Constraint *) lfirst(listptr);
398 if (cdef->contype == CONSTR_CHECK)
399 add_nonduplicate_constraint(cdef, check, &ncheck);
403 * parse_utilcmd.c might have passed some precooked constraints too,
404 * due to LIKE tab INCLUDING CONSTRAINTS
406 foreach(listptr, stmt->constraints)
408 Constraint *cdef = (Constraint *) lfirst(listptr);
410 if (cdef->contype == CONSTR_CHECK && cdef->cooked_expr != NULL)
411 add_nonduplicate_constraint(cdef, check, &ncheck);
413 /* if we found any, insert 'em into the descriptor */
416 if (descriptor->constr == NULL)
418 descriptor->constr = (TupleConstr *) palloc(sizeof(TupleConstr));
419 descriptor->constr->defval = NULL;
420 descriptor->constr->num_defval = 0;
421 descriptor->constr->has_not_null = false;
423 descriptor->constr->num_check = ncheck;
424 descriptor->constr->check = check;
428 relationId = heap_create_with_catalog(relname,
440 allowSystemTableMods);
442 StoreCatalogInheritance(relationId, inheritOids);
445 * We must bump the command counter to make the newly-created relation
446 * tuple visible for opening.
448 CommandCounterIncrement();
451 * Open the new relation and acquire exclusive lock on it. This isn't
452 * really necessary for locking out other backends (since they can't see
453 * the new rel anyway until we commit), but it keeps the lock manager from
454 * complaining about deadlock risks.
456 rel = relation_open(relationId, AccessExclusiveLock);
459 * Now add any newly specified column default values and CHECK constraints
460 * to the new relation. These are passed to us in the form of raw
461 * parsetrees; we need to transform them to executable expression trees
462 * before they can be added. The most convenient way to do that is to
463 * apply the parser's transformExpr routine, but transformExpr doesn't
464 * work unless we have a pre-existing relation. So, the transformation has
465 * to be postponed to this final step of CREATE TABLE.
467 * First, scan schema to find new column defaults.
472 foreach(listptr, schema)
474 ColumnDef *colDef = lfirst(listptr);
478 if (colDef->raw_default != NULL)
480 RawColumnDefault *rawEnt;
482 Assert(colDef->cooked_default == NULL);
484 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
485 rawEnt->attnum = attnum;
486 rawEnt->raw_default = colDef->raw_default;
487 rawDefaults = lappend(rawDefaults, rawEnt);
492 * Parse and add the defaults/constraints, if any.
494 if (rawDefaults || stmt->constraints)
495 AddRelationRawConstraints(rel, rawDefaults, stmt->constraints);
498 * Clean up. We keep lock on new relation (although it shouldn't be
499 * visible to anyone else anyway, until commit).
501 relation_close(rel, NoLock);
508 * Deletes a relation.
511 RemoveRelation(const RangeVar *relation, DropBehavior behavior)
514 ObjectAddress object;
516 relOid = RangeVarGetRelid(relation, false);
518 object.classId = RelationRelationId;
519 object.objectId = relOid;
520 object.objectSubId = 0;
522 performDeletion(&object, behavior);
527 * Executes a TRUNCATE command.
529 * This is a multi-relation truncate. We first open and grab exclusive
530 * lock on all relations involved, checking permissions and otherwise
531 * verifying that the relation is OK for truncation. In CASCADE mode,
532 * relations having FK references to the targeted relations are automatically
533 * added to the group; in RESTRICT mode, we check that all FK references are
534 * internal to the group that's being truncated. Finally all the relations
535 * are truncated and reindexed.
538 ExecuteTruncate(TruncateStmt *stmt)
543 ResultRelInfo *resultRelInfos;
544 ResultRelInfo *resultRelInfo;
548 * Open, exclusive-lock, and check all the explicitly-specified relations
550 foreach(cell, stmt->relations)
552 RangeVar *rv = lfirst(cell);
555 rel = heap_openrv(rv, AccessExclusiveLock);
556 truncate_check_rel(rel);
557 rels = lappend(rels, rel);
558 relids = lappend_oid(relids, RelationGetRelid(rel));
562 * In CASCADE mode, suck in all referencing relations as well. This
563 * requires multiple iterations to find indirectly-dependent relations. At
564 * each phase, we need to exclusive-lock new rels before looking for their
565 * dependencies, else we might miss something. Also, we check each rel as
566 * soon as we open it, to avoid a faux pas such as holding lock for a long
567 * time on a rel we have no permissions for.
569 if (stmt->behavior == DROP_CASCADE)
575 newrelids = heap_truncate_find_FKs(relids);
576 if (newrelids == NIL)
577 break; /* nothing else to add */
579 foreach(cell, newrelids)
581 Oid relid = lfirst_oid(cell);
584 rel = heap_open(relid, AccessExclusiveLock);
586 (errmsg("truncate cascades to table \"%s\"",
587 RelationGetRelationName(rel))));
588 truncate_check_rel(rel);
589 rels = lappend(rels, rel);
590 relids = lappend_oid(relids, relid);
596 * Check foreign key references. In CASCADE mode, this should be
597 * unnecessary since we just pulled in all the references; but as a
598 * cross-check, do it anyway if in an Assert-enabled build.
600 #ifdef USE_ASSERT_CHECKING
601 heap_truncate_check_FKs(rels, false);
603 if (stmt->behavior == DROP_RESTRICT)
604 heap_truncate_check_FKs(rels, false);
607 /* Prepare to catch AFTER triggers. */
608 AfterTriggerBeginQuery();
611 * To fire triggers, we'll need an EState as well as a ResultRelInfo
614 estate = CreateExecutorState();
615 resultRelInfos = (ResultRelInfo *)
616 palloc(list_length(rels) * sizeof(ResultRelInfo));
617 resultRelInfo = resultRelInfos;
620 Relation rel = (Relation) lfirst(cell);
622 InitResultRelInfo(resultRelInfo,
624 0, /* dummy rangetable index */
625 CMD_DELETE, /* don't need any index info */
629 estate->es_result_relations = resultRelInfos;
630 estate->es_num_result_relations = list_length(rels);
633 * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
634 * truncating (this is because one of them might throw an error).
635 * Also, if we were to allow them to prevent statement execution,
636 * that would need to be handled here.
638 resultRelInfo = resultRelInfos;
641 estate->es_result_relation_info = resultRelInfo;
642 ExecBSTruncateTriggers(estate, resultRelInfo);
647 * OK, truncate each table.
651 Relation rel = (Relation) lfirst(cell);
656 * Create a new empty storage file for the relation, and assign it as
657 * the relfilenode value. The old storage file is scheduled for
658 * deletion at commit.
660 setNewRelfilenode(rel, RecentXmin);
662 heap_relid = RelationGetRelid(rel);
663 toast_relid = rel->rd_rel->reltoastrelid;
666 * The same for the toast table, if any.
668 if (OidIsValid(toast_relid))
670 rel = relation_open(toast_relid, AccessExclusiveLock);
671 setNewRelfilenode(rel, RecentXmin);
672 heap_close(rel, NoLock);
676 * Reconstruct the indexes to match, and we're done.
678 reindex_relation(heap_relid, true);
682 * Process all AFTER STATEMENT TRUNCATE triggers.
684 resultRelInfo = resultRelInfos;
687 estate->es_result_relation_info = resultRelInfo;
688 ExecASTruncateTriggers(estate, resultRelInfo);
692 /* Handle queued AFTER triggers */
693 AfterTriggerEndQuery(estate);
695 /* We can clean up the EState now */
696 FreeExecutorState(estate);
698 /* And close the rels (can't do this while EState still holds refs) */
701 Relation rel = (Relation) lfirst(cell);
703 heap_close(rel, NoLock);
708 * Check that a given rel is safe to truncate. Subroutine for ExecuteTruncate
711 truncate_check_rel(Relation rel)
713 /* Only allow truncate on regular tables */
714 if (rel->rd_rel->relkind != RELKIND_RELATION)
716 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
717 errmsg("\"%s\" is not a table",
718 RelationGetRelationName(rel))));
720 /* Permissions checks */
721 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
722 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
723 RelationGetRelationName(rel));
725 if (!allowSystemTableMods && IsSystemRelation(rel))
727 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
728 errmsg("permission denied: \"%s\" is a system catalog",
729 RelationGetRelationName(rel))));
732 * We can never allow truncation of shared or nailed-in-cache relations,
733 * because we can't support changing their relfilenode values.
735 if (rel->rd_rel->relisshared || rel->rd_isnailed)
737 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
738 errmsg("cannot truncate system relation \"%s\"",
739 RelationGetRelationName(rel))));
742 * Don't allow truncate on temp tables of other backends ... their local
743 * buffer manager is not going to cope.
745 if (isOtherTempNamespace(RelationGetNamespace(rel)))
747 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
748 errmsg("cannot truncate temporary tables of other sessions")));
751 * Also check for active uses of the relation in the current transaction,
752 * including open scans and pending AFTER trigger events.
754 CheckTableNotInUse(rel, "TRUNCATE");
759 * Returns new schema given initial schema and superclasses.
762 * 'schema' is the column/attribute definition for the table. (It's a list
763 * of ColumnDef's.) It is destructively changed.
764 * 'supers' is a list of names (as RangeVar nodes) of parent relations.
765 * 'istemp' is TRUE if we are creating a temp relation.
768 * 'supOids' receives a list of the OIDs of the parent relations.
769 * 'supconstr' receives a list of constraints belonging to the parents,
770 * updated as necessary to be valid for the child.
771 * 'supOidCount' is set to the number of parents that have OID columns.
774 * Completed schema list.
777 * The order in which the attributes are inherited is very important.
778 * Intuitively, the inherited attributes should come first. If a table
779 * inherits from multiple parents, the order of those attributes are
780 * according to the order of the parents specified in CREATE TABLE.
784 * create table person (name text, age int4, location point);
785 * create table emp (salary int4, manager text) inherits(person);
786 * create table student (gpa float8) inherits (person);
787 * create table stud_emp (percent int4) inherits (emp, student);
789 * The order of the attributes of stud_emp is:
791 * person {1:name, 2:age, 3:location}
793 * {6:gpa} student emp {4:salary, 5:manager}
795 * stud_emp {7:percent}
797 * If the same attribute name appears multiple times, then it appears
798 * in the result table in the proper location for its first appearance.
800 * Constraints (including NOT NULL constraints) for the child table
801 * are the union of all relevant constraints, from both the child schema
804 * The default value for a child column is defined as:
805 * (1) If the child schema specifies a default, that value is used.
806 * (2) If neither the child nor any parent specifies a default, then
807 * the column will not have a default.
808 * (3) If conflicting defaults are inherited from different parents
809 * (and not overridden by the child), an error is raised.
810 * (4) Otherwise the inherited default is used.
811 * Rule (3) is new in Postgres 7.1; in earlier releases you got a
812 * rather arbitrary choice of which parent default to use.
816 MergeAttributes(List *schema, List *supers, bool istemp,
817 List **supOids, List **supconstr, int *supOidCount)
820 List *inhSchema = NIL;
821 List *parentOids = NIL;
822 List *constraints = NIL;
823 int parentsWithOids = 0;
824 bool have_bogus_defaults = false;
825 char *bogus_marker = "Bogus!"; /* marks conflicting defaults */
829 * Check for and reject tables with too many columns. We perform this
830 * check relatively early for two reasons: (a) we don't run the risk of
831 * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
832 * okay if we're processing <= 1600 columns, but could take minutes to
833 * execute if the user attempts to create a table with hundreds of
834 * thousands of columns.
836 * Note that we also need to check that any we do not exceed this figure
837 * after including columns from inherited relations.
839 if (list_length(schema) > MaxHeapAttributeNumber)
841 (errcode(ERRCODE_TOO_MANY_COLUMNS),
842 errmsg("tables can have at most %d columns",
843 MaxHeapAttributeNumber)));
846 * Check for duplicate names in the explicit list of attributes.
848 * Although we might consider merging such entries in the same way that we
849 * handle name conflicts for inherited attributes, it seems to make more
850 * sense to assume such conflicts are errors.
852 foreach(entry, schema)
854 ColumnDef *coldef = lfirst(entry);
857 for_each_cell(rest, lnext(entry))
859 ColumnDef *restdef = lfirst(rest);
861 if (strcmp(coldef->colname, restdef->colname) == 0)
863 (errcode(ERRCODE_DUPLICATE_COLUMN),
864 errmsg("column \"%s\" specified more than once",
870 * Scan the parents left-to-right, and merge their attributes to form a
871 * list of inherited attributes (inhSchema). Also check to see if we need
872 * to inherit an OID column.
875 foreach(entry, supers)
877 RangeVar *parent = (RangeVar *) lfirst(entry);
881 AttrNumber *newattno;
882 AttrNumber parent_attno;
884 relation = heap_openrv(parent, AccessShareLock);
886 if (relation->rd_rel->relkind != RELKIND_RELATION)
888 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
889 errmsg("inherited relation \"%s\" is not a table",
891 /* Permanent rels cannot inherit from temporary ones */
892 if (!istemp && isTempNamespace(RelationGetNamespace(relation)))
894 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
895 errmsg("cannot inherit from temporary relation \"%s\"",
899 * We should have an UNDER permission flag for this, but for now,
900 * demand that creator of a child table own the parent.
902 if (!pg_class_ownercheck(RelationGetRelid(relation), GetUserId()))
903 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
904 RelationGetRelationName(relation));
907 * Reject duplications in the list of parents.
909 if (list_member_oid(parentOids, RelationGetRelid(relation)))
911 (errcode(ERRCODE_DUPLICATE_TABLE),
912 errmsg("relation \"%s\" would be inherited from more than once",
915 parentOids = lappend_oid(parentOids, RelationGetRelid(relation));
917 if (relation->rd_rel->relhasoids)
920 tupleDesc = RelationGetDescr(relation);
921 constr = tupleDesc->constr;
924 * newattno[] will contain the child-table attribute numbers for the
925 * attributes of this parent table. (They are not the same for
926 * parents after the first one, nor if we have dropped columns.)
928 newattno = (AttrNumber *)
929 palloc(tupleDesc->natts * sizeof(AttrNumber));
931 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
934 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
935 char *attributeName = NameStr(attribute->attname);
940 * Ignore dropped columns in the parent.
942 if (attribute->attisdropped)
945 * change_varattnos_of_a_node asserts that this is greater
946 * than zero, so if anything tries to use it, we should find
949 newattno[parent_attno - 1] = 0;
954 * Does it conflict with some previously inherited column?
956 exist_attno = findAttrByName(attributeName, inhSchema);
963 * Yes, try to merge the two column definitions. They must
964 * have the same type and typmod.
967 (errmsg("merging multiple inherited definitions of column \"%s\"",
969 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
970 defTypeId = typenameTypeId(NULL, def->typename, &deftypmod);
971 if (defTypeId != attribute->atttypid ||
972 deftypmod != attribute->atttypmod)
974 (errcode(ERRCODE_DATATYPE_MISMATCH),
975 errmsg("inherited column \"%s\" has a type conflict",
977 errdetail("%s versus %s",
978 TypeNameToString(def->typename),
979 format_type_be(attribute->atttypid))));
981 /* Merge of NOT NULL constraints = OR 'em together */
982 def->is_not_null |= attribute->attnotnull;
983 /* Default and other constraints are handled below */
984 newattno[parent_attno - 1] = exist_attno;
989 * No, create a new inherited column
991 def = makeNode(ColumnDef);
992 def->colname = pstrdup(attributeName);
993 def->typename = makeTypeNameFromOid(attribute->atttypid,
994 attribute->atttypmod);
996 def->is_local = false;
997 def->is_not_null = attribute->attnotnull;
998 def->raw_default = NULL;
999 def->cooked_default = NULL;
1000 def->constraints = NIL;
1001 inhSchema = lappend(inhSchema, def);
1002 newattno[parent_attno - 1] = ++child_attno;
1006 * Copy default if any
1008 if (attribute->atthasdef)
1010 char *this_default = NULL;
1011 AttrDefault *attrdef;
1014 /* Find default in constraint structure */
1015 Assert(constr != NULL);
1016 attrdef = constr->defval;
1017 for (i = 0; i < constr->num_defval; i++)
1019 if (attrdef[i].adnum == parent_attno)
1021 this_default = attrdef[i].adbin;
1025 Assert(this_default != NULL);
1028 * If default expr could contain any vars, we'd need to fix
1029 * 'em, but it can't; so default is ready to apply to child.
1031 * If we already had a default from some prior parent, check
1032 * to see if they are the same. If so, no problem; if not,
1033 * mark the column as having a bogus default. Below, we will
1034 * complain if the bogus default isn't overridden by the child
1037 Assert(def->raw_default == NULL);
1038 if (def->cooked_default == NULL)
1039 def->cooked_default = pstrdup(this_default);
1040 else if (strcmp(def->cooked_default, this_default) != 0)
1042 def->cooked_default = bogus_marker;
1043 have_bogus_defaults = true;
1049 * Now copy the constraints of this parent, adjusting attnos using the
1050 * completed newattno[] map
1052 if (constr && constr->num_check > 0)
1054 ConstrCheck *check = constr->check;
1057 for (i = 0; i < constr->num_check; i++)
1059 Constraint *cdef = makeNode(Constraint);
1062 cdef->contype = CONSTR_CHECK;
1063 cdef->name = pstrdup(check[i].ccname);
1064 cdef->raw_expr = NULL;
1065 /* adjust varattnos of ccbin here */
1066 expr = stringToNode(check[i].ccbin);
1067 change_varattnos_of_a_node(expr, newattno);
1068 cdef->cooked_expr = nodeToString(expr);
1069 constraints = lappend(constraints, cdef);
1076 * Close the parent rel, but keep our AccessShareLock on it until xact
1077 * commit. That will prevent someone else from deleting or ALTERing
1078 * the parent before the child is committed.
1080 heap_close(relation, NoLock);
1084 * If we had no inherited attributes, the result schema is just the
1085 * explicitly declared columns. Otherwise, we need to merge the declared
1086 * columns into the inherited schema list.
1088 if (inhSchema != NIL)
1090 foreach(entry, schema)
1092 ColumnDef *newdef = lfirst(entry);
1093 char *attributeName = newdef->colname;
1097 * Does it conflict with some previously inherited column?
1099 exist_attno = findAttrByName(attributeName, inhSchema);
1100 if (exist_attno > 0)
1109 * Yes, try to merge the two column definitions. They must
1110 * have the same type and typmod.
1113 (errmsg("merging column \"%s\" with inherited definition",
1115 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1116 defTypeId = typenameTypeId(NULL, def->typename, &deftypmod);
1117 newTypeId = typenameTypeId(NULL, newdef->typename, &newtypmod);
1118 if (defTypeId != newTypeId || deftypmod != newtypmod)
1120 (errcode(ERRCODE_DATATYPE_MISMATCH),
1121 errmsg("column \"%s\" has a type conflict",
1123 errdetail("%s versus %s",
1124 TypeNameToString(def->typename),
1125 TypeNameToString(newdef->typename))));
1126 /* Mark the column as locally defined */
1127 def->is_local = true;
1128 /* Merge of NOT NULL constraints = OR 'em together */
1129 def->is_not_null |= newdef->is_not_null;
1130 /* If new def has a default, override previous default */
1131 if (newdef->raw_default != NULL)
1133 def->raw_default = newdef->raw_default;
1134 def->cooked_default = newdef->cooked_default;
1140 * No, attach new column to result schema
1142 inhSchema = lappend(inhSchema, newdef);
1149 * Check that we haven't exceeded the legal # of columns after merging
1150 * in inherited columns.
1152 if (list_length(schema) > MaxHeapAttributeNumber)
1154 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1155 errmsg("tables can have at most %d columns",
1156 MaxHeapAttributeNumber)));
1160 * If we found any conflicting parent default values, check to make sure
1161 * they were overridden by the child.
1163 if (have_bogus_defaults)
1165 foreach(entry, schema)
1167 ColumnDef *def = lfirst(entry);
1169 if (def->cooked_default == bogus_marker)
1171 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
1172 errmsg("column \"%s\" inherits conflicting default values",
1174 errhint("To resolve the conflict, specify a default explicitly.")));
1178 *supOids = parentOids;
1179 *supconstr = constraints;
1180 *supOidCount = parentsWithOids;
1186 * In multiple-inheritance situations, it's possible to inherit
1187 * the same grandparent constraint through multiple parents.
1188 * Hence, we want to discard inherited constraints that match as to
1189 * both name and expression. Otherwise, gripe if there are conflicting
1190 * names. Nonconflicting constraints are added to the array check[]
1191 * of length *ncheck ... caller must ensure there is room!
1194 add_nonduplicate_constraint(Constraint *cdef, ConstrCheck *check, int *ncheck)
1198 /* Should only see precooked constraints here */
1199 Assert(cdef->contype == CONSTR_CHECK);
1200 Assert(cdef->name != NULL);
1201 Assert(cdef->raw_expr == NULL && cdef->cooked_expr != NULL);
1203 for (i = 0; i < *ncheck; i++)
1205 if (strcmp(check[i].ccname, cdef->name) != 0)
1207 if (strcmp(check[i].ccbin, cdef->cooked_expr) == 0)
1208 return; /* duplicate constraint, so ignore it */
1210 (errcode(ERRCODE_DUPLICATE_OBJECT),
1211 errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
1214 /* No match on name, so add it to array */
1215 check[*ncheck].ccname = cdef->name;
1216 check[*ncheck].ccbin = pstrdup(cdef->cooked_expr);
1222 * Replace varattno values in an expression tree according to the given
1223 * map array, that is, varattno N is replaced by newattno[N-1]. It is
1224 * caller's responsibility to ensure that the array is long enough to
1225 * define values for all user varattnos present in the tree. System column
1226 * attnos remain unchanged.
1228 * Note that the passed node tree is modified in-place!
1231 change_varattnos_of_a_node(Node *node, const AttrNumber *newattno)
1233 /* no setup needed, so away we go */
1234 (void) change_varattnos_walker(node, newattno);
1238 change_varattnos_walker(Node *node, const AttrNumber *newattno)
1244 Var *var = (Var *) node;
1246 if (var->varlevelsup == 0 && var->varno == 1 &&
1250 * ??? the following may be a problem when the node is multiply
1251 * referenced though stringToNode() doesn't create such a node
1254 Assert(newattno[var->varattno - 1] > 0);
1255 var->varattno = newattno[var->varattno - 1];
1259 return expression_tree_walker(node, change_varattnos_walker,
1264 * Generate a map for change_varattnos_of_a_node from old and new TupleDesc's,
1265 * matching according to column name.
1268 varattnos_map(TupleDesc old, TupleDesc new)
1274 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * old->natts);
1275 for (i = 1; i <= old->natts; i++)
1277 if (old->attrs[i - 1]->attisdropped)
1278 continue; /* leave the entry as zero */
1280 for (j = 1; j <= new->natts; j++)
1282 if (strcmp(NameStr(old->attrs[i - 1]->attname),
1283 NameStr(new->attrs[j - 1]->attname)) == 0)
1294 * Generate a map for change_varattnos_of_a_node from a TupleDesc and a list
1298 varattnos_map_schema(TupleDesc old, List *schema)
1303 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * old->natts);
1304 for (i = 1; i <= old->natts; i++)
1306 if (old->attrs[i - 1]->attisdropped)
1307 continue; /* leave the entry as zero */
1309 attmap[i - 1] = findAttrByName(NameStr(old->attrs[i - 1]->attname),
1317 * StoreCatalogInheritance
1318 * Updates the system catalogs with proper inheritance information.
1320 * supers is a list of the OIDs of the new relation's direct ancestors.
1323 StoreCatalogInheritance(Oid relationId, List *supers)
1332 AssertArg(OidIsValid(relationId));
1338 * Store INHERITS information in pg_inherits using direct ancestors only.
1339 * Also enter dependencies on the direct ancestors, and make sure they are
1340 * marked with relhassubclass = true.
1342 * (Once upon a time, both direct and indirect ancestors were found here
1343 * and then entered into pg_ipl. Since that catalog doesn't exist
1344 * anymore, there's no need to look for indirect ancestors.)
1346 relation = heap_open(InheritsRelationId, RowExclusiveLock);
1349 foreach(entry, supers)
1351 Oid parentOid = lfirst_oid(entry);
1353 StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation);
1357 heap_close(relation, RowExclusiveLock);
1361 * Make catalog entries showing relationId as being an inheritance child
1362 * of parentOid. inhRelation is the already-opened pg_inherits catalog.
1365 StoreCatalogInheritance1(Oid relationId, Oid parentOid,
1366 int16 seqNumber, Relation inhRelation)
1368 TupleDesc desc = RelationGetDescr(inhRelation);
1369 Datum datum[Natts_pg_inherits];
1370 char nullarr[Natts_pg_inherits];
1371 ObjectAddress childobject,
1376 * Make the pg_inherits entry
1378 datum[0] = ObjectIdGetDatum(relationId); /* inhrelid */
1379 datum[1] = ObjectIdGetDatum(parentOid); /* inhparent */
1380 datum[2] = Int16GetDatum(seqNumber); /* inhseqno */
1386 tuple = heap_formtuple(desc, datum, nullarr);
1388 simple_heap_insert(inhRelation, tuple);
1390 CatalogUpdateIndexes(inhRelation, tuple);
1392 heap_freetuple(tuple);
1395 * Store a dependency too
1397 parentobject.classId = RelationRelationId;
1398 parentobject.objectId = parentOid;
1399 parentobject.objectSubId = 0;
1400 childobject.classId = RelationRelationId;
1401 childobject.objectId = relationId;
1402 childobject.objectSubId = 0;
1404 recordDependencyOn(&childobject, &parentobject, DEPENDENCY_NORMAL);
1407 * Mark the parent as having subclasses.
1409 setRelhassubclassInRelation(parentOid, true);
1413 * Look for an existing schema entry with the given name.
1415 * Returns the index (starting with 1) if attribute already exists in schema,
1419 findAttrByName(const char *attributeName, List *schema)
1426 ColumnDef *def = lfirst(s);
1428 if (strcmp(attributeName, def->colname) == 0)
1437 * Update a relation's pg_class.relhassubclass entry to the given value
1440 setRelhassubclassInRelation(Oid relationId, bool relhassubclass)
1442 Relation relationRelation;
1444 Form_pg_class classtuple;
1447 * Fetch a modifiable copy of the tuple, modify it, update pg_class.
1449 * If the tuple already has the right relhassubclass setting, we don't
1450 * need to update it, but we still need to issue an SI inval message.
1452 relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
1453 tuple = SearchSysCacheCopy(RELOID,
1454 ObjectIdGetDatum(relationId),
1456 if (!HeapTupleIsValid(tuple))
1457 elog(ERROR, "cache lookup failed for relation %u", relationId);
1458 classtuple = (Form_pg_class) GETSTRUCT(tuple);
1460 if (classtuple->relhassubclass != relhassubclass)
1462 classtuple->relhassubclass = relhassubclass;
1463 simple_heap_update(relationRelation, &tuple->t_self, tuple);
1465 /* keep the catalog indexes up to date */
1466 CatalogUpdateIndexes(relationRelation, tuple);
1470 /* no need to change tuple, but force relcache rebuild anyway */
1471 CacheInvalidateRelcacheByTuple(tuple);
1474 heap_freetuple(tuple);
1475 heap_close(relationRelation, RowExclusiveLock);
1480 * renameatt - changes the name of a attribute in a relation
1482 * Attname attribute is changed in attribute catalog.
1483 * No record of the previous attname is kept (correct?).
1485 * get proper relrelation from relation catalog (if not arg)
1486 * scan attribute catalog
1487 * for name conflict (within rel)
1488 * for original attribute (if not arg)
1489 * modify attname in attribute tuple
1490 * insert modified attribute in attribute catalog
1491 * delete original attribute from attribute catalog
1494 renameatt(Oid myrelid,
1495 const char *oldattname,
1496 const char *newattname,
1500 Relation targetrelation;
1501 Relation attrelation;
1503 Form_pg_attribute attform;
1506 ListCell *indexoidscan;
1509 * Grab an exclusive lock on the target table, which we will NOT release
1510 * until end of transaction.
1512 targetrelation = relation_open(myrelid, AccessExclusiveLock);
1515 * permissions checking. this would normally be done in utility.c, but
1516 * this particular routine is recursive.
1518 * normally, only the owner of a class can change its schema.
1520 if (!pg_class_ownercheck(myrelid, GetUserId()))
1521 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1522 RelationGetRelationName(targetrelation));
1523 if (!allowSystemTableMods && IsSystemRelation(targetrelation))
1525 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1526 errmsg("permission denied: \"%s\" is a system catalog",
1527 RelationGetRelationName(targetrelation))));
1530 * if the 'recurse' flag is set then we are supposed to rename this
1531 * attribute in all classes that inherit from 'relname' (as well as in
1534 * any permissions or problems with duplicate attributes will cause the
1535 * whole transaction to abort, which is what we want -- all or nothing.
1542 /* this routine is actually in the planner */
1543 children = find_all_inheritors(myrelid);
1546 * find_all_inheritors does the recursive search of the inheritance
1547 * hierarchy, so all we have to do is process all of the relids in the
1548 * list that it returns.
1550 foreach(child, children)
1552 Oid childrelid = lfirst_oid(child);
1554 if (childrelid == myrelid)
1556 /* note we need not recurse again */
1557 renameatt(childrelid, oldattname, newattname, false, true);
1563 * If we are told not to recurse, there had better not be any child
1564 * tables; else the rename would put them out of step.
1567 find_inheritance_children(myrelid) != NIL)
1569 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1570 errmsg("inherited column \"%s\" must be renamed in child tables too",
1574 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
1576 atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
1577 if (!HeapTupleIsValid(atttup))
1579 (errcode(ERRCODE_UNDEFINED_COLUMN),
1580 errmsg("column \"%s\" does not exist",
1582 attform = (Form_pg_attribute) GETSTRUCT(atttup);
1584 attnum = attform->attnum;
1587 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1588 errmsg("cannot rename system column \"%s\"",
1592 * if the attribute is inherited, forbid the renaming, unless we are
1593 * already inside a recursive rename.
1595 if (attform->attinhcount > 0 && !recursing)
1597 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1598 errmsg("cannot rename inherited column \"%s\"",
1601 /* should not already exist */
1602 /* this test is deliberately not attisdropped-aware */
1603 if (SearchSysCacheExists(ATTNAME,
1604 ObjectIdGetDatum(myrelid),
1605 PointerGetDatum(newattname),
1608 (errcode(ERRCODE_DUPLICATE_COLUMN),
1609 errmsg("column \"%s\" of relation \"%s\" already exists",
1610 newattname, RelationGetRelationName(targetrelation))));
1612 namestrcpy(&(attform->attname), newattname);
1614 simple_heap_update(attrelation, &atttup->t_self, atttup);
1616 /* keep system catalog indexes current */
1617 CatalogUpdateIndexes(attrelation, atttup);
1619 heap_freetuple(atttup);
1622 * Update column names of indexes that refer to the column being renamed.
1624 indexoidlist = RelationGetIndexList(targetrelation);
1626 foreach(indexoidscan, indexoidlist)
1628 Oid indexoid = lfirst_oid(indexoidscan);
1630 Form_pg_index indexform;
1634 * Scan through index columns to see if there's any simple index
1635 * entries for this attribute. We ignore expressional entries.
1637 indextup = SearchSysCache(INDEXRELID,
1638 ObjectIdGetDatum(indexoid),
1640 if (!HeapTupleIsValid(indextup))
1641 elog(ERROR, "cache lookup failed for index %u", indexoid);
1642 indexform = (Form_pg_index) GETSTRUCT(indextup);
1644 for (i = 0; i < indexform->indnatts; i++)
1646 if (attnum != indexform->indkey.values[i])
1650 * Found one, rename it.
1652 atttup = SearchSysCacheCopy(ATTNUM,
1653 ObjectIdGetDatum(indexoid),
1654 Int16GetDatum(i + 1),
1656 if (!HeapTupleIsValid(atttup))
1657 continue; /* should we raise an error? */
1660 * Update the (copied) attribute tuple.
1662 namestrcpy(&(((Form_pg_attribute) GETSTRUCT(atttup))->attname),
1665 simple_heap_update(attrelation, &atttup->t_self, atttup);
1667 /* keep system catalog indexes current */
1668 CatalogUpdateIndexes(attrelation, atttup);
1670 heap_freetuple(atttup);
1673 ReleaseSysCache(indextup);
1676 list_free(indexoidlist);
1678 heap_close(attrelation, RowExclusiveLock);
1680 relation_close(targetrelation, NoLock); /* close rel but keep lock */
1685 * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW RENAME
1687 * Caller has already done permissions checks.
1690 RenameRelation(Oid myrelid, const char *newrelname, ObjectType reltype)
1692 Relation targetrelation;
1697 * Grab an exclusive lock on the target table, index, sequence or view,
1698 * which we will NOT release until end of transaction.
1700 targetrelation = relation_open(myrelid, AccessExclusiveLock);
1702 namespaceId = RelationGetNamespace(targetrelation);
1703 relkind = targetrelation->rd_rel->relkind;
1706 * For compatibility with prior releases, we don't complain if ALTER TABLE
1707 * or ALTER INDEX is used to rename a sequence or view.
1709 if (reltype == OBJECT_SEQUENCE && relkind != RELKIND_SEQUENCE)
1711 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1712 errmsg("\"%s\" is not a sequence",
1713 RelationGetRelationName(targetrelation))));
1715 if (reltype == OBJECT_VIEW && relkind != RELKIND_VIEW)
1717 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1718 errmsg("\"%s\" is not a view",
1719 RelationGetRelationName(targetrelation))));
1722 * Don't allow ALTER TABLE on composite types.
1723 * We want people to use ALTER TYPE for that.
1725 if (relkind == RELKIND_COMPOSITE_TYPE)
1727 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1728 errmsg("\"%s\" is a composite type",
1729 RelationGetRelationName(targetrelation)),
1730 errhint("Use ALTER TYPE instead.")));
1733 RenameRelationInternal(myrelid, newrelname, namespaceId);
1736 * Close rel, but keep exclusive lock!
1738 relation_close(targetrelation, NoLock);
1742 * RenameRelationInternal - change the name of a relation
1744 * XXX - When renaming sequences, we don't bother to modify the
1745 * sequence name that is stored within the sequence itself
1746 * (this would cause problems with MVCC). In the future,
1747 * the sequence name should probably be removed from the
1748 * sequence, AFAIK there's no need for it to be there.
1751 RenameRelationInternal(Oid myrelid, const char *newrelname, Oid namespaceId)
1753 Relation targetrelation;
1754 Relation relrelation; /* for RELATION relation */
1756 Form_pg_class relform;
1759 * Grab an exclusive lock on the target table, index, sequence or
1760 * view, which we will NOT release until end of transaction.
1762 targetrelation = relation_open(myrelid, AccessExclusiveLock);
1765 * Find relation's pg_class tuple, and make sure newrelname isn't in use.
1767 relrelation = heap_open(RelationRelationId, RowExclusiveLock);
1769 reltup = SearchSysCacheCopy(RELOID,
1770 ObjectIdGetDatum(myrelid),
1772 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
1773 elog(ERROR, "cache lookup failed for relation %u", myrelid);
1774 relform = (Form_pg_class) GETSTRUCT(reltup);
1776 if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
1778 (errcode(ERRCODE_DUPLICATE_TABLE),
1779 errmsg("relation \"%s\" already exists",
1783 * Update pg_class tuple with new relname. (Scribbling on reltup is OK
1784 * because it's a copy...)
1786 namestrcpy(&(relform->relname), newrelname);
1788 simple_heap_update(relrelation, &reltup->t_self, reltup);
1790 /* keep the system catalog indexes current */
1791 CatalogUpdateIndexes(relrelation, reltup);
1793 heap_freetuple(reltup);
1794 heap_close(relrelation, RowExclusiveLock);
1797 * Also rename the associated type, if any.
1799 if (OidIsValid(targetrelation->rd_rel->reltype))
1800 RenameTypeInternal(targetrelation->rd_rel->reltype,
1801 newrelname, namespaceId);
1804 * Also rename the associated constraint, if any.
1806 if (targetrelation->rd_rel->relkind == RELKIND_INDEX)
1808 Oid constraintId = get_index_constraint(myrelid);
1810 if (OidIsValid(constraintId))
1811 RenameConstraintById(constraintId, newrelname);
1815 * Close rel, but keep exclusive lock!
1817 relation_close(targetrelation, NoLock);
1821 * Disallow ALTER TABLE (and similar commands) when the current backend has
1822 * any open reference to the target table besides the one just acquired by
1823 * the calling command; this implies there's an open cursor or active plan.
1824 * We need this check because our AccessExclusiveLock doesn't protect us
1825 * against stomping on our own foot, only other people's feet!
1827 * For ALTER TABLE, the only case known to cause serious trouble is ALTER
1828 * COLUMN TYPE, and some changes are obviously pretty benign, so this could
1829 * possibly be relaxed to only error out for certain types of alterations.
1830 * But the use-case for allowing any of these things is not obvious, so we
1831 * won't work hard at it for now.
1833 * We also reject these commands if there are any pending AFTER trigger events
1834 * for the rel. This is certainly necessary for the rewriting variants of
1835 * ALTER TABLE, because they don't preserve tuple TIDs and so the pending
1836 * events would try to fetch the wrong tuples. It might be overly cautious
1837 * in other cases, but again it seems better to err on the side of paranoia.
1839 * REINDEX calls this with "rel" referencing the index to be rebuilt; here
1840 * we are worried about active indexscans on the index. The trigger-event
1841 * check can be skipped, since we are doing no damage to the parent table.
1843 * The statement name (eg, "ALTER TABLE") is passed for use in error messages.
1846 CheckTableNotInUse(Relation rel, const char *stmt)
1848 int expected_refcnt;
1850 expected_refcnt = rel->rd_isnailed ? 2 : 1;
1851 if (rel->rd_refcnt != expected_refcnt)
1853 (errcode(ERRCODE_OBJECT_IN_USE),
1854 /* translator: first %s is a SQL command, eg ALTER TABLE */
1855 errmsg("cannot %s \"%s\" because "
1856 "it is being used by active queries in this session",
1857 stmt, RelationGetRelationName(rel))));
1859 if (rel->rd_rel->relkind != RELKIND_INDEX &&
1860 AfterTriggerPendingOnRel(RelationGetRelid(rel)))
1862 (errcode(ERRCODE_OBJECT_IN_USE),
1863 /* translator: first %s is a SQL command, eg ALTER TABLE */
1864 errmsg("cannot %s \"%s\" because "
1865 "it has pending trigger events",
1866 stmt, RelationGetRelationName(rel))));
1871 * Execute ALTER TABLE, which can be a list of subcommands
1873 * ALTER TABLE is performed in three phases:
1874 * 1. Examine subcommands and perform pre-transformation checking.
1875 * 2. Update system catalogs.
1876 * 3. Scan table(s) to check new constraints, and optionally recopy
1877 * the data into new table(s).
1878 * Phase 3 is not performed unless one or more of the subcommands requires
1879 * it. The intention of this design is to allow multiple independent
1880 * updates of the table schema to be performed with only one pass over the
1883 * ATPrepCmd performs phase 1. A "work queue" entry is created for
1884 * each table to be affected (there may be multiple affected tables if the
1885 * commands traverse a table inheritance hierarchy). Also we do preliminary
1886 * validation of the subcommands, including parse transformation of those
1887 * expressions that need to be evaluated with respect to the old table
1890 * ATRewriteCatalogs performs phase 2 for each affected table (note that
1891 * phases 2 and 3 do no explicit recursion, since phase 1 already did it).
1892 * Certain subcommands need to be performed before others to avoid
1893 * unnecessary conflicts; for example, DROP COLUMN should come before
1894 * ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
1895 * lists, one for each logical "pass" of phase 2.
1897 * ATRewriteTables performs phase 3 for those tables that need it.
1899 * Thanks to the magic of MVCC, an error anywhere along the way rolls back
1900 * the whole operation; we don't have to do anything special to clean up.
1903 AlterTable(AlterTableStmt *stmt)
1905 Relation rel = relation_openrv(stmt->relation, AccessExclusiveLock);
1907 CheckTableNotInUse(rel, "ALTER TABLE");
1909 ATController(rel, stmt->cmds, interpretInhOption(stmt->relation->inhOpt));
1913 * AlterTableInternal
1915 * ALTER TABLE with target specified by OID
1917 * We do not reject if the relation is already open, because it's quite
1918 * likely that one or more layers of caller have it open. That means it
1919 * is unsafe to use this entry point for alterations that could break
1920 * existing query plans. On the assumption it's not used for such, we
1921 * don't have to reject pending AFTER triggers, either.
1924 AlterTableInternal(Oid relid, List *cmds, bool recurse)
1926 Relation rel = relation_open(relid, AccessExclusiveLock);
1928 ATController(rel, cmds, recurse);
1932 ATController(Relation rel, List *cmds, bool recurse)
1937 /* Phase 1: preliminary examination of commands, create work queue */
1940 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
1942 ATPrepCmd(&wqueue, rel, cmd, recurse, false);
1945 /* Close the relation, but keep lock until commit */
1946 relation_close(rel, NoLock);
1948 /* Phase 2: update system catalogs */
1949 ATRewriteCatalogs(&wqueue);
1951 /* Phase 3: scan/rewrite tables as needed */
1952 ATRewriteTables(&wqueue);
1958 * Traffic cop for ALTER TABLE Phase 1 operations, including simple
1959 * recursion and permission checks.
1961 * Caller must have acquired AccessExclusiveLock on relation already.
1962 * This lock should be held until commit.
1965 ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
1966 bool recurse, bool recursing)
1968 AlteredTableInfo *tab;
1971 /* Find or create work queue entry for this table */
1972 tab = ATGetQueueEntry(wqueue, rel);
1975 * Copy the original subcommand for each table. This avoids conflicts
1976 * when different child tables need to make different parse
1977 * transformations (for example, the same column may have different column
1978 * numbers in different children).
1980 cmd = copyObject(cmd);
1983 * Do permissions checking, recursion to child tables if needed, and any
1984 * additional phase-1 processing needed.
1986 switch (cmd->subtype)
1988 case AT_AddColumn: /* ADD COLUMN */
1989 ATSimplePermissions(rel, false);
1990 /* Performs own recursion */
1991 ATPrepAddColumn(wqueue, rel, recurse, cmd);
1992 pass = AT_PASS_ADD_COL;
1994 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
1997 * We allow defaults on views so that INSERT into a view can have
1998 * default-ish behavior. This works because the rewriter
1999 * substitutes default values into INSERTs before it expands
2002 ATSimplePermissions(rel, true);
2003 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2004 /* No command-specific prep needed */
2005 pass = cmd->def ? AT_PASS_ADD_CONSTR : AT_PASS_DROP;
2007 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
2008 ATSimplePermissions(rel, false);
2009 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2010 /* No command-specific prep needed */
2011 pass = AT_PASS_DROP;
2013 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
2014 ATSimplePermissions(rel, false);
2015 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2016 /* No command-specific prep needed */
2017 pass = AT_PASS_ADD_CONSTR;
2019 case AT_SetStatistics: /* ALTER COLUMN STATISTICS */
2020 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2021 /* Performs own permission checks */
2022 ATPrepSetStatistics(rel, cmd->name, cmd->def);
2023 pass = AT_PASS_COL_ATTRS;
2025 case AT_SetStorage: /* ALTER COLUMN STORAGE */
2026 ATSimplePermissions(rel, false);
2027 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2028 /* No command-specific prep needed */
2029 pass = AT_PASS_COL_ATTRS;
2031 case AT_DropColumn: /* DROP COLUMN */
2032 ATSimplePermissions(rel, false);
2033 /* Recursion occurs during execution phase */
2034 /* No command-specific prep needed except saving recurse flag */
2036 cmd->subtype = AT_DropColumnRecurse;
2037 pass = AT_PASS_DROP;
2039 case AT_AddIndex: /* ADD INDEX */
2040 ATSimplePermissions(rel, false);
2041 /* This command never recurses */
2042 /* No command-specific prep needed */
2043 pass = AT_PASS_ADD_INDEX;
2045 case AT_AddConstraint: /* ADD CONSTRAINT */
2046 ATSimplePermissions(rel, false);
2049 * Currently we recurse only for CHECK constraints, never for
2050 * foreign-key constraints. UNIQUE/PKEY constraints won't be seen
2053 if (IsA(cmd->def, Constraint))
2054 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2055 /* No command-specific prep needed */
2056 pass = AT_PASS_ADD_CONSTR;
2058 case AT_DropConstraint: /* DROP CONSTRAINT */
2059 ATSimplePermissions(rel, false);
2060 /* Performs own recursion */
2061 ATPrepDropConstraint(wqueue, rel, recurse, cmd);
2062 pass = AT_PASS_DROP;
2064 case AT_DropConstraintQuietly: /* DROP CONSTRAINT for child */
2065 ATSimplePermissions(rel, false);
2066 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2067 /* No command-specific prep needed */
2068 pass = AT_PASS_DROP;
2070 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
2071 ATSimplePermissions(rel, false);
2072 /* Performs own recursion */
2073 ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd);
2074 pass = AT_PASS_ALTER_TYPE;
2076 case AT_ChangeOwner: /* ALTER OWNER */
2077 /* This command never recurses */
2078 /* No command-specific prep needed */
2079 pass = AT_PASS_MISC;
2081 case AT_ClusterOn: /* CLUSTER ON */
2082 case AT_DropCluster: /* SET WITHOUT CLUSTER */
2083 ATSimplePermissions(rel, false);
2084 /* These commands never recurse */
2085 /* No command-specific prep needed */
2086 pass = AT_PASS_MISC;
2088 case AT_DropOids: /* SET WITHOUT OIDS */
2089 ATSimplePermissions(rel, false);
2090 /* Performs own recursion */
2091 if (rel->rd_rel->relhasoids)
2093 AlterTableCmd *dropCmd = makeNode(AlterTableCmd);
2095 dropCmd->subtype = AT_DropColumn;
2096 dropCmd->name = pstrdup("oid");
2097 dropCmd->behavior = cmd->behavior;
2098 ATPrepCmd(wqueue, rel, dropCmd, recurse, false);
2100 pass = AT_PASS_DROP;
2102 case AT_SetTableSpace: /* SET TABLESPACE */
2103 ATSimplePermissionsRelationOrIndex(rel);
2104 /* This command never recurses */
2105 ATPrepSetTableSpace(tab, rel, cmd->name);
2106 pass = AT_PASS_MISC; /* doesn't actually matter */
2108 case AT_SetRelOptions: /* SET (...) */
2109 case AT_ResetRelOptions: /* RESET (...) */
2110 ATSimplePermissionsRelationOrIndex(rel);
2111 /* This command never recurses */
2112 /* No command-specific prep needed */
2113 pass = AT_PASS_MISC;
2115 case AT_EnableTrig: /* ENABLE TRIGGER variants */
2116 case AT_EnableAlwaysTrig:
2117 case AT_EnableReplicaTrig:
2118 case AT_EnableTrigAll:
2119 case AT_EnableTrigUser:
2120 case AT_DisableTrig: /* DISABLE TRIGGER variants */
2121 case AT_DisableTrigAll:
2122 case AT_DisableTrigUser:
2123 case AT_EnableRule: /* ENABLE/DISABLE RULE variants */
2124 case AT_EnableAlwaysRule:
2125 case AT_EnableReplicaRule:
2126 case AT_DisableRule:
2127 case AT_AddInherit: /* INHERIT / NO INHERIT */
2128 case AT_DropInherit:
2129 ATSimplePermissions(rel, false);
2130 /* These commands never recurse */
2131 /* No command-specific prep needed */
2132 pass = AT_PASS_MISC;
2135 elog(ERROR, "unrecognized alter table type: %d",
2136 (int) cmd->subtype);
2137 pass = 0; /* keep compiler quiet */
2141 /* Add the subcommand to the appropriate list for phase 2 */
2142 tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
2148 * Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
2149 * dispatched in a "safe" execution order (designed to avoid unnecessary
2153 ATRewriteCatalogs(List **wqueue)
2159 * We process all the tables "in parallel", one pass at a time. This is
2160 * needed because we may have to propagate work from one table to another
2161 * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
2162 * re-adding of the foreign key constraint to the other table). Work can
2163 * only be propagated into later passes, however.
2165 for (pass = 0; pass < AT_NUM_PASSES; pass++)
2167 /* Go through each table that needs to be processed */
2168 foreach(ltab, *wqueue)
2170 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2171 List *subcmds = tab->subcmds[pass];
2179 * Exclusive lock was obtained by phase 1, needn't get it again
2181 rel = relation_open(tab->relid, NoLock);
2183 foreach(lcmd, subcmds)
2184 ATExecCmd(tab, rel, (AlterTableCmd *) lfirst(lcmd));
2187 * After the ALTER TYPE pass, do cleanup work (this is not done in
2188 * ATExecAlterColumnType since it should be done only once if
2189 * multiple columns of a table are altered).
2191 if (pass == AT_PASS_ALTER_TYPE)
2192 ATPostAlterTypeCleanup(wqueue, tab);
2194 relation_close(rel, NoLock);
2199 * Check to see if a toast table must be added, if we executed any
2200 * subcommands that might have added a column or changed column storage.
2202 foreach(ltab, *wqueue)
2204 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2206 if (tab->relkind == RELKIND_RELATION &&
2207 (tab->subcmds[AT_PASS_ADD_COL] ||
2208 tab->subcmds[AT_PASS_ALTER_TYPE] ||
2209 tab->subcmds[AT_PASS_COL_ATTRS]))
2210 AlterTableCreateToastTable(tab->relid);
2215 * ATExecCmd: dispatch a subcommand to appropriate execution routine
2218 ATExecCmd(AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd)
2220 switch (cmd->subtype)
2222 case AT_AddColumn: /* ADD COLUMN */
2223 ATExecAddColumn(tab, rel, (ColumnDef *) cmd->def);
2225 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
2226 ATExecColumnDefault(rel, cmd->name, cmd->def);
2228 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
2229 ATExecDropNotNull(rel, cmd->name);
2231 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
2232 ATExecSetNotNull(tab, rel, cmd->name);
2234 case AT_SetStatistics: /* ALTER COLUMN STATISTICS */
2235 ATExecSetStatistics(rel, cmd->name, cmd->def);
2237 case AT_SetStorage: /* ALTER COLUMN STORAGE */
2238 ATExecSetStorage(rel, cmd->name, cmd->def);
2240 case AT_DropColumn: /* DROP COLUMN */
2241 ATExecDropColumn(rel, cmd->name, cmd->behavior, false, false);
2243 case AT_DropColumnRecurse: /* DROP COLUMN with recursion */
2244 ATExecDropColumn(rel, cmd->name, cmd->behavior, true, false);
2246 case AT_AddIndex: /* ADD INDEX */
2247 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false);
2249 case AT_ReAddIndex: /* ADD INDEX */
2250 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true);
2252 case AT_AddConstraint: /* ADD CONSTRAINT */
2253 ATExecAddConstraint(tab, rel, cmd->def);
2255 case AT_DropConstraint: /* DROP CONSTRAINT */
2256 ATExecDropConstraint(rel, cmd->name, cmd->behavior, false);
2258 case AT_DropConstraintQuietly: /* DROP CONSTRAINT for child */
2259 ATExecDropConstraint(rel, cmd->name, cmd->behavior, true);
2261 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
2262 ATExecAlterColumnType(tab, rel, cmd->name, (TypeName *) cmd->def);
2264 case AT_ChangeOwner: /* ALTER OWNER */
2265 ATExecChangeOwner(RelationGetRelid(rel),
2266 get_roleid_checked(cmd->name),
2269 case AT_ClusterOn: /* CLUSTER ON */
2270 ATExecClusterOn(rel, cmd->name);
2272 case AT_DropCluster: /* SET WITHOUT CLUSTER */
2273 ATExecDropCluster(rel);
2275 case AT_DropOids: /* SET WITHOUT OIDS */
2278 * Nothing to do here; we'll have generated a DropColumn
2279 * subcommand to do the real work
2282 case AT_SetTableSpace: /* SET TABLESPACE */
2285 * Nothing to do here; Phase 3 does the work
2288 case AT_SetRelOptions: /* SET (...) */
2289 ATExecSetRelOptions(rel, (List *) cmd->def, false);
2291 case AT_ResetRelOptions: /* RESET (...) */
2292 ATExecSetRelOptions(rel, (List *) cmd->def, true);
2295 case AT_EnableTrig: /* ENABLE TRIGGER name */
2296 ATExecEnableDisableTrigger(rel, cmd->name,
2297 TRIGGER_FIRES_ON_ORIGIN, false);
2299 case AT_EnableAlwaysTrig: /* ENABLE ALWAYS TRIGGER name */
2300 ATExecEnableDisableTrigger(rel, cmd->name,
2301 TRIGGER_FIRES_ALWAYS, false);
2303 case AT_EnableReplicaTrig: /* ENABLE REPLICA TRIGGER name */
2304 ATExecEnableDisableTrigger(rel, cmd->name,
2305 TRIGGER_FIRES_ON_REPLICA, false);
2307 case AT_DisableTrig: /* DISABLE TRIGGER name */
2308 ATExecEnableDisableTrigger(rel, cmd->name,
2309 TRIGGER_DISABLED, false);
2311 case AT_EnableTrigAll: /* ENABLE TRIGGER ALL */
2312 ATExecEnableDisableTrigger(rel, NULL,
2313 TRIGGER_FIRES_ON_ORIGIN, false);
2315 case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
2316 ATExecEnableDisableTrigger(rel, NULL,
2317 TRIGGER_DISABLED, false);
2319 case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
2320 ATExecEnableDisableTrigger(rel, NULL,
2321 TRIGGER_FIRES_ON_ORIGIN, true);
2323 case AT_DisableTrigUser: /* DISABLE TRIGGER USER */
2324 ATExecEnableDisableTrigger(rel, NULL,
2325 TRIGGER_DISABLED, true);
2328 case AT_EnableRule: /* ENABLE RULE name */
2329 ATExecEnableDisableRule(rel, cmd->name,
2330 RULE_FIRES_ON_ORIGIN);
2332 case AT_EnableAlwaysRule: /* ENABLE ALWAYS RULE name */
2333 ATExecEnableDisableRule(rel, cmd->name,
2336 case AT_EnableReplicaRule: /* ENABLE REPLICA RULE name */
2337 ATExecEnableDisableRule(rel, cmd->name,
2338 RULE_FIRES_ON_REPLICA);
2340 case AT_DisableRule: /* DISABLE RULE name */
2341 ATExecEnableDisableRule(rel, cmd->name,
2346 ATExecAddInherit(rel, (RangeVar *) cmd->def);
2348 case AT_DropInherit:
2349 ATExecDropInherit(rel, (RangeVar *) cmd->def);
2352 elog(ERROR, "unrecognized alter table type: %d",
2353 (int) cmd->subtype);
2358 * Bump the command counter to ensure the next subcommand in the sequence
2359 * can see the changes so far
2361 CommandCounterIncrement();
2365 * ATRewriteTables: ALTER TABLE phase 3
2368 ATRewriteTables(List **wqueue)
2372 /* Go through each table that needs to be checked or rewritten */
2373 foreach(ltab, *wqueue)
2375 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2378 * We only need to rewrite the table if at least one column needs to
2381 if (tab->newvals != NIL)
2383 /* Build a temporary relation and copy data */
2385 char NewHeapName[NAMEDATALEN];
2388 ObjectAddress object;
2390 OldHeap = heap_open(tab->relid, NoLock);
2393 * We can never allow rewriting of shared or nailed-in-cache
2394 * relations, because we can't support changing their relfilenode
2397 if (OldHeap->rd_rel->relisshared || OldHeap->rd_isnailed)
2399 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2400 errmsg("cannot rewrite system relation \"%s\"",
2401 RelationGetRelationName(OldHeap))));
2404 * Don't allow rewrite on temp tables of other backends ... their
2405 * local buffer manager is not going to cope.
2407 if (isOtherTempNamespace(RelationGetNamespace(OldHeap)))
2409 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2410 errmsg("cannot rewrite temporary tables of other sessions")));
2413 * Select destination tablespace (same as original unless user
2414 * requested a change)
2416 if (tab->newTableSpace)
2417 NewTableSpace = tab->newTableSpace;
2419 NewTableSpace = OldHeap->rd_rel->reltablespace;
2421 heap_close(OldHeap, NoLock);
2424 * Create the new heap, using a temporary name in the same
2425 * namespace as the existing table. NOTE: there is some risk of
2426 * collision with user relnames. Working around this seems more
2427 * trouble than it's worth; in particular, we can't create the new
2428 * heap in a different namespace from the old, or we will have
2429 * problems with the TEMP status of temp tables.
2431 snprintf(NewHeapName, sizeof(NewHeapName),
2432 "pg_temp_%u", tab->relid);
2434 OIDNewHeap = make_new_heap(tab->relid, NewHeapName, NewTableSpace);
2437 * Copy the heap data into the new table with the desired
2438 * modifications, and test the current data within the table
2439 * against new constraints generated by ALTER TABLE commands.
2441 ATRewriteTable(tab, OIDNewHeap);
2444 * Swap the physical files of the old and new heaps. Since we are
2445 * generating a new heap, we can use RecentXmin for the table's
2446 * new relfrozenxid because we rewrote all the tuples on
2447 * ATRewriteTable, so no older Xid remains on the table.
2449 swap_relation_files(tab->relid, OIDNewHeap, RecentXmin);
2451 CommandCounterIncrement();
2453 /* Destroy new heap with old filenode */
2454 object.classId = RelationRelationId;
2455 object.objectId = OIDNewHeap;
2456 object.objectSubId = 0;
2459 * The new relation is local to our transaction and we know
2460 * nothing depends on it, so DROP_RESTRICT should be OK.
2462 performDeletion(&object, DROP_RESTRICT);
2463 /* performDeletion does CommandCounterIncrement at end */
2466 * Rebuild each index on the relation (but not the toast table,
2467 * which is all-new anyway). We do not need
2468 * CommandCounterIncrement() because reindex_relation does it.
2470 reindex_relation(tab->relid, false);
2475 * Test the current data within the table against new constraints
2476 * generated by ALTER TABLE commands, but don't rebuild data.
2478 if (tab->constraints != NIL || tab->new_notnull)
2479 ATRewriteTable(tab, InvalidOid);
2482 * If we had SET TABLESPACE but no reason to reconstruct tuples,
2483 * just do a block-by-block copy.
2485 if (tab->newTableSpace)
2486 ATExecSetTableSpace(tab->relid, tab->newTableSpace);
2491 * Foreign key constraints are checked in a final pass, since (a) it's
2492 * generally best to examine each one separately, and (b) it's at least
2493 * theoretically possible that we have changed both relations of the
2494 * foreign key, and we'd better have finished both rewrites before we try
2495 * to read the tables.
2497 foreach(ltab, *wqueue)
2499 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2500 Relation rel = NULL;
2503 foreach(lcon, tab->constraints)
2505 NewConstraint *con = lfirst(lcon);
2507 if (con->contype == CONSTR_FOREIGN)
2509 FkConstraint *fkconstraint = (FkConstraint *) con->qual;
2514 /* Long since locked, no need for another */
2515 rel = heap_open(tab->relid, NoLock);
2518 refrel = heap_open(con->refrelid, RowShareLock);
2520 validateForeignKeyConstraint(fkconstraint, rel, refrel,
2523 heap_close(refrel, NoLock);
2528 heap_close(rel, NoLock);
2533 * ATRewriteTable: scan or rewrite one table
2535 * OIDNewHeap is InvalidOid if we don't need to rewrite
2538 ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap)
2542 TupleDesc oldTupDesc;
2543 TupleDesc newTupDesc;
2544 bool needscan = false;
2545 List *notnull_attrs;
2551 * Open the relation(s). We have surely already locked the existing
2554 oldrel = heap_open(tab->relid, NoLock);
2555 oldTupDesc = tab->oldDesc;
2556 newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
2558 if (OidIsValid(OIDNewHeap))
2559 newrel = heap_open(OIDNewHeap, AccessExclusiveLock);
2564 * If we need to rewrite the table, the operation has to be propagated to
2565 * tables that use this table's rowtype as a column type.
2567 * (Eventually this will probably become true for scans as well, but at
2568 * the moment a composite type does not enforce any constraints, so it's
2569 * not necessary/appropriate to enforce them just during ALTER.)
2572 find_composite_type_dependencies(oldrel->rd_rel->reltype,
2573 RelationGetRelationName(oldrel),
2577 * Generate the constraint and default execution states
2580 estate = CreateExecutorState();
2582 /* Build the needed expression execution states */
2583 foreach(l, tab->constraints)
2585 NewConstraint *con = lfirst(l);
2587 switch (con->contype)
2591 con->qualstate = (List *)
2592 ExecPrepareExpr((Expr *) con->qual, estate);
2594 case CONSTR_FOREIGN:
2595 /* Nothing to do here */
2598 elog(ERROR, "unrecognized constraint type: %d",
2599 (int) con->contype);
2603 foreach(l, tab->newvals)
2605 NewColumnValue *ex = lfirst(l);
2609 ex->exprstate = ExecPrepareExpr((Expr *) ex->expr, estate);
2612 notnull_attrs = NIL;
2613 if (newrel || tab->new_notnull)
2616 * If we are rebuilding the tuples OR if we added any new NOT NULL
2617 * constraints, check all not-null constraints. This is a bit of
2618 * overkill but it minimizes risk of bugs, and heap_attisnull is a
2619 * pretty cheap test anyway.
2621 for (i = 0; i < newTupDesc->natts; i++)
2623 if (newTupDesc->attrs[i]->attnotnull &&
2624 !newTupDesc->attrs[i]->attisdropped)
2625 notnull_attrs = lappend_int(notnull_attrs, i);
2633 ExprContext *econtext;
2636 TupleTableSlot *oldslot;
2637 TupleTableSlot *newslot;
2640 MemoryContext oldCxt;
2641 List *dropped_attrs = NIL;
2644 econtext = GetPerTupleExprContext(estate);
2647 * Make tuple slots for old and new tuples. Note that even when the
2648 * tuples are the same, the tupDescs might not be (consider ADD COLUMN
2649 * without a default).
2651 oldslot = MakeSingleTupleTableSlot(oldTupDesc);
2652 newslot = MakeSingleTupleTableSlot(newTupDesc);
2654 /* Preallocate values/isnull arrays */
2655 i = Max(newTupDesc->natts, oldTupDesc->natts);
2656 values = (Datum *) palloc(i * sizeof(Datum));
2657 isnull = (bool *) palloc(i * sizeof(bool));
2658 memset(values, 0, i * sizeof(Datum));
2659 memset(isnull, true, i * sizeof(bool));
2662 * Any attributes that are dropped according to the new tuple
2663 * descriptor can be set to NULL. We precompute the list of dropped
2664 * attributes to avoid needing to do so in the per-tuple loop.
2666 for (i = 0; i < newTupDesc->natts; i++)
2668 if (newTupDesc->attrs[i]->attisdropped)
2669 dropped_attrs = lappend_int(dropped_attrs, i);
2673 * Scan through the rows, generating a new row if needed and then
2674 * checking all the constraints.
2676 scan = heap_beginscan(oldrel, SnapshotNow, 0, NULL);
2679 * Switch to per-tuple memory context and reset it for each tuple
2680 * produced, so we don't leak memory.
2682 oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
2684 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2688 Oid tupOid = InvalidOid;
2690 /* Extract data from old tuple */
2691 heap_deform_tuple(tuple, oldTupDesc, values, isnull);
2692 if (oldTupDesc->tdhasoid)
2693 tupOid = HeapTupleGetOid(tuple);
2695 /* Set dropped attributes to null in new tuple */
2696 foreach(lc, dropped_attrs)
2697 isnull[lfirst_int(lc)] = true;
2700 * Process supplied expressions to replace selected columns.
2701 * Expression inputs come from the old tuple.
2703 ExecStoreTuple(tuple, oldslot, InvalidBuffer, false);
2704 econtext->ecxt_scantuple = oldslot;
2706 foreach(l, tab->newvals)
2708 NewColumnValue *ex = lfirst(l);
2710 values[ex->attnum - 1] = ExecEvalExpr(ex->exprstate,
2712 &isnull[ex->attnum - 1],
2717 * Form the new tuple. Note that we don't explicitly pfree it,
2718 * since the per-tuple memory context will be reset shortly.
2720 tuple = heap_form_tuple(newTupDesc, values, isnull);
2722 /* Preserve OID, if any */
2723 if (newTupDesc->tdhasoid)
2724 HeapTupleSetOid(tuple, tupOid);
2727 /* Now check any constraints on the possibly-changed tuple */
2728 ExecStoreTuple(tuple, newslot, InvalidBuffer, false);
2729 econtext->ecxt_scantuple = newslot;
2731 foreach(l, notnull_attrs)
2733 int attn = lfirst_int(l);
2735 if (heap_attisnull(tuple, attn + 1))
2737 (errcode(ERRCODE_NOT_NULL_VIOLATION),
2738 errmsg("column \"%s\" contains null values",
2739 NameStr(newTupDesc->attrs[attn]->attname))));
2742 foreach(l, tab->constraints)
2744 NewConstraint *con = lfirst(l);
2746 switch (con->contype)
2749 if (!ExecQual(con->qualstate, econtext, true))
2751 (errcode(ERRCODE_CHECK_VIOLATION),
2752 errmsg("check constraint \"%s\" is violated by some row",
2755 case CONSTR_FOREIGN:
2756 /* Nothing to do here */
2759 elog(ERROR, "unrecognized constraint type: %d",
2760 (int) con->contype);
2764 /* Write the tuple out to the new relation */
2766 simple_heap_insert(newrel, tuple);
2768 ResetExprContext(econtext);
2770 CHECK_FOR_INTERRUPTS();
2773 MemoryContextSwitchTo(oldCxt);
2776 ExecDropSingleTupleTableSlot(oldslot);
2777 ExecDropSingleTupleTableSlot(newslot);
2780 FreeExecutorState(estate);
2782 heap_close(oldrel, NoLock);
2784 heap_close(newrel, NoLock);
2788 * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
2790 static AlteredTableInfo *
2791 ATGetQueueEntry(List **wqueue, Relation rel)
2793 Oid relid = RelationGetRelid(rel);
2794 AlteredTableInfo *tab;
2797 foreach(ltab, *wqueue)
2799 tab = (AlteredTableInfo *) lfirst(ltab);
2800 if (tab->relid == relid)
2805 * Not there, so add it. Note that we make a copy of the relation's
2806 * existing descriptor before anything interesting can happen to it.
2808 tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
2810 tab->relkind = rel->rd_rel->relkind;
2811 tab->oldDesc = CreateTupleDescCopy(RelationGetDescr(rel));
2813 *wqueue = lappend(*wqueue, tab);
2819 * ATSimplePermissions
2821 * - Ensure that it is a relation (or possibly a view)
2822 * - Ensure this user is the owner
2823 * - Ensure that it is not a system table
2826 ATSimplePermissions(Relation rel, bool allowView)
2828 if (rel->rd_rel->relkind != RELKIND_RELATION)
2832 if (rel->rd_rel->relkind != RELKIND_VIEW)
2834 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2835 errmsg("\"%s\" is not a table or view",
2836 RelationGetRelationName(rel))));
2840 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2841 errmsg("\"%s\" is not a table",
2842 RelationGetRelationName(rel))));
2845 /* Permissions checks */
2846 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
2847 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
2848 RelationGetRelationName(rel));
2850 if (!allowSystemTableMods && IsSystemRelation(rel))
2852 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2853 errmsg("permission denied: \"%s\" is a system catalog",
2854 RelationGetRelationName(rel))));
2858 * ATSimplePermissionsRelationOrIndex
2860 * - Ensure that it is a relation or an index
2861 * - Ensure this user is the owner
2862 * - Ensure that it is not a system table
2865 ATSimplePermissionsRelationOrIndex(Relation rel)
2867 if (rel->rd_rel->relkind != RELKIND_RELATION &&
2868 rel->rd_rel->relkind != RELKIND_INDEX)
2870 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2871 errmsg("\"%s\" is not a table or index",
2872 RelationGetRelationName(rel))));
2874 /* Permissions checks */
2875 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
2876 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
2877 RelationGetRelationName(rel));
2879 if (!allowSystemTableMods && IsSystemRelation(rel))
2881 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2882 errmsg("permission denied: \"%s\" is a system catalog",
2883 RelationGetRelationName(rel))));
2889 * Simple table recursion sufficient for most ALTER TABLE operations.
2890 * All direct and indirect children are processed in an unspecified order.
2891 * Note that if a child inherits from the original table via multiple
2892 * inheritance paths, it will be visited just once.
2895 ATSimpleRecursion(List **wqueue, Relation rel,
2896 AlterTableCmd *cmd, bool recurse)
2899 * Propagate to children if desired. Non-table relations never have
2900 * children, so no need to search in that case.
2902 if (recurse && rel->rd_rel->relkind == RELKIND_RELATION)
2904 Oid relid = RelationGetRelid(rel);
2908 /* this routine is actually in the planner */
2909 children = find_all_inheritors(relid);
2912 * find_all_inheritors does the recursive search of the inheritance
2913 * hierarchy, so all we have to do is process all of the relids in the
2914 * list that it returns.
2916 foreach(child, children)
2918 Oid childrelid = lfirst_oid(child);
2921 if (childrelid == relid)
2923 childrel = relation_open(childrelid, AccessExclusiveLock);
2924 CheckTableNotInUse(childrel, "ALTER TABLE");
2925 ATPrepCmd(wqueue, childrel, cmd, false, true);
2926 relation_close(childrel, NoLock);
2932 * ATOneLevelRecursion
2934 * Here, we visit only direct inheritance children. It is expected that
2935 * the command's prep routine will recurse again to find indirect children.
2936 * When using this technique, a multiply-inheriting child will be visited
2940 ATOneLevelRecursion(List **wqueue, Relation rel,
2943 Oid relid = RelationGetRelid(rel);
2947 /* this routine is actually in the planner */
2948 children = find_inheritance_children(relid);
2950 foreach(child, children)
2952 Oid childrelid = lfirst_oid(child);
2955 childrel = relation_open(childrelid, AccessExclusiveLock);
2956 CheckTableNotInUse(childrel, "ALTER TABLE");
2957 ATPrepCmd(wqueue, childrel, cmd, true, true);
2958 relation_close(childrel, NoLock);
2964 * find_composite_type_dependencies
2966 * Check to see if a composite type is being used as a column in some
2967 * other table (possibly nested several levels deep in composite types!).
2968 * Eventually, we'd like to propagate the check or rewrite operation
2969 * into other such tables, but for now, just error out if we find any.
2971 * Caller should provide either a table name or a type name (not both) to
2972 * report in the error message, if any.
2974 * We assume that functions and views depending on the type are not reasons
2975 * to reject the ALTER. (How safe is this really?)
2978 find_composite_type_dependencies(Oid typeOid,
2979 const char *origTblName,
2980 const char *origTypeName)
2984 SysScanDesc depScan;
2989 * We scan pg_depend to find those things that depend on the rowtype. (We
2990 * assume we can ignore refobjsubid for a rowtype.)
2992 depRel = heap_open(DependRelationId, AccessShareLock);
2994 ScanKeyInit(&key[0],
2995 Anum_pg_depend_refclassid,
2996 BTEqualStrategyNumber, F_OIDEQ,
2997 ObjectIdGetDatum(TypeRelationId));
2998 ScanKeyInit(&key[1],
2999 Anum_pg_depend_refobjid,
3000 BTEqualStrategyNumber, F_OIDEQ,
3001 ObjectIdGetDatum(typeOid));
3003 depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
3004 SnapshotNow, 2, key);
3006 while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
3008 Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
3010 Form_pg_attribute att;
3012 /* Ignore dependees that aren't user columns of relations */
3013 /* (we assume system columns are never of rowtypes) */
3014 if (pg_depend->classid != RelationRelationId ||
3015 pg_depend->objsubid <= 0)
3018 rel = relation_open(pg_depend->objid, AccessShareLock);
3019 att = rel->rd_att->attrs[pg_depend->objsubid - 1];
3021 if (rel->rd_rel->relkind == RELKIND_RELATION)
3025 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3026 errmsg("cannot alter table \"%s\" because column \"%s\".\"%s\" uses its rowtype",
3028 RelationGetRelationName(rel),
3029 NameStr(att->attname))));
3032 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3033 errmsg("cannot alter type \"%s\" because column \"%s\".\"%s\" uses it",
3035 RelationGetRelationName(rel),
3036 NameStr(att->attname))));
3038 else if (OidIsValid(rel->rd_rel->reltype))
3041 * A view or composite type itself isn't a problem, but we must
3042 * recursively check for indirect dependencies via its rowtype.
3044 find_composite_type_dependencies(rel->rd_rel->reltype,
3045 origTblName, origTypeName);
3048 relation_close(rel, AccessShareLock);
3051 systable_endscan(depScan);
3053 relation_close(depRel, AccessShareLock);
3056 * If there's an array type for the rowtype, must check for uses of it,
3059 arrayOid = get_array_type(typeOid);
3060 if (OidIsValid(arrayOid))
3061 find_composite_type_dependencies(arrayOid, origTblName, origTypeName);
3066 * ALTER TABLE ADD COLUMN
3068 * Adds an additional attribute to a relation making the assumption that
3069 * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
3070 * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
3074 ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
3078 * Recurse to add the column to child classes, if requested.
3080 * We must recurse one level at a time, so that multiply-inheriting
3081 * children are visited the right number of times and end up with the
3082 * right attinhcount.
3086 AlterTableCmd *childCmd = copyObject(cmd);
3087 ColumnDef *colDefChild = (ColumnDef *) childCmd->def;
3089 /* Child should see column as singly inherited */
3090 colDefChild->inhcount = 1;
3091 colDefChild->is_local = false;
3093 ATOneLevelRecursion(wqueue, rel, childCmd);
3098 * If we are told not to recurse, there had better not be any child
3099 * tables; else the addition would put them out of step.
3101 if (find_inheritance_children(RelationGetRelid(rel)) != NIL)
3103 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3104 errmsg("column must be added to child tables too")));
3109 ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
3112 Oid myrelid = RelationGetRelid(rel);
3116 HeapTuple attributeTuple;
3117 Form_pg_attribute attribute;
3118 FormData_pg_attribute attributeD;
3122 HeapTuple typeTuple;
3128 attrdesc = heap_open(AttributeRelationId, RowExclusiveLock);
3131 * Are we adding the column to a recursion child? If so, check whether to
3132 * merge with an existing definition for the column.
3134 if (colDef->inhcount > 0)
3138 /* Does child already have a column by this name? */
3139 tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
3140 if (HeapTupleIsValid(tuple))
3142 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
3146 /* Okay if child matches by type */
3147 ctypeId = typenameTypeId(NULL, colDef->typename, &ctypmod);
3148 if (ctypeId != childatt->atttypid ||
3149 ctypmod != childatt->atttypmod)
3151 (errcode(ERRCODE_DATATYPE_MISMATCH),
3152 errmsg("child table \"%s\" has different type for column \"%s\"",
3153 RelationGetRelationName(rel), colDef->colname)));
3155 /* Bump the existing child att's inhcount */
3156 childatt->attinhcount++;
3157 simple_heap_update(attrdesc, &tuple->t_self, tuple);
3158 CatalogUpdateIndexes(attrdesc, tuple);
3160 heap_freetuple(tuple);
3162 /* Inform the user about the merge */
3164 (errmsg("merging definition of column \"%s\" for child \"%s\"",
3165 colDef->colname, RelationGetRelationName(rel))));
3167 heap_close(attrdesc, RowExclusiveLock);
3172 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
3174 reltup = SearchSysCacheCopy(RELOID,
3175 ObjectIdGetDatum(myrelid),
3177 if (!HeapTupleIsValid(reltup))
3178 elog(ERROR, "cache lookup failed for relation %u", myrelid);
3181 * this test is deliberately not attisdropped-aware, since if one tries to
3182 * add a column matching a dropped column name, it's gonna fail anyway.
3184 if (SearchSysCacheExists(ATTNAME,
3185 ObjectIdGetDatum(myrelid),
3186 PointerGetDatum(colDef->colname),
3189 (errcode(ERRCODE_DUPLICATE_COLUMN),
3190 errmsg("column \"%s\" of relation \"%s\" already exists",
3191 colDef->colname, RelationGetRelationName(rel))));
3193 minattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts;
3194 maxatts = minattnum + 1;
3195 if (maxatts > MaxHeapAttributeNumber)
3197 (errcode(ERRCODE_TOO_MANY_COLUMNS),
3198 errmsg("tables can have at most %d columns",
3199 MaxHeapAttributeNumber)));
3202 typeTuple = typenameType(NULL, colDef->typename, &typmod);
3203 tform = (Form_pg_type) GETSTRUCT(typeTuple);
3204 typeOid = HeapTupleGetOid(typeTuple);
3206 /* make sure datatype is legal for a column */
3207 CheckAttributeType(colDef->colname, typeOid);
3209 attributeTuple = heap_addheader(Natts_pg_attribute,
3211 ATTRIBUTE_TUPLE_SIZE,
3212 (void *) &attributeD);
3214 attribute = (Form_pg_attribute) GETSTRUCT(attributeTuple);
3216 attribute->attrelid = myrelid;
3217 namestrcpy(&(attribute->attname), colDef->colname);
3218 attribute->atttypid = typeOid;
3219 attribute->attstattarget = -1;
3220 attribute->attlen = tform->typlen;
3221 attribute->attcacheoff = -1;
3222 attribute->atttypmod = typmod;
3223 attribute->attnum = i;
3224 attribute->attbyval = tform->typbyval;
3225 attribute->attndims = list_length(colDef->typename->arrayBounds);
3226 attribute->attstorage = tform->typstorage;
3227 attribute->attalign = tform->typalign;
3228 attribute->attnotnull = colDef->is_not_null;
3229 attribute->atthasdef = false;
3230 attribute->attisdropped = false;
3231 attribute->attislocal = colDef->is_local;
3232 attribute->attinhcount = colDef->inhcount;
3234 ReleaseSysCache(typeTuple);
3236 simple_heap_insert(attrdesc, attributeTuple);
3238 /* Update indexes on pg_attribute */
3239 CatalogUpdateIndexes(attrdesc, attributeTuple);
3241 heap_close(attrdesc, RowExclusiveLock);
3244 * Update number of attributes in pg_class tuple
3246 ((Form_pg_class) GETSTRUCT(reltup))->relnatts = maxatts;
3248 simple_heap_update(pgclass, &reltup->t_self, reltup);
3250 /* keep catalog indexes current */
3251 CatalogUpdateIndexes(pgclass, reltup);
3253 heap_freetuple(reltup);
3255 heap_close(pgclass, RowExclusiveLock);
3257 /* Make the attribute's catalog entry visible */
3258 CommandCounterIncrement();
3261 * Store the DEFAULT, if any, in the catalogs
3263 if (colDef->raw_default)
3265 RawColumnDefault *rawEnt;
3267 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3268 rawEnt->attnum = attribute->attnum;
3269 rawEnt->raw_default = copyObject(colDef->raw_default);
3272 * This function is intended for CREATE TABLE, so it processes a
3273 * _list_ of defaults, but we just do one.
3275 AddRelationRawConstraints(rel, list_make1(rawEnt), NIL);
3277 /* Make the additional catalog changes visible */
3278 CommandCounterIncrement();
3282 * Tell Phase 3 to fill in the default expression, if there is one.
3284 * If there is no default, Phase 3 doesn't have to do anything, because
3285 * that effectively means that the default is NULL. The heap tuple access
3286 * routines always check for attnum > # of attributes in tuple, and return
3287 * NULL if so, so without any modification of the tuple data we will get
3288 * the effect of NULL values in the new column.
3290 * An exception occurs when the new column is of a domain type: the domain
3291 * might have a NOT NULL constraint, or a check constraint that indirectly
3292 * rejects nulls. If there are any domain constraints then we construct
3293 * an explicit NULL default value that will be passed through
3294 * CoerceToDomain processing. (This is a tad inefficient, since it causes
3295 * rewriting the table which we really don't have to do, but the present
3296 * design of domain processing doesn't offer any simple way of checking
3297 * the constraints more directly.)
3299 * Note: we use build_column_default, and not just the cooked default
3300 * returned by AddRelationRawConstraints, so that the right thing happens
3301 * when a datatype's default applies.
3303 defval = (Expr *) build_column_default(rel, attribute->attnum);
3305 if (!defval && GetDomainConstraints(typeOid) != NIL)
3310 baseTypeMod = typmod;
3311 baseTypeId = getBaseTypeAndTypmod(typeOid, &baseTypeMod);
3312 defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod);
3313 defval = (Expr *) coerce_to_target_type(NULL,
3318 COERCION_ASSIGNMENT,
3319 COERCE_IMPLICIT_CAST);
3320 if (defval == NULL) /* should not happen */
3321 elog(ERROR, "failed to coerce base type to domain");
3326 NewColumnValue *newval;
3328 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
3329 newval->attnum = attribute->attnum;
3330 newval->expr = defval;
3332 tab->newvals = lappend(tab->newvals, newval);
3336 * If the new column is NOT NULL, tell Phase 3 it needs to test that.
3338 tab->new_notnull |= colDef->is_not_null;
3341 * Add needed dependency entries for the new column.
3343 add_column_datatype_dependency(myrelid, i, attribute->atttypid);
3347 * Install a column's dependency on its datatype.
3350 add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
3352 ObjectAddress myself,
3355 myself.classId = RelationRelationId;
3356 myself.objectId = relid;
3357 myself.objectSubId = attnum;
3358 referenced.classId = TypeRelationId;
3359 referenced.objectId = typid;
3360 referenced.objectSubId = 0;
3361 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
3365 * ALTER TABLE ALTER COLUMN DROP NOT NULL
3368 ATExecDropNotNull(Relation rel, const char *colName)
3374 ListCell *indexoidscan;
3377 * lookup the attribute
3379 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3381 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3383 if (!HeapTupleIsValid(tuple))
3385 (errcode(ERRCODE_UNDEFINED_COLUMN),
3386 errmsg("column \"%s\" of relation \"%s\" does not exist",
3387 colName, RelationGetRelationName(rel))));
3389 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3391 /* Prevent them from altering a system attribute */
3394 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3395 errmsg("cannot alter system column \"%s\"",
3399 * Check that the attribute is not in a primary key
3402 /* Loop over all indexes on the relation */
3403 indexoidlist = RelationGetIndexList(rel);
3405 foreach(indexoidscan, indexoidlist)
3407 Oid indexoid = lfirst_oid(indexoidscan);
3408 HeapTuple indexTuple;
3409 Form_pg_index indexStruct;
3412 indexTuple = SearchSysCache(INDEXRELID,
3413 ObjectIdGetDatum(indexoid),
3415 if (!HeapTupleIsValid(indexTuple))
3416 elog(ERROR, "cache lookup failed for index %u", indexoid);
3417 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
3419 /* If the index is not a primary key, skip the check */
3420 if (indexStruct->indisprimary)
3423 * Loop over each attribute in the primary key and see if it
3424 * matches the to-be-altered attribute
3426 for (i = 0; i < indexStruct->indnatts; i++)
3428 if (indexStruct->indkey.values[i] == attnum)
3430 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3431 errmsg("column \"%s\" is in a primary key",
3436 ReleaseSysCache(indexTuple);
3439 list_free(indexoidlist);
3442 * Okay, actually perform the catalog change ... if needed
3444 if (((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3446 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = FALSE;
3448 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3450 /* keep the system catalog indexes current */
3451 CatalogUpdateIndexes(attr_rel, tuple);
3454 heap_close(attr_rel, RowExclusiveLock);
3458 * ALTER TABLE ALTER COLUMN SET NOT NULL
3461 ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
3462 const char *colName)
3469 * lookup the attribute
3471 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3473 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3475 if (!HeapTupleIsValid(tuple))
3477 (errcode(ERRCODE_UNDEFINED_COLUMN),
3478 errmsg("column \"%s\" of relation \"%s\" does not exist",
3479 colName, RelationGetRelationName(rel))));
3481 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3483 /* Prevent them from altering a system attribute */
3486 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3487 errmsg("cannot alter system column \"%s\"",
3491 * Okay, actually perform the catalog change ... if needed
3493 if (!((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3495 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = TRUE;
3497 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3499 /* keep the system catalog indexes current */
3500 CatalogUpdateIndexes(attr_rel, tuple);
3502 /* Tell Phase 3 it needs to test the constraint */
3503 tab->new_notnull = true;
3506 heap_close(attr_rel, RowExclusiveLock);
3510 * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
3513 ATExecColumnDefault(Relation rel, const char *colName,
3519 * get the number of the attribute
3521 attnum = get_attnum(RelationGetRelid(rel), colName);
3522 if (attnum == InvalidAttrNumber)
3524 (errcode(ERRCODE_UNDEFINED_COLUMN),
3525 errmsg("column \"%s\" of relation \"%s\" does not exist",
3526 colName, RelationGetRelationName(rel))));
3528 /* Prevent them from altering a system attribute */
3531 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3532 errmsg("cannot alter system column \"%s\"",
3536 * Remove any old default for the column. We use RESTRICT here for
3537 * safety, but at present we do not expect anything to depend on the
3540 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false);
3545 RawColumnDefault *rawEnt;
3547 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3548 rawEnt->attnum = attnum;
3549 rawEnt->raw_default = newDefault;
3552 * This function is intended for CREATE TABLE, so it processes a
3553 * _list_ of defaults, but we just do one.
3555 AddRelationRawConstraints(rel, list_make1(rawEnt), NIL);
3560 * ALTER TABLE ALTER COLUMN SET STATISTICS
3563 ATPrepSetStatistics(Relation rel, const char *colName, Node *flagValue)
3566 * We do our own permission checking because (a) we want to allow SET
3567 * STATISTICS on indexes (for expressional index columns), and (b) we want
3568 * to allow SET STATISTICS on system catalogs without requiring
3569 * allowSystemTableMods to be turned on.
3571 if (rel->rd_rel->relkind != RELKIND_RELATION &&
3572 rel->rd_rel->relkind != RELKIND_INDEX)
3574 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3575 errmsg("\"%s\" is not a table or index",
3576 RelationGetRelationName(rel))));
3578 /* Permissions checks */
3579 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3580 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3581 RelationGetRelationName(rel));
3585 ATExecSetStatistics(Relation rel, const char *colName, Node *newValue)
3588 Relation attrelation;
3590 Form_pg_attribute attrtuple;
3592 Assert(IsA(newValue, Integer));
3593 newtarget = intVal(newValue);
3596 * Limit target to a sane range
3601 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3602 errmsg("statistics target %d is too low",
3605 else if (newtarget > 1000)
3609 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3610 errmsg("lowering statistics target to %d",
3614 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
3616 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3618 if (!HeapTupleIsValid(tuple))
3620 (errcode(ERRCODE_UNDEFINED_COLUMN),
3621 errmsg("column \"%s\" of relation \"%s\" does not exist",
3622 colName, RelationGetRelationName(rel))));
3623 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
3625 if (attrtuple->attnum <= 0)
3627 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3628 errmsg("cannot alter system column \"%s\"",
3631 attrtuple->attstattarget = newtarget;
3633 simple_heap_update(attrelation, &tuple->t_self, tuple);
3635 /* keep system catalog indexes current */
3636 CatalogUpdateIndexes(attrelation, tuple);
3638 heap_freetuple(tuple);
3640 heap_close(attrelation, RowExclusiveLock);
3644 * ALTER TABLE ALTER COLUMN SET STORAGE
3647 ATExecSetStorage(Relation rel, const char *colName, Node *newValue)
3651 Relation attrelation;
3653 Form_pg_attribute attrtuple;
3655 Assert(IsA(newValue, String));
3656 storagemode = strVal(newValue);
3658 if (pg_strcasecmp(storagemode, "plain") == 0)
3660 else if (pg_strcasecmp(storagemode, "external") == 0)
3662 else if (pg_strcasecmp(storagemode, "extended") == 0)
3664 else if (pg_strcasecmp(storagemode, "main") == 0)
3669 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3670 errmsg("invalid storage type \"%s\"",
3672 newstorage = 0; /* keep compiler quiet */
3675 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
3677 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3679 if (!HeapTupleIsValid(tuple))
3681 (errcode(ERRCODE_UNDEFINED_COLUMN),
3682 errmsg("column \"%s\" of relation \"%s\" does not exist",
3683 colName, RelationGetRelationName(rel))));
3684 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
3686 if (attrtuple->attnum <= 0)
3688 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3689 errmsg("cannot alter system column \"%s\"",
3693 * safety check: do not allow toasted storage modes unless column datatype
3696 if (newstorage == 'p' || TypeIsToastable(attrtuple->atttypid))
3697 attrtuple->attstorage = newstorage;
3700 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3701 errmsg("column data type %s can only have storage PLAIN",
3702 format_type_be(attrtuple->atttypid))));
3704 simple_heap_update(attrelation, &tuple->t_self, tuple);
3706 /* keep system catalog indexes current */
3707 CatalogUpdateIndexes(attrelation, tuple);
3709 heap_freetuple(tuple);
3711 heap_close(attrelation, RowExclusiveLock);
3716 * ALTER TABLE DROP COLUMN
3718 * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
3719 * because we have to decide at runtime whether to recurse or not depending
3720 * on whether attinhcount goes to zero or not. (We can't check this in a
3721 * static pre-pass because it won't handle multiple inheritance situations
3722 * correctly.) Since DROP COLUMN doesn't need to create any work queue
3723 * entries for Phase 3, it's okay to recurse internally in this routine
3724 * without considering the work queue.
3727 ATExecDropColumn(Relation rel, const char *colName,
3728 DropBehavior behavior,
3729 bool recurse, bool recursing)
3732 Form_pg_attribute targetatt;
3735 ObjectAddress object;
3737 /* At top level, permission check was done in ATPrepCmd, else do it */
3739 ATSimplePermissions(rel, false);
3742 * get the number of the attribute
3744 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
3745 if (!HeapTupleIsValid(tuple))
3747 (errcode(ERRCODE_UNDEFINED_COLUMN),
3748 errmsg("column \"%s\" of relation \"%s\" does not exist",
3749 colName, RelationGetRelationName(rel))));
3750 targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
3752 attnum = targetatt->attnum;
3754 /* Can't drop a system attribute, except OID */
3755 if (attnum <= 0 && attnum != ObjectIdAttributeNumber)
3757 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3758 errmsg("cannot drop system column \"%s\"",
3761 /* Don't drop inherited columns */
3762 if (targetatt->attinhcount > 0 && !recursing)
3764 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3765 errmsg("cannot drop inherited column \"%s\"",
3768 ReleaseSysCache(tuple);
3771 * Propagate to children as appropriate. Unlike most other ALTER
3772 * routines, we have to do this one level of recursion at a time; we can't
3773 * use find_all_inheritors to do it in one pass.
3775 children = find_inheritance_children(RelationGetRelid(rel));
3782 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3783 foreach(child, children)
3785 Oid childrelid = lfirst_oid(child);
3787 Form_pg_attribute childatt;
3789 childrel = heap_open(childrelid, AccessExclusiveLock);
3790 CheckTableNotInUse(childrel, "ALTER TABLE");
3792 tuple = SearchSysCacheCopyAttName(childrelid, colName);
3793 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
3794 elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
3795 colName, childrelid);
3796 childatt = (Form_pg_attribute) GETSTRUCT(tuple);
3798 if (childatt->attinhcount <= 0) /* shouldn't happen */
3799 elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
3800 childrelid, colName);
3805 * If the child column has other definition sources, just
3806 * decrement its inheritance count; if not, recurse to delete
3809 if (childatt->attinhcount == 1 && !childatt->attislocal)
3811 /* Time to delete this child column, too */
3812 ATExecDropColumn(childrel, colName, behavior, true, true);
3816 /* Child column must survive my deletion */
3817 childatt->attinhcount--;
3819 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3821 /* keep the system catalog indexes current */
3822 CatalogUpdateIndexes(attr_rel, tuple);
3824 /* Make update visible */
3825 CommandCounterIncrement();
3831 * If we were told to drop ONLY in this table (no recursion),
3832 * we need to mark the inheritors' attribute as locally
3833 * defined rather than inherited.
3835 childatt->attinhcount--;
3836 childatt->attislocal = true;
3838 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3840 /* keep the system catalog indexes current */
3841 CatalogUpdateIndexes(attr_rel, tuple);
3843 /* Make update visible */
3844 CommandCounterIncrement();
3847 heap_freetuple(tuple);
3849 heap_close(childrel, NoLock);
3851 heap_close(attr_rel, RowExclusiveLock);
3855 * Perform the actual column deletion
3857 object.classId = RelationRelationId;
3858 object.objectId = RelationGetRelid(rel);
3859 object.objectSubId = attnum;
3861 performDeletion(&object, behavior);
3864 * If we dropped the OID column, must adjust pg_class.relhasoids
3866 if (attnum == ObjectIdAttributeNumber)
3869 Form_pg_class tuple_class;
3871 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
3873 tuple = SearchSysCacheCopy(RELOID,
3874 ObjectIdGetDatum(RelationGetRelid(rel)),
3876 if (!HeapTupleIsValid(tuple))
3877 elog(ERROR, "cache lookup failed for relation %u",
3878 RelationGetRelid(rel));
3879 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
3881 tuple_class->relhasoids = false;
3882 simple_heap_update(class_rel, &tuple->t_self, tuple);
3884 /* Keep the catalog indexes up to date */
3885 CatalogUpdateIndexes(class_rel, tuple);
3887 heap_close(class_rel, RowExclusiveLock);
3892 * ALTER TABLE ADD INDEX
3894 * There is no such command in the grammar, but parse_utilcmd.c converts
3895 * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands. This lets
3896 * us schedule creation of the index at the appropriate time during ALTER.
3899 ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
3900 IndexStmt *stmt, bool is_rebuild)
3906 Assert(IsA(stmt, IndexStmt));
3908 /* suppress schema rights check when rebuilding existing index */
3909 check_rights = !is_rebuild;
3910 /* skip index build if phase 3 will have to rewrite table anyway */
3911 skip_build = (tab->newvals != NIL);
3912 /* suppress notices when rebuilding existing index */
3915 /* The IndexStmt has already been through transformIndexStmt */
3917 DefineIndex(stmt->relation, /* relation */
3918 stmt->idxname, /* index name */
3919 InvalidOid, /* no predefined OID */
3920 stmt->accessMethod, /* am name */
3922 stmt->indexParams, /* parameters */
3923 (Expr *) stmt->whereClause,
3928 true, /* is_alter_table */
3936 * ALTER TABLE ADD CONSTRAINT
3939 ATExecAddConstraint(AlteredTableInfo *tab, Relation rel, Node *newConstraint)
3941 switch (nodeTag(newConstraint))
3945 Constraint *constr = (Constraint *) newConstraint;
3948 * Currently, we only expect to see CONSTR_CHECK nodes
3949 * arriving here (see the preprocessing done in
3950 * parse_utilcmd.c). Use a switch anyway to make it easier to
3951 * add more code later.
3953 switch (constr->contype)
3961 * Call AddRelationRawConstraints to do the work.
3962 * It returns a list of cooked constraints.
3964 newcons = AddRelationRawConstraints(rel, NIL,
3965 list_make1(constr));
3966 /* Add each constraint to Phase 3's queue */
3967 foreach(lcon, newcons)
3969 CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
3970 NewConstraint *newcon;
3972 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
3973 newcon->name = ccon->name;
3974 newcon->contype = ccon->contype;
3975 /* ExecQual wants implicit-AND format */
3976 newcon->qual = (Node *)
3977 make_ands_implicit((Expr *) ccon->expr);
3979 tab->constraints = lappend(tab->constraints,
3985 elog(ERROR, "unrecognized constraint type: %d",
3986 (int) constr->contype);
3990 case T_FkConstraint:
3992 FkConstraint *fkconstraint = (FkConstraint *) newConstraint;
3995 * Assign or validate constraint name
3997 if (fkconstraint->constr_name)
3999 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
4000 RelationGetRelid(rel),
4001 RelationGetNamespace(rel),
4002 fkconstraint->constr_name))
4004 (errcode(ERRCODE_DUPLICATE_OBJECT),
4005 errmsg("constraint \"%s\" for relation \"%s\" already exists",
4006 fkconstraint->constr_name,
4007 RelationGetRelationName(rel))));
4010 fkconstraint->constr_name =
4011 ChooseConstraintName(RelationGetRelationName(rel),
4012 strVal(linitial(fkconstraint->fk_attrs)),
4014 RelationGetNamespace(rel),
4017 ATAddForeignKeyConstraint(tab, rel, fkconstraint);
4022 elog(ERROR, "unrecognized node type: %d",
4023 (int) nodeTag(newConstraint));
4028 * Add a foreign-key constraint to a single table
4030 * Subroutine for ATExecAddConstraint. Must already hold exclusive
4031 * lock on the rel, and have done appropriate validity/permissions checks
4035 ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
4036 FkConstraint *fkconstraint)
4039 AclResult aclresult;
4040 int16 pkattnum[INDEX_MAX_KEYS];
4041 int16 fkattnum[INDEX_MAX_KEYS];
4042 Oid pktypoid[INDEX_MAX_KEYS];
4043 Oid fktypoid[INDEX_MAX_KEYS];
4044 Oid opclasses[INDEX_MAX_KEYS];
4045 Oid pfeqoperators[INDEX_MAX_KEYS];
4046 Oid ppeqoperators[INDEX_MAX_KEYS];
4047 Oid ffeqoperators[INDEX_MAX_KEYS];
4055 * Grab an exclusive lock on the pk table, so that someone doesn't delete
4056 * rows out from under us. (Although a lesser lock would do for that
4057 * purpose, we'll need exclusive lock anyway to add triggers to the pk
4058 * table; trying to start with a lesser lock will just create a risk of
4061 pkrel = heap_openrv(fkconstraint->pktable, AccessExclusiveLock);
4064 * Validity and permissions checks
4066 * Note: REFERENCES permissions checks are redundant with CREATE TRIGGER,
4067 * but we may as well error out sooner instead of later.
4069 if (pkrel->rd_rel->relkind != RELKIND_RELATION)
4071 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4072 errmsg("referenced relation \"%s\" is not a table",
4073 RelationGetRelationName(pkrel))));
4075 aclresult = pg_class_aclcheck(RelationGetRelid(pkrel), GetUserId(),
4077 if (aclresult != ACLCHECK_OK)
4078 aclcheck_error(aclresult, ACL_KIND_CLASS,
4079 RelationGetRelationName(pkrel));
4081 if (!allowSystemTableMods && IsSystemRelation(pkrel))
4083 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4084 errmsg("permission denied: \"%s\" is a system catalog",
4085 RelationGetRelationName(pkrel))));
4087 aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
4089 if (aclresult != ACLCHECK_OK)
4090 aclcheck_error(aclresult, ACL_KIND_CLASS,
4091 RelationGetRelationName(rel));
4094 * Disallow reference from permanent table to temp table or vice versa.
4095 * (The ban on perm->temp is for fairly obvious reasons. The ban on
4096 * temp->perm is because other backends might need to run the RI triggers
4097 * on the perm table, but they can't reliably see tuples the owning
4098 * backend has created in the temp table, because non-shared buffers are
4099 * used for temp tables.)
4101 if (isTempNamespace(RelationGetNamespace(pkrel)))
4103 if (!isTempNamespace(RelationGetNamespace(rel)))
4105 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4106 errmsg("cannot reference temporary table from permanent table constraint")));
4110 if (isTempNamespace(RelationGetNamespace(rel)))
4112 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4113 errmsg("cannot reference permanent table from temporary table constraint")));
4117 * Look up the referencing attributes to make sure they exist, and record
4118 * their attnums and type OIDs.
4120 MemSet(pkattnum, 0, sizeof(pkattnum));
4121 MemSet(fkattnum, 0, sizeof(fkattnum));
4122 MemSet(pktypoid, 0, sizeof(pktypoid));
4123 MemSet(fktypoid, 0, sizeof(fktypoid));
4124 MemSet(opclasses, 0, sizeof(opclasses));
4125 MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
4126 MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
4127 MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
4129 numfks = transformColumnNameList(RelationGetRelid(rel),
4130 fkconstraint->fk_attrs,
4131 fkattnum, fktypoid);
4134 * If the attribute list for the referenced table was omitted, lookup the
4135 * definition of the primary key and use it. Otherwise, validate the
4136 * supplied attribute list. In either case, discover the index OID and
4137 * index opclasses, and the attnums and type OIDs of the attributes.
4139 if (fkconstraint->pk_attrs == NIL)
4141 numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
4142 &fkconstraint->pk_attrs,
4148 numpks = transformColumnNameList(RelationGetRelid(pkrel),
4149 fkconstraint->pk_attrs,
4150 pkattnum, pktypoid);
4151 /* Look for an index matching the column list */
4152 indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
4157 * Look up the equality operators to use in the constraint.
4159 * Note that we have to be careful about the difference between the actual
4160 * PK column type and the opclass' declared input type, which might be
4161 * only binary-compatible with it. The declared opcintype is the right
4162 * thing to probe pg_amop with.
4164 if (numfks != numpks)
4166 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4167 errmsg("number of referencing and referenced columns for foreign key disagree")));
4169 for (i = 0; i < numpks; i++)
4171 Oid pktype = pktypoid[i];
4172 Oid fktype = fktypoid[i];
4175 Form_pg_opclass cla_tup;
4184 /* We need several fields out of the pg_opclass entry */
4185 cla_ht = SearchSysCache(CLAOID,
4186 ObjectIdGetDatum(opclasses[i]),
4188 if (!HeapTupleIsValid(cla_ht))
4189 elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
4190 cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
4191 amid = cla_tup->opcmethod;
4192 opfamily = cla_tup->opcfamily;
4193 opcintype = cla_tup->opcintype;
4194 ReleaseSysCache(cla_ht);
4197 * Check it's a btree; currently this can never fail since no other
4198 * index AMs support unique indexes. If we ever did have other types
4199 * of unique indexes, we'd need a way to determine which operator
4200 * strategy number is equality. (Is it reasonable to insist that
4201 * every such index AM use btree's number for equality?)
4203 if (amid != BTREE_AM_OID)
4204 elog(ERROR, "only b-tree indexes are supported for foreign keys");
4205 eqstrategy = BTEqualStrategyNumber;
4208 * There had better be a primary equality operator for the index.
4209 * We'll use it for PK = PK comparisons.
4211 ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
4214 if (!OidIsValid(ppeqop))
4215 elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
4216 eqstrategy, opcintype, opcintype, opfamily);
4219 * Are there equality operators that take exactly the FK type? Assume
4220 * we should look through any domain here.
4222 fktyped = getBaseType(fktype);
4224 pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
4226 if (OidIsValid(pfeqop))
4227 ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
4230 ffeqop = InvalidOid; /* keep compiler quiet */
4232 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4235 * Otherwise, look for an implicit cast from the FK type to the
4236 * opcintype, and if found, use the primary equality operator.
4237 * This is a bit tricky because opcintype might be a generic type
4238 * such as ANYARRAY, and so what we have to test is whether the
4239 * two actual column types can be concurrently cast to that type.
4240 * (Otherwise, we'd fail to reject combinations such as int[] and
4243 Oid input_typeids[2];
4244 Oid target_typeids[2];
4246 input_typeids[0] = pktype;
4247 input_typeids[1] = fktype;
4248 target_typeids[0] = opcintype;
4249 target_typeids[1] = opcintype;
4250 if (can_coerce_type(2, input_typeids, target_typeids,
4252 pfeqop = ffeqop = ppeqop;
4255 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4257 (errcode(ERRCODE_DATATYPE_MISMATCH),
4258 errmsg("foreign key constraint \"%s\" "
4259 "cannot be implemented",
4260 fkconstraint->constr_name),
4261 errdetail("Key columns \"%s\" and \"%s\" "
4262 "are of incompatible types: %s and %s.",
4263 strVal(list_nth(fkconstraint->fk_attrs, i)),
4264 strVal(list_nth(fkconstraint->pk_attrs, i)),
4265 format_type_be(fktype),
4266 format_type_be(pktype))));
4268 pfeqoperators[i] = pfeqop;
4269 ppeqoperators[i] = ppeqop;
4270 ffeqoperators[i] = ffeqop;
4274 * Record the FK constraint in pg_constraint.
4276 constrOid = CreateConstraintEntry(fkconstraint->constr_name,
4277 RelationGetNamespace(rel),
4279 fkconstraint->deferrable,
4280 fkconstraint->initdeferred,
4281 RelationGetRelid(rel),
4284 InvalidOid, /* not a domain
4286 RelationGetRelid(pkrel),
4292 fkconstraint->fk_upd_action,
4293 fkconstraint->fk_del_action,
4294 fkconstraint->fk_matchtype,
4296 NULL, /* no check constraint */
4301 * Create the triggers that will enforce the constraint.
4303 createForeignKeyTriggers(rel, fkconstraint, constrOid);
4306 * Tell Phase 3 to check that the constraint is satisfied by existing rows
4307 * (we can skip this during table creation).
4309 if (!fkconstraint->skip_validation)
4311 NewConstraint *newcon;
4313 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
4314 newcon->name = fkconstraint->constr_name;
4315 newcon->contype = CONSTR_FOREIGN;
4316 newcon->refrelid = RelationGetRelid(pkrel);
4317 newcon->conid = constrOid;
4318 newcon->qual = (Node *) fkconstraint;
4320 tab->constraints = lappend(tab->constraints, newcon);
4324 * Close pk table, but keep lock until we've committed.
4326 heap_close(pkrel, NoLock);
4331 * transformColumnNameList - transform list of column names
4333 * Lookup each name and return its attnum and type OID
4336 transformColumnNameList(Oid relId, List *colList,
4337 int16 *attnums, Oid *atttypids)
4345 char *attname = strVal(lfirst(l));
4348 atttuple = SearchSysCacheAttName(relId, attname);
4349 if (!HeapTupleIsValid(atttuple))
4351 (errcode(ERRCODE_UNDEFINED_COLUMN),
4352 errmsg("column \"%s\" referenced in foreign key constraint does not exist",
4354 if (attnum >= INDEX_MAX_KEYS)
4356 (errcode(ERRCODE_TOO_MANY_COLUMNS),
4357 errmsg("cannot have more than %d keys in a foreign key",
4359 attnums[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->attnum;
4360 atttypids[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->atttypid;
4361 ReleaseSysCache(atttuple);
4369 * transformFkeyGetPrimaryKey -
4371 * Look up the names, attnums, and types of the primary key attributes
4372 * for the pkrel. Also return the index OID and index opclasses of the
4373 * index supporting the primary key.
4375 * All parameters except pkrel are output parameters. Also, the function
4376 * return value is the number of attributes in the primary key.
4378 * Used when the column list in the REFERENCES specification is omitted.
4381 transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
4383 int16 *attnums, Oid *atttypids,
4387 ListCell *indexoidscan;
4388 HeapTuple indexTuple = NULL;
4389 Form_pg_index indexStruct = NULL;
4390 Datum indclassDatum;
4392 oidvector *indclass;
4396 * Get the list of index OIDs for the table from the relcache, and look up
4397 * each one in the pg_index syscache until we find one marked primary key
4398 * (hopefully there isn't more than one such).
4400 *indexOid = InvalidOid;
4402 indexoidlist = RelationGetIndexList(pkrel);
4404 foreach(indexoidscan, indexoidlist)
4406 Oid indexoid = lfirst_oid(indexoidscan);
4408 indexTuple = SearchSysCache(INDEXRELID,
4409 ObjectIdGetDatum(indexoid),
4411 if (!HeapTupleIsValid(indexTuple))
4412 elog(ERROR, "cache lookup failed for index %u", indexoid);
4413 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4414 if (indexStruct->indisprimary)
4416 *indexOid = indexoid;
4419 ReleaseSysCache(indexTuple);
4422 list_free(indexoidlist);
4425 * Check that we found it
4427 if (!OidIsValid(*indexOid))
4429 (errcode(ERRCODE_UNDEFINED_OBJECT),
4430 errmsg("there is no primary key for referenced table \"%s\"",
4431 RelationGetRelationName(pkrel))));
4433 /* Must get indclass the hard way */
4434 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4435 Anum_pg_index_indclass, &isnull);
4437 indclass = (oidvector *) DatumGetPointer(indclassDatum);
4440 * Now build the list of PK attributes from the indkey definition (we
4441 * assume a primary key cannot have expressional elements)
4444 for (i = 0; i < indexStruct->indnatts; i++)
4446 int pkattno = indexStruct->indkey.values[i];
4448 attnums[i] = pkattno;
4449 atttypids[i] = attnumTypeId(pkrel, pkattno);
4450 opclasses[i] = indclass->values[i];
4451 *attnamelist = lappend(*attnamelist,
4452 makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
4455 ReleaseSysCache(indexTuple);
4461 * transformFkeyCheckAttrs -
4463 * Make sure that the attributes of a referenced table belong to a unique
4464 * (or primary key) constraint. Return the OID of the index supporting
4465 * the constraint, as well as the opclasses associated with the index
4469 transformFkeyCheckAttrs(Relation pkrel,
4470 int numattrs, int16 *attnums,
4471 Oid *opclasses) /* output parameter */
4473 Oid indexoid = InvalidOid;
4476 ListCell *indexoidscan;
4479 * Get the list of index OIDs for the table from the relcache, and look up
4480 * each one in the pg_index syscache, and match unique indexes to the list
4481 * of attnums we are given.
4483 indexoidlist = RelationGetIndexList(pkrel);
4485 foreach(indexoidscan, indexoidlist)
4487 HeapTuple indexTuple;
4488 Form_pg_index indexStruct;
4492 indexoid = lfirst_oid(indexoidscan);
4493 indexTuple = SearchSysCache(INDEXRELID,
4494 ObjectIdGetDatum(indexoid),
4496 if (!HeapTupleIsValid(indexTuple))
4497 elog(ERROR, "cache lookup failed for index %u", indexoid);
4498 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4501 * Must have the right number of columns; must be unique and not a
4502 * partial index; forget it if there are any expressions, too
4504 if (indexStruct->indnatts == numattrs &&
4505 indexStruct->indisunique &&
4506 heap_attisnull(indexTuple, Anum_pg_index_indpred) &&
4507 heap_attisnull(indexTuple, Anum_pg_index_indexprs))
4509 /* Must get indclass the hard way */
4510 Datum indclassDatum;
4512 oidvector *indclass;
4514 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4515 Anum_pg_index_indclass, &isnull);
4517 indclass = (oidvector *) DatumGetPointer(indclassDatum);
4520 * The given attnum list may match the index columns in any order.
4521 * Check that each list is a subset of the other.
4523 for (i = 0; i < numattrs; i++)
4526 for (j = 0; j < numattrs; j++)
4528 if (attnums[i] == indexStruct->indkey.values[j])
4539 for (i = 0; i < numattrs; i++)
4542 for (j = 0; j < numattrs; j++)
4544 if (attnums[j] == indexStruct->indkey.values[i])
4546 opclasses[j] = indclass->values[i];
4556 ReleaseSysCache(indexTuple);
4563 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4564 errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
4565 RelationGetRelationName(pkrel))));
4567 list_free(indexoidlist);
4573 * Scan the existing rows in a table to verify they meet a proposed FK
4576 * Caller must have opened and locked both relations.
4579 validateForeignKeyConstraint(FkConstraint *fkconstraint,
4589 * Build a trigger call structure; we'll need it either way.
4591 MemSet(&trig, 0, sizeof(trig));
4592 trig.tgoid = InvalidOid;
4593 trig.tgname = fkconstraint->constr_name;
4594 trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
4595 trig.tgisconstraint = TRUE;
4596 trig.tgconstrrelid = RelationGetRelid(pkrel);
4597 trig.tgconstraint = constraintOid;
4598 trig.tgdeferrable = FALSE;
4599 trig.tginitdeferred = FALSE;
4600 /* we needn't fill in tgargs */
4603 * See if we can do it with a single LEFT JOIN query. A FALSE result
4604 * indicates we must proceed with the fire-the-trigger method.
4606 if (RI_Initial_Check(&trig, rel, pkrel))
4610 * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
4611 * if that tuple had just been inserted. If any of those fail, it should
4612 * ereport(ERROR) and that's that.
4614 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
4616 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
4618 FunctionCallInfoData fcinfo;
4619 TriggerData trigdata;
4622 * Make a call to the trigger function
4624 * No parameters are passed, but we do set a context
4626 MemSet(&fcinfo, 0, sizeof(fcinfo));
4629 * We assume RI_FKey_check_ins won't look at flinfo...
4631 trigdata.type = T_TriggerData;
4632 trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
4633 trigdata.tg_relation = rel;
4634 trigdata.tg_trigtuple = tuple;
4635 trigdata.tg_newtuple = NULL;
4636 trigdata.tg_trigger = &trig;
4637 trigdata.tg_trigtuplebuf = scan->rs_cbuf;
4638 trigdata.tg_newtuplebuf = InvalidBuffer;
4640 fcinfo.context = (Node *) &trigdata;
4642 RI_FKey_check_ins(&fcinfo);
4649 CreateFKCheckTrigger(RangeVar *myRel, FkConstraint *fkconstraint,
4650 Oid constraintOid, bool on_insert)
4652 CreateTrigStmt *fk_trigger;
4654 fk_trigger = makeNode(CreateTrigStmt);
4655 fk_trigger->trigname = fkconstraint->constr_name;
4656 fk_trigger->relation = myRel;
4657 fk_trigger->before = false;
4658 fk_trigger->row = true;
4660 /* Either ON INSERT or ON UPDATE */
4663 fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
4664 fk_trigger->actions[0] = 'i';
4668 fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
4669 fk_trigger->actions[0] = 'u';
4671 fk_trigger->actions[1] = '\0';
4673 fk_trigger->isconstraint = true;
4674 fk_trigger->deferrable = fkconstraint->deferrable;
4675 fk_trigger->initdeferred = fkconstraint->initdeferred;
4676 fk_trigger->constrrel = fkconstraint->pktable;
4677 fk_trigger->args = NIL;
4679 (void) CreateTrigger(fk_trigger, constraintOid);
4681 /* Make changes-so-far visible */
4682 CommandCounterIncrement();
4686 * Create the triggers that implement an FK constraint.
4689 createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
4693 CreateTrigStmt *fk_trigger;
4696 * Reconstruct a RangeVar for my relation (not passed in, unfortunately).
4698 myRel = makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
4699 pstrdup(RelationGetRelationName(rel)));
4701 /* Make changes-so-far visible */
4702 CommandCounterIncrement();
4705 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the CHECK
4706 * action for both INSERTs and UPDATEs on the referencing table.
4708 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, true);
4709 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, false);
4712 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
4713 * DELETE action on the referenced table.
4715 fk_trigger = makeNode(CreateTrigStmt);
4716 fk_trigger->trigname = fkconstraint->constr_name;
4717 fk_trigger->relation = fkconstraint->pktable;
4718 fk_trigger->before = false;
4719 fk_trigger->row = true;
4720 fk_trigger->actions[0] = 'd';
4721 fk_trigger->actions[1] = '\0';
4723 fk_trigger->isconstraint = true;
4724 fk_trigger->constrrel = myRel;
4725 switch (fkconstraint->fk_del_action)
4727 case FKCONSTR_ACTION_NOACTION:
4728 fk_trigger->deferrable = fkconstraint->deferrable;
4729 fk_trigger->initdeferred = fkconstraint->initdeferred;
4730 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
4732 case FKCONSTR_ACTION_RESTRICT:
4733 fk_trigger->deferrable = false;
4734 fk_trigger->initdeferred = false;
4735 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
4737 case FKCONSTR_ACTION_CASCADE:
4738 fk_trigger->deferrable = false;
4739 fk_trigger->initdeferred = false;
4740 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
4742 case FKCONSTR_ACTION_SETNULL:
4743 fk_trigger->deferrable = false;
4744 fk_trigger->initdeferred = false;
4745 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
4747 case FKCONSTR_ACTION_SETDEFAULT:
4748 fk_trigger->deferrable = false;
4749 fk_trigger->initdeferred = false;
4750 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
4753 elog(ERROR, "unrecognized FK action type: %d",
4754 (int) fkconstraint->fk_del_action);
4757 fk_trigger->args = NIL;
4759 (void) CreateTrigger(fk_trigger, constraintOid);
4761 /* Make changes-so-far visible */
4762 CommandCounterIncrement();
4765 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
4766 * UPDATE action on the referenced table.
4768 fk_trigger = makeNode(CreateTrigStmt);
4769 fk_trigger->trigname = fkconstraint->constr_name;
4770 fk_trigger->relation = fkconstraint->pktable;
4771 fk_trigger->before = false;
4772 fk_trigger->row = true;
4773 fk_trigger->actions[0] = 'u';
4774 fk_trigger->actions[1] = '\0';
4775 fk_trigger->isconstraint = true;
4776 fk_trigger->constrrel = myRel;
4777 switch (fkconstraint->fk_upd_action)
4779 case FKCONSTR_ACTION_NOACTION:
4780 fk_trigger->deferrable = fkconstraint->deferrable;
4781 fk_trigger->initdeferred = fkconstraint->initdeferred;
4782 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
4784 case FKCONSTR_ACTION_RESTRICT:
4785 fk_trigger->deferrable = false;
4786 fk_trigger->initdeferred = false;
4787 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
4789 case FKCONSTR_ACTION_CASCADE:
4790 fk_trigger->deferrable = false;
4791 fk_trigger->initdeferred = false;
4792 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
4794 case FKCONSTR_ACTION_SETNULL:
4795 fk_trigger->deferrable = false;
4796 fk_trigger->initdeferred = false;
4797 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
4799 case FKCONSTR_ACTION_SETDEFAULT:
4800 fk_trigger->deferrable = false;
4801 fk_trigger->initdeferred = false;
4802 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
4805 elog(ERROR, "unrecognized FK action type: %d",
4806 (int) fkconstraint->fk_upd_action);
4809 fk_trigger->args = NIL;
4811 (void) CreateTrigger(fk_trigger, constraintOid);
4815 * ALTER TABLE DROP CONSTRAINT
4818 ATPrepDropConstraint(List **wqueue, Relation rel,
4819 bool recurse, AlterTableCmd *cmd)
4822 * We don't want errors or noise from child tables, so we have to pass
4823 * down a modified command.
4827 AlterTableCmd *childCmd = copyObject(cmd);
4829 childCmd->subtype = AT_DropConstraintQuietly;
4830 ATSimpleRecursion(wqueue, rel, childCmd, recurse);
4835 ATExecDropConstraint(Relation rel, const char *constrName,
4836 DropBehavior behavior, bool quiet)
4840 deleted = RemoveRelConstraints(rel, constrName, behavior);
4844 /* If zero constraints deleted, complain */
4847 (errcode(ERRCODE_UNDEFINED_OBJECT),
4848 errmsg("constraint \"%s\" does not exist",
4850 /* Otherwise if more than one constraint deleted, notify */
4851 else if (deleted > 1)
4853 (errmsg("multiple constraints named \"%s\" were dropped",
4862 ATPrepAlterColumnType(List **wqueue,
4863 AlteredTableInfo *tab, Relation rel,
4864 bool recurse, bool recursing,
4867 char *colName = cmd->name;
4868 TypeName *typename = (TypeName *) cmd->def;
4870 Form_pg_attribute attTup;
4875 NewColumnValue *newval;
4876 ParseState *pstate = make_parsestate(NULL);
4878 /* lookup the attribute so we can check inheritance status */
4879 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
4880 if (!HeapTupleIsValid(tuple))
4882 (errcode(ERRCODE_UNDEFINED_COLUMN),
4883 errmsg("column \"%s\" of relation \"%s\" does not exist",
4884 colName, RelationGetRelationName(rel))));
4885 attTup = (Form_pg_attribute) GETSTRUCT(tuple);
4886 attnum = attTup->attnum;
4888 /* Can't alter a system attribute */
4891 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4892 errmsg("cannot alter system column \"%s\"",
4895 /* Don't alter inherited columns */
4896 if (attTup->attinhcount > 0 && !recursing)
4898 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4899 errmsg("cannot alter inherited column \"%s\"",
4902 /* Look up the target type */
4903 targettype = typenameTypeId(NULL, typename, &targettypmod);
4905 /* make sure datatype is legal for a column */
4906 CheckAttributeType(colName, targettype);
4909 * Set up an expression to transform the old data value to the new type.
4910 * If a USING option was given, transform and use that expression, else
4911 * just take the old value and try to coerce it. We do this first so that
4912 * type incompatibility can be detected before we waste effort, and
4913 * because we need the expression to be parsed against the original table
4920 /* Expression must be able to access vars of old table */
4921 rte = addRangeTableEntryForRelation(pstate,
4926 addRTEtoQuery(pstate, rte, false, true, true);
4928 transform = transformExpr(pstate, cmd->transform);
4930 /* It can't return a set */
4931 if (expression_returns_set(transform))
4933 (errcode(ERRCODE_DATATYPE_MISMATCH),
4934 errmsg("transform expression must not return a set")));
4936 /* No subplans or aggregates, either... */
4937 if (pstate->p_hasSubLinks)
4939 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4940 errmsg("cannot use subquery in transform expression")));
4941 if (pstate->p_hasAggs)
4943 (errcode(ERRCODE_GROUPING_ERROR),
4944 errmsg("cannot use aggregate function in transform expression")));
4948 transform = (Node *) makeVar(1, attnum,
4949 attTup->atttypid, attTup->atttypmod,
4953 transform = coerce_to_target_type(pstate,
4954 transform, exprType(transform),
4955 targettype, targettypmod,
4956 COERCION_ASSIGNMENT,
4957 COERCE_IMPLICIT_CAST);
4958 if (transform == NULL)
4960 (errcode(ERRCODE_DATATYPE_MISMATCH),
4961 errmsg("column \"%s\" cannot be cast to type \"%s\"",
4962 colName, TypeNameToString(typename))));
4965 * Add a work queue item to make ATRewriteTable update the column
4968 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
4969 newval->attnum = attnum;
4970 newval->expr = (Expr *) transform;
4972 tab->newvals = lappend(tab->newvals, newval);
4974 ReleaseSysCache(tuple);
4977 * The recursion case is handled by ATSimpleRecursion. However, if we are
4978 * told not to recurse, there had better not be any child tables; else the
4979 * alter would put them out of step.
4982 ATSimpleRecursion(wqueue, rel, cmd, recurse);
4983 else if (!recursing &&
4984 find_inheritance_children(RelationGetRelid(rel)) != NIL)
4986 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4987 errmsg("type of inherited column \"%s\" must be changed in child tables too",
4992 ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
4993 const char *colName, TypeName *typename)
4996 Form_pg_attribute attTup;
4998 HeapTuple typeTuple;
5003 Relation attrelation;
5009 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
5011 /* Look up the target column */
5012 heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5013 if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
5015 (errcode(ERRCODE_UNDEFINED_COLUMN),
5016 errmsg("column \"%s\" of relation \"%s\" does not exist",
5017 colName, RelationGetRelationName(rel))));
5018 attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
5019 attnum = attTup->attnum;
5021 /* Check for multiple ALTER TYPE on same column --- can't cope */
5022 if (attTup->atttypid != tab->oldDesc->attrs[attnum - 1]->atttypid ||
5023 attTup->atttypmod != tab->oldDesc->attrs[attnum - 1]->atttypmod)
5025 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5026 errmsg("cannot alter type of column \"%s\" twice",
5029 /* Look up the target type (should not fail, since prep found it) */
5030 typeTuple = typenameType(NULL, typename, &targettypmod);
5031 tform = (Form_pg_type) GETSTRUCT(typeTuple);
5032 targettype = HeapTupleGetOid(typeTuple);
5035 * If there is a default expression for the column, get it and ensure we
5036 * can coerce it to the new datatype. (We must do this before changing
5037 * the column type, because build_column_default itself will try to
5038 * coerce, and will not issue the error message we want if it fails.)
5040 * We remove any implicit coercion steps at the top level of the old
5041 * default expression; this has been agreed to satisfy the principle of
5042 * least surprise. (The conversion to the new column type should act like
5043 * it started from what the user sees as the stored expression, and the
5044 * implicit coercions aren't going to be shown.)
5046 if (attTup->atthasdef)
5048 defaultexpr = build_column_default(rel, attnum);
5049 Assert(defaultexpr);
5050 defaultexpr = strip_implicit_coercions(defaultexpr);
5051 defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
5052 defaultexpr, exprType(defaultexpr),
5053 targettype, targettypmod,
5054 COERCION_ASSIGNMENT,
5055 COERCE_IMPLICIT_CAST);
5056 if (defaultexpr == NULL)
5058 (errcode(ERRCODE_DATATYPE_MISMATCH),
5059 errmsg("default for column \"%s\" cannot be cast to type \"%s\"",
5060 colName, TypeNameToString(typename))));
5066 * Find everything that depends on the column (constraints, indexes, etc),
5067 * and record enough information to let us recreate the objects.
5069 * The actual recreation does not happen here, but only after we have
5070 * performed all the individual ALTER TYPE operations. We have to save
5071 * the info before executing ALTER TYPE, though, else the deparser will
5074 * There could be multiple entries for the same object, so we must check
5075 * to ensure we process each one only once. Note: we assume that an index
5076 * that implements a constraint will not show a direct dependency on the
5079 depRel = heap_open(DependRelationId, RowExclusiveLock);
5081 ScanKeyInit(&key[0],
5082 Anum_pg_depend_refclassid,
5083 BTEqualStrategyNumber, F_OIDEQ,
5084 ObjectIdGetDatum(RelationRelationId));
5085 ScanKeyInit(&key[1],
5086 Anum_pg_depend_refobjid,
5087 BTEqualStrategyNumber, F_OIDEQ,
5088 ObjectIdGetDatum(RelationGetRelid(rel)));
5089 ScanKeyInit(&key[2],
5090 Anum_pg_depend_refobjsubid,
5091 BTEqualStrategyNumber, F_INT4EQ,
5092 Int32GetDatum((int32) attnum));
5094 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
5095 SnapshotNow, 3, key);
5097 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5099 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5100 ObjectAddress foundObject;
5102 /* We don't expect any PIN dependencies on columns */
5103 if (foundDep->deptype == DEPENDENCY_PIN)
5104 elog(ERROR, "cannot alter type of a pinned column");
5106 foundObject.classId = foundDep->classid;
5107 foundObject.objectId = foundDep->objid;
5108 foundObject.objectSubId = foundDep->objsubid;
5110 switch (getObjectClass(&foundObject))
5114 char relKind = get_rel_relkind(foundObject.objectId);
5116 if (relKind == RELKIND_INDEX)
5118 Assert(foundObject.objectSubId == 0);
5119 if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
5121 tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
5122 foundObject.objectId);
5123 tab->changedIndexDefs = lappend(tab->changedIndexDefs,
5124 pg_get_indexdef_string(foundObject.objectId));
5127 else if (relKind == RELKIND_SEQUENCE)
5130 * This must be a SERIAL column's sequence. We need
5131 * not do anything to it.
5133 Assert(foundObject.objectSubId == 0);
5137 /* Not expecting any other direct dependencies... */
5138 elog(ERROR, "unexpected object depending on column: %s",
5139 getObjectDescription(&foundObject));
5144 case OCLASS_CONSTRAINT:
5145 Assert(foundObject.objectSubId == 0);
5146 if (!list_member_oid(tab->changedConstraintOids,
5147 foundObject.objectId))
5149 char *defstring = pg_get_constraintdef_string(foundObject.objectId);
5152 * Put NORMAL dependencies at the front of the list and
5153 * AUTO dependencies at the back. This makes sure that
5154 * foreign-key constraints depending on this column will
5155 * be dropped before unique or primary-key constraints of
5156 * the column; which we must have because the FK
5157 * constraints depend on the indexes belonging to the
5158 * unique constraints.
5160 if (foundDep->deptype == DEPENDENCY_NORMAL)
5162 tab->changedConstraintOids =
5163 lcons_oid(foundObject.objectId,
5164 tab->changedConstraintOids);
5165 tab->changedConstraintDefs =
5167 tab->changedConstraintDefs);
5171 tab->changedConstraintOids =
5172 lappend_oid(tab->changedConstraintOids,
5173 foundObject.objectId);
5174 tab->changedConstraintDefs =
5175 lappend(tab->changedConstraintDefs,
5181 case OCLASS_REWRITE:
5182 /* XXX someday see if we can cope with revising views */
5184 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5185 errmsg("cannot alter type of a column used by a view or rule"),
5186 errdetail("%s depends on column \"%s\"",
5187 getObjectDescription(&foundObject),
5191 case OCLASS_DEFAULT:
5194 * Ignore the column's default expression, since we will fix
5197 Assert(defaultexpr);
5203 case OCLASS_CONVERSION:
5204 case OCLASS_LANGUAGE:
5205 case OCLASS_OPERATOR:
5206 case OCLASS_OPCLASS:
5207 case OCLASS_OPFAMILY:
5208 case OCLASS_TRIGGER:
5210 case OCLASS_TSPARSER:
5212 case OCLASS_TSTEMPLATE:
5213 case OCLASS_TSCONFIG:
5216 * We don't expect any of these sorts of objects to depend on
5219 elog(ERROR, "unexpected object depending on column: %s",
5220 getObjectDescription(&foundObject));
5224 elog(ERROR, "unrecognized object class: %u",
5225 foundObject.classId);
5229 systable_endscan(scan);
5232 * Now scan for dependencies of this column on other things. The only
5233 * thing we should find is the dependency on the column datatype, which we
5236 ScanKeyInit(&key[0],
5237 Anum_pg_depend_classid,
5238 BTEqualStrategyNumber, F_OIDEQ,
5239 ObjectIdGetDatum(RelationRelationId));
5240 ScanKeyInit(&key[1],
5241 Anum_pg_depend_objid,
5242 BTEqualStrategyNumber, F_OIDEQ,
5243 ObjectIdGetDatum(RelationGetRelid(rel)));
5244 ScanKeyInit(&key[2],
5245 Anum_pg_depend_objsubid,
5246 BTEqualStrategyNumber, F_INT4EQ,
5247 Int32GetDatum((int32) attnum));
5249 scan = systable_beginscan(depRel, DependDependerIndexId, true,
5250 SnapshotNow, 3, key);
5252 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5254 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5256 if (foundDep->deptype != DEPENDENCY_NORMAL)
5257 elog(ERROR, "found unexpected dependency type '%c'",
5259 if (foundDep->refclassid != TypeRelationId ||
5260 foundDep->refobjid != attTup->atttypid)
5261 elog(ERROR, "found unexpected dependency for column");
5263 simple_heap_delete(depRel, &depTup->t_self);
5266 systable_endscan(scan);
5268 heap_close(depRel, RowExclusiveLock);
5271 * Here we go --- change the recorded column type. (Note heapTup is a
5272 * copy of the syscache entry, so okay to scribble on.)
5274 attTup->atttypid = targettype;
5275 attTup->atttypmod = targettypmod;
5276 attTup->attndims = list_length(typename->arrayBounds);
5277 attTup->attlen = tform->typlen;
5278 attTup->attbyval = tform->typbyval;
5279 attTup->attalign = tform->typalign;
5280 attTup->attstorage = tform->typstorage;
5282 ReleaseSysCache(typeTuple);
5284 simple_heap_update(attrelation, &heapTup->t_self, heapTup);
5286 /* keep system catalog indexes current */
5287 CatalogUpdateIndexes(attrelation, heapTup);
5289 heap_close(attrelation, RowExclusiveLock);
5291 /* Install dependency on new datatype */
5292 add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
5295 * Drop any pg_statistic entry for the column, since it's now wrong type
5297 RemoveStatistics(RelationGetRelid(rel), attnum);
5300 * Update the default, if present, by brute force --- remove and re-add
5301 * the default. Probably unsafe to take shortcuts, since the new version
5302 * may well have additional dependencies. (It's okay to do this now,
5303 * rather than after other ALTER TYPE commands, since the default won't
5304 * depend on other column types.)
5308 /* Must make new row visible since it will be updated again */
5309 CommandCounterIncrement();
5312 * We use RESTRICT here for safety, but at present we do not expect
5313 * anything to depend on the default.
5315 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true);
5317 StoreAttrDefault(rel, attnum, nodeToString(defaultexpr));
5321 heap_freetuple(heapTup);
5325 * Cleanup after we've finished all the ALTER TYPE operations for a
5326 * particular relation. We have to drop and recreate all the indexes
5327 * and constraints that depend on the altered columns.
5330 ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab)
5336 * Re-parse the index and constraint definitions, and attach them to the
5337 * appropriate work queue entries. We do this before dropping because in
5338 * the case of a FOREIGN KEY constraint, we might not yet have exclusive
5339 * lock on the table the constraint is attached to, and we need to get
5340 * that before dropping. It's safe because the parser won't actually look
5341 * at the catalogs to detect the existing entry.
5343 foreach(l, tab->changedIndexDefs)
5344 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
5345 foreach(l, tab->changedConstraintDefs)
5346 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
5349 * Now we can drop the existing constraints and indexes --- constraints
5350 * first, since some of them might depend on the indexes. In fact, we
5351 * have to delete FOREIGN KEY constraints before UNIQUE constraints, but
5352 * we already ordered the constraint list to ensure that would happen. It
5353 * should be okay to use DROP_RESTRICT here, since nothing else should be
5354 * depending on these objects.
5356 foreach(l, tab->changedConstraintOids)
5358 obj.classId = ConstraintRelationId;
5359 obj.objectId = lfirst_oid(l);
5360 obj.objectSubId = 0;
5361 performDeletion(&obj, DROP_RESTRICT);
5364 foreach(l, tab->changedIndexOids)
5366 obj.classId = RelationRelationId;
5367 obj.objectId = lfirst_oid(l);
5368 obj.objectSubId = 0;
5369 performDeletion(&obj, DROP_RESTRICT);
5373 * The objects will get recreated during subsequent passes over the work
5379 ATPostAlterTypeParse(char *cmd, List **wqueue)
5381 List *raw_parsetree_list;
5382 List *querytree_list;
5383 ListCell *list_item;
5386 * We expect that we will get only ALTER TABLE and CREATE INDEX
5387 * statements. Hence, there is no need to pass them through
5388 * parse_analyze() or the rewriter, but instead we need to pass them
5389 * through parse_utilcmd.c to make them ready for execution.
5391 raw_parsetree_list = raw_parser(cmd);
5392 querytree_list = NIL;
5393 foreach(list_item, raw_parsetree_list)
5395 Node *stmt = (Node *) lfirst(list_item);
5397 if (IsA(stmt, IndexStmt))
5398 querytree_list = lappend(querytree_list,
5399 transformIndexStmt((IndexStmt *) stmt,
5401 else if (IsA(stmt, AlterTableStmt))
5402 querytree_list = list_concat(querytree_list,
5403 transformAlterTableStmt((AlterTableStmt *) stmt,
5406 querytree_list = lappend(querytree_list, stmt);
5410 * Attach each generated command to the proper place in the work queue.
5411 * Note this could result in creation of entirely new work-queue entries.
5413 foreach(list_item, querytree_list)
5415 Node *stm = (Node *) lfirst(list_item);
5417 AlteredTableInfo *tab;
5419 switch (nodeTag(stm))
5423 IndexStmt *stmt = (IndexStmt *) stm;
5424 AlterTableCmd *newcmd;
5426 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
5427 tab = ATGetQueueEntry(wqueue, rel);
5428 newcmd = makeNode(AlterTableCmd);
5429 newcmd->subtype = AT_ReAddIndex;
5430 newcmd->def = (Node *) stmt;
5431 tab->subcmds[AT_PASS_OLD_INDEX] =
5432 lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
5433 relation_close(rel, NoLock);
5436 case T_AlterTableStmt:
5438 AlterTableStmt *stmt = (AlterTableStmt *) stm;
5441 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
5442 tab = ATGetQueueEntry(wqueue, rel);
5443 foreach(lcmd, stmt->cmds)
5445 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
5447 switch (cmd->subtype)
5450 cmd->subtype = AT_ReAddIndex;
5451 tab->subcmds[AT_PASS_OLD_INDEX] =
5452 lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
5454 case AT_AddConstraint:
5455 tab->subcmds[AT_PASS_OLD_CONSTR] =
5456 lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
5459 elog(ERROR, "unexpected statement type: %d",
5460 (int) cmd->subtype);
5463 relation_close(rel, NoLock);
5467 elog(ERROR, "unexpected statement type: %d",
5468 (int) nodeTag(stm));
5477 * recursing is true if we are recursing from a table to its indexes,
5478 * sequences, or toast table. We don't allow the ownership of those things to
5479 * be changed separately from the parent table. Also, we can skip permission
5480 * checks (this is necessary not just an optimization, else we'd fail to
5481 * handle toast tables properly).
5483 * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
5484 * free-standing composite type.
5487 ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing)
5489 Relation target_rel;
5492 Form_pg_class tuple_class;
5495 * Get exclusive lock till end of transaction on the target table. Use
5496 * relation_open so that we can work on indexes and sequences.
5498 target_rel = relation_open(relationOid, AccessExclusiveLock);
5500 /* Get its pg_class tuple, too */
5501 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
5503 tuple = SearchSysCache(RELOID,
5504 ObjectIdGetDatum(relationOid),
5506 if (!HeapTupleIsValid(tuple))
5507 elog(ERROR, "cache lookup failed for relation %u", relationOid);
5508 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
5510 /* Can we change the ownership of this tuple? */
5511 switch (tuple_class->relkind)
5513 case RELKIND_RELATION:
5515 /* ok to change owner */
5521 * Because ALTER INDEX OWNER used to be allowed, and in fact
5522 * is generated by old versions of pg_dump, we give a warning
5523 * and do nothing rather than erroring out. Also, to avoid
5524 * unnecessary chatter while restoring those old dumps, say
5525 * nothing at all if the command would be a no-op anyway.
5527 if (tuple_class->relowner != newOwnerId)
5529 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5530 errmsg("cannot change owner of index \"%s\"",
5531 NameStr(tuple_class->relname)),
5532 errhint("Change the ownership of the index's table, instead.")));
5533 /* quick hack to exit via the no-op path */
5534 newOwnerId = tuple_class->relowner;
5537 case RELKIND_SEQUENCE:
5539 tuple_class->relowner != newOwnerId)
5541 /* if it's an owned sequence, disallow changing it by itself */
5545 if (sequenceIsOwned(relationOid, &tableId, &colId))
5547 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5548 errmsg("cannot change owner of sequence \"%s\"",
5549 NameStr(tuple_class->relname)),
5550 errdetail("Sequence \"%s\" is linked to table \"%s\".",
5551 NameStr(tuple_class->relname),
5552 get_rel_name(tableId))));
5555 case RELKIND_COMPOSITE_TYPE:
5559 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5560 errmsg("\"%s\" is a composite type",
5561 NameStr(tuple_class->relname)),
5562 errhint("Use ALTER TYPE instead.")));
5564 case RELKIND_TOASTVALUE:
5570 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5571 errmsg("\"%s\" is not a table, view, or sequence",
5572 NameStr(tuple_class->relname))));
5576 * If the new owner is the same as the existing owner, consider the
5577 * command to have succeeded. This is for dump restoration purposes.
5579 if (tuple_class->relowner != newOwnerId)
5581 Datum repl_val[Natts_pg_class];
5582 char repl_null[Natts_pg_class];
5583 char repl_repl[Natts_pg_class];
5589 /* skip permission checks when recursing to index or toast table */
5592 /* Superusers can always do it */
5595 Oid namespaceOid = tuple_class->relnamespace;
5596 AclResult aclresult;
5598 /* Otherwise, must be owner of the existing object */
5599 if (!pg_class_ownercheck(relationOid, GetUserId()))
5600 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
5601 RelationGetRelationName(target_rel));
5603 /* Must be able to become new owner */
5604 check_is_member_of_role(GetUserId(), newOwnerId);
5606 /* New owner must have CREATE privilege on namespace */
5607 aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
5609 if (aclresult != ACLCHECK_OK)
5610 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
5611 get_namespace_name(namespaceOid));
5615 memset(repl_null, ' ', sizeof(repl_null));
5616 memset(repl_repl, ' ', sizeof(repl_repl));
5618 repl_repl[Anum_pg_class_relowner - 1] = 'r';
5619 repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
5622 * Determine the modified ACL for the new owner. This is only
5623 * necessary when the ACL is non-null.
5625 aclDatum = SysCacheGetAttr(RELOID, tuple,
5626 Anum_pg_class_relacl,
5630 newAcl = aclnewowner(DatumGetAclP(aclDatum),
5631 tuple_class->relowner, newOwnerId);
5632 repl_repl[Anum_pg_class_relacl - 1] = 'r';
5633 repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
5636 newtuple = heap_modifytuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
5638 simple_heap_update(class_rel, &newtuple->t_self, newtuple);
5639 CatalogUpdateIndexes(class_rel, newtuple);
5641 heap_freetuple(newtuple);
5644 * Update owner dependency reference, if any. A composite type has
5645 * none, because it's tracked for the pg_type entry instead of here;
5646 * indexes and TOAST tables don't have their own entries either.
5648 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
5649 tuple_class->relkind != RELKIND_INDEX &&
5650 tuple_class->relkind != RELKIND_TOASTVALUE)
5651 changeDependencyOnOwner(RelationRelationId, relationOid,
5655 * Also change the ownership of the table's rowtype, if it has one
5657 if (tuple_class->relkind != RELKIND_INDEX)
5658 AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId,
5659 tuple_class->relkind == RELKIND_COMPOSITE_TYPE);
5662 * If we are operating on a table, also change the ownership of any
5663 * indexes and sequences that belong to the table, as well as the
5664 * table's toast table (if it has one)
5666 if (tuple_class->relkind == RELKIND_RELATION ||
5667 tuple_class->relkind == RELKIND_TOASTVALUE)
5669 List *index_oid_list;
5672 /* Find all the indexes belonging to this relation */
5673 index_oid_list = RelationGetIndexList(target_rel);
5675 /* For each index, recursively change its ownership */
5676 foreach(i, index_oid_list)
5677 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true);
5679 list_free(index_oid_list);
5682 if (tuple_class->relkind == RELKIND_RELATION)
5684 /* If it has a toast table, recurse to change its ownership */
5685 if (tuple_class->reltoastrelid != InvalidOid)
5686 ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
5689 /* If it has dependent sequences, recurse to change them too */
5690 change_owner_recurse_to_sequences(relationOid, newOwnerId);
5694 ReleaseSysCache(tuple);
5695 heap_close(class_rel, RowExclusiveLock);
5696 relation_close(target_rel, NoLock);
5700 * change_owner_recurse_to_sequences
5702 * Helper function for ATExecChangeOwner. Examines pg_depend searching
5703 * for sequences that are dependent on serial columns, and changes their
5707 change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId)
5715 * SERIAL sequences are those having an auto dependency on one of the
5716 * table's columns (we don't care *which* column, exactly).
5718 depRel = heap_open(DependRelationId, AccessShareLock);
5720 ScanKeyInit(&key[0],
5721 Anum_pg_depend_refclassid,
5722 BTEqualStrategyNumber, F_OIDEQ,
5723 ObjectIdGetDatum(RelationRelationId));
5724 ScanKeyInit(&key[1],
5725 Anum_pg_depend_refobjid,
5726 BTEqualStrategyNumber, F_OIDEQ,
5727 ObjectIdGetDatum(relationOid));
5728 /* we leave refobjsubid unspecified */
5730 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
5731 SnapshotNow, 2, key);
5733 while (HeapTupleIsValid(tup = systable_getnext(scan)))
5735 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
5738 /* skip dependencies other than auto dependencies on columns */
5739 if (depForm->refobjsubid == 0 ||
5740 depForm->classid != RelationRelationId ||
5741 depForm->objsubid != 0 ||
5742 depForm->deptype != DEPENDENCY_AUTO)
5745 /* Use relation_open just in case it's an index */
5746 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
5748 /* skip non-sequence relations */
5749 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
5751 /* No need to keep the lock */
5752 relation_close(seqRel, AccessExclusiveLock);
5756 /* We don't need to close the sequence while we alter it. */
5757 ATExecChangeOwner(depForm->objid, newOwnerId, true);
5759 /* Now we can close it. Keep the lock till end of transaction. */
5760 relation_close(seqRel, NoLock);
5763 systable_endscan(scan);
5765 relation_close(depRel, AccessShareLock);
5769 * ALTER TABLE CLUSTER ON
5771 * The only thing we have to do is to change the indisclustered bits.
5774 ATExecClusterOn(Relation rel, const char *indexName)
5778 indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
5780 if (!OidIsValid(indexOid))
5782 (errcode(ERRCODE_UNDEFINED_OBJECT),
5783 errmsg("index \"%s\" for table \"%s\" does not exist",
5784 indexName, RelationGetRelationName(rel))));
5786 /* Check index is valid to cluster on */
5787 check_index_is_clusterable(rel, indexOid, false);
5789 /* And do the work */
5790 mark_index_clustered(rel, indexOid);
5794 * ALTER TABLE SET WITHOUT CLUSTER
5796 * We have to find any indexes on the table that have indisclustered bit
5797 * set and turn it off.
5800 ATExecDropCluster(Relation rel)
5802 mark_index_clustered(rel, InvalidOid);
5806 * ALTER TABLE SET TABLESPACE
5809 ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, char *tablespacename)
5812 AclResult aclresult;
5814 /* Check that the tablespace exists */
5815 tablespaceId = get_tablespace_oid(tablespacename);
5816 if (!OidIsValid(tablespaceId))
5818 (errcode(ERRCODE_UNDEFINED_OBJECT),
5819 errmsg("tablespace \"%s\" does not exist", tablespacename)));
5821 /* Check its permissions */
5822 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(), ACL_CREATE);
5823 if (aclresult != ACLCHECK_OK)
5824 aclcheck_error(aclresult, ACL_KIND_TABLESPACE, tablespacename);
5826 /* Save info for Phase 3 to do the real work */
5827 if (OidIsValid(tab->newTableSpace))
5829 (errcode(ERRCODE_SYNTAX_ERROR),
5830 errmsg("cannot have multiple SET TABLESPACE subcommands")));
5831 tab->newTableSpace = tablespaceId;
5835 * ALTER TABLE/INDEX SET (...) or RESET (...)
5838 ATExecSetRelOptions(Relation rel, List *defList, bool isReset)
5847 Datum repl_val[Natts_pg_class];
5848 char repl_null[Natts_pg_class];
5849 char repl_repl[Natts_pg_class];
5852 return; /* nothing to do */
5854 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
5856 /* Get the old reloptions */
5857 relid = RelationGetRelid(rel);
5858 tuple = SearchSysCache(RELOID,
5859 ObjectIdGetDatum(relid),
5861 if (!HeapTupleIsValid(tuple))
5862 elog(ERROR, "cache lookup failed for relation %u", relid);
5864 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions, &isnull);
5866 /* Generate new proposed reloptions (text array) */
5867 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
5868 defList, false, isReset);
5871 switch (rel->rd_rel->relkind)
5873 case RELKIND_RELATION:
5874 case RELKIND_TOASTVALUE:
5875 (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
5878 (void) index_reloptions(rel->rd_am->amoptions, newOptions, true);
5882 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5883 errmsg("\"%s\" is not a table, index, or TOAST table",
5884 RelationGetRelationName(rel))));
5889 * All we need do here is update the pg_class row; the new options will be
5890 * propagated into relcaches during post-commit cache inval.
5892 memset(repl_val, 0, sizeof(repl_val));
5893 memset(repl_null, ' ', sizeof(repl_null));
5894 memset(repl_repl, ' ', sizeof(repl_repl));
5896 if (newOptions != (Datum) 0)
5897 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
5899 repl_null[Anum_pg_class_reloptions - 1] = 'n';
5901 repl_repl[Anum_pg_class_reloptions - 1] = 'r';
5903 newtuple = heap_modifytuple(tuple, RelationGetDescr(pgclass),
5904 repl_val, repl_null, repl_repl);
5906 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
5908 CatalogUpdateIndexes(pgclass, newtuple);
5910 heap_freetuple(newtuple);
5912 ReleaseSysCache(tuple);
5914 heap_close(pgclass, RowExclusiveLock);
5918 * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
5919 * rewriting to be done, so we just want to copy the data as fast as possible.
5922 ATExecSetTableSpace(Oid tableOid, Oid newTableSpace)
5928 RelFileNode newrnode;
5929 SMgrRelation dstrel;
5932 Form_pg_class rd_rel;
5935 * Need lock here in case we are recursing to toast table or index
5937 rel = relation_open(tableOid, AccessExclusiveLock);
5940 * We can never allow moving of shared or nailed-in-cache relations,
5941 * because we can't support changing their reltablespace values.
5943 if (rel->rd_rel->relisshared || rel->rd_isnailed)
5945 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5946 errmsg("cannot move system relation \"%s\"",
5947 RelationGetRelationName(rel))));
5949 /* Can't move a non-shared relation into pg_global */
5950 if (newTableSpace == GLOBALTABLESPACE_OID)
5952 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5953 errmsg("only shared relations can be placed in pg_global tablespace")));
5956 * Don't allow moving temp tables of other backends ... their local buffer
5957 * manager is not going to cope.
5959 if (isOtherTempNamespace(RelationGetNamespace(rel)))
5961 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5962 errmsg("cannot move temporary tables of other sessions")));
5965 * No work if no change in tablespace.
5967 oldTableSpace = rel->rd_rel->reltablespace;
5968 if (newTableSpace == oldTableSpace ||
5969 (newTableSpace == MyDatabaseTableSpace && oldTableSpace == 0))
5971 relation_close(rel, NoLock);
5975 reltoastrelid = rel->rd_rel->reltoastrelid;
5976 reltoastidxid = rel->rd_rel->reltoastidxid;
5978 /* Get a modifiable copy of the relation's pg_class row */
5979 pg_class = heap_open(RelationRelationId, RowExclusiveLock);
5981 tuple = SearchSysCacheCopy(RELOID,
5982 ObjectIdGetDatum(tableOid),
5984 if (!HeapTupleIsValid(tuple))
5985 elog(ERROR, "cache lookup failed for relation %u", tableOid);
5986 rd_rel = (Form_pg_class) GETSTRUCT(tuple);
5988 /* create another storage file. Is it a little ugly ? */
5989 /* NOTE: any conflict in relfilenode value will be caught here */
5990 newrnode = rel->rd_node;
5991 newrnode.spcNode = newTableSpace;
5993 dstrel = smgropen(newrnode);
5994 smgrcreate(dstrel, rel->rd_istemp, false);
5996 /* copy relation data to the new physical file */
5997 copy_relation_data(rel, dstrel);
5999 /* schedule unlinking old physical file */
6000 RelationOpenSmgr(rel);
6001 smgrscheduleunlink(rel->rd_smgr, rel->rd_istemp);
6004 * Now drop smgr references. The source was already dropped by
6005 * smgrscheduleunlink.
6009 /* update the pg_class row */
6010 rd_rel->reltablespace = (newTableSpace == MyDatabaseTableSpace) ? InvalidOid : newTableSpace;
6011 simple_heap_update(pg_class, &tuple->t_self, tuple);
6012 CatalogUpdateIndexes(pg_class, tuple);
6014 heap_freetuple(tuple);
6016 heap_close(pg_class, RowExclusiveLock);
6018 relation_close(rel, NoLock);
6020 /* Make sure the reltablespace change is visible */
6021 CommandCounterIncrement();
6023 /* Move associated toast relation and/or index, too */
6024 if (OidIsValid(reltoastrelid))
6025 ATExecSetTableSpace(reltoastrelid, newTableSpace);
6026 if (OidIsValid(reltoastidxid))
6027 ATExecSetTableSpace(reltoastidxid, newTableSpace);
6031 * Copy data, block by block
6034 copy_relation_data(Relation rel, SMgrRelation dst)
6038 BlockNumber nblocks;
6041 Page page = (Page) buf;
6044 * Since we copy the file directly without looking at the shared buffers,
6045 * we'd better first flush out any pages of the source relation that are
6046 * in shared buffers. We assume no new changes will be made while we are
6047 * holding exclusive lock on the rel.
6049 FlushRelationBuffers(rel);
6052 * We need to log the copied data in WAL iff WAL archiving is enabled AND
6053 * it's not a temp rel.
6055 use_wal = XLogArchivingActive() && !rel->rd_istemp;
6057 nblocks = RelationGetNumberOfBlocks(rel);
6058 /* RelationGetNumberOfBlocks will certainly have opened rd_smgr */
6061 for (blkno = 0; blkno < nblocks; blkno++)
6063 smgrread(src, blkno, buf);
6067 log_newpage(&dst->smgr_rnode, blkno, page);
6070 * Now write the page. We say isTemp = true even if it's not a temp
6071 * rel, because there's no need for smgr to schedule an fsync for this
6072 * write; we'll do it ourselves below.
6074 smgrextend(dst, blkno, buf, true);
6078 * If the rel isn't temp, we must fsync it down to disk before it's safe
6079 * to commit the transaction. (For a temp rel we don't care since the rel
6080 * will be uninteresting after a crash anyway.)
6082 * It's obvious that we must do this when not WAL-logging the copy. It's
6083 * less obvious that we have to do it even if we did WAL-log the copied
6084 * pages. The reason is that since we're copying outside shared buffers, a
6085 * CHECKPOINT occurring during the copy has no way to flush the previously
6086 * written data to disk (indeed it won't know the new rel even exists). A
6087 * crash later on would replay WAL from the checkpoint, therefore it
6088 * wouldn't replay our earlier WAL entries. If we do not fsync those pages
6089 * here, they might still not be on disk when the crash occurs.
6091 if (!rel->rd_istemp)
6096 * ALTER TABLE ENABLE/DISABLE TRIGGER
6098 * We just pass this off to trigger.c.
6101 ATExecEnableDisableTrigger(Relation rel, char *trigname,
6102 char fires_when, bool skip_system)
6104 EnableDisableTrigger(rel, trigname, fires_when, skip_system);
6108 * ALTER TABLE ENABLE/DISABLE RULE
6110 * We just pass this off to rewriteDefine.c.
6113 ATExecEnableDisableRule(Relation rel, char *trigname,
6116 EnableDisableRule(rel, trigname, fires_when);
6120 * ALTER TABLE INHERIT
6122 * Add a parent to the child's parents. This verifies that all the columns and
6123 * check constraints of the parent appear in the child and that they have the
6124 * same data types and expressions.
6127 ATExecAddInherit(Relation child_rel, RangeVar *parent)
6129 Relation parent_rel,
6133 HeapTuple inheritsTuple;
6138 * AccessShareLock on the parent is what's obtained during normal CREATE
6139 * TABLE ... INHERITS ..., so should be enough here.
6141 parent_rel = heap_openrv(parent, AccessShareLock);
6144 * Must be owner of both parent and child -- child was checked by
6145 * ATSimplePermissions call in ATPrepCmd
6147 ATSimplePermissions(parent_rel, false);
6149 /* Permanent rels cannot inherit from temporary ones */
6150 if (!isTempNamespace(RelationGetNamespace(child_rel)) &&
6151 isTempNamespace(RelationGetNamespace(parent_rel)))
6153 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6154 errmsg("cannot inherit from temporary relation \"%s\"",
6155 RelationGetRelationName(parent_rel))));
6158 * Check for duplicates in the list of parents, and determine the highest
6159 * inhseqno already present; we'll use the next one for the new parent.
6160 * (Note: get RowExclusiveLock because we will write pg_inherits below.)
6162 * Note: we do not reject the case where the child already inherits from
6163 * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
6165 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
6167 Anum_pg_inherits_inhrelid,
6168 BTEqualStrategyNumber, F_OIDEQ,
6169 ObjectIdGetDatum(RelationGetRelid(child_rel)));
6170 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
6171 true, SnapshotNow, 1, &key);
6173 /* inhseqno sequences start at 1 */
6175 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
6177 Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
6179 if (inh->inhparent == RelationGetRelid(parent_rel))
6181 (errcode(ERRCODE_DUPLICATE_TABLE),
6182 errmsg("relation \"%s\" would be inherited from more than once",
6183 RelationGetRelationName(parent_rel))));
6184 if (inh->inhseqno > inhseqno)
6185 inhseqno = inh->inhseqno;
6187 systable_endscan(scan);
6190 * Prevent circularity by seeing if proposed parent inherits from child.
6191 * (In particular, this disallows making a rel inherit from itself.)
6193 * This is not completely bulletproof because of race conditions: in
6194 * multi-level inheritance trees, someone else could concurrently be
6195 * making another inheritance link that closes the loop but does not join
6196 * either of the rels we have locked. Preventing that seems to require
6197 * exclusive locks on the entire inheritance tree, which is a cure worse
6198 * than the disease. find_all_inheritors() will cope with circularity
6199 * anyway, so don't sweat it too much.
6201 children = find_all_inheritors(RelationGetRelid(child_rel));
6203 if (list_member_oid(children, RelationGetRelid(parent_rel)))
6205 (errcode(ERRCODE_DUPLICATE_TABLE),
6206 errmsg("circular inheritance not allowed"),
6207 errdetail("\"%s\" is already a child of \"%s\".",
6209 RelationGetRelationName(child_rel))));
6211 /* If parent has OIDs then child must have OIDs */
6212 if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
6214 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6215 errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
6216 RelationGetRelationName(child_rel),
6217 RelationGetRelationName(parent_rel))));
6219 /* Match up the columns and bump attinhcount and attislocal */
6220 MergeAttributesIntoExisting(child_rel, parent_rel);
6222 /* Match up the constraints and make sure they're present in child */
6223 MergeConstraintsIntoExisting(child_rel, parent_rel);
6226 * OK, it looks valid. Make the catalog entries that show inheritance.
6228 StoreCatalogInheritance1(RelationGetRelid(child_rel),
6229 RelationGetRelid(parent_rel),
6233 /* Now we're done with pg_inherits */
6234 heap_close(catalogRelation, RowExclusiveLock);
6236 /* keep our lock on the parent relation until commit */
6237 heap_close(parent_rel, NoLock);
6241 * Obtain the source-text form of the constraint expression for a check
6242 * constraint, given its pg_constraint tuple
6245 decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
6247 Form_pg_constraint con;
6252 con = (Form_pg_constraint) GETSTRUCT(contup);
6253 attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
6255 elog(ERROR, "null conbin for constraint %u", HeapTupleGetOid(contup));
6257 expr = DirectFunctionCall2(pg_get_expr, attr,
6258 ObjectIdGetDatum(con->conrelid));
6259 return TextDatumGetCString(expr);
6263 * Check columns in child table match up with columns in parent, and increment
6264 * their attinhcount.
6266 * Called by ATExecAddInherit
6268 * Currently all parent columns must be found in child. Missing columns are an
6269 * error. One day we might consider creating new columns like CREATE TABLE
6270 * does. However, that is widely unpopular --- in the common use case of
6271 * partitioned tables it's a foot-gun.
6273 * The data type must match exactly. If the parent column is NOT NULL then
6274 * the child must be as well. Defaults are not compared, however.
6277 MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel)
6280 AttrNumber parent_attno;
6282 TupleDesc tupleDesc;
6283 TupleConstr *constr;
6286 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
6288 tupleDesc = RelationGetDescr(parent_rel);
6289 parent_natts = tupleDesc->natts;
6290 constr = tupleDesc->constr;
6292 for (parent_attno = 1; parent_attno <= parent_natts; parent_attno++)
6294 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
6295 char *attributeName = NameStr(attribute->attname);
6297 /* Ignore dropped columns in the parent. */
6298 if (attribute->attisdropped)
6301 /* Find same column in child (matching on column name). */
6302 tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel),
6304 if (HeapTupleIsValid(tuple))
6306 /* Check they are same type and typmod */
6307 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
6309 if (attribute->atttypid != childatt->atttypid ||
6310 attribute->atttypmod != childatt->atttypmod)
6312 (errcode(ERRCODE_DATATYPE_MISMATCH),
6313 errmsg("child table \"%s\" has different type for column \"%s\"",
6314 RelationGetRelationName(child_rel),
6317 if (attribute->attnotnull && !childatt->attnotnull)
6319 (errcode(ERRCODE_DATATYPE_MISMATCH),
6320 errmsg("column \"%s\" in child table must be marked NOT NULL",
6324 * OK, bump the child column's inheritance count. (If we fail
6325 * later on, this change will just roll back.)
6327 childatt->attinhcount++;
6328 simple_heap_update(attrrel, &tuple->t_self, tuple);
6329 CatalogUpdateIndexes(attrrel, tuple);
6330 heap_freetuple(tuple);
6335 (errcode(ERRCODE_DATATYPE_MISMATCH),
6336 errmsg("child table is missing column \"%s\"",
6341 heap_close(attrrel, RowExclusiveLock);
6345 * Check constraints in child table match up with constraints in parent
6347 * Called by ATExecAddInherit
6349 * Currently all constraints in parent must be present in the child. One day we
6350 * may consider adding new constraints like CREATE TABLE does. We may also want
6351 * to allow an optional flag on parent table constraints indicating they are
6352 * intended to ONLY apply to the master table, not to the children. That would
6353 * make it possible to ensure no records are mistakenly inserted into the
6354 * master in partitioned tables rather than the appropriate child.
6356 * XXX This is O(N^2) which may be an issue with tables with hundreds of
6357 * constraints. As long as tables have more like 10 constraints it shouldn't be
6358 * a problem though. Even 100 constraints ought not be the end of the world.
6361 MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
6363 Relation catalogRelation;
6364 TupleDesc tupleDesc;
6367 HeapTuple constraintTuple;
6371 /* First gather up the child's constraint definitions */
6372 catalogRelation = heap_open(ConstraintRelationId, AccessShareLock);
6373 tupleDesc = RelationGetDescr(catalogRelation);
6376 Anum_pg_constraint_conrelid,
6377 BTEqualStrategyNumber, F_OIDEQ,
6378 ObjectIdGetDatum(RelationGetRelid(child_rel)));
6379 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
6380 true, SnapshotNow, 1, &key);
6383 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
6385 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
6387 if (con->contype != CONSTRAINT_CHECK)
6390 constraints = lappend(constraints, heap_copytuple(constraintTuple));
6393 systable_endscan(scan);
6395 /* Then scan through the parent's constraints looking for matches */
6397 Anum_pg_constraint_conrelid,
6398 BTEqualStrategyNumber, F_OIDEQ,
6399 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
6400 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId, true,
6401 SnapshotNow, 1, &key);
6403 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
6405 Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
6407 Form_pg_constraint child_con = NULL;
6408 HeapTuple child_contuple = NULL;
6410 if (parent_con->contype != CONSTRAINT_CHECK)
6413 foreach(elem, constraints)
6415 child_contuple = (HeapTuple) lfirst(elem);
6416 child_con = (Form_pg_constraint) GETSTRUCT(child_contuple);
6417 if (strcmp(NameStr(parent_con->conname),
6418 NameStr(child_con->conname)) == 0)
6427 (errcode(ERRCODE_DATATYPE_MISMATCH),
6428 errmsg("child table is missing constraint \"%s\"",
6429 NameStr(parent_con->conname))));
6431 if (parent_con->condeferrable != child_con->condeferrable ||
6432 parent_con->condeferred != child_con->condeferred ||
6433 strcmp(decompile_conbin(constraintTuple, tupleDesc),
6434 decompile_conbin(child_contuple, tupleDesc)) != 0)
6436 (errcode(ERRCODE_DATATYPE_MISMATCH),
6437 errmsg("constraint definition for check constraint \"%s\" does not match",
6438 NameStr(parent_con->conname))));
6441 * TODO: add conislocal,coninhcount to constraints. This is where we
6442 * would have to bump them just like attributes
6446 systable_endscan(scan);
6447 heap_close(catalogRelation, AccessShareLock);
6451 * ALTER TABLE NO INHERIT
6453 * Drop a parent from the child's parents. This just adjusts the attinhcount
6454 * and attislocal of the columns and removes the pg_inherit and pg_depend
6457 * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
6458 * up attislocal stays true, which means if a child is ever removed from a
6459 * parent then its columns will never be automatically dropped which may
6460 * surprise. But at least we'll never surprise by dropping columns someone
6461 * isn't expecting to be dropped which would actually mean data loss.
6464 ATExecDropInherit(Relation rel, RangeVar *parent)
6466 Relation parent_rel;
6467 Relation catalogRelation;
6470 HeapTuple inheritsTuple,
6476 * AccessShareLock on the parent is probably enough, seeing that DROP
6477 * TABLE doesn't lock parent tables at all. We need some lock since we'll
6478 * be inspecting the parent's schema.
6480 parent_rel = heap_openrv(parent, AccessShareLock);
6483 * We don't bother to check ownership of the parent table --- ownership of
6484 * the child is presumed enough rights.
6488 * Find and destroy the pg_inherits entry linking the two, or error out if
6491 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
6492 ScanKeyInit(&key[0],
6493 Anum_pg_inherits_inhrelid,
6494 BTEqualStrategyNumber, F_OIDEQ,
6495 ObjectIdGetDatum(RelationGetRelid(rel)));
6496 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
6497 true, SnapshotNow, 1, key);
6499 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
6503 inhparent = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
6504 if (inhparent == RelationGetRelid(parent_rel))
6506 simple_heap_delete(catalogRelation, &inheritsTuple->t_self);
6512 systable_endscan(scan);
6513 heap_close(catalogRelation, RowExclusiveLock);
6517 (errcode(ERRCODE_UNDEFINED_TABLE),
6518 errmsg("relation \"%s\" is not a parent of relation \"%s\"",
6519 RelationGetRelationName(parent_rel),
6520 RelationGetRelationName(rel))));
6523 * Search through child columns looking for ones matching parent rel
6525 catalogRelation = heap_open(AttributeRelationId, RowExclusiveLock);
6526 ScanKeyInit(&key[0],
6527 Anum_pg_attribute_attrelid,
6528 BTEqualStrategyNumber, F_OIDEQ,
6529 ObjectIdGetDatum(RelationGetRelid(rel)));
6530 scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
6531 true, SnapshotNow, 1, key);
6532 while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
6534 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
6536 /* Ignore if dropped or not inherited */
6537 if (att->attisdropped)
6539 if (att->attinhcount <= 0)
6542 if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
6543 NameStr(att->attname)))
6545 /* Decrement inhcount and possibly set islocal to true */
6546 HeapTuple copyTuple = heap_copytuple(attributeTuple);
6547 Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
6549 copy_att->attinhcount--;
6550 if (copy_att->attinhcount == 0)
6551 copy_att->attislocal = true;
6553 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
6554 CatalogUpdateIndexes(catalogRelation, copyTuple);
6555 heap_freetuple(copyTuple);
6558 systable_endscan(scan);
6559 heap_close(catalogRelation, RowExclusiveLock);
6562 * Drop the dependency
6564 * There's no convenient way to do this, so go trawling through pg_depend
6566 catalogRelation = heap_open(DependRelationId, RowExclusiveLock);
6568 ScanKeyInit(&key[0],
6569 Anum_pg_depend_classid,
6570 BTEqualStrategyNumber, F_OIDEQ,
6571 ObjectIdGetDatum(RelationRelationId));
6572 ScanKeyInit(&key[1],
6573 Anum_pg_depend_objid,
6574 BTEqualStrategyNumber, F_OIDEQ,
6575 ObjectIdGetDatum(RelationGetRelid(rel)));
6576 ScanKeyInit(&key[2],
6577 Anum_pg_depend_objsubid,
6578 BTEqualStrategyNumber, F_INT4EQ,
6581 scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
6582 SnapshotNow, 3, key);
6584 while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
6586 Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
6588 if (dep->refclassid == RelationRelationId &&
6589 dep->refobjid == RelationGetRelid(parent_rel) &&
6590 dep->refobjsubid == 0 &&
6591 dep->deptype == DEPENDENCY_NORMAL)
6592 simple_heap_delete(catalogRelation, &depTuple->t_self);
6595 systable_endscan(scan);
6596 heap_close(catalogRelation, RowExclusiveLock);
6598 /* keep our lock on the parent relation until commit */
6599 heap_close(parent_rel, NoLock);
6604 * Execute ALTER TABLE SET SCHEMA
6606 * Note: caller must have checked ownership of the relation already
6609 AlterTableNamespace(RangeVar *relation, const char *newschema)
6617 rel = relation_openrv(relation, AccessExclusiveLock);
6619 relid = RelationGetRelid(rel);
6620 oldNspOid = RelationGetNamespace(rel);
6622 /* Can we change the schema of this tuple? */
6623 switch (rel->rd_rel->relkind)
6625 case RELKIND_RELATION:
6627 /* ok to change schema */
6629 case RELKIND_SEQUENCE:
6631 /* if it's an owned sequence, disallow moving it by itself */
6635 if (sequenceIsOwned(relid, &tableId, &colId))
6637 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6638 errmsg("cannot move an owned sequence into another schema"),
6639 errdetail("Sequence \"%s\" is linked to table \"%s\".",
6640 RelationGetRelationName(rel),
6641 get_rel_name(tableId))));
6644 case RELKIND_COMPOSITE_TYPE:
6646 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6647 errmsg("\"%s\" is a composite type",
6648 RelationGetRelationName(rel)),
6649 errhint("Use ALTER TYPE instead.")));
6652 case RELKIND_TOASTVALUE:
6656 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6657 errmsg("\"%s\" is not a table, view, or sequence",
6658 RelationGetRelationName(rel))));
6661 /* get schema OID and check its permissions */
6662 nspOid = LookupCreationNamespace(newschema);
6664 if (oldNspOid == nspOid)
6666 (errcode(ERRCODE_DUPLICATE_TABLE),
6667 errmsg("relation \"%s\" is already in schema \"%s\"",
6668 RelationGetRelationName(rel),
6671 /* disallow renaming into or out of temp schemas */
6672 if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
6674 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6675 errmsg("cannot move objects into or out of temporary schemas")));
6677 /* same for TOAST schema */
6678 if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
6680 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6681 errmsg("cannot move objects into or out of TOAST schema")));
6683 /* OK, modify the pg_class row and pg_depend entry */
6684 classRel = heap_open(RelationRelationId, RowExclusiveLock);
6686 AlterRelationNamespaceInternal(classRel, relid, oldNspOid, nspOid, true);
6688 /* Fix the table's rowtype too */
6689 AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid, false, false);
6691 /* Fix other dependent stuff */
6692 if (rel->rd_rel->relkind == RELKIND_RELATION)
6694 AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid);
6695 AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid, newschema);
6696 AlterConstraintNamespaces(relid, oldNspOid, nspOid, false);
6699 heap_close(classRel, RowExclusiveLock);
6701 /* close rel, but keep lock until commit */
6702 relation_close(rel, NoLock);
6706 * The guts of relocating a relation to another namespace: fix the pg_class
6707 * entry, and the pg_depend entry if any. Caller must already have
6708 * opened and write-locked pg_class.
6711 AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
6712 Oid oldNspOid, Oid newNspOid,
6713 bool hasDependEntry)
6716 Form_pg_class classForm;
6718 classTup = SearchSysCacheCopy(RELOID,
6719 ObjectIdGetDatum(relOid),
6721 if (!HeapTupleIsValid(classTup))
6722 elog(ERROR, "cache lookup failed for relation %u", relOid);
6723 classForm = (Form_pg_class) GETSTRUCT(classTup);
6725 Assert(classForm->relnamespace == oldNspOid);
6727 /* check for duplicate name (more friendly than unique-index failure) */
6728 if (get_relname_relid(NameStr(classForm->relname),
6729 newNspOid) != InvalidOid)
6731 (errcode(ERRCODE_DUPLICATE_TABLE),
6732 errmsg("relation \"%s\" already exists in schema \"%s\"",
6733 NameStr(classForm->relname),
6734 get_namespace_name(newNspOid))));
6736 /* classTup is a copy, so OK to scribble on */
6737 classForm->relnamespace = newNspOid;
6739 simple_heap_update(classRel, &classTup->t_self, classTup);
6740 CatalogUpdateIndexes(classRel, classTup);
6742 /* Update dependency on schema if caller said so */
6743 if (hasDependEntry &&
6744 changeDependencyFor(RelationRelationId, relOid,
6745 NamespaceRelationId, oldNspOid, newNspOid) != 1)
6746 elog(ERROR, "failed to change schema dependency for relation \"%s\"",
6747 NameStr(classForm->relname));
6749 heap_freetuple(classTup);
6753 * Move all indexes for the specified relation to another namespace.
6755 * Note: we assume adequate permission checking was done by the caller,
6756 * and that the caller has a suitable lock on the owning relation.
6759 AlterIndexNamespaces(Relation classRel, Relation rel,
6760 Oid oldNspOid, Oid newNspOid)
6765 indexList = RelationGetIndexList(rel);
6767 foreach(l, indexList)
6769 Oid indexOid = lfirst_oid(l);
6772 * Note: currently, the index will not have its own dependency on the
6773 * namespace, so we don't need to do changeDependencyFor(). There's no
6774 * rowtype in pg_type, either.
6776 AlterRelationNamespaceInternal(classRel, indexOid,
6777 oldNspOid, newNspOid,
6781 list_free(indexList);
6785 * Move all SERIAL-column sequences of the specified relation to another
6788 * Note: we assume adequate permission checking was done by the caller,
6789 * and that the caller has a suitable lock on the owning relation.
6792 AlterSeqNamespaces(Relation classRel, Relation rel,
6793 Oid oldNspOid, Oid newNspOid, const char *newNspName)
6801 * SERIAL sequences are those having an auto dependency on one of the
6802 * table's columns (we don't care *which* column, exactly).
6804 depRel = heap_open(DependRelationId, AccessShareLock);
6806 ScanKeyInit(&key[0],
6807 Anum_pg_depend_refclassid,
6808 BTEqualStrategyNumber, F_OIDEQ,
6809 ObjectIdGetDatum(RelationRelationId));
6810 ScanKeyInit(&key[1],
6811 Anum_pg_depend_refobjid,
6812 BTEqualStrategyNumber, F_OIDEQ,
6813 ObjectIdGetDatum(RelationGetRelid(rel)));
6814 /* we leave refobjsubid unspecified */
6816 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
6817 SnapshotNow, 2, key);
6819 while (HeapTupleIsValid(tup = systable_getnext(scan)))
6821 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
6824 /* skip dependencies other than auto dependencies on columns */
6825 if (depForm->refobjsubid == 0 ||
6826 depForm->classid != RelationRelationId ||
6827 depForm->objsubid != 0 ||
6828 depForm->deptype != DEPENDENCY_AUTO)
6831 /* Use relation_open just in case it's an index */
6832 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
6834 /* skip non-sequence relations */
6835 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
6837 /* No need to keep the lock */
6838 relation_close(seqRel, AccessExclusiveLock);
6842 /* Fix the pg_class and pg_depend entries */
6843 AlterRelationNamespaceInternal(classRel, depForm->objid,
6844 oldNspOid, newNspOid,
6848 * Sequences have entries in pg_type. We need to be careful to move
6849 * them to the new namespace, too.
6851 AlterTypeNamespaceInternal(RelationGetForm(seqRel)->reltype,
6852 newNspOid, false, false);
6854 /* Now we can close it. Keep the lock till end of transaction. */
6855 relation_close(seqRel, NoLock);
6858 systable_endscan(scan);
6860 relation_close(depRel, AccessShareLock);
6865 * This code supports
6866 * CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
6868 * Because we only support this for TEMP tables, it's sufficient to remember
6869 * the state in a backend-local data structure.
6873 * Register a newly-created relation's ON COMMIT action.
6876 register_on_commit_action(Oid relid, OnCommitAction action)
6879 MemoryContext oldcxt;
6882 * We needn't bother registering the relation unless there is an ON COMMIT
6883 * action we need to take.
6885 if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
6888 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
6890 oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
6892 oc->oncommit = action;
6893 oc->creating_subid = GetCurrentSubTransactionId();
6894 oc->deleting_subid = InvalidSubTransactionId;
6896 on_commits = lcons(oc, on_commits);
6898 MemoryContextSwitchTo(oldcxt);
6902 * Unregister any ON COMMIT action when a relation is deleted.
6904 * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
6907 remove_on_commit_action(Oid relid)
6911 foreach(l, on_commits)
6913 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
6915 if (oc->relid == relid)
6917 oc->deleting_subid = GetCurrentSubTransactionId();
6924 * Perform ON COMMIT actions.
6926 * This is invoked just before actually committing, since it's possible
6927 * to encounter errors.
6930 PreCommit_on_commit_actions(void)
6933 List *oids_to_truncate = NIL;
6935 foreach(l, on_commits)
6937 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
6939 /* Ignore entry if already dropped in this xact */
6940 if (oc->deleting_subid != InvalidSubTransactionId)
6943 switch (oc->oncommit)
6946 case ONCOMMIT_PRESERVE_ROWS:
6947 /* Do nothing (there shouldn't be such entries, actually) */
6949 case ONCOMMIT_DELETE_ROWS:
6950 oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
6954 ObjectAddress object;
6956 object.classId = RelationRelationId;
6957 object.objectId = oc->relid;
6958 object.objectSubId = 0;
6959 performDeletion(&object, DROP_CASCADE);
6962 * Note that table deletion will call
6963 * remove_on_commit_action, so the entry should get marked
6966 Assert(oc->deleting_subid != InvalidSubTransactionId);
6971 if (oids_to_truncate != NIL)
6973 heap_truncate(oids_to_truncate);
6974 CommandCounterIncrement(); /* XXX needed? */
6979 * Post-commit or post-abort cleanup for ON COMMIT management.
6981 * All we do here is remove no-longer-needed OnCommitItem entries.
6983 * During commit, remove entries that were deleted during this transaction;
6984 * during abort, remove those created during this transaction.
6987 AtEOXact_on_commit_actions(bool isCommit)
6990 ListCell *prev_item;
6993 cur_item = list_head(on_commits);
6995 while (cur_item != NULL)
6997 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
6999 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
7000 oc->creating_subid != InvalidSubTransactionId)
7002 /* cur_item must be removed */
7003 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
7006 cur_item = lnext(prev_item);
7008 cur_item = list_head(on_commits);
7012 /* cur_item must be preserved */
7013 oc->creating_subid = InvalidSubTransactionId;
7014 oc->deleting_subid = InvalidSubTransactionId;
7015 prev_item = cur_item;
7016 cur_item = lnext(prev_item);
7022 * Post-subcommit or post-subabort cleanup for ON COMMIT management.
7024 * During subabort, we can immediately remove entries created during this
7025 * subtransaction. During subcommit, just relabel entries marked during
7026 * this subtransaction as being the parent's responsibility.
7029 AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
7030 SubTransactionId parentSubid)
7033 ListCell *prev_item;
7036 cur_item = list_head(on_commits);
7038 while (cur_item != NULL)
7040 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
7042 if (!isCommit && oc->creating_subid == mySubid)
7044 /* cur_item must be removed */
7045 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
7048 cur_item = lnext(prev_item);
7050 cur_item = list_head(on_commits);
7054 /* cur_item must be preserved */
7055 if (oc->creating_subid == mySubid)
7056 oc->creating_subid = parentSubid;
7057 if (oc->deleting_subid == mySubid)
7058 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
7059 prev_item = cur_item;
7060 cur_item = lnext(prev_item);