1 /*-------------------------------------------------------------------------
4 * Commands for creating and altering table structures and settings
6 * Portions Copyright (c) 1996-2007, 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.229 2007/07/03 01:30:36 neilc 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_trigger.h"
33 #include "catalog/pg_type.h"
34 #include "catalog/toasting.h"
35 #include "commands/cluster.h"
36 #include "commands/defrem.h"
37 #include "commands/tablecmds.h"
38 #include "commands/tablespace.h"
39 #include "commands/trigger.h"
40 #include "commands/typecmds.h"
41 #include "executor/executor.h"
42 #include "miscadmin.h"
43 #include "nodes/makefuncs.h"
44 #include "nodes/parsenodes.h"
45 #include "optimizer/clauses.h"
46 #include "optimizer/plancat.h"
47 #include "optimizer/prep.h"
48 #include "parser/gramparse.h"
49 #include "parser/parse_clause.h"
50 #include "parser/parse_coerce.h"
51 #include "parser/parse_expr.h"
52 #include "parser/parse_oper.h"
53 #include "parser/parse_relation.h"
54 #include "parser/parse_type.h"
55 #include "parser/parse_utilcmd.h"
56 #include "parser/parser.h"
57 #include "rewrite/rewriteDefine.h"
58 #include "rewrite/rewriteHandler.h"
59 #include "storage/smgr.h"
60 #include "utils/acl.h"
61 #include "utils/builtins.h"
62 #include "utils/fmgroids.h"
63 #include "utils/inval.h"
64 #include "utils/lsyscache.h"
65 #include "utils/memutils.h"
66 #include "utils/relcache.h"
67 #include "utils/syscache.h"
71 * ON COMMIT action list
73 typedef struct OnCommitItem
75 Oid relid; /* relid of relation */
76 OnCommitAction oncommit; /* what to do at end of xact */
79 * If this entry was created during the current transaction,
80 * creating_subid is the ID of the creating subxact; if created in a prior
81 * transaction, creating_subid is zero. If deleted during the current
82 * transaction, deleting_subid is the ID of the deleting subxact; if no
83 * deletion request is pending, deleting_subid is zero.
85 SubTransactionId creating_subid;
86 SubTransactionId deleting_subid;
89 static List *on_commits = NIL;
93 * State information for ALTER TABLE
95 * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
96 * structs, one for each table modified by the operation (the named table
97 * plus any child tables that are affected). We save lists of subcommands
98 * to apply to this table (possibly modified by parse transformation steps);
99 * these lists will be executed in Phase 2. If a Phase 3 step is needed,
100 * necessary information is stored in the constraints and newvals lists.
102 * Phase 2 is divided into multiple passes; subcommands are executed in
103 * a pass determined by subcommand type.
106 #define AT_PASS_DROP 0 /* DROP (all flavors) */
107 #define AT_PASS_ALTER_TYPE 1 /* ALTER COLUMN TYPE */
108 #define AT_PASS_OLD_INDEX 2 /* re-add existing indexes */
109 #define AT_PASS_OLD_CONSTR 3 /* re-add existing constraints */
110 #define AT_PASS_COL_ATTRS 4 /* set other column attributes */
111 /* We could support a RENAME COLUMN pass here, but not currently used */
112 #define AT_PASS_ADD_COL 5 /* ADD COLUMN */
113 #define AT_PASS_ADD_INDEX 6 /* ADD indexes */
114 #define AT_PASS_ADD_CONSTR 7 /* ADD constraints, defaults */
115 #define AT_PASS_MISC 8 /* other stuff */
116 #define AT_NUM_PASSES 9
118 typedef struct AlteredTableInfo
120 /* Information saved before any work commences: */
121 Oid relid; /* Relation to work on */
122 char relkind; /* Its relkind */
123 TupleDesc oldDesc; /* Pre-modification tuple descriptor */
124 /* Information saved by Phase 1 for Phase 2: */
125 List *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
126 /* Information saved by Phases 1/2 for Phase 3: */
127 List *constraints; /* List of NewConstraint */
128 List *newvals; /* List of NewColumnValue */
129 bool new_notnull; /* T if we added new NOT NULL constraints */
130 Oid newTableSpace; /* new tablespace; 0 means no change */
131 /* Objects to rebuild after completing ALTER TYPE operations */
132 List *changedConstraintOids; /* OIDs of constraints to rebuild */
133 List *changedConstraintDefs; /* string definitions of same */
134 List *changedIndexOids; /* OIDs of indexes to rebuild */
135 List *changedIndexDefs; /* string definitions of same */
138 /* Struct describing one new constraint to check in Phase 3 scan */
139 /* Note: new NOT NULL constraints are handled elsewhere */
140 typedef struct NewConstraint
142 char *name; /* Constraint name, or NULL if none */
143 ConstrType contype; /* CHECK or FOREIGN */
144 Oid refrelid; /* PK rel, if FOREIGN */
145 Oid conid; /* OID of pg_constraint entry, if FOREIGN */
146 Node *qual; /* Check expr or FkConstraint struct */
147 List *qualstate; /* Execution state for CHECK */
151 * Struct describing one new column value that needs to be computed during
152 * Phase 3 copy (this could be either a new column with a non-null default, or
153 * a column that we're changing the type of). Columns without such an entry
154 * are just copied from the old table during ATRewriteTable. Note that the
155 * expr is an expression over *old* table values.
157 typedef struct NewColumnValue
159 AttrNumber attnum; /* which column */
160 Expr *expr; /* expression to compute */
161 ExprState *exprstate; /* execution state */
165 static void truncate_check_rel(Relation rel);
166 static List *MergeAttributes(List *schema, List *supers, bool istemp,
167 List **supOids, List **supconstr, int *supOidCount);
168 static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
169 static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel);
170 static void add_nonduplicate_constraint(Constraint *cdef,
171 ConstrCheck *check, int *ncheck);
172 static bool change_varattnos_walker(Node *node, const AttrNumber *newattno);
173 static void StoreCatalogInheritance(Oid relationId, List *supers);
174 static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
175 int16 seqNumber, Relation inhRelation);
176 static int findAttrByName(const char *attributeName, List *schema);
177 static void setRelhassubclassInRelation(Oid relationId, bool relhassubclass);
178 static void AlterIndexNamespaces(Relation classRel, Relation rel,
179 Oid oldNspOid, Oid newNspOid);
180 static void AlterSeqNamespaces(Relation classRel, Relation rel,
181 Oid oldNspOid, Oid newNspOid,
182 const char *newNspName);
183 static int transformColumnNameList(Oid relId, List *colList,
184 int16 *attnums, Oid *atttypids);
185 static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
187 int16 *attnums, Oid *atttypids,
189 static Oid transformFkeyCheckAttrs(Relation pkrel,
190 int numattrs, int16 *attnums,
192 static void validateForeignKeyConstraint(FkConstraint *fkconstraint,
193 Relation rel, Relation pkrel, Oid constraintOid);
194 static void createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
196 static void ATController(Relation rel, List *cmds, bool recurse);
197 static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
198 bool recurse, bool recursing);
199 static void ATRewriteCatalogs(List **wqueue);
200 static void ATExecCmd(AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd);
201 static void ATRewriteTables(List **wqueue);
202 static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap);
203 static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
204 static void ATSimplePermissions(Relation rel, bool allowView);
205 static void ATSimplePermissionsRelationOrIndex(Relation rel);
206 static void ATSimpleRecursion(List **wqueue, Relation rel,
207 AlterTableCmd *cmd, bool recurse);
208 static void ATOneLevelRecursion(List **wqueue, Relation rel,
210 static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
212 static void ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
214 static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
215 static void ATExecDropNotNull(Relation rel, const char *colName);
216 static void ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
217 const char *colName);
218 static void ATExecColumnDefault(Relation rel, const char *colName,
220 static void ATPrepSetStatistics(Relation rel, const char *colName,
222 static void ATExecSetStatistics(Relation rel, const char *colName,
224 static void ATExecSetStorage(Relation rel, const char *colName,
226 static void ATExecDropColumn(Relation rel, const char *colName,
227 DropBehavior behavior,
228 bool recurse, bool recursing);
229 static void ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
230 IndexStmt *stmt, bool is_rebuild);
231 static void ATExecAddConstraint(AlteredTableInfo *tab, Relation rel,
232 Node *newConstraint);
233 static void ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
234 FkConstraint *fkconstraint);
235 static void ATPrepDropConstraint(List **wqueue, Relation rel,
236 bool recurse, AlterTableCmd *cmd);
237 static void ATExecDropConstraint(Relation rel, const char *constrName,
238 DropBehavior behavior, bool quiet);
239 static void ATPrepAlterColumnType(List **wqueue,
240 AlteredTableInfo *tab, Relation rel,
241 bool recurse, bool recursing,
243 static void ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
244 const char *colName, TypeName *typename);
245 static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab);
246 static void ATPostAlterTypeParse(char *cmd, List **wqueue);
247 static void change_owner_recurse_to_sequences(Oid relationOid,
249 static void ATExecClusterOn(Relation rel, const char *indexName);
250 static void ATExecDropCluster(Relation rel);
251 static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
252 char *tablespacename);
253 static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace);
254 static void ATExecSetRelOptions(Relation rel, List *defList, bool isReset);
255 static void ATExecEnableDisableTrigger(Relation rel, char *trigname,
256 char fires_when, bool skip_system);
257 static void ATExecEnableDisableRule(Relation rel, char *rulename,
259 static void ATExecAddInherit(Relation rel, RangeVar *parent);
260 static void ATExecDropInherit(Relation rel, RangeVar *parent);
261 static void copy_relation_data(Relation rel, SMgrRelation dst);
264 /* ----------------------------------------------------------------
266 * Creates a new relation.
268 * If successful, returns the OID of the new relation.
269 * ----------------------------------------------------------------
272 DefineRelation(CreateStmt *stmt, char relkind)
274 char relname[NAMEDATALEN];
276 List *schema = stmt->tableElts;
280 TupleDesc descriptor;
282 List *old_constraints;
291 * Truncate relname to appropriate length (probably a waste of time, as
292 * parser should have done this already).
294 StrNCpy(relname, stmt->relation->relname, NAMEDATALEN);
297 * Check consistency of arguments
299 if (stmt->oncommit != ONCOMMIT_NOOP && !stmt->relation->istemp)
301 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
302 errmsg("ON COMMIT can only be used on temporary tables")));
305 * Look up the namespace in which we are supposed to create the relation.
306 * Check we have permission to create there. Skip check if bootstrapping,
307 * since permissions machinery may not be working yet.
309 namespaceId = RangeVarGetCreationNamespace(stmt->relation);
311 if (!IsBootstrapProcessingMode())
315 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
317 if (aclresult != ACLCHECK_OK)
318 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
319 get_namespace_name(namespaceId));
323 * Select tablespace to use. If not specified, use default tablespace
324 * (which may in turn default to database's default).
326 if (stmt->tablespacename)
328 tablespaceId = get_tablespace_oid(stmt->tablespacename);
329 if (!OidIsValid(tablespaceId))
331 (errcode(ERRCODE_UNDEFINED_OBJECT),
332 errmsg("tablespace \"%s\" does not exist",
333 stmt->tablespacename)));
337 tablespaceId = GetDefaultTablespace(stmt->relation->istemp);
338 /* note InvalidOid is OK in this case */
341 /* Check permissions except when using database's default */
342 if (OidIsValid(tablespaceId))
346 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
348 if (aclresult != ACLCHECK_OK)
349 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
350 get_tablespace_name(tablespaceId));
354 * Parse and validate reloptions, if any.
356 reloptions = transformRelOptions((Datum) 0, stmt->options, true, false);
358 (void) heap_reloptions(relkind, reloptions, true);
361 * Look up inheritance ancestors and generate relation schema, including
362 * inherited attributes.
364 schema = MergeAttributes(schema, stmt->inhRelations,
365 stmt->relation->istemp,
366 &inheritOids, &old_constraints, &parentOidCount);
369 * Create a relation descriptor from the relation schema and create the
370 * relation. Note that in this stage only inherited (pre-cooked) defaults
371 * and constraints will be included into the new relation.
372 * (BuildDescForRelation takes care of the inherited defaults, but we have
373 * to copy inherited constraints here.)
375 descriptor = BuildDescForRelation(schema);
377 localHasOids = interpretOidsOption(stmt->options);
378 descriptor->tdhasoid = (localHasOids || parentOidCount > 0);
380 if (old_constraints || stmt->constraints)
385 /* make array that's certainly big enough */
386 check = (ConstrCheck *)
387 palloc((list_length(old_constraints) +
388 list_length(stmt->constraints)) * sizeof(ConstrCheck));
389 /* deal with constraints from MergeAttributes */
390 foreach(listptr, old_constraints)
392 Constraint *cdef = (Constraint *) lfirst(listptr);
394 if (cdef->contype == CONSTR_CHECK)
395 add_nonduplicate_constraint(cdef, check, &ncheck);
398 * parse_utilcmd.c might have passed some precooked constraints too,
399 * due to LIKE tab INCLUDING CONSTRAINTS
401 foreach(listptr, stmt->constraints)
403 Constraint *cdef = (Constraint *) lfirst(listptr);
405 if (cdef->contype == CONSTR_CHECK && cdef->cooked_expr != NULL)
406 add_nonduplicate_constraint(cdef, check, &ncheck);
408 /* if we found any, insert 'em into the descriptor */
411 if (descriptor->constr == NULL)
413 descriptor->constr = (TupleConstr *) palloc(sizeof(TupleConstr));
414 descriptor->constr->defval = NULL;
415 descriptor->constr->num_defval = 0;
416 descriptor->constr->has_not_null = false;
418 descriptor->constr->num_check = ncheck;
419 descriptor->constr->check = check;
423 relationId = heap_create_with_catalog(relname,
435 allowSystemTableMods);
437 StoreCatalogInheritance(relationId, inheritOids);
440 * We must bump the command counter to make the newly-created relation
441 * tuple visible for opening.
443 CommandCounterIncrement();
446 * Open the new relation and acquire exclusive lock on it. This isn't
447 * really necessary for locking out other backends (since they can't see
448 * the new rel anyway until we commit), but it keeps the lock manager from
449 * complaining about deadlock risks.
451 rel = relation_open(relationId, AccessExclusiveLock);
454 * Now add any newly specified column default values and CHECK constraints
455 * to the new relation. These are passed to us in the form of raw
456 * parsetrees; we need to transform them to executable expression trees
457 * before they can be added. The most convenient way to do that is to
458 * apply the parser's transformExpr routine, but transformExpr doesn't
459 * work unless we have a pre-existing relation. So, the transformation has
460 * to be postponed to this final step of CREATE TABLE.
462 * First, scan schema to find new column defaults.
467 foreach(listptr, schema)
469 ColumnDef *colDef = lfirst(listptr);
473 if (colDef->raw_default != NULL)
475 RawColumnDefault *rawEnt;
477 Assert(colDef->cooked_default == NULL);
479 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
480 rawEnt->attnum = attnum;
481 rawEnt->raw_default = colDef->raw_default;
482 rawDefaults = lappend(rawDefaults, rawEnt);
487 * Parse and add the defaults/constraints, if any.
489 if (rawDefaults || stmt->constraints)
490 AddRelationRawConstraints(rel, rawDefaults, stmt->constraints);
493 * Clean up. We keep lock on new relation (although it shouldn't be
494 * visible to anyone else anyway, until commit).
496 relation_close(rel, NoLock);
503 * Deletes a relation.
506 RemoveRelation(const RangeVar *relation, DropBehavior behavior)
509 ObjectAddress object;
511 relOid = RangeVarGetRelid(relation, false);
513 object.classId = RelationRelationId;
514 object.objectId = relOid;
515 object.objectSubId = 0;
517 performDeletion(&object, behavior);
522 * Executes a TRUNCATE command.
524 * This is a multi-relation truncate. We first open and grab exclusive
525 * lock on all relations involved, checking permissions and otherwise
526 * verifying that the relation is OK for truncation. In CASCADE mode,
527 * relations having FK references to the targeted relations are automatically
528 * added to the group; in RESTRICT mode, we check that all FK references are
529 * internal to the group that's being truncated. Finally all the relations
530 * are truncated and reindexed.
533 ExecuteTruncate(TruncateStmt *stmt)
540 * Open, exclusive-lock, and check all the explicitly-specified relations
542 foreach(cell, stmt->relations)
544 RangeVar *rv = lfirst(cell);
547 rel = heap_openrv(rv, AccessExclusiveLock);
548 truncate_check_rel(rel);
549 rels = lappend(rels, rel);
550 relids = lappend_oid(relids, RelationGetRelid(rel));
554 * In CASCADE mode, suck in all referencing relations as well. This
555 * requires multiple iterations to find indirectly-dependent relations. At
556 * each phase, we need to exclusive-lock new rels before looking for their
557 * dependencies, else we might miss something. Also, we check each rel as
558 * soon as we open it, to avoid a faux pas such as holding lock for a long
559 * time on a rel we have no permissions for.
561 if (stmt->behavior == DROP_CASCADE)
567 newrelids = heap_truncate_find_FKs(relids);
568 if (newrelids == NIL)
569 break; /* nothing else to add */
571 foreach(cell, newrelids)
573 Oid relid = lfirst_oid(cell);
576 rel = heap_open(relid, AccessExclusiveLock);
578 (errmsg("truncate cascades to table \"%s\"",
579 RelationGetRelationName(rel))));
580 truncate_check_rel(rel);
581 rels = lappend(rels, rel);
582 relids = lappend_oid(relids, relid);
588 * Check foreign key references. In CASCADE mode, this should be
589 * unnecessary since we just pulled in all the references; but as a
590 * cross-check, do it anyway if in an Assert-enabled build.
592 #ifdef USE_ASSERT_CHECKING
593 heap_truncate_check_FKs(rels, false);
595 if (stmt->behavior == DROP_RESTRICT)
596 heap_truncate_check_FKs(rels, false);
600 * Also check for pending AFTER trigger events on the target relations. We
601 * can't just leave those be, since they will try to fetch tuples that the
604 AfterTriggerCheckTruncate(relids);
607 * OK, truncate each table.
611 Relation rel = (Relation) lfirst(cell);
616 * Create a new empty storage file for the relation, and assign it as
617 * the relfilenode value. The old storage file is scheduled for
618 * deletion at commit.
620 setNewRelfilenode(rel, RecentXmin);
622 heap_relid = RelationGetRelid(rel);
623 toast_relid = rel->rd_rel->reltoastrelid;
625 heap_close(rel, NoLock);
628 * The same for the toast table, if any.
630 if (OidIsValid(toast_relid))
632 rel = relation_open(toast_relid, AccessExclusiveLock);
633 setNewRelfilenode(rel, RecentXmin);
634 heap_close(rel, NoLock);
638 * Reconstruct the indexes to match, and we're done.
640 reindex_relation(heap_relid, true);
645 * Check that a given rel is safe to truncate. Subroutine for ExecuteTruncate
648 truncate_check_rel(Relation rel)
650 /* Only allow truncate on regular tables */
651 if (rel->rd_rel->relkind != RELKIND_RELATION)
653 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
654 errmsg("\"%s\" is not a table",
655 RelationGetRelationName(rel))));
657 /* Permissions checks */
658 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
659 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
660 RelationGetRelationName(rel));
662 if (!allowSystemTableMods && IsSystemRelation(rel))
664 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
665 errmsg("permission denied: \"%s\" is a system catalog",
666 RelationGetRelationName(rel))));
669 * We can never allow truncation of shared or nailed-in-cache relations,
670 * because we can't support changing their relfilenode values.
672 if (rel->rd_rel->relisshared || rel->rd_isnailed)
674 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
675 errmsg("cannot truncate system relation \"%s\"",
676 RelationGetRelationName(rel))));
679 * Don't allow truncate on temp tables of other backends ... their local
680 * buffer manager is not going to cope.
682 if (isOtherTempNamespace(RelationGetNamespace(rel)))
684 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
685 errmsg("cannot truncate temporary tables of other sessions")));
690 * Returns new schema given initial schema and superclasses.
693 * 'schema' is the column/attribute definition for the table. (It's a list
694 * of ColumnDef's.) It is destructively changed.
695 * 'supers' is a list of names (as RangeVar nodes) of parent relations.
696 * 'istemp' is TRUE if we are creating a temp relation.
699 * 'supOids' receives a list of the OIDs of the parent relations.
700 * 'supconstr' receives a list of constraints belonging to the parents,
701 * updated as necessary to be valid for the child.
702 * 'supOidCount' is set to the number of parents that have OID columns.
705 * Completed schema list.
708 * The order in which the attributes are inherited is very important.
709 * Intuitively, the inherited attributes should come first. If a table
710 * inherits from multiple parents, the order of those attributes are
711 * according to the order of the parents specified in CREATE TABLE.
715 * create table person (name text, age int4, location point);
716 * create table emp (salary int4, manager text) inherits(person);
717 * create table student (gpa float8) inherits (person);
718 * create table stud_emp (percent int4) inherits (emp, student);
720 * The order of the attributes of stud_emp is:
722 * person {1:name, 2:age, 3:location}
724 * {6:gpa} student emp {4:salary, 5:manager}
726 * stud_emp {7:percent}
728 * If the same attribute name appears multiple times, then it appears
729 * in the result table in the proper location for its first appearance.
731 * Constraints (including NOT NULL constraints) for the child table
732 * are the union of all relevant constraints, from both the child schema
735 * The default value for a child column is defined as:
736 * (1) If the child schema specifies a default, that value is used.
737 * (2) If neither the child nor any parent specifies a default, then
738 * the column will not have a default.
739 * (3) If conflicting defaults are inherited from different parents
740 * (and not overridden by the child), an error is raised.
741 * (4) Otherwise the inherited default is used.
742 * Rule (3) is new in Postgres 7.1; in earlier releases you got a
743 * rather arbitrary choice of which parent default to use.
747 MergeAttributes(List *schema, List *supers, bool istemp,
748 List **supOids, List **supconstr, int *supOidCount)
751 List *inhSchema = NIL;
752 List *parentOids = NIL;
753 List *constraints = NIL;
754 int parentsWithOids = 0;
755 bool have_bogus_defaults = false;
756 char *bogus_marker = "Bogus!"; /* marks conflicting defaults */
760 * Check for and reject tables with too many columns. We perform this
761 * check relatively early for two reasons: (a) we don't run the risk of
762 * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
763 * okay if we're processing <= 1600 columns, but could take minutes to
764 * execute if the user attempts to create a table with hundreds of
765 * thousands of columns.
767 * Note that we also need to check that any we do not exceed this figure
768 * after including columns from inherited relations.
770 if (list_length(schema) > MaxHeapAttributeNumber)
772 (errcode(ERRCODE_TOO_MANY_COLUMNS),
773 errmsg("tables can have at most %d columns",
774 MaxHeapAttributeNumber)));
777 * Check for duplicate names in the explicit list of attributes.
779 * Although we might consider merging such entries in the same way that we
780 * handle name conflicts for inherited attributes, it seems to make more
781 * sense to assume such conflicts are errors.
783 foreach(entry, schema)
785 ColumnDef *coldef = lfirst(entry);
788 for_each_cell(rest, lnext(entry))
790 ColumnDef *restdef = lfirst(rest);
792 if (strcmp(coldef->colname, restdef->colname) == 0)
794 (errcode(ERRCODE_DUPLICATE_COLUMN),
795 errmsg("column \"%s\" specified more than once",
801 * Scan the parents left-to-right, and merge their attributes to form a
802 * list of inherited attributes (inhSchema). Also check to see if we need
803 * to inherit an OID column.
806 foreach(entry, supers)
808 RangeVar *parent = (RangeVar *) lfirst(entry);
812 AttrNumber *newattno;
813 AttrNumber parent_attno;
815 relation = heap_openrv(parent, AccessShareLock);
817 if (relation->rd_rel->relkind != RELKIND_RELATION)
819 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
820 errmsg("inherited relation \"%s\" is not a table",
822 /* Permanent rels cannot inherit from temporary ones */
823 if (!istemp && isTempNamespace(RelationGetNamespace(relation)))
825 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
826 errmsg("cannot inherit from temporary relation \"%s\"",
830 * We should have an UNDER permission flag for this, but for now,
831 * demand that creator of a child table own the parent.
833 if (!pg_class_ownercheck(RelationGetRelid(relation), GetUserId()))
834 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
835 RelationGetRelationName(relation));
838 * Reject duplications in the list of parents.
840 if (list_member_oid(parentOids, RelationGetRelid(relation)))
842 (errcode(ERRCODE_DUPLICATE_TABLE),
843 errmsg("relation \"%s\" would be inherited from more than once",
846 parentOids = lappend_oid(parentOids, RelationGetRelid(relation));
848 if (relation->rd_rel->relhasoids)
851 tupleDesc = RelationGetDescr(relation);
852 constr = tupleDesc->constr;
855 * newattno[] will contain the child-table attribute numbers for the
856 * attributes of this parent table. (They are not the same for
857 * parents after the first one, nor if we have dropped columns.)
859 newattno = (AttrNumber *)
860 palloc(tupleDesc->natts * sizeof(AttrNumber));
862 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
865 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
866 char *attributeName = NameStr(attribute->attname);
871 * Ignore dropped columns in the parent.
873 if (attribute->attisdropped)
876 * change_varattnos_of_a_node asserts that this is greater
877 * than zero, so if anything tries to use it, we should find
880 newattno[parent_attno - 1] = 0;
885 * Does it conflict with some previously inherited column?
887 exist_attno = findAttrByName(attributeName, inhSchema);
894 * Yes, try to merge the two column definitions. They must
895 * have the same type and typmod.
898 (errmsg("merging multiple inherited definitions of column \"%s\"",
900 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
901 defTypeId = typenameTypeId(NULL, def->typename);
902 deftypmod = typenameTypeMod(NULL, def->typename, defTypeId);
903 if (defTypeId != attribute->atttypid ||
904 deftypmod != attribute->atttypmod)
906 (errcode(ERRCODE_DATATYPE_MISMATCH),
907 errmsg("inherited column \"%s\" has a type conflict",
909 errdetail("%s versus %s",
910 TypeNameToString(def->typename),
911 format_type_be(attribute->atttypid))));
913 /* Merge of NOT NULL constraints = OR 'em together */
914 def->is_not_null |= attribute->attnotnull;
915 /* Default and other constraints are handled below */
916 newattno[parent_attno - 1] = exist_attno;
921 * No, create a new inherited column
923 def = makeNode(ColumnDef);
924 def->colname = pstrdup(attributeName);
925 def->typename = makeTypeNameFromOid(attribute->atttypid,
926 attribute->atttypmod);
928 def->is_local = false;
929 def->is_not_null = attribute->attnotnull;
930 def->raw_default = NULL;
931 def->cooked_default = NULL;
932 def->constraints = NIL;
933 inhSchema = lappend(inhSchema, def);
934 newattno[parent_attno - 1] = ++child_attno;
938 * Copy default if any
940 if (attribute->atthasdef)
942 char *this_default = NULL;
943 AttrDefault *attrdef;
946 /* Find default in constraint structure */
947 Assert(constr != NULL);
948 attrdef = constr->defval;
949 for (i = 0; i < constr->num_defval; i++)
951 if (attrdef[i].adnum == parent_attno)
953 this_default = attrdef[i].adbin;
957 Assert(this_default != NULL);
960 * If default expr could contain any vars, we'd need to fix
961 * 'em, but it can't; so default is ready to apply to child.
963 * If we already had a default from some prior parent, check
964 * to see if they are the same. If so, no problem; if not,
965 * mark the column as having a bogus default. Below, we will
966 * complain if the bogus default isn't overridden by the child
969 Assert(def->raw_default == NULL);
970 if (def->cooked_default == NULL)
971 def->cooked_default = pstrdup(this_default);
972 else if (strcmp(def->cooked_default, this_default) != 0)
974 def->cooked_default = bogus_marker;
975 have_bogus_defaults = true;
981 * Now copy the constraints of this parent, adjusting attnos using the
982 * completed newattno[] map
984 if (constr && constr->num_check > 0)
986 ConstrCheck *check = constr->check;
989 for (i = 0; i < constr->num_check; i++)
991 Constraint *cdef = makeNode(Constraint);
994 cdef->contype = CONSTR_CHECK;
995 cdef->name = pstrdup(check[i].ccname);
996 cdef->raw_expr = NULL;
997 /* adjust varattnos of ccbin here */
998 expr = stringToNode(check[i].ccbin);
999 change_varattnos_of_a_node(expr, newattno);
1000 cdef->cooked_expr = nodeToString(expr);
1001 constraints = lappend(constraints, cdef);
1008 * Close the parent rel, but keep our AccessShareLock on it until xact
1009 * commit. That will prevent someone else from deleting or ALTERing
1010 * the parent before the child is committed.
1012 heap_close(relation, NoLock);
1016 * If we had no inherited attributes, the result schema is just the
1017 * explicitly declared columns. Otherwise, we need to merge the declared
1018 * columns into the inherited schema list.
1020 if (inhSchema != NIL)
1022 foreach(entry, schema)
1024 ColumnDef *newdef = lfirst(entry);
1025 char *attributeName = newdef->colname;
1029 * Does it conflict with some previously inherited column?
1031 exist_attno = findAttrByName(attributeName, inhSchema);
1032 if (exist_attno > 0)
1035 Oid defTypeId, newTypeId;
1036 int32 deftypmod, newtypmod;
1039 * Yes, try to merge the two column definitions. They must
1040 * have the same type and typmod.
1043 (errmsg("merging column \"%s\" with inherited definition",
1045 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1046 defTypeId = typenameTypeId(NULL, def->typename);
1047 deftypmod = typenameTypeMod(NULL, def->typename, defTypeId);
1048 newTypeId = typenameTypeId(NULL, newdef->typename);
1049 newtypmod = typenameTypeMod(NULL, newdef->typename, newTypeId);
1050 if (defTypeId != newTypeId || deftypmod != newtypmod)
1052 (errcode(ERRCODE_DATATYPE_MISMATCH),
1053 errmsg("column \"%s\" has a type conflict",
1055 errdetail("%s versus %s",
1056 TypeNameToString(def->typename),
1057 TypeNameToString(newdef->typename))));
1058 /* Mark the column as locally defined */
1059 def->is_local = true;
1060 /* Merge of NOT NULL constraints = OR 'em together */
1061 def->is_not_null |= newdef->is_not_null;
1062 /* If new def has a default, override previous default */
1063 if (newdef->raw_default != NULL)
1065 def->raw_default = newdef->raw_default;
1066 def->cooked_default = newdef->cooked_default;
1072 * No, attach new column to result schema
1074 inhSchema = lappend(inhSchema, newdef);
1081 * Check that we haven't exceeded the legal # of columns after merging
1082 * in inherited columns.
1084 if (list_length(schema) > MaxHeapAttributeNumber)
1086 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1087 errmsg("tables can have at most %d columns",
1088 MaxHeapAttributeNumber)));
1092 * If we found any conflicting parent default values, check to make sure
1093 * they were overridden by the child.
1095 if (have_bogus_defaults)
1097 foreach(entry, schema)
1099 ColumnDef *def = lfirst(entry);
1101 if (def->cooked_default == bogus_marker)
1103 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
1104 errmsg("column \"%s\" inherits conflicting default values",
1106 errhint("To resolve the conflict, specify a default explicitly.")));
1110 *supOids = parentOids;
1111 *supconstr = constraints;
1112 *supOidCount = parentsWithOids;
1118 * In multiple-inheritance situations, it's possible to inherit
1119 * the same grandparent constraint through multiple parents.
1120 * Hence, we want to discard inherited constraints that match as to
1121 * both name and expression. Otherwise, gripe if there are conflicting
1122 * names. Nonconflicting constraints are added to the array check[]
1123 * of length *ncheck ... caller must ensure there is room!
1126 add_nonduplicate_constraint(Constraint *cdef, ConstrCheck *check, int *ncheck)
1130 /* Should only see precooked constraints here */
1131 Assert(cdef->contype == CONSTR_CHECK);
1132 Assert(cdef->name != NULL);
1133 Assert(cdef->raw_expr == NULL && cdef->cooked_expr != NULL);
1135 for (i = 0; i < *ncheck; i++)
1137 if (strcmp(check[i].ccname, cdef->name) != 0)
1139 if (strcmp(check[i].ccbin, cdef->cooked_expr) == 0)
1140 return; /* duplicate constraint, so ignore it */
1142 (errcode(ERRCODE_DUPLICATE_OBJECT),
1143 errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
1146 /* No match on name, so add it to array */
1147 check[*ncheck].ccname = cdef->name;
1148 check[*ncheck].ccbin = pstrdup(cdef->cooked_expr);
1154 * Replace varattno values in an expression tree according to the given
1155 * map array, that is, varattno N is replaced by newattno[N-1]. It is
1156 * caller's responsibility to ensure that the array is long enough to
1157 * define values for all user varattnos present in the tree. System column
1158 * attnos remain unchanged.
1160 * Note that the passed node tree is modified in-place!
1163 change_varattnos_of_a_node(Node *node, const AttrNumber *newattno)
1165 /* no setup needed, so away we go */
1166 (void) change_varattnos_walker(node, newattno);
1170 change_varattnos_walker(Node *node, const AttrNumber *newattno)
1176 Var *var = (Var *) node;
1178 if (var->varlevelsup == 0 && var->varno == 1 &&
1182 * ??? the following may be a problem when the node is multiply
1183 * referenced though stringToNode() doesn't create such a node
1186 Assert(newattno[var->varattno - 1] > 0);
1187 var->varattno = newattno[var->varattno - 1];
1191 return expression_tree_walker(node, change_varattnos_walker,
1196 * Generate a map for change_varattnos_of_a_node from old and new TupleDesc's,
1197 * matching according to column name.
1200 varattnos_map(TupleDesc old, TupleDesc new)
1206 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * old->natts);
1207 for (i = 1; i <= old->natts; i++)
1209 if (old->attrs[i - 1]->attisdropped)
1210 continue; /* leave the entry as zero */
1212 for (j = 1; j <= new->natts; j++)
1214 if (strcmp(NameStr(old->attrs[i - 1]->attname),
1215 NameStr(new->attrs[j - 1]->attname)) == 0)
1226 * Generate a map for change_varattnos_of_a_node from a TupleDesc and a list
1230 varattnos_map_schema(TupleDesc old, List *schema)
1235 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * old->natts);
1236 for (i = 1; i <= old->natts; i++)
1238 if (old->attrs[i - 1]->attisdropped)
1239 continue; /* leave the entry as zero */
1241 attmap[i - 1] = findAttrByName(NameStr(old->attrs[i - 1]->attname),
1249 * StoreCatalogInheritance
1250 * Updates the system catalogs with proper inheritance information.
1252 * supers is a list of the OIDs of the new relation's direct ancestors.
1255 StoreCatalogInheritance(Oid relationId, List *supers)
1264 AssertArg(OidIsValid(relationId));
1270 * Store INHERITS information in pg_inherits using direct ancestors only.
1271 * Also enter dependencies on the direct ancestors, and make sure they are
1272 * marked with relhassubclass = true.
1274 * (Once upon a time, both direct and indirect ancestors were found here
1275 * and then entered into pg_ipl. Since that catalog doesn't exist
1276 * anymore, there's no need to look for indirect ancestors.)
1278 relation = heap_open(InheritsRelationId, RowExclusiveLock);
1281 foreach(entry, supers)
1283 Oid parentOid = lfirst_oid(entry);
1285 StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation);
1289 heap_close(relation, RowExclusiveLock);
1293 * Make catalog entries showing relationId as being an inheritance child
1294 * of parentOid. inhRelation is the already-opened pg_inherits catalog.
1297 StoreCatalogInheritance1(Oid relationId, Oid parentOid,
1298 int16 seqNumber, Relation inhRelation)
1300 TupleDesc desc = RelationGetDescr(inhRelation);
1301 Datum datum[Natts_pg_inherits];
1302 char nullarr[Natts_pg_inherits];
1303 ObjectAddress childobject,
1308 * Make the pg_inherits entry
1310 datum[0] = ObjectIdGetDatum(relationId); /* inhrelid */
1311 datum[1] = ObjectIdGetDatum(parentOid); /* inhparent */
1312 datum[2] = Int16GetDatum(seqNumber); /* inhseqno */
1318 tuple = heap_formtuple(desc, datum, nullarr);
1320 simple_heap_insert(inhRelation, tuple);
1322 CatalogUpdateIndexes(inhRelation, tuple);
1324 heap_freetuple(tuple);
1327 * Store a dependency too
1329 parentobject.classId = RelationRelationId;
1330 parentobject.objectId = parentOid;
1331 parentobject.objectSubId = 0;
1332 childobject.classId = RelationRelationId;
1333 childobject.objectId = relationId;
1334 childobject.objectSubId = 0;
1336 recordDependencyOn(&childobject, &parentobject, DEPENDENCY_NORMAL);
1339 * Mark the parent as having subclasses.
1341 setRelhassubclassInRelation(parentOid, true);
1345 * Look for an existing schema entry with the given name.
1347 * Returns the index (starting with 1) if attribute already exists in schema,
1351 findAttrByName(const char *attributeName, List *schema)
1358 ColumnDef *def = lfirst(s);
1360 if (strcmp(attributeName, def->colname) == 0)
1369 * Update a relation's pg_class.relhassubclass entry to the given value
1372 setRelhassubclassInRelation(Oid relationId, bool relhassubclass)
1374 Relation relationRelation;
1376 Form_pg_class classtuple;
1379 * Fetch a modifiable copy of the tuple, modify it, update pg_class.
1381 * If the tuple already has the right relhassubclass setting, we don't
1382 * need to update it, but we still need to issue an SI inval message.
1384 relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
1385 tuple = SearchSysCacheCopy(RELOID,
1386 ObjectIdGetDatum(relationId),
1388 if (!HeapTupleIsValid(tuple))
1389 elog(ERROR, "cache lookup failed for relation %u", relationId);
1390 classtuple = (Form_pg_class) GETSTRUCT(tuple);
1392 if (classtuple->relhassubclass != relhassubclass)
1394 classtuple->relhassubclass = relhassubclass;
1395 simple_heap_update(relationRelation, &tuple->t_self, tuple);
1397 /* keep the catalog indexes up to date */
1398 CatalogUpdateIndexes(relationRelation, tuple);
1402 /* no need to change tuple, but force relcache rebuild anyway */
1403 CacheInvalidateRelcacheByTuple(tuple);
1406 heap_freetuple(tuple);
1407 heap_close(relationRelation, RowExclusiveLock);
1412 * renameatt - changes the name of a attribute in a relation
1414 * Attname attribute is changed in attribute catalog.
1415 * No record of the previous attname is kept (correct?).
1417 * get proper relrelation from relation catalog (if not arg)
1418 * scan attribute catalog
1419 * for name conflict (within rel)
1420 * for original attribute (if not arg)
1421 * modify attname in attribute tuple
1422 * insert modified attribute in attribute catalog
1423 * delete original attribute from attribute catalog
1426 renameatt(Oid myrelid,
1427 const char *oldattname,
1428 const char *newattname,
1432 Relation targetrelation;
1433 Relation attrelation;
1435 Form_pg_attribute attform;
1438 ListCell *indexoidscan;
1441 * Grab an exclusive lock on the target table, which we will NOT release
1442 * until end of transaction.
1444 targetrelation = relation_open(myrelid, AccessExclusiveLock);
1447 * permissions checking. this would normally be done in utility.c, but
1448 * this particular routine is recursive.
1450 * normally, only the owner of a class can change its schema.
1452 if (!pg_class_ownercheck(myrelid, GetUserId()))
1453 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1454 RelationGetRelationName(targetrelation));
1455 if (!allowSystemTableMods && IsSystemRelation(targetrelation))
1457 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1458 errmsg("permission denied: \"%s\" is a system catalog",
1459 RelationGetRelationName(targetrelation))));
1462 * if the 'recurse' flag is set then we are supposed to rename this
1463 * attribute in all classes that inherit from 'relname' (as well as in
1466 * any permissions or problems with duplicate attributes will cause the
1467 * whole transaction to abort, which is what we want -- all or nothing.
1474 /* this routine is actually in the planner */
1475 children = find_all_inheritors(myrelid);
1478 * find_all_inheritors does the recursive search of the inheritance
1479 * hierarchy, so all we have to do is process all of the relids in the
1480 * list that it returns.
1482 foreach(child, children)
1484 Oid childrelid = lfirst_oid(child);
1486 if (childrelid == myrelid)
1488 /* note we need not recurse again */
1489 renameatt(childrelid, oldattname, newattname, false, true);
1495 * If we are told not to recurse, there had better not be any child
1496 * tables; else the rename would put them out of step.
1499 find_inheritance_children(myrelid) != NIL)
1501 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1502 errmsg("inherited column \"%s\" must be renamed in child tables too",
1506 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
1508 atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
1509 if (!HeapTupleIsValid(atttup))
1511 (errcode(ERRCODE_UNDEFINED_COLUMN),
1512 errmsg("column \"%s\" does not exist",
1514 attform = (Form_pg_attribute) GETSTRUCT(atttup);
1516 attnum = attform->attnum;
1519 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1520 errmsg("cannot rename system column \"%s\"",
1524 * if the attribute is inherited, forbid the renaming, unless we are
1525 * already inside a recursive rename.
1527 if (attform->attinhcount > 0 && !recursing)
1529 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1530 errmsg("cannot rename inherited column \"%s\"",
1533 /* should not already exist */
1534 /* this test is deliberately not attisdropped-aware */
1535 if (SearchSysCacheExists(ATTNAME,
1536 ObjectIdGetDatum(myrelid),
1537 PointerGetDatum(newattname),
1540 (errcode(ERRCODE_DUPLICATE_COLUMN),
1541 errmsg("column \"%s\" of relation \"%s\" already exists",
1542 newattname, RelationGetRelationName(targetrelation))));
1544 namestrcpy(&(attform->attname), newattname);
1546 simple_heap_update(attrelation, &atttup->t_self, atttup);
1548 /* keep system catalog indexes current */
1549 CatalogUpdateIndexes(attrelation, atttup);
1551 heap_freetuple(atttup);
1554 * Update column names of indexes that refer to the column being renamed.
1556 indexoidlist = RelationGetIndexList(targetrelation);
1558 foreach(indexoidscan, indexoidlist)
1560 Oid indexoid = lfirst_oid(indexoidscan);
1562 Form_pg_index indexform;
1566 * Scan through index columns to see if there's any simple index
1567 * entries for this attribute. We ignore expressional entries.
1569 indextup = SearchSysCache(INDEXRELID,
1570 ObjectIdGetDatum(indexoid),
1572 if (!HeapTupleIsValid(indextup))
1573 elog(ERROR, "cache lookup failed for index %u", indexoid);
1574 indexform = (Form_pg_index) GETSTRUCT(indextup);
1576 for (i = 0; i < indexform->indnatts; i++)
1578 if (attnum != indexform->indkey.values[i])
1582 * Found one, rename it.
1584 atttup = SearchSysCacheCopy(ATTNUM,
1585 ObjectIdGetDatum(indexoid),
1586 Int16GetDatum(i + 1),
1588 if (!HeapTupleIsValid(atttup))
1589 continue; /* should we raise an error? */
1592 * Update the (copied) attribute tuple.
1594 namestrcpy(&(((Form_pg_attribute) GETSTRUCT(atttup))->attname),
1597 simple_heap_update(attrelation, &atttup->t_self, atttup);
1599 /* keep system catalog indexes current */
1600 CatalogUpdateIndexes(attrelation, atttup);
1602 heap_freetuple(atttup);
1605 ReleaseSysCache(indextup);
1608 list_free(indexoidlist);
1610 heap_close(attrelation, RowExclusiveLock);
1612 relation_close(targetrelation, NoLock); /* close rel but keep lock */
1616 * renamerel - change the name of a relation
1618 * XXX - When renaming sequences, we don't bother to modify the
1619 * sequence name that is stored within the sequence itself
1620 * (this would cause problems with MVCC). In the future,
1621 * the sequence name should probably be removed from the
1622 * sequence, AFAIK there's no need for it to be there.
1625 renamerel(Oid myrelid, const char *newrelname, ObjectType reltype)
1627 Relation targetrelation;
1628 Relation relrelation; /* for RELATION relation */
1630 Form_pg_class relform;
1634 bool relhastriggers;
1637 * Grab an exclusive lock on the target table, index, sequence or
1638 * view, which we will NOT release until end of transaction.
1640 targetrelation = relation_open(myrelid, AccessExclusiveLock);
1642 oldrelname = pstrdup(RelationGetRelationName(targetrelation));
1643 namespaceId = RelationGetNamespace(targetrelation);
1645 if (!allowSystemTableMods && IsSystemRelation(targetrelation))
1647 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1648 errmsg("permission denied: \"%s\" is a system catalog",
1649 RelationGetRelationName(targetrelation))));
1652 * For compatibility with prior releases, we don't complain if
1653 * ALTER TABLE or ALTER INDEX is used to rename a sequence or
1656 relkind = targetrelation->rd_rel->relkind;
1657 if (reltype == OBJECT_SEQUENCE && relkind != 'S')
1659 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1660 errmsg("\"%s\" is not a sequence",
1661 RelationGetRelationName(targetrelation))));
1663 if (reltype == OBJECT_VIEW && relkind != 'v')
1665 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1666 errmsg("\"%s\" is not a view",
1667 RelationGetRelationName(targetrelation))));
1669 relhastriggers = (targetrelation->rd_rel->reltriggers > 0);
1672 * Find relation's pg_class tuple, and make sure newrelname isn't in use.
1674 relrelation = heap_open(RelationRelationId, RowExclusiveLock);
1676 reltup = SearchSysCacheCopy(RELOID,
1677 ObjectIdGetDatum(myrelid),
1679 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
1680 elog(ERROR, "cache lookup failed for relation %u", myrelid);
1681 relform = (Form_pg_class) GETSTRUCT(reltup);
1683 if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
1685 (errcode(ERRCODE_DUPLICATE_TABLE),
1686 errmsg("relation \"%s\" already exists",
1690 * Update pg_class tuple with new relname. (Scribbling on reltup is OK
1691 * because it's a copy...)
1693 namestrcpy(&(relform->relname), newrelname);
1695 simple_heap_update(relrelation, &reltup->t_self, reltup);
1697 /* keep the system catalog indexes current */
1698 CatalogUpdateIndexes(relrelation, reltup);
1700 heap_freetuple(reltup);
1701 heap_close(relrelation, RowExclusiveLock);
1704 * Also rename the associated type, if any.
1706 if (OidIsValid(targetrelation->rd_rel->reltype))
1707 TypeRename(targetrelation->rd_rel->reltype, newrelname, namespaceId);
1710 * Close rel, but keep exclusive lock!
1712 relation_close(targetrelation, NoLock);
1717 * Execute ALTER TABLE, which can be a list of subcommands
1719 * ALTER TABLE is performed in three phases:
1720 * 1. Examine subcommands and perform pre-transformation checking.
1721 * 2. Update system catalogs.
1722 * 3. Scan table(s) to check new constraints, and optionally recopy
1723 * the data into new table(s).
1724 * Phase 3 is not performed unless one or more of the subcommands requires
1725 * it. The intention of this design is to allow multiple independent
1726 * updates of the table schema to be performed with only one pass over the
1729 * ATPrepCmd performs phase 1. A "work queue" entry is created for
1730 * each table to be affected (there may be multiple affected tables if the
1731 * commands traverse a table inheritance hierarchy). Also we do preliminary
1732 * validation of the subcommands, including parse transformation of those
1733 * expressions that need to be evaluated with respect to the old table
1736 * ATRewriteCatalogs performs phase 2 for each affected table (note that
1737 * phases 2 and 3 do no explicit recursion, since phase 1 already did it).
1738 * Certain subcommands need to be performed before others to avoid
1739 * unnecessary conflicts; for example, DROP COLUMN should come before
1740 * ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
1741 * lists, one for each logical "pass" of phase 2.
1743 * ATRewriteTables performs phase 3 for those tables that need it.
1745 * Thanks to the magic of MVCC, an error anywhere along the way rolls back
1746 * the whole operation; we don't have to do anything special to clean up.
1749 AlterTable(AlterTableStmt *stmt)
1751 Relation rel = relation_openrv(stmt->relation, AccessExclusiveLock);
1752 int expected_refcnt;
1755 * Disallow ALTER TABLE when the current backend has any open reference
1756 * to it besides the one we just got (such as an open cursor or active
1757 * plan); our AccessExclusiveLock doesn't protect us against stomping on
1758 * our own foot, only other people's feet!
1760 * Note: the only case known to cause serious trouble is ALTER COLUMN TYPE,
1761 * and some changes are obviously pretty benign, so this could possibly
1762 * be relaxed to only error out for certain types of alterations. But
1763 * the use-case for allowing any of these things is not obvious, so we
1764 * won't work hard at it for now.
1766 expected_refcnt = rel->rd_isnailed ? 2 : 1;
1767 if (rel->rd_refcnt != expected_refcnt)
1769 (errcode(ERRCODE_OBJECT_IN_USE),
1770 errmsg("relation \"%s\" is being used by active queries in this session",
1771 RelationGetRelationName(rel))));
1773 ATController(rel, stmt->cmds, interpretInhOption(stmt->relation->inhOpt));
1777 * AlterTableInternal
1779 * ALTER TABLE with target specified by OID
1781 * We do not reject if the relation is already open, because it's quite
1782 * likely that one or more layers of caller have it open. That means it
1783 * is unsafe to use this entry point for alterations that could break
1784 * existing query plans.
1787 AlterTableInternal(Oid relid, List *cmds, bool recurse)
1789 Relation rel = relation_open(relid, AccessExclusiveLock);
1791 ATController(rel, cmds, recurse);
1795 ATController(Relation rel, List *cmds, bool recurse)
1800 /* Phase 1: preliminary examination of commands, create work queue */
1803 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
1805 ATPrepCmd(&wqueue, rel, cmd, recurse, false);
1808 /* Close the relation, but keep lock until commit */
1809 relation_close(rel, NoLock);
1811 /* Phase 2: update system catalogs */
1812 ATRewriteCatalogs(&wqueue);
1814 /* Phase 3: scan/rewrite tables as needed */
1815 ATRewriteTables(&wqueue);
1821 * Traffic cop for ALTER TABLE Phase 1 operations, including simple
1822 * recursion and permission checks.
1824 * Caller must have acquired AccessExclusiveLock on relation already.
1825 * This lock should be held until commit.
1828 ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
1829 bool recurse, bool recursing)
1831 AlteredTableInfo *tab;
1834 /* Find or create work queue entry for this table */
1835 tab = ATGetQueueEntry(wqueue, rel);
1838 * Copy the original subcommand for each table. This avoids conflicts
1839 * when different child tables need to make different parse
1840 * transformations (for example, the same column may have different column
1841 * numbers in different children).
1843 cmd = copyObject(cmd);
1846 * Do permissions checking, recursion to child tables if needed, and any
1847 * additional phase-1 processing needed.
1849 switch (cmd->subtype)
1851 case AT_AddColumn: /* ADD COLUMN */
1852 ATSimplePermissions(rel, false);
1853 /* Performs own recursion */
1854 ATPrepAddColumn(wqueue, rel, recurse, cmd);
1855 pass = AT_PASS_ADD_COL;
1857 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
1860 * We allow defaults on views so that INSERT into a view can have
1861 * default-ish behavior. This works because the rewriter
1862 * substitutes default values into INSERTs before it expands
1865 ATSimplePermissions(rel, true);
1866 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1867 /* No command-specific prep needed */
1868 pass = cmd->def ? AT_PASS_ADD_CONSTR : AT_PASS_DROP;
1870 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
1871 ATSimplePermissions(rel, false);
1872 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1873 /* No command-specific prep needed */
1874 pass = AT_PASS_DROP;
1876 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
1877 ATSimplePermissions(rel, false);
1878 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1879 /* No command-specific prep needed */
1880 pass = AT_PASS_ADD_CONSTR;
1882 case AT_SetStatistics: /* ALTER COLUMN STATISTICS */
1883 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1884 /* Performs own permission checks */
1885 ATPrepSetStatistics(rel, cmd->name, cmd->def);
1886 pass = AT_PASS_COL_ATTRS;
1888 case AT_SetStorage: /* ALTER COLUMN STORAGE */
1889 ATSimplePermissions(rel, false);
1890 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1891 /* No command-specific prep needed */
1892 pass = AT_PASS_COL_ATTRS;
1894 case AT_DropColumn: /* DROP COLUMN */
1895 ATSimplePermissions(rel, false);
1896 /* Recursion occurs during execution phase */
1897 /* No command-specific prep needed except saving recurse flag */
1899 cmd->subtype = AT_DropColumnRecurse;
1900 pass = AT_PASS_DROP;
1902 case AT_AddIndex: /* ADD INDEX */
1903 ATSimplePermissions(rel, false);
1904 /* This command never recurses */
1905 /* No command-specific prep needed */
1906 pass = AT_PASS_ADD_INDEX;
1908 case AT_AddConstraint: /* ADD CONSTRAINT */
1909 ATSimplePermissions(rel, false);
1912 * Currently we recurse only for CHECK constraints, never for
1913 * foreign-key constraints. UNIQUE/PKEY constraints won't be seen
1916 if (IsA(cmd->def, Constraint))
1917 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1918 /* No command-specific prep needed */
1919 pass = AT_PASS_ADD_CONSTR;
1921 case AT_DropConstraint: /* DROP CONSTRAINT */
1922 ATSimplePermissions(rel, false);
1923 /* Performs own recursion */
1924 ATPrepDropConstraint(wqueue, rel, recurse, cmd);
1925 pass = AT_PASS_DROP;
1927 case AT_DropConstraintQuietly: /* DROP CONSTRAINT for child */
1928 ATSimplePermissions(rel, false);
1929 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1930 /* No command-specific prep needed */
1931 pass = AT_PASS_DROP;
1933 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
1934 ATSimplePermissions(rel, false);
1935 /* Performs own recursion */
1936 ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd);
1937 pass = AT_PASS_ALTER_TYPE;
1939 case AT_ChangeOwner: /* ALTER OWNER */
1940 /* This command never recurses */
1941 /* No command-specific prep needed */
1942 pass = AT_PASS_MISC;
1944 case AT_ClusterOn: /* CLUSTER ON */
1945 case AT_DropCluster: /* SET WITHOUT CLUSTER */
1946 ATSimplePermissions(rel, false);
1947 /* These commands never recurse */
1948 /* No command-specific prep needed */
1949 pass = AT_PASS_MISC;
1951 case AT_DropOids: /* SET WITHOUT OIDS */
1952 ATSimplePermissions(rel, false);
1953 /* Performs own recursion */
1954 if (rel->rd_rel->relhasoids)
1956 AlterTableCmd *dropCmd = makeNode(AlterTableCmd);
1958 dropCmd->subtype = AT_DropColumn;
1959 dropCmd->name = pstrdup("oid");
1960 dropCmd->behavior = cmd->behavior;
1961 ATPrepCmd(wqueue, rel, dropCmd, recurse, false);
1963 pass = AT_PASS_DROP;
1965 case AT_SetTableSpace: /* SET TABLESPACE */
1966 ATSimplePermissionsRelationOrIndex(rel);
1967 /* This command never recurses */
1968 ATPrepSetTableSpace(tab, rel, cmd->name);
1969 pass = AT_PASS_MISC; /* doesn't actually matter */
1971 case AT_SetRelOptions: /* SET (...) */
1972 case AT_ResetRelOptions: /* RESET (...) */
1973 ATSimplePermissionsRelationOrIndex(rel);
1974 /* This command never recurses */
1975 /* No command-specific prep needed */
1976 pass = AT_PASS_MISC;
1978 case AT_EnableTrig: /* ENABLE TRIGGER variants */
1979 case AT_EnableAlwaysTrig:
1980 case AT_EnableReplicaTrig:
1981 case AT_EnableTrigAll:
1982 case AT_EnableTrigUser:
1983 case AT_DisableTrig: /* DISABLE TRIGGER variants */
1984 case AT_DisableTrigAll:
1985 case AT_DisableTrigUser:
1986 case AT_EnableRule: /* ENABLE/DISABLE RULE variants */
1987 case AT_EnableAlwaysRule:
1988 case AT_EnableReplicaRule:
1989 case AT_DisableRule:
1990 case AT_AddInherit: /* INHERIT / NO INHERIT */
1991 case AT_DropInherit:
1992 ATSimplePermissions(rel, false);
1993 /* These commands never recurse */
1994 /* No command-specific prep needed */
1995 pass = AT_PASS_MISC;
1998 elog(ERROR, "unrecognized alter table type: %d",
1999 (int) cmd->subtype);
2000 pass = 0; /* keep compiler quiet */
2004 /* Add the subcommand to the appropriate list for phase 2 */
2005 tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
2011 * Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
2012 * dispatched in a "safe" execution order (designed to avoid unnecessary
2016 ATRewriteCatalogs(List **wqueue)
2022 * We process all the tables "in parallel", one pass at a time. This is
2023 * needed because we may have to propagate work from one table to another
2024 * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
2025 * re-adding of the foreign key constraint to the other table). Work can
2026 * only be propagated into later passes, however.
2028 for (pass = 0; pass < AT_NUM_PASSES; pass++)
2030 /* Go through each table that needs to be processed */
2031 foreach(ltab, *wqueue)
2033 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2034 List *subcmds = tab->subcmds[pass];
2042 * Exclusive lock was obtained by phase 1, needn't get it again
2044 rel = relation_open(tab->relid, NoLock);
2046 foreach(lcmd, subcmds)
2047 ATExecCmd(tab, rel, (AlterTableCmd *) lfirst(lcmd));
2050 * After the ALTER TYPE pass, do cleanup work (this is not done in
2051 * ATExecAlterColumnType since it should be done only once if
2052 * multiple columns of a table are altered).
2054 if (pass == AT_PASS_ALTER_TYPE)
2055 ATPostAlterTypeCleanup(wqueue, tab);
2057 relation_close(rel, NoLock);
2062 * Check to see if a toast table must be added, if we executed any
2063 * subcommands that might have added a column or changed column storage.
2065 foreach(ltab, *wqueue)
2067 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2069 if (tab->relkind == RELKIND_RELATION &&
2070 (tab->subcmds[AT_PASS_ADD_COL] ||
2071 tab->subcmds[AT_PASS_ALTER_TYPE] ||
2072 tab->subcmds[AT_PASS_COL_ATTRS]))
2073 AlterTableCreateToastTable(tab->relid);
2078 * ATExecCmd: dispatch a subcommand to appropriate execution routine
2081 ATExecCmd(AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd)
2083 switch (cmd->subtype)
2085 case AT_AddColumn: /* ADD COLUMN */
2086 ATExecAddColumn(tab, rel, (ColumnDef *) cmd->def);
2088 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
2089 ATExecColumnDefault(rel, cmd->name, cmd->def);
2091 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
2092 ATExecDropNotNull(rel, cmd->name);
2094 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
2095 ATExecSetNotNull(tab, rel, cmd->name);
2097 case AT_SetStatistics: /* ALTER COLUMN STATISTICS */
2098 ATExecSetStatistics(rel, cmd->name, cmd->def);
2100 case AT_SetStorage: /* ALTER COLUMN STORAGE */
2101 ATExecSetStorage(rel, cmd->name, cmd->def);
2103 case AT_DropColumn: /* DROP COLUMN */
2104 ATExecDropColumn(rel, cmd->name, cmd->behavior, false, false);
2106 case AT_DropColumnRecurse: /* DROP COLUMN with recursion */
2107 ATExecDropColumn(rel, cmd->name, cmd->behavior, true, false);
2109 case AT_AddIndex: /* ADD INDEX */
2110 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false);
2112 case AT_ReAddIndex: /* ADD INDEX */
2113 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true);
2115 case AT_AddConstraint: /* ADD CONSTRAINT */
2116 ATExecAddConstraint(tab, rel, cmd->def);
2118 case AT_DropConstraint: /* DROP CONSTRAINT */
2119 ATExecDropConstraint(rel, cmd->name, cmd->behavior, false);
2121 case AT_DropConstraintQuietly: /* DROP CONSTRAINT for child */
2122 ATExecDropConstraint(rel, cmd->name, cmd->behavior, true);
2124 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
2125 ATExecAlterColumnType(tab, rel, cmd->name, (TypeName *) cmd->def);
2127 case AT_ChangeOwner: /* ALTER OWNER */
2128 ATExecChangeOwner(RelationGetRelid(rel),
2129 get_roleid_checked(cmd->name),
2132 case AT_ClusterOn: /* CLUSTER ON */
2133 ATExecClusterOn(rel, cmd->name);
2135 case AT_DropCluster: /* SET WITHOUT CLUSTER */
2136 ATExecDropCluster(rel);
2138 case AT_DropOids: /* SET WITHOUT OIDS */
2141 * Nothing to do here; we'll have generated a DropColumn
2142 * subcommand to do the real work
2145 case AT_SetTableSpace: /* SET TABLESPACE */
2148 * Nothing to do here; Phase 3 does the work
2151 case AT_SetRelOptions: /* SET (...) */
2152 ATExecSetRelOptions(rel, (List *) cmd->def, false);
2154 case AT_ResetRelOptions: /* RESET (...) */
2155 ATExecSetRelOptions(rel, (List *) cmd->def, true);
2158 case AT_EnableTrig: /* ENABLE TRIGGER name */
2159 ATExecEnableDisableTrigger(rel, cmd->name,
2160 TRIGGER_FIRES_ON_ORIGIN, false);
2162 case AT_EnableAlwaysTrig: /* ENABLE ALWAYS TRIGGER name */
2163 ATExecEnableDisableTrigger(rel, cmd->name,
2164 TRIGGER_FIRES_ALWAYS, false);
2166 case AT_EnableReplicaTrig: /* ENABLE REPLICA TRIGGER name */
2167 ATExecEnableDisableTrigger(rel, cmd->name,
2168 TRIGGER_FIRES_ON_REPLICA, false);
2170 case AT_DisableTrig: /* DISABLE TRIGGER name */
2171 ATExecEnableDisableTrigger(rel, cmd->name,
2172 TRIGGER_DISABLED, false);
2174 case AT_EnableTrigAll: /* ENABLE TRIGGER ALL */
2175 ATExecEnableDisableTrigger(rel, NULL,
2176 TRIGGER_FIRES_ON_ORIGIN, false);
2178 case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
2179 ATExecEnableDisableTrigger(rel, NULL,
2180 TRIGGER_DISABLED, false);
2182 case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
2183 ATExecEnableDisableTrigger(rel, NULL,
2184 TRIGGER_FIRES_ON_ORIGIN, true);
2186 case AT_DisableTrigUser: /* DISABLE TRIGGER USER */
2187 ATExecEnableDisableTrigger(rel, NULL,
2188 TRIGGER_DISABLED, true);
2191 case AT_EnableRule: /* ENABLE RULE name */
2192 ATExecEnableDisableRule(rel, cmd->name,
2193 RULE_FIRES_ON_ORIGIN);
2195 case AT_EnableAlwaysRule: /* ENABLE ALWAYS RULE name */
2196 ATExecEnableDisableRule(rel, cmd->name,
2199 case AT_EnableReplicaRule: /* ENABLE REPLICA RULE name */
2200 ATExecEnableDisableRule(rel, cmd->name,
2201 RULE_FIRES_ON_REPLICA);
2203 case AT_DisableRule: /* DISABLE RULE name */
2204 ATExecEnableDisableRule(rel, cmd->name,
2209 ATExecAddInherit(rel, (RangeVar *) cmd->def);
2211 case AT_DropInherit:
2212 ATExecDropInherit(rel, (RangeVar *) cmd->def);
2215 elog(ERROR, "unrecognized alter table type: %d",
2216 (int) cmd->subtype);
2221 * Bump the command counter to ensure the next subcommand in the sequence
2222 * can see the changes so far
2224 CommandCounterIncrement();
2228 * ATRewriteTables: ALTER TABLE phase 3
2231 ATRewriteTables(List **wqueue)
2235 /* Go through each table that needs to be checked or rewritten */
2236 foreach(ltab, *wqueue)
2238 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2241 * We only need to rewrite the table if at least one column needs to
2244 if (tab->newvals != NIL)
2246 /* Build a temporary relation and copy data */
2248 char NewHeapName[NAMEDATALEN];
2251 ObjectAddress object;
2253 OldHeap = heap_open(tab->relid, NoLock);
2256 * We can never allow rewriting of shared or nailed-in-cache
2257 * relations, because we can't support changing their relfilenode
2260 if (OldHeap->rd_rel->relisshared || OldHeap->rd_isnailed)
2262 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2263 errmsg("cannot rewrite system relation \"%s\"",
2264 RelationGetRelationName(OldHeap))));
2267 * Don't allow rewrite on temp tables of other backends ... their
2268 * local buffer manager is not going to cope.
2270 if (isOtherTempNamespace(RelationGetNamespace(OldHeap)))
2272 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2273 errmsg("cannot rewrite temporary tables of other sessions")));
2276 * Select destination tablespace (same as original unless user
2277 * requested a change)
2279 if (tab->newTableSpace)
2280 NewTableSpace = tab->newTableSpace;
2282 NewTableSpace = OldHeap->rd_rel->reltablespace;
2284 heap_close(OldHeap, NoLock);
2287 * Create the new heap, using a temporary name in the same
2288 * namespace as the existing table. NOTE: there is some risk of
2289 * collision with user relnames. Working around this seems more
2290 * trouble than it's worth; in particular, we can't create the new
2291 * heap in a different namespace from the old, or we will have
2292 * problems with the TEMP status of temp tables.
2294 snprintf(NewHeapName, sizeof(NewHeapName),
2295 "pg_temp_%u", tab->relid);
2297 OIDNewHeap = make_new_heap(tab->relid, NewHeapName, NewTableSpace);
2300 * Copy the heap data into the new table with the desired
2301 * modifications, and test the current data within the table
2302 * against new constraints generated by ALTER TABLE commands.
2304 ATRewriteTable(tab, OIDNewHeap);
2307 * Swap the physical files of the old and new heaps. Since we are
2308 * generating a new heap, we can use RecentXmin for the table's new
2309 * relfrozenxid because we rewrote all the tuples on
2310 * ATRewriteTable, so no older Xid remains on the table.
2312 swap_relation_files(tab->relid, OIDNewHeap, RecentXmin);
2314 CommandCounterIncrement();
2316 /* Destroy new heap with old filenode */
2317 object.classId = RelationRelationId;
2318 object.objectId = OIDNewHeap;
2319 object.objectSubId = 0;
2322 * The new relation is local to our transaction and we know
2323 * nothing depends on it, so DROP_RESTRICT should be OK.
2325 performDeletion(&object, DROP_RESTRICT);
2326 /* performDeletion does CommandCounterIncrement at end */
2329 * Rebuild each index on the relation (but not the toast table,
2330 * which is all-new anyway). We do not need
2331 * CommandCounterIncrement() because reindex_relation does it.
2333 reindex_relation(tab->relid, false);
2338 * Test the current data within the table against new constraints
2339 * generated by ALTER TABLE commands, but don't rebuild data.
2341 if (tab->constraints != NIL || tab->new_notnull)
2342 ATRewriteTable(tab, InvalidOid);
2345 * If we had SET TABLESPACE but no reason to reconstruct tuples,
2346 * just do a block-by-block copy.
2348 if (tab->newTableSpace)
2349 ATExecSetTableSpace(tab->relid, tab->newTableSpace);
2354 * Foreign key constraints are checked in a final pass, since (a) it's
2355 * generally best to examine each one separately, and (b) it's at least
2356 * theoretically possible that we have changed both relations of the
2357 * foreign key, and we'd better have finished both rewrites before we try
2358 * to read the tables.
2360 foreach(ltab, *wqueue)
2362 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2363 Relation rel = NULL;
2366 foreach(lcon, tab->constraints)
2368 NewConstraint *con = lfirst(lcon);
2370 if (con->contype == CONSTR_FOREIGN)
2372 FkConstraint *fkconstraint = (FkConstraint *) con->qual;
2377 /* Long since locked, no need for another */
2378 rel = heap_open(tab->relid, NoLock);
2381 refrel = heap_open(con->refrelid, RowShareLock);
2383 validateForeignKeyConstraint(fkconstraint, rel, refrel,
2386 heap_close(refrel, NoLock);
2391 heap_close(rel, NoLock);
2396 * ATRewriteTable: scan or rewrite one table
2398 * OIDNewHeap is InvalidOid if we don't need to rewrite
2401 ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap)
2405 TupleDesc oldTupDesc;
2406 TupleDesc newTupDesc;
2407 bool needscan = false;
2408 List *notnull_attrs;
2414 * Open the relation(s). We have surely already locked the existing
2417 oldrel = heap_open(tab->relid, NoLock);
2418 oldTupDesc = tab->oldDesc;
2419 newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
2421 if (OidIsValid(OIDNewHeap))
2422 newrel = heap_open(OIDNewHeap, AccessExclusiveLock);
2427 * If we need to rewrite the table, the operation has to be propagated to
2428 * tables that use this table's rowtype as a column type.
2430 * (Eventually this will probably become true for scans as well, but at
2431 * the moment a composite type does not enforce any constraints, so it's
2432 * not necessary/appropriate to enforce them just during ALTER.)
2435 find_composite_type_dependencies(oldrel->rd_rel->reltype,
2436 RelationGetRelationName(oldrel),
2440 * Generate the constraint and default execution states
2443 estate = CreateExecutorState();
2445 /* Build the needed expression execution states */
2446 foreach(l, tab->constraints)
2448 NewConstraint *con = lfirst(l);
2450 switch (con->contype)
2454 con->qualstate = (List *)
2455 ExecPrepareExpr((Expr *) con->qual, estate);
2457 case CONSTR_FOREIGN:
2458 /* Nothing to do here */
2461 elog(ERROR, "unrecognized constraint type: %d",
2462 (int) con->contype);
2466 foreach(l, tab->newvals)
2468 NewColumnValue *ex = lfirst(l);
2472 ex->exprstate = ExecPrepareExpr((Expr *) ex->expr, estate);
2475 notnull_attrs = NIL;
2476 if (newrel || tab->new_notnull)
2479 * If we are rebuilding the tuples OR if we added any new NOT NULL
2480 * constraints, check all not-null constraints. This is a bit of
2481 * overkill but it minimizes risk of bugs, and heap_attisnull is a
2482 * pretty cheap test anyway.
2484 for (i = 0; i < newTupDesc->natts; i++)
2486 if (newTupDesc->attrs[i]->attnotnull &&
2487 !newTupDesc->attrs[i]->attisdropped)
2488 notnull_attrs = lappend_int(notnull_attrs, i);
2496 ExprContext *econtext;
2499 TupleTableSlot *oldslot;
2500 TupleTableSlot *newslot;
2503 MemoryContext oldCxt;
2504 List *dropped_attrs = NIL;
2507 econtext = GetPerTupleExprContext(estate);
2510 * Make tuple slots for old and new tuples. Note that even when the
2511 * tuples are the same, the tupDescs might not be (consider ADD COLUMN
2512 * without a default).
2514 oldslot = MakeSingleTupleTableSlot(oldTupDesc);
2515 newslot = MakeSingleTupleTableSlot(newTupDesc);
2517 /* Preallocate values/isnull arrays */
2518 i = Max(newTupDesc->natts, oldTupDesc->natts);
2519 values = (Datum *) palloc(i * sizeof(Datum));
2520 isnull = (bool *) palloc(i * sizeof(bool));
2521 memset(values, 0, i * sizeof(Datum));
2522 memset(isnull, true, i * sizeof(bool));
2525 * Any attributes that are dropped according to the new tuple
2526 * descriptor can be set to NULL. We precompute the list of dropped
2527 * attributes to avoid needing to do so in the per-tuple loop.
2529 for (i = 0; i < newTupDesc->natts; i++)
2531 if (newTupDesc->attrs[i]->attisdropped)
2532 dropped_attrs = lappend_int(dropped_attrs, i);
2536 * Scan through the rows, generating a new row if needed and then
2537 * checking all the constraints.
2539 scan = heap_beginscan(oldrel, SnapshotNow, 0, NULL);
2542 * Switch to per-tuple memory context and reset it for each tuple
2543 * produced, so we don't leak memory.
2545 oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
2547 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2551 Oid tupOid = InvalidOid;
2553 /* Extract data from old tuple */
2554 heap_deform_tuple(tuple, oldTupDesc, values, isnull);
2555 if (oldTupDesc->tdhasoid)
2556 tupOid = HeapTupleGetOid(tuple);
2558 /* Set dropped attributes to null in new tuple */
2559 foreach(lc, dropped_attrs)
2560 isnull[lfirst_int(lc)] = true;
2563 * Process supplied expressions to replace selected columns.
2564 * Expression inputs come from the old tuple.
2566 ExecStoreTuple(tuple, oldslot, InvalidBuffer, false);
2567 econtext->ecxt_scantuple = oldslot;
2569 foreach(l, tab->newvals)
2571 NewColumnValue *ex = lfirst(l);
2573 values[ex->attnum - 1] = ExecEvalExpr(ex->exprstate,
2575 &isnull[ex->attnum - 1],
2580 * Form the new tuple. Note that we don't explicitly pfree it,
2581 * since the per-tuple memory context will be reset shortly.
2583 tuple = heap_form_tuple(newTupDesc, values, isnull);
2585 /* Preserve OID, if any */
2586 if (newTupDesc->tdhasoid)
2587 HeapTupleSetOid(tuple, tupOid);
2590 /* Now check any constraints on the possibly-changed tuple */
2591 ExecStoreTuple(tuple, newslot, InvalidBuffer, false);
2592 econtext->ecxt_scantuple = newslot;
2594 foreach(l, notnull_attrs)
2596 int attn = lfirst_int(l);
2598 if (heap_attisnull(tuple, attn + 1))
2600 (errcode(ERRCODE_NOT_NULL_VIOLATION),
2601 errmsg("column \"%s\" contains null values",
2602 NameStr(newTupDesc->attrs[attn]->attname))));
2605 foreach(l, tab->constraints)
2607 NewConstraint *con = lfirst(l);
2609 switch (con->contype)
2612 if (!ExecQual(con->qualstate, econtext, true))
2614 (errcode(ERRCODE_CHECK_VIOLATION),
2615 errmsg("check constraint \"%s\" is violated by some row",
2618 case CONSTR_FOREIGN:
2619 /* Nothing to do here */
2622 elog(ERROR, "unrecognized constraint type: %d",
2623 (int) con->contype);
2627 /* Write the tuple out to the new relation */
2629 simple_heap_insert(newrel, tuple);
2631 ResetExprContext(econtext);
2633 CHECK_FOR_INTERRUPTS();
2636 MemoryContextSwitchTo(oldCxt);
2639 ExecDropSingleTupleTableSlot(oldslot);
2640 ExecDropSingleTupleTableSlot(newslot);
2643 FreeExecutorState(estate);
2645 heap_close(oldrel, NoLock);
2647 heap_close(newrel, NoLock);
2651 * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
2653 static AlteredTableInfo *
2654 ATGetQueueEntry(List **wqueue, Relation rel)
2656 Oid relid = RelationGetRelid(rel);
2657 AlteredTableInfo *tab;
2660 foreach(ltab, *wqueue)
2662 tab = (AlteredTableInfo *) lfirst(ltab);
2663 if (tab->relid == relid)
2668 * Not there, so add it. Note that we make a copy of the relation's
2669 * existing descriptor before anything interesting can happen to it.
2671 tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
2673 tab->relkind = rel->rd_rel->relkind;
2674 tab->oldDesc = CreateTupleDescCopy(RelationGetDescr(rel));
2676 *wqueue = lappend(*wqueue, tab);
2682 * ATSimplePermissions
2684 * - Ensure that it is a relation (or possibly a view)
2685 * - Ensure this user is the owner
2686 * - Ensure that it is not a system table
2689 ATSimplePermissions(Relation rel, bool allowView)
2691 if (rel->rd_rel->relkind != RELKIND_RELATION)
2695 if (rel->rd_rel->relkind != RELKIND_VIEW)
2697 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2698 errmsg("\"%s\" is not a table or view",
2699 RelationGetRelationName(rel))));
2703 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2704 errmsg("\"%s\" is not a table",
2705 RelationGetRelationName(rel))));
2708 /* Permissions checks */
2709 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
2710 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
2711 RelationGetRelationName(rel));
2713 if (!allowSystemTableMods && IsSystemRelation(rel))
2715 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2716 errmsg("permission denied: \"%s\" is a system catalog",
2717 RelationGetRelationName(rel))));
2721 * ATSimplePermissionsRelationOrIndex
2723 * - Ensure that it is a relation or an index
2724 * - Ensure this user is the owner
2725 * - Ensure that it is not a system table
2728 ATSimplePermissionsRelationOrIndex(Relation rel)
2730 if (rel->rd_rel->relkind != RELKIND_RELATION &&
2731 rel->rd_rel->relkind != RELKIND_INDEX)
2733 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2734 errmsg("\"%s\" is not a table or index",
2735 RelationGetRelationName(rel))));
2737 /* Permissions checks */
2738 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
2739 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
2740 RelationGetRelationName(rel));
2742 if (!allowSystemTableMods && IsSystemRelation(rel))
2744 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2745 errmsg("permission denied: \"%s\" is a system catalog",
2746 RelationGetRelationName(rel))));
2752 * Simple table recursion sufficient for most ALTER TABLE operations.
2753 * All direct and indirect children are processed in an unspecified order.
2754 * Note that if a child inherits from the original table via multiple
2755 * inheritance paths, it will be visited just once.
2758 ATSimpleRecursion(List **wqueue, Relation rel,
2759 AlterTableCmd *cmd, bool recurse)
2762 * Propagate to children if desired. Non-table relations never have
2763 * children, so no need to search in that case.
2765 if (recurse && rel->rd_rel->relkind == RELKIND_RELATION)
2767 Oid relid = RelationGetRelid(rel);
2771 /* this routine is actually in the planner */
2772 children = find_all_inheritors(relid);
2775 * find_all_inheritors does the recursive search of the inheritance
2776 * hierarchy, so all we have to do is process all of the relids in the
2777 * list that it returns.
2779 foreach(child, children)
2781 Oid childrelid = lfirst_oid(child);
2784 if (childrelid == relid)
2786 childrel = relation_open(childrelid, AccessExclusiveLock);
2787 /* check for child relation in use in this session */
2788 if (childrel->rd_refcnt != 1)
2790 (errcode(ERRCODE_OBJECT_IN_USE),
2791 errmsg("relation \"%s\" is being used by active queries in this session",
2792 RelationGetRelationName(childrel))));
2793 ATPrepCmd(wqueue, childrel, cmd, false, true);
2794 relation_close(childrel, NoLock);
2800 * ATOneLevelRecursion
2802 * Here, we visit only direct inheritance children. It is expected that
2803 * the command's prep routine will recurse again to find indirect children.
2804 * When using this technique, a multiply-inheriting child will be visited
2808 ATOneLevelRecursion(List **wqueue, Relation rel,
2811 Oid relid = RelationGetRelid(rel);
2815 /* this routine is actually in the planner */
2816 children = find_inheritance_children(relid);
2818 foreach(child, children)
2820 Oid childrelid = lfirst_oid(child);
2823 childrel = relation_open(childrelid, AccessExclusiveLock);
2824 /* check for child relation in use in this session */
2825 if (childrel->rd_refcnt != 1)
2827 (errcode(ERRCODE_OBJECT_IN_USE),
2828 errmsg("relation \"%s\" is being used by active queries in this session",
2829 RelationGetRelationName(childrel))));
2830 ATPrepCmd(wqueue, childrel, cmd, true, true);
2831 relation_close(childrel, NoLock);
2837 * find_composite_type_dependencies
2839 * Check to see if a composite type is being used as a column in some
2840 * other table (possibly nested several levels deep in composite types!).
2841 * Eventually, we'd like to propagate the check or rewrite operation
2842 * into other such tables, but for now, just error out if we find any.
2844 * Caller should provide either a table name or a type name (not both) to
2845 * report in the error message, if any.
2847 * We assume that functions and views depending on the type are not reasons
2848 * to reject the ALTER. (How safe is this really?)
2851 find_composite_type_dependencies(Oid typeOid,
2852 const char *origTblName,
2853 const char *origTypeName)
2857 SysScanDesc depScan;
2862 * We scan pg_depend to find those things that depend on the rowtype. (We
2863 * assume we can ignore refobjsubid for a rowtype.)
2865 depRel = heap_open(DependRelationId, AccessShareLock);
2867 ScanKeyInit(&key[0],
2868 Anum_pg_depend_refclassid,
2869 BTEqualStrategyNumber, F_OIDEQ,
2870 ObjectIdGetDatum(TypeRelationId));
2871 ScanKeyInit(&key[1],
2872 Anum_pg_depend_refobjid,
2873 BTEqualStrategyNumber, F_OIDEQ,
2874 ObjectIdGetDatum(typeOid));
2876 depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
2877 SnapshotNow, 2, key);
2879 while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
2881 Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
2883 Form_pg_attribute att;
2885 /* Ignore dependees that aren't user columns of relations */
2886 /* (we assume system columns are never of rowtypes) */
2887 if (pg_depend->classid != RelationRelationId ||
2888 pg_depend->objsubid <= 0)
2891 rel = relation_open(pg_depend->objid, AccessShareLock);
2892 att = rel->rd_att->attrs[pg_depend->objsubid - 1];
2894 if (rel->rd_rel->relkind == RELKIND_RELATION)
2898 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2899 errmsg("cannot alter table \"%s\" because column \"%s\".\"%s\" uses its rowtype",
2901 RelationGetRelationName(rel),
2902 NameStr(att->attname))));
2905 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2906 errmsg("cannot alter type \"%s\" because column \"%s\".\"%s\" uses it",
2908 RelationGetRelationName(rel),
2909 NameStr(att->attname))));
2911 else if (OidIsValid(rel->rd_rel->reltype))
2914 * A view or composite type itself isn't a problem, but we must
2915 * recursively check for indirect dependencies via its rowtype.
2917 find_composite_type_dependencies(rel->rd_rel->reltype,
2918 origTblName, origTypeName);
2921 relation_close(rel, AccessShareLock);
2924 systable_endscan(depScan);
2926 relation_close(depRel, AccessShareLock);
2929 * If there's an array type for the rowtype, must check for uses of it,
2932 arrayOid = get_array_type(typeOid);
2933 if (OidIsValid(arrayOid))
2934 find_composite_type_dependencies(arrayOid, origTblName, origTypeName);
2939 * ALTER TABLE ADD COLUMN
2941 * Adds an additional attribute to a relation making the assumption that
2942 * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
2943 * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
2947 ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
2951 * Recurse to add the column to child classes, if requested.
2953 * We must recurse one level at a time, so that multiply-inheriting
2954 * children are visited the right number of times and end up with the
2955 * right attinhcount.
2959 AlterTableCmd *childCmd = copyObject(cmd);
2960 ColumnDef *colDefChild = (ColumnDef *) childCmd->def;
2962 /* Child should see column as singly inherited */
2963 colDefChild->inhcount = 1;
2964 colDefChild->is_local = false;
2966 ATOneLevelRecursion(wqueue, rel, childCmd);
2971 * If we are told not to recurse, there had better not be any child
2972 * tables; else the addition would put them out of step.
2974 if (find_inheritance_children(RelationGetRelid(rel)) != NIL)
2976 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2977 errmsg("column must be added to child tables too")));
2982 ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
2985 Oid myrelid = RelationGetRelid(rel);
2989 HeapTuple attributeTuple;
2990 Form_pg_attribute attribute;
2991 FormData_pg_attribute attributeD;
2995 HeapTuple typeTuple;
3001 attrdesc = heap_open(AttributeRelationId, RowExclusiveLock);
3004 * Are we adding the column to a recursion child? If so, check whether to
3005 * merge with an existing definition for the column.
3007 if (colDef->inhcount > 0)
3011 /* Does child already have a column by this name? */
3012 tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
3013 if (HeapTupleIsValid(tuple))
3015 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
3019 /* Okay if child matches by type */
3020 ctypeId = typenameTypeId(NULL, colDef->typename);
3021 ctypmod = typenameTypeMod(NULL, colDef->typename, ctypeId);
3022 if (ctypeId != childatt->atttypid ||
3023 ctypmod != childatt->atttypmod)
3025 (errcode(ERRCODE_DATATYPE_MISMATCH),
3026 errmsg("child table \"%s\" has different type for column \"%s\"",
3027 RelationGetRelationName(rel), colDef->colname)));
3029 /* Bump the existing child att's inhcount */
3030 childatt->attinhcount++;
3031 simple_heap_update(attrdesc, &tuple->t_self, tuple);
3032 CatalogUpdateIndexes(attrdesc, tuple);
3034 heap_freetuple(tuple);
3036 /* Inform the user about the merge */
3038 (errmsg("merging definition of column \"%s\" for child \"%s\"",
3039 colDef->colname, RelationGetRelationName(rel))));
3041 heap_close(attrdesc, RowExclusiveLock);
3046 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
3048 reltup = SearchSysCacheCopy(RELOID,
3049 ObjectIdGetDatum(myrelid),
3051 if (!HeapTupleIsValid(reltup))
3052 elog(ERROR, "cache lookup failed for relation %u", myrelid);
3055 * this test is deliberately not attisdropped-aware, since if one tries to
3056 * add a column matching a dropped column name, it's gonna fail anyway.
3058 if (SearchSysCacheExists(ATTNAME,
3059 ObjectIdGetDatum(myrelid),
3060 PointerGetDatum(colDef->colname),
3063 (errcode(ERRCODE_DUPLICATE_COLUMN),
3064 errmsg("column \"%s\" of relation \"%s\" already exists",
3065 colDef->colname, RelationGetRelationName(rel))));
3067 minattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts;
3068 maxatts = minattnum + 1;
3069 if (maxatts > MaxHeapAttributeNumber)
3071 (errcode(ERRCODE_TOO_MANY_COLUMNS),
3072 errmsg("tables can have at most %d columns",
3073 MaxHeapAttributeNumber)));
3076 typeTuple = typenameType(NULL, colDef->typename);
3077 tform = (Form_pg_type) GETSTRUCT(typeTuple);
3078 typeOid = HeapTupleGetOid(typeTuple);
3079 typmod = typenameTypeMod(NULL, colDef->typename, typeOid);
3081 /* make sure datatype is legal for a column */
3082 CheckAttributeType(colDef->colname, typeOid);
3084 attributeTuple = heap_addheader(Natts_pg_attribute,
3086 ATTRIBUTE_TUPLE_SIZE,
3087 (void *) &attributeD);
3089 attribute = (Form_pg_attribute) GETSTRUCT(attributeTuple);
3091 attribute->attrelid = myrelid;
3092 namestrcpy(&(attribute->attname), colDef->colname);
3093 attribute->atttypid = typeOid;
3094 attribute->attstattarget = -1;
3095 attribute->attlen = tform->typlen;
3096 attribute->attcacheoff = -1;
3097 attribute->atttypmod = typmod;
3098 attribute->attnum = i;
3099 attribute->attbyval = tform->typbyval;
3100 attribute->attndims = list_length(colDef->typename->arrayBounds);
3101 attribute->attstorage = tform->typstorage;
3102 attribute->attalign = tform->typalign;
3103 attribute->attnotnull = colDef->is_not_null;
3104 attribute->atthasdef = false;
3105 attribute->attisdropped = false;
3106 attribute->attislocal = colDef->is_local;
3107 attribute->attinhcount = colDef->inhcount;
3109 ReleaseSysCache(typeTuple);
3111 simple_heap_insert(attrdesc, attributeTuple);
3113 /* Update indexes on pg_attribute */
3114 CatalogUpdateIndexes(attrdesc, attributeTuple);
3116 heap_close(attrdesc, RowExclusiveLock);
3119 * Update number of attributes in pg_class tuple
3121 ((Form_pg_class) GETSTRUCT(reltup))->relnatts = maxatts;
3123 simple_heap_update(pgclass, &reltup->t_self, reltup);
3125 /* keep catalog indexes current */
3126 CatalogUpdateIndexes(pgclass, reltup);
3128 heap_freetuple(reltup);
3130 heap_close(pgclass, RowExclusiveLock);
3132 /* Make the attribute's catalog entry visible */
3133 CommandCounterIncrement();
3136 * Store the DEFAULT, if any, in the catalogs
3138 if (colDef->raw_default)
3140 RawColumnDefault *rawEnt;
3142 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3143 rawEnt->attnum = attribute->attnum;
3144 rawEnt->raw_default = copyObject(colDef->raw_default);
3147 * This function is intended for CREATE TABLE, so it processes a
3148 * _list_ of defaults, but we just do one.
3150 AddRelationRawConstraints(rel, list_make1(rawEnt), NIL);
3152 /* Make the additional catalog changes visible */
3153 CommandCounterIncrement();
3157 * Tell Phase 3 to fill in the default expression, if there is one.
3159 * If there is no default, Phase 3 doesn't have to do anything, because
3160 * that effectively means that the default is NULL. The heap tuple access
3161 * routines always check for attnum > # of attributes in tuple, and return
3162 * NULL if so, so without any modification of the tuple data we will get
3163 * the effect of NULL values in the new column.
3165 * An exception occurs when the new column is of a domain type: the domain
3166 * might have a NOT NULL constraint, or a check constraint that indirectly
3167 * rejects nulls. If there are any domain constraints then we construct
3168 * an explicit NULL default value that will be passed through
3169 * CoerceToDomain processing. (This is a tad inefficient, since it causes
3170 * rewriting the table which we really don't have to do, but the present
3171 * design of domain processing doesn't offer any simple way of checking
3172 * the constraints more directly.)
3174 * Note: we use build_column_default, and not just the cooked default
3175 * returned by AddRelationRawConstraints, so that the right thing happens
3176 * when a datatype's default applies.
3178 defval = (Expr *) build_column_default(rel, attribute->attnum);
3180 if (!defval && GetDomainConstraints(typeOid) != NIL)
3182 Oid basetype = getBaseType(typeOid);
3184 defval = (Expr *) makeNullConst(basetype);
3185 defval = (Expr *) coerce_to_target_type(NULL,
3190 COERCION_ASSIGNMENT,
3191 COERCE_IMPLICIT_CAST);
3192 if (defval == NULL) /* should not happen */
3193 elog(ERROR, "failed to coerce base type to domain");
3198 NewColumnValue *newval;
3200 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
3201 newval->attnum = attribute->attnum;
3202 newval->expr = defval;
3204 tab->newvals = lappend(tab->newvals, newval);
3208 * Add needed dependency entries for the new column.
3210 add_column_datatype_dependency(myrelid, i, attribute->atttypid);
3214 * Install a column's dependency on its datatype.
3217 add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
3219 ObjectAddress myself,
3222 myself.classId = RelationRelationId;
3223 myself.objectId = relid;
3224 myself.objectSubId = attnum;
3225 referenced.classId = TypeRelationId;
3226 referenced.objectId = typid;
3227 referenced.objectSubId = 0;
3228 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
3232 * ALTER TABLE ALTER COLUMN DROP NOT NULL
3235 ATExecDropNotNull(Relation rel, const char *colName)
3241 ListCell *indexoidscan;
3244 * lookup the attribute
3246 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3248 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3250 if (!HeapTupleIsValid(tuple))
3252 (errcode(ERRCODE_UNDEFINED_COLUMN),
3253 errmsg("column \"%s\" of relation \"%s\" does not exist",
3254 colName, RelationGetRelationName(rel))));
3256 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3258 /* Prevent them from altering a system attribute */
3261 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3262 errmsg("cannot alter system column \"%s\"",
3266 * Check that the attribute is not in a primary key
3269 /* Loop over all indexes on the relation */
3270 indexoidlist = RelationGetIndexList(rel);
3272 foreach(indexoidscan, indexoidlist)
3274 Oid indexoid = lfirst_oid(indexoidscan);
3275 HeapTuple indexTuple;
3276 Form_pg_index indexStruct;
3279 indexTuple = SearchSysCache(INDEXRELID,
3280 ObjectIdGetDatum(indexoid),
3282 if (!HeapTupleIsValid(indexTuple))
3283 elog(ERROR, "cache lookup failed for index %u", indexoid);
3284 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
3286 /* If the index is not a primary key, skip the check */
3287 if (indexStruct->indisprimary)
3290 * Loop over each attribute in the primary key and see if it
3291 * matches the to-be-altered attribute
3293 for (i = 0; i < indexStruct->indnatts; i++)
3295 if (indexStruct->indkey.values[i] == attnum)
3297 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3298 errmsg("column \"%s\" is in a primary key",
3303 ReleaseSysCache(indexTuple);
3306 list_free(indexoidlist);
3309 * Okay, actually perform the catalog change ... if needed
3311 if (((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3313 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = FALSE;
3315 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3317 /* keep the system catalog indexes current */
3318 CatalogUpdateIndexes(attr_rel, tuple);
3321 heap_close(attr_rel, RowExclusiveLock);
3325 * ALTER TABLE ALTER COLUMN SET NOT NULL
3328 ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
3329 const char *colName)
3336 * lookup the attribute
3338 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3340 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3342 if (!HeapTupleIsValid(tuple))
3344 (errcode(ERRCODE_UNDEFINED_COLUMN),
3345 errmsg("column \"%s\" of relation \"%s\" does not exist",
3346 colName, RelationGetRelationName(rel))));
3348 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3350 /* Prevent them from altering a system attribute */
3353 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3354 errmsg("cannot alter system column \"%s\"",
3358 * Okay, actually perform the catalog change ... if needed
3360 if (!((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3362 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = TRUE;
3364 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3366 /* keep the system catalog indexes current */
3367 CatalogUpdateIndexes(attr_rel, tuple);
3369 /* Tell Phase 3 it needs to test the constraint */
3370 tab->new_notnull = true;
3373 heap_close(attr_rel, RowExclusiveLock);
3377 * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
3380 ATExecColumnDefault(Relation rel, const char *colName,
3386 * get the number of the attribute
3388 attnum = get_attnum(RelationGetRelid(rel), colName);
3389 if (attnum == InvalidAttrNumber)
3391 (errcode(ERRCODE_UNDEFINED_COLUMN),
3392 errmsg("column \"%s\" of relation \"%s\" does not exist",
3393 colName, RelationGetRelationName(rel))));
3395 /* Prevent them from altering a system attribute */
3398 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3399 errmsg("cannot alter system column \"%s\"",
3403 * Remove any old default for the column. We use RESTRICT here for
3404 * safety, but at present we do not expect anything to depend on the
3407 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false);
3412 RawColumnDefault *rawEnt;
3414 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3415 rawEnt->attnum = attnum;
3416 rawEnt->raw_default = newDefault;
3419 * This function is intended for CREATE TABLE, so it processes a
3420 * _list_ of defaults, but we just do one.
3422 AddRelationRawConstraints(rel, list_make1(rawEnt), NIL);
3427 * ALTER TABLE ALTER COLUMN SET STATISTICS
3430 ATPrepSetStatistics(Relation rel, const char *colName, Node *flagValue)
3433 * We do our own permission checking because (a) we want to allow SET
3434 * STATISTICS on indexes (for expressional index columns), and (b) we want
3435 * to allow SET STATISTICS on system catalogs without requiring
3436 * allowSystemTableMods to be turned on.
3438 if (rel->rd_rel->relkind != RELKIND_RELATION &&
3439 rel->rd_rel->relkind != RELKIND_INDEX)
3441 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3442 errmsg("\"%s\" is not a table or index",
3443 RelationGetRelationName(rel))));
3445 /* Permissions checks */
3446 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3447 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3448 RelationGetRelationName(rel));
3452 ATExecSetStatistics(Relation rel, const char *colName, Node *newValue)
3455 Relation attrelation;
3457 Form_pg_attribute attrtuple;
3459 Assert(IsA(newValue, Integer));
3460 newtarget = intVal(newValue);
3463 * Limit target to a sane range
3468 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3469 errmsg("statistics target %d is too low",
3472 else if (newtarget > 1000)
3476 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3477 errmsg("lowering statistics target to %d",
3481 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
3483 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3485 if (!HeapTupleIsValid(tuple))
3487 (errcode(ERRCODE_UNDEFINED_COLUMN),
3488 errmsg("column \"%s\" of relation \"%s\" does not exist",
3489 colName, RelationGetRelationName(rel))));
3490 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
3492 if (attrtuple->attnum <= 0)
3494 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3495 errmsg("cannot alter system column \"%s\"",
3498 attrtuple->attstattarget = newtarget;
3500 simple_heap_update(attrelation, &tuple->t_self, tuple);
3502 /* keep system catalog indexes current */
3503 CatalogUpdateIndexes(attrelation, tuple);
3505 heap_freetuple(tuple);
3507 heap_close(attrelation, RowExclusiveLock);
3511 * ALTER TABLE ALTER COLUMN SET STORAGE
3514 ATExecSetStorage(Relation rel, const char *colName, Node *newValue)
3518 Relation attrelation;
3520 Form_pg_attribute attrtuple;
3522 Assert(IsA(newValue, String));
3523 storagemode = strVal(newValue);
3525 if (pg_strcasecmp(storagemode, "plain") == 0)
3527 else if (pg_strcasecmp(storagemode, "external") == 0)
3529 else if (pg_strcasecmp(storagemode, "extended") == 0)
3531 else if (pg_strcasecmp(storagemode, "main") == 0)
3536 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3537 errmsg("invalid storage type \"%s\"",
3539 newstorage = 0; /* keep compiler quiet */
3542 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
3544 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3546 if (!HeapTupleIsValid(tuple))
3548 (errcode(ERRCODE_UNDEFINED_COLUMN),
3549 errmsg("column \"%s\" of relation \"%s\" does not exist",
3550 colName, RelationGetRelationName(rel))));
3551 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
3553 if (attrtuple->attnum <= 0)
3555 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3556 errmsg("cannot alter system column \"%s\"",
3560 * safety check: do not allow toasted storage modes unless column datatype
3563 if (newstorage == 'p' || TypeIsToastable(attrtuple->atttypid))
3564 attrtuple->attstorage = newstorage;
3567 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3568 errmsg("column data type %s can only have storage PLAIN",
3569 format_type_be(attrtuple->atttypid))));
3571 simple_heap_update(attrelation, &tuple->t_self, tuple);
3573 /* keep system catalog indexes current */
3574 CatalogUpdateIndexes(attrelation, tuple);
3576 heap_freetuple(tuple);
3578 heap_close(attrelation, RowExclusiveLock);
3583 * ALTER TABLE DROP COLUMN
3585 * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
3586 * because we have to decide at runtime whether to recurse or not depending
3587 * on whether attinhcount goes to zero or not. (We can't check this in a
3588 * static pre-pass because it won't handle multiple inheritance situations
3589 * correctly.) Since DROP COLUMN doesn't need to create any work queue
3590 * entries for Phase 3, it's okay to recurse internally in this routine
3591 * without considering the work queue.
3594 ATExecDropColumn(Relation rel, const char *colName,
3595 DropBehavior behavior,
3596 bool recurse, bool recursing)
3599 Form_pg_attribute targetatt;
3602 ObjectAddress object;
3604 /* At top level, permission check was done in ATPrepCmd, else do it */
3606 ATSimplePermissions(rel, false);
3609 * get the number of the attribute
3611 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
3612 if (!HeapTupleIsValid(tuple))
3614 (errcode(ERRCODE_UNDEFINED_COLUMN),
3615 errmsg("column \"%s\" of relation \"%s\" does not exist",
3616 colName, RelationGetRelationName(rel))));
3617 targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
3619 attnum = targetatt->attnum;
3621 /* Can't drop a system attribute, except OID */
3622 if (attnum <= 0 && attnum != ObjectIdAttributeNumber)
3624 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3625 errmsg("cannot drop system column \"%s\"",
3628 /* Don't drop inherited columns */
3629 if (targetatt->attinhcount > 0 && !recursing)
3631 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3632 errmsg("cannot drop inherited column \"%s\"",
3635 ReleaseSysCache(tuple);
3638 * Propagate to children as appropriate. Unlike most other ALTER
3639 * routines, we have to do this one level of recursion at a time; we can't
3640 * use find_all_inheritors to do it in one pass.
3642 children = find_inheritance_children(RelationGetRelid(rel));
3649 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3650 foreach(child, children)
3652 Oid childrelid = lfirst_oid(child);
3654 Form_pg_attribute childatt;
3656 childrel = heap_open(childrelid, AccessExclusiveLock);
3657 /* check for child relation in use in this session */
3658 if (childrel->rd_refcnt != 1)
3660 (errcode(ERRCODE_OBJECT_IN_USE),
3661 errmsg("relation \"%s\" is being used by active queries in this session",
3662 RelationGetRelationName(childrel))));
3664 tuple = SearchSysCacheCopyAttName(childrelid, colName);
3665 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
3666 elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
3667 colName, childrelid);
3668 childatt = (Form_pg_attribute) GETSTRUCT(tuple);
3670 if (childatt->attinhcount <= 0) /* shouldn't happen */
3671 elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
3672 childrelid, colName);
3677 * If the child column has other definition sources, just
3678 * decrement its inheritance count; if not, recurse to delete
3681 if (childatt->attinhcount == 1 && !childatt->attislocal)
3683 /* Time to delete this child column, too */
3684 ATExecDropColumn(childrel, colName, behavior, true, true);
3688 /* Child column must survive my deletion */
3689 childatt->attinhcount--;
3691 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3693 /* keep the system catalog indexes current */
3694 CatalogUpdateIndexes(attr_rel, tuple);
3696 /* Make update visible */
3697 CommandCounterIncrement();
3703 * If we were told to drop ONLY in this table (no recursion),
3704 * we need to mark the inheritors' attribute as locally
3705 * defined rather than inherited.
3707 childatt->attinhcount--;
3708 childatt->attislocal = true;
3710 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3712 /* keep the system catalog indexes current */
3713 CatalogUpdateIndexes(attr_rel, tuple);
3715 /* Make update visible */
3716 CommandCounterIncrement();
3719 heap_freetuple(tuple);
3721 heap_close(childrel, NoLock);
3723 heap_close(attr_rel, RowExclusiveLock);
3727 * Perform the actual column deletion
3729 object.classId = RelationRelationId;
3730 object.objectId = RelationGetRelid(rel);
3731 object.objectSubId = attnum;
3733 performDeletion(&object, behavior);
3736 * If we dropped the OID column, must adjust pg_class.relhasoids
3738 if (attnum == ObjectIdAttributeNumber)
3741 Form_pg_class tuple_class;
3743 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
3745 tuple = SearchSysCacheCopy(RELOID,
3746 ObjectIdGetDatum(RelationGetRelid(rel)),
3748 if (!HeapTupleIsValid(tuple))
3749 elog(ERROR, "cache lookup failed for relation %u",
3750 RelationGetRelid(rel));
3751 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
3753 tuple_class->relhasoids = false;
3754 simple_heap_update(class_rel, &tuple->t_self, tuple);
3756 /* Keep the catalog indexes up to date */
3757 CatalogUpdateIndexes(class_rel, tuple);
3759 heap_close(class_rel, RowExclusiveLock);
3764 * ALTER TABLE ADD INDEX
3766 * There is no such command in the grammar, but parse_utilcmd.c converts
3767 * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands. This lets
3768 * us schedule creation of the index at the appropriate time during ALTER.
3771 ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
3772 IndexStmt *stmt, bool is_rebuild)
3778 Assert(IsA(stmt, IndexStmt));
3780 /* suppress schema rights check when rebuilding existing index */
3781 check_rights = !is_rebuild;
3782 /* skip index build if phase 3 will have to rewrite table anyway */
3783 skip_build = (tab->newvals != NIL);
3784 /* suppress notices when rebuilding existing index */
3787 /* The IndexStmt has already been through transformIndexStmt */
3789 DefineIndex(stmt->relation, /* relation */
3790 stmt->idxname, /* index name */
3791 InvalidOid, /* no predefined OID */
3792 stmt->accessMethod, /* am name */
3794 stmt->indexParams, /* parameters */
3795 (Expr *) stmt->whereClause,
3800 true, /* is_alter_table */
3808 * ALTER TABLE ADD CONSTRAINT
3811 ATExecAddConstraint(AlteredTableInfo *tab, Relation rel, Node *newConstraint)
3813 switch (nodeTag(newConstraint))
3817 Constraint *constr = (Constraint *) newConstraint;
3820 * Currently, we only expect to see CONSTR_CHECK nodes
3821 * arriving here (see the preprocessing done in
3822 * parse_utilcmd.c). Use a switch anyway to make it easier
3823 * to add more code later.
3825 switch (constr->contype)
3833 * Call AddRelationRawConstraints to do the work.
3834 * It returns a list of cooked constraints.
3836 newcons = AddRelationRawConstraints(rel, NIL,
3837 list_make1(constr));
3838 /* Add each constraint to Phase 3's queue */
3839 foreach(lcon, newcons)
3841 CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
3842 NewConstraint *newcon;
3844 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
3845 newcon->name = ccon->name;
3846 newcon->contype = ccon->contype;
3847 /* ExecQual wants implicit-AND format */
3848 newcon->qual = (Node *)
3849 make_ands_implicit((Expr *) ccon->expr);
3851 tab->constraints = lappend(tab->constraints,
3857 elog(ERROR, "unrecognized constraint type: %d",
3858 (int) constr->contype);
3862 case T_FkConstraint:
3864 FkConstraint *fkconstraint = (FkConstraint *) newConstraint;
3867 * Assign or validate constraint name
3869 if (fkconstraint->constr_name)
3871 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
3872 RelationGetRelid(rel),
3873 RelationGetNamespace(rel),
3874 fkconstraint->constr_name))
3876 (errcode(ERRCODE_DUPLICATE_OBJECT),
3877 errmsg("constraint \"%s\" for relation \"%s\" already exists",
3878 fkconstraint->constr_name,
3879 RelationGetRelationName(rel))));
3882 fkconstraint->constr_name =
3883 ChooseConstraintName(RelationGetRelationName(rel),
3884 strVal(linitial(fkconstraint->fk_attrs)),
3886 RelationGetNamespace(rel),
3889 ATAddForeignKeyConstraint(tab, rel, fkconstraint);
3894 elog(ERROR, "unrecognized node type: %d",
3895 (int) nodeTag(newConstraint));
3900 * Add a foreign-key constraint to a single table
3902 * Subroutine for ATExecAddConstraint. Must already hold exclusive
3903 * lock on the rel, and have done appropriate validity/permissions checks
3907 ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
3908 FkConstraint *fkconstraint)
3911 AclResult aclresult;
3912 int16 pkattnum[INDEX_MAX_KEYS];
3913 int16 fkattnum[INDEX_MAX_KEYS];
3914 Oid pktypoid[INDEX_MAX_KEYS];
3915 Oid fktypoid[INDEX_MAX_KEYS];
3916 Oid opclasses[INDEX_MAX_KEYS];
3917 Oid pfeqoperators[INDEX_MAX_KEYS];
3918 Oid ppeqoperators[INDEX_MAX_KEYS];
3919 Oid ffeqoperators[INDEX_MAX_KEYS];
3927 * Grab an exclusive lock on the pk table, so that someone doesn't delete
3928 * rows out from under us. (Although a lesser lock would do for that
3929 * purpose, we'll need exclusive lock anyway to add triggers to the pk
3930 * table; trying to start with a lesser lock will just create a risk of
3933 pkrel = heap_openrv(fkconstraint->pktable, AccessExclusiveLock);
3936 * Validity and permissions checks
3938 * Note: REFERENCES permissions checks are redundant with CREATE TRIGGER,
3939 * but we may as well error out sooner instead of later.
3941 if (pkrel->rd_rel->relkind != RELKIND_RELATION)
3943 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3944 errmsg("referenced relation \"%s\" is not a table",
3945 RelationGetRelationName(pkrel))));
3947 aclresult = pg_class_aclcheck(RelationGetRelid(pkrel), GetUserId(),
3949 if (aclresult != ACLCHECK_OK)
3950 aclcheck_error(aclresult, ACL_KIND_CLASS,
3951 RelationGetRelationName(pkrel));
3953 if (!allowSystemTableMods && IsSystemRelation(pkrel))
3955 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3956 errmsg("permission denied: \"%s\" is a system catalog",
3957 RelationGetRelationName(pkrel))));
3959 aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
3961 if (aclresult != ACLCHECK_OK)
3962 aclcheck_error(aclresult, ACL_KIND_CLASS,
3963 RelationGetRelationName(rel));
3966 * Disallow reference from permanent table to temp table or vice versa.
3967 * (The ban on perm->temp is for fairly obvious reasons. The ban on
3968 * temp->perm is because other backends might need to run the RI triggers
3969 * on the perm table, but they can't reliably see tuples the owning
3970 * backend has created in the temp table, because non-shared buffers are
3971 * used for temp tables.)
3973 if (isTempNamespace(RelationGetNamespace(pkrel)))
3975 if (!isTempNamespace(RelationGetNamespace(rel)))
3977 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3978 errmsg("cannot reference temporary table from permanent table constraint")));
3982 if (isTempNamespace(RelationGetNamespace(rel)))
3984 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3985 errmsg("cannot reference permanent table from temporary table constraint")));
3989 * Look up the referencing attributes to make sure they exist, and record
3990 * their attnums and type OIDs.
3992 MemSet(pkattnum, 0, sizeof(pkattnum));
3993 MemSet(fkattnum, 0, sizeof(fkattnum));
3994 MemSet(pktypoid, 0, sizeof(pktypoid));
3995 MemSet(fktypoid, 0, sizeof(fktypoid));
3996 MemSet(opclasses, 0, sizeof(opclasses));
3997 MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
3998 MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
3999 MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
4001 numfks = transformColumnNameList(RelationGetRelid(rel),
4002 fkconstraint->fk_attrs,
4003 fkattnum, fktypoid);
4006 * If the attribute list for the referenced table was omitted, lookup the
4007 * definition of the primary key and use it. Otherwise, validate the
4008 * supplied attribute list. In either case, discover the index OID and
4009 * index opclasses, and the attnums and type OIDs of the attributes.
4011 if (fkconstraint->pk_attrs == NIL)
4013 numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
4014 &fkconstraint->pk_attrs,
4020 numpks = transformColumnNameList(RelationGetRelid(pkrel),
4021 fkconstraint->pk_attrs,
4022 pkattnum, pktypoid);
4023 /* Look for an index matching the column list */
4024 indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
4029 * Look up the equality operators to use in the constraint.
4031 * Note that we have to be careful about the difference between the actual
4032 * PK column type and the opclass' declared input type, which might be
4033 * only binary-compatible with it. The declared opcintype is the right
4034 * thing to probe pg_amop with.
4036 if (numfks != numpks)
4038 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4039 errmsg("number of referencing and referenced columns for foreign key disagree")));
4041 for (i = 0; i < numpks; i++)
4043 Oid pktype = pktypoid[i];
4044 Oid fktype = fktypoid[i];
4047 Form_pg_opclass cla_tup;
4056 /* We need several fields out of the pg_opclass entry */
4057 cla_ht = SearchSysCache(CLAOID,
4058 ObjectIdGetDatum(opclasses[i]),
4060 if (!HeapTupleIsValid(cla_ht))
4061 elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
4062 cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
4063 amid = cla_tup->opcmethod;
4064 opfamily = cla_tup->opcfamily;
4065 opcintype = cla_tup->opcintype;
4066 ReleaseSysCache(cla_ht);
4069 * Check it's a btree; currently this can never fail since no other
4070 * index AMs support unique indexes. If we ever did have other
4071 * types of unique indexes, we'd need a way to determine which
4072 * operator strategy number is equality. (Is it reasonable to
4073 * insist that every such index AM use btree's number for equality?)
4075 if (amid != BTREE_AM_OID)
4076 elog(ERROR, "only b-tree indexes are supported for foreign keys");
4077 eqstrategy = BTEqualStrategyNumber;
4080 * There had better be a primary equality operator for the index.
4081 * We'll use it for PK = PK comparisons.
4083 ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
4086 if (!OidIsValid(ppeqop))
4087 elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
4088 eqstrategy, opcintype, opcintype, opfamily);
4091 * Are there equality operators that take exactly the FK type?
4092 * Assume we should look through any domain here.
4094 fktyped = getBaseType(fktype);
4096 pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
4098 if (OidIsValid(pfeqop))
4099 ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
4102 ffeqop = InvalidOid; /* keep compiler quiet */
4104 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4107 * Otherwise, look for an implicit cast from the FK type to
4108 * the opcintype, and if found, use the primary equality operator.
4109 * This is a bit tricky because opcintype might be a generic type
4110 * such as ANYARRAY, and so what we have to test is whether the
4111 * two actual column types can be concurrently cast to that type.
4112 * (Otherwise, we'd fail to reject combinations such as int[] and
4115 Oid input_typeids[2];
4116 Oid target_typeids[2];
4118 input_typeids[0] = pktype;
4119 input_typeids[1] = fktype;
4120 target_typeids[0] = opcintype;
4121 target_typeids[1] = opcintype;
4122 if (can_coerce_type(2, input_typeids, target_typeids,
4124 pfeqop = ffeqop = ppeqop;
4127 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4129 (errcode(ERRCODE_DATATYPE_MISMATCH),
4130 errmsg("foreign key constraint \"%s\" "
4131 "cannot be implemented",
4132 fkconstraint->constr_name),
4133 errdetail("Key columns \"%s\" and \"%s\" "
4134 "are of incompatible types: %s and %s.",
4135 strVal(list_nth(fkconstraint->fk_attrs, i)),
4136 strVal(list_nth(fkconstraint->pk_attrs, i)),
4137 format_type_be(fktype),
4138 format_type_be(pktype))));
4140 pfeqoperators[i] = pfeqop;
4141 ppeqoperators[i] = ppeqop;
4142 ffeqoperators[i] = ffeqop;
4146 * Record the FK constraint in pg_constraint.
4148 constrOid = CreateConstraintEntry(fkconstraint->constr_name,
4149 RelationGetNamespace(rel),
4151 fkconstraint->deferrable,
4152 fkconstraint->initdeferred,
4153 RelationGetRelid(rel),
4156 InvalidOid, /* not a domain
4158 RelationGetRelid(pkrel),
4164 fkconstraint->fk_upd_action,
4165 fkconstraint->fk_del_action,
4166 fkconstraint->fk_matchtype,
4168 NULL, /* no check constraint */
4173 * Create the triggers that will enforce the constraint.
4175 createForeignKeyTriggers(rel, fkconstraint, constrOid);
4178 * Tell Phase 3 to check that the constraint is satisfied by existing rows
4179 * (we can skip this during table creation).
4181 if (!fkconstraint->skip_validation)
4183 NewConstraint *newcon;
4185 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
4186 newcon->name = fkconstraint->constr_name;
4187 newcon->contype = CONSTR_FOREIGN;
4188 newcon->refrelid = RelationGetRelid(pkrel);
4189 newcon->conid = constrOid;
4190 newcon->qual = (Node *) fkconstraint;
4192 tab->constraints = lappend(tab->constraints, newcon);
4196 * Close pk table, but keep lock until we've committed.
4198 heap_close(pkrel, NoLock);
4203 * transformColumnNameList - transform list of column names
4205 * Lookup each name and return its attnum and type OID
4208 transformColumnNameList(Oid relId, List *colList,
4209 int16 *attnums, Oid *atttypids)
4217 char *attname = strVal(lfirst(l));
4220 atttuple = SearchSysCacheAttName(relId, attname);
4221 if (!HeapTupleIsValid(atttuple))
4223 (errcode(ERRCODE_UNDEFINED_COLUMN),
4224 errmsg("column \"%s\" referenced in foreign key constraint does not exist",
4226 if (attnum >= INDEX_MAX_KEYS)
4228 (errcode(ERRCODE_TOO_MANY_COLUMNS),
4229 errmsg("cannot have more than %d keys in a foreign key",
4231 attnums[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->attnum;
4232 atttypids[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->atttypid;
4233 ReleaseSysCache(atttuple);
4241 * transformFkeyGetPrimaryKey -
4243 * Look up the names, attnums, and types of the primary key attributes
4244 * for the pkrel. Also return the index OID and index opclasses of the
4245 * index supporting the primary key.
4247 * All parameters except pkrel are output parameters. Also, the function
4248 * return value is the number of attributes in the primary key.
4250 * Used when the column list in the REFERENCES specification is omitted.
4253 transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
4255 int16 *attnums, Oid *atttypids,
4259 ListCell *indexoidscan;
4260 HeapTuple indexTuple = NULL;
4261 Form_pg_index indexStruct = NULL;
4262 Datum indclassDatum;
4264 oidvector *indclass;
4268 * Get the list of index OIDs for the table from the relcache, and look up
4269 * each one in the pg_index syscache until we find one marked primary key
4270 * (hopefully there isn't more than one such).
4272 *indexOid = InvalidOid;
4274 indexoidlist = RelationGetIndexList(pkrel);
4276 foreach(indexoidscan, indexoidlist)
4278 Oid indexoid = lfirst_oid(indexoidscan);
4280 indexTuple = SearchSysCache(INDEXRELID,
4281 ObjectIdGetDatum(indexoid),
4283 if (!HeapTupleIsValid(indexTuple))
4284 elog(ERROR, "cache lookup failed for index %u", indexoid);
4285 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4286 if (indexStruct->indisprimary)
4288 *indexOid = indexoid;
4291 ReleaseSysCache(indexTuple);
4294 list_free(indexoidlist);
4297 * Check that we found it
4299 if (!OidIsValid(*indexOid))
4301 (errcode(ERRCODE_UNDEFINED_OBJECT),
4302 errmsg("there is no primary key for referenced table \"%s\"",
4303 RelationGetRelationName(pkrel))));
4305 /* Must get indclass the hard way */
4306 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4307 Anum_pg_index_indclass, &isnull);
4309 indclass = (oidvector *) DatumGetPointer(indclassDatum);
4312 * Now build the list of PK attributes from the indkey definition (we
4313 * assume a primary key cannot have expressional elements)
4316 for (i = 0; i < indexStruct->indnatts; i++)
4318 int pkattno = indexStruct->indkey.values[i];
4320 attnums[i] = pkattno;
4321 atttypids[i] = attnumTypeId(pkrel, pkattno);
4322 opclasses[i] = indclass->values[i];
4323 *attnamelist = lappend(*attnamelist,
4324 makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
4327 ReleaseSysCache(indexTuple);
4333 * transformFkeyCheckAttrs -
4335 * Make sure that the attributes of a referenced table belong to a unique
4336 * (or primary key) constraint. Return the OID of the index supporting
4337 * the constraint, as well as the opclasses associated with the index
4341 transformFkeyCheckAttrs(Relation pkrel,
4342 int numattrs, int16 *attnums,
4343 Oid *opclasses) /* output parameter */
4345 Oid indexoid = InvalidOid;
4348 ListCell *indexoidscan;
4351 * Get the list of index OIDs for the table from the relcache, and look up
4352 * each one in the pg_index syscache, and match unique indexes to the list
4353 * of attnums we are given.
4355 indexoidlist = RelationGetIndexList(pkrel);
4357 foreach(indexoidscan, indexoidlist)
4359 HeapTuple indexTuple;
4360 Form_pg_index indexStruct;
4364 indexoid = lfirst_oid(indexoidscan);
4365 indexTuple = SearchSysCache(INDEXRELID,
4366 ObjectIdGetDatum(indexoid),
4368 if (!HeapTupleIsValid(indexTuple))
4369 elog(ERROR, "cache lookup failed for index %u", indexoid);
4370 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4373 * Must have the right number of columns; must be unique and not a
4374 * partial index; forget it if there are any expressions, too
4376 if (indexStruct->indnatts == numattrs &&
4377 indexStruct->indisunique &&
4378 heap_attisnull(indexTuple, Anum_pg_index_indpred) &&
4379 heap_attisnull(indexTuple, Anum_pg_index_indexprs))
4381 /* Must get indclass the hard way */
4382 Datum indclassDatum;
4384 oidvector *indclass;
4386 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4387 Anum_pg_index_indclass, &isnull);
4389 indclass = (oidvector *) DatumGetPointer(indclassDatum);
4392 * The given attnum list may match the index columns in any order.
4393 * Check that each list is a subset of the other.
4395 for (i = 0; i < numattrs; i++)
4398 for (j = 0; j < numattrs; j++)
4400 if (attnums[i] == indexStruct->indkey.values[j])
4411 for (i = 0; i < numattrs; i++)
4414 for (j = 0; j < numattrs; j++)
4416 if (attnums[j] == indexStruct->indkey.values[i])
4418 opclasses[j] = indclass->values[i];
4428 ReleaseSysCache(indexTuple);
4435 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4436 errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
4437 RelationGetRelationName(pkrel))));
4439 list_free(indexoidlist);
4445 * Scan the existing rows in a table to verify they meet a proposed FK
4448 * Caller must have opened and locked both relations.
4451 validateForeignKeyConstraint(FkConstraint *fkconstraint,
4461 * Build a trigger call structure; we'll need it either way.
4463 MemSet(&trig, 0, sizeof(trig));
4464 trig.tgoid = InvalidOid;
4465 trig.tgname = fkconstraint->constr_name;
4466 trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
4467 trig.tgisconstraint = TRUE;
4468 trig.tgconstrrelid = RelationGetRelid(pkrel);
4469 trig.tgconstraint = constraintOid;
4470 trig.tgdeferrable = FALSE;
4471 trig.tginitdeferred = FALSE;
4472 /* we needn't fill in tgargs */
4475 * See if we can do it with a single LEFT JOIN query. A FALSE result
4476 * indicates we must proceed with the fire-the-trigger method.
4478 if (RI_Initial_Check(&trig, rel, pkrel))
4482 * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
4483 * if that tuple had just been inserted. If any of those fail, it should
4484 * ereport(ERROR) and that's that.
4486 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
4488 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
4490 FunctionCallInfoData fcinfo;
4491 TriggerData trigdata;
4494 * Make a call to the trigger function
4496 * No parameters are passed, but we do set a context
4498 MemSet(&fcinfo, 0, sizeof(fcinfo));
4501 * We assume RI_FKey_check_ins won't look at flinfo...
4503 trigdata.type = T_TriggerData;
4504 trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
4505 trigdata.tg_relation = rel;
4506 trigdata.tg_trigtuple = tuple;
4507 trigdata.tg_newtuple = NULL;
4508 trigdata.tg_trigger = &trig;
4509 trigdata.tg_trigtuplebuf = scan->rs_cbuf;
4510 trigdata.tg_newtuplebuf = InvalidBuffer;
4512 fcinfo.context = (Node *) &trigdata;
4514 RI_FKey_check_ins(&fcinfo);
4521 CreateFKCheckTrigger(RangeVar *myRel, FkConstraint *fkconstraint,
4522 Oid constraintOid, bool on_insert)
4524 CreateTrigStmt *fk_trigger;
4526 fk_trigger = makeNode(CreateTrigStmt);
4527 fk_trigger->trigname = fkconstraint->constr_name;
4528 fk_trigger->relation = myRel;
4529 fk_trigger->before = false;
4530 fk_trigger->row = true;
4532 /* Either ON INSERT or ON UPDATE */
4535 fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
4536 fk_trigger->actions[0] = 'i';
4540 fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
4541 fk_trigger->actions[0] = 'u';
4543 fk_trigger->actions[1] = '\0';
4545 fk_trigger->isconstraint = true;
4546 fk_trigger->deferrable = fkconstraint->deferrable;
4547 fk_trigger->initdeferred = fkconstraint->initdeferred;
4548 fk_trigger->constrrel = fkconstraint->pktable;
4549 fk_trigger->args = NIL;
4551 (void) CreateTrigger(fk_trigger, constraintOid);
4553 /* Make changes-so-far visible */
4554 CommandCounterIncrement();
4558 * Create the triggers that implement an FK constraint.
4561 createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
4565 CreateTrigStmt *fk_trigger;
4568 * Reconstruct a RangeVar for my relation (not passed in, unfortunately).
4570 myRel = makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
4571 pstrdup(RelationGetRelationName(rel)));
4573 /* Make changes-so-far visible */
4574 CommandCounterIncrement();
4577 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the CHECK
4578 * action for both INSERTs and UPDATEs on the referencing table.
4580 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, true);
4581 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, false);
4584 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
4585 * DELETE action on the referenced table.
4587 fk_trigger = makeNode(CreateTrigStmt);
4588 fk_trigger->trigname = fkconstraint->constr_name;
4589 fk_trigger->relation = fkconstraint->pktable;
4590 fk_trigger->before = false;
4591 fk_trigger->row = true;
4592 fk_trigger->actions[0] = 'd';
4593 fk_trigger->actions[1] = '\0';
4595 fk_trigger->isconstraint = true;
4596 fk_trigger->constrrel = myRel;
4597 switch (fkconstraint->fk_del_action)
4599 case FKCONSTR_ACTION_NOACTION:
4600 fk_trigger->deferrable = fkconstraint->deferrable;
4601 fk_trigger->initdeferred = fkconstraint->initdeferred;
4602 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
4604 case FKCONSTR_ACTION_RESTRICT:
4605 fk_trigger->deferrable = false;
4606 fk_trigger->initdeferred = false;
4607 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
4609 case FKCONSTR_ACTION_CASCADE:
4610 fk_trigger->deferrable = false;
4611 fk_trigger->initdeferred = false;
4612 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
4614 case FKCONSTR_ACTION_SETNULL:
4615 fk_trigger->deferrable = false;
4616 fk_trigger->initdeferred = false;
4617 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
4619 case FKCONSTR_ACTION_SETDEFAULT:
4620 fk_trigger->deferrable = false;
4621 fk_trigger->initdeferred = false;
4622 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
4625 elog(ERROR, "unrecognized FK action type: %d",
4626 (int) fkconstraint->fk_del_action);
4629 fk_trigger->args = NIL;
4631 (void) CreateTrigger(fk_trigger, constraintOid);
4633 /* Make changes-so-far visible */
4634 CommandCounterIncrement();
4637 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
4638 * UPDATE action on the referenced table.
4640 fk_trigger = makeNode(CreateTrigStmt);
4641 fk_trigger->trigname = fkconstraint->constr_name;
4642 fk_trigger->relation = fkconstraint->pktable;
4643 fk_trigger->before = false;
4644 fk_trigger->row = true;
4645 fk_trigger->actions[0] = 'u';
4646 fk_trigger->actions[1] = '\0';
4647 fk_trigger->isconstraint = true;
4648 fk_trigger->constrrel = myRel;
4649 switch (fkconstraint->fk_upd_action)
4651 case FKCONSTR_ACTION_NOACTION:
4652 fk_trigger->deferrable = fkconstraint->deferrable;
4653 fk_trigger->initdeferred = fkconstraint->initdeferred;
4654 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
4656 case FKCONSTR_ACTION_RESTRICT:
4657 fk_trigger->deferrable = false;
4658 fk_trigger->initdeferred = false;
4659 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
4661 case FKCONSTR_ACTION_CASCADE:
4662 fk_trigger->deferrable = false;
4663 fk_trigger->initdeferred = false;
4664 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
4666 case FKCONSTR_ACTION_SETNULL:
4667 fk_trigger->deferrable = false;
4668 fk_trigger->initdeferred = false;
4669 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
4671 case FKCONSTR_ACTION_SETDEFAULT:
4672 fk_trigger->deferrable = false;
4673 fk_trigger->initdeferred = false;
4674 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
4677 elog(ERROR, "unrecognized FK action type: %d",
4678 (int) fkconstraint->fk_upd_action);
4681 fk_trigger->args = NIL;
4683 (void) CreateTrigger(fk_trigger, constraintOid);
4687 * ALTER TABLE DROP CONSTRAINT
4690 ATPrepDropConstraint(List **wqueue, Relation rel,
4691 bool recurse, AlterTableCmd *cmd)
4694 * We don't want errors or noise from child tables, so we have to pass
4695 * down a modified command.
4699 AlterTableCmd *childCmd = copyObject(cmd);
4701 childCmd->subtype = AT_DropConstraintQuietly;
4702 ATSimpleRecursion(wqueue, rel, childCmd, recurse);
4707 ATExecDropConstraint(Relation rel, const char *constrName,
4708 DropBehavior behavior, bool quiet)
4712 deleted = RemoveRelConstraints(rel, constrName, behavior);
4716 /* If zero constraints deleted, complain */
4719 (errcode(ERRCODE_UNDEFINED_OBJECT),
4720 errmsg("constraint \"%s\" does not exist",
4722 /* Otherwise if more than one constraint deleted, notify */
4723 else if (deleted > 1)
4725 (errmsg("multiple constraints named \"%s\" were dropped",
4734 ATPrepAlterColumnType(List **wqueue,
4735 AlteredTableInfo *tab, Relation rel,
4736 bool recurse, bool recursing,
4739 char *colName = cmd->name;
4740 TypeName *typename = (TypeName *) cmd->def;
4742 Form_pg_attribute attTup;
4747 NewColumnValue *newval;
4748 ParseState *pstate = make_parsestate(NULL);
4750 /* lookup the attribute so we can check inheritance status */
4751 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
4752 if (!HeapTupleIsValid(tuple))
4754 (errcode(ERRCODE_UNDEFINED_COLUMN),
4755 errmsg("column \"%s\" of relation \"%s\" does not exist",
4756 colName, RelationGetRelationName(rel))));
4757 attTup = (Form_pg_attribute) GETSTRUCT(tuple);
4758 attnum = attTup->attnum;
4760 /* Can't alter a system attribute */
4763 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4764 errmsg("cannot alter system column \"%s\"",
4767 /* Don't alter inherited columns */
4768 if (attTup->attinhcount > 0 && !recursing)
4770 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4771 errmsg("cannot alter inherited column \"%s\"",
4774 /* Look up the target type */
4775 targettype = typenameTypeId(NULL, typename);
4776 targettypmod = typenameTypeMod(NULL, typename, targettype);
4778 /* make sure datatype is legal for a column */
4779 CheckAttributeType(colName, targettype);
4782 * Set up an expression to transform the old data value to the new type.
4783 * If a USING option was given, transform and use that expression, else
4784 * just take the old value and try to coerce it. We do this first so that
4785 * type incompatibility can be detected before we waste effort, and
4786 * because we need the expression to be parsed against the original table
4793 /* Expression must be able to access vars of old table */
4794 rte = addRangeTableEntryForRelation(pstate,
4799 addRTEtoQuery(pstate, rte, false, true, true);
4801 transform = transformExpr(pstate, cmd->transform);
4803 /* It can't return a set */
4804 if (expression_returns_set(transform))
4806 (errcode(ERRCODE_DATATYPE_MISMATCH),
4807 errmsg("transform expression must not return a set")));
4809 /* No subplans or aggregates, either... */
4810 if (pstate->p_hasSubLinks)
4812 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4813 errmsg("cannot use subquery in transform expression")));
4814 if (pstate->p_hasAggs)
4816 (errcode(ERRCODE_GROUPING_ERROR),
4817 errmsg("cannot use aggregate function in transform expression")));
4821 transform = (Node *) makeVar(1, attnum,
4822 attTup->atttypid, attTup->atttypmod,
4826 transform = coerce_to_target_type(pstate,
4827 transform, exprType(transform),
4828 targettype, targettypmod,
4829 COERCION_ASSIGNMENT,
4830 COERCE_IMPLICIT_CAST);
4831 if (transform == NULL)
4833 (errcode(ERRCODE_DATATYPE_MISMATCH),
4834 errmsg("column \"%s\" cannot be cast to type \"%s\"",
4835 colName, TypeNameToString(typename))));
4838 * Add a work queue item to make ATRewriteTable update the column
4841 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
4842 newval->attnum = attnum;
4843 newval->expr = (Expr *) transform;
4845 tab->newvals = lappend(tab->newvals, newval);
4847 ReleaseSysCache(tuple);
4850 * The recursion case is handled by ATSimpleRecursion. However, if we are
4851 * told not to recurse, there had better not be any child tables; else the
4852 * alter would put them out of step.
4855 ATSimpleRecursion(wqueue, rel, cmd, recurse);
4856 else if (!recursing &&
4857 find_inheritance_children(RelationGetRelid(rel)) != NIL)
4859 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4860 errmsg("type of inherited column \"%s\" must be changed in child tables too",
4865 ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
4866 const char *colName, TypeName *typename)
4869 Form_pg_attribute attTup;
4871 HeapTuple typeTuple;
4876 Relation attrelation;
4882 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
4884 /* Look up the target column */
4885 heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4886 if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
4888 (errcode(ERRCODE_UNDEFINED_COLUMN),
4889 errmsg("column \"%s\" of relation \"%s\" does not exist",
4890 colName, RelationGetRelationName(rel))));
4891 attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
4892 attnum = attTup->attnum;
4894 /* Check for multiple ALTER TYPE on same column --- can't cope */
4895 if (attTup->atttypid != tab->oldDesc->attrs[attnum - 1]->atttypid ||
4896 attTup->atttypmod != tab->oldDesc->attrs[attnum - 1]->atttypmod)
4898 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4899 errmsg("cannot alter type of column \"%s\" twice",
4902 /* Look up the target type (should not fail, since prep found it) */
4903 typeTuple = typenameType(NULL, typename);
4904 tform = (Form_pg_type) GETSTRUCT(typeTuple);
4905 targettype = HeapTupleGetOid(typeTuple);
4906 targettypmod = typenameTypeMod(NULL, typename, targettype);
4909 * If there is a default expression for the column, get it and ensure we
4910 * can coerce it to the new datatype. (We must do this before changing
4911 * the column type, because build_column_default itself will try to
4912 * coerce, and will not issue the error message we want if it fails.)
4914 * We remove any implicit coercion steps at the top level of the old
4915 * default expression; this has been agreed to satisfy the principle of
4916 * least surprise. (The conversion to the new column type should act like
4917 * it started from what the user sees as the stored expression, and the
4918 * implicit coercions aren't going to be shown.)
4920 if (attTup->atthasdef)
4922 defaultexpr = build_column_default(rel, attnum);
4923 Assert(defaultexpr);
4924 defaultexpr = strip_implicit_coercions(defaultexpr);
4925 defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
4926 defaultexpr, exprType(defaultexpr),
4927 targettype, targettypmod,
4928 COERCION_ASSIGNMENT,
4929 COERCE_IMPLICIT_CAST);
4930 if (defaultexpr == NULL)
4932 (errcode(ERRCODE_DATATYPE_MISMATCH),
4933 errmsg("default for column \"%s\" cannot be cast to type \"%s\"",
4934 colName, TypeNameToString(typename))));
4940 * Find everything that depends on the column (constraints, indexes, etc),
4941 * and record enough information to let us recreate the objects.
4943 * The actual recreation does not happen here, but only after we have
4944 * performed all the individual ALTER TYPE operations. We have to save
4945 * the info before executing ALTER TYPE, though, else the deparser will
4948 * There could be multiple entries for the same object, so we must check
4949 * to ensure we process each one only once. Note: we assume that an index
4950 * that implements a constraint will not show a direct dependency on the
4953 depRel = heap_open(DependRelationId, RowExclusiveLock);
4955 ScanKeyInit(&key[0],
4956 Anum_pg_depend_refclassid,
4957 BTEqualStrategyNumber, F_OIDEQ,
4958 ObjectIdGetDatum(RelationRelationId));
4959 ScanKeyInit(&key[1],
4960 Anum_pg_depend_refobjid,
4961 BTEqualStrategyNumber, F_OIDEQ,
4962 ObjectIdGetDatum(RelationGetRelid(rel)));
4963 ScanKeyInit(&key[2],
4964 Anum_pg_depend_refobjsubid,
4965 BTEqualStrategyNumber, F_INT4EQ,
4966 Int32GetDatum((int32) attnum));
4968 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
4969 SnapshotNow, 3, key);
4971 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
4973 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
4974 ObjectAddress foundObject;
4976 /* We don't expect any PIN dependencies on columns */
4977 if (foundDep->deptype == DEPENDENCY_PIN)
4978 elog(ERROR, "cannot alter type of a pinned column");
4980 foundObject.classId = foundDep->classid;
4981 foundObject.objectId = foundDep->objid;
4982 foundObject.objectSubId = foundDep->objsubid;
4984 switch (getObjectClass(&foundObject))
4988 char relKind = get_rel_relkind(foundObject.objectId);
4990 if (relKind == RELKIND_INDEX)
4992 Assert(foundObject.objectSubId == 0);
4993 if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
4995 tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
4996 foundObject.objectId);
4997 tab->changedIndexDefs = lappend(tab->changedIndexDefs,
4998 pg_get_indexdef_string(foundObject.objectId));
5001 else if (relKind == RELKIND_SEQUENCE)
5004 * This must be a SERIAL column's sequence. We need
5005 * not do anything to it.
5007 Assert(foundObject.objectSubId == 0);
5011 /* Not expecting any other direct dependencies... */
5012 elog(ERROR, "unexpected object depending on column: %s",
5013 getObjectDescription(&foundObject));
5018 case OCLASS_CONSTRAINT:
5019 Assert(foundObject.objectSubId == 0);
5020 if (!list_member_oid(tab->changedConstraintOids,
5021 foundObject.objectId))
5023 char *defstring = pg_get_constraintdef_string(foundObject.objectId);
5026 * Put NORMAL dependencies at the front of the list and
5027 * AUTO dependencies at the back. This makes sure that
5028 * foreign-key constraints depending on this column will
5029 * be dropped before unique or primary-key constraints of
5030 * the column; which we must have because the FK
5031 * constraints depend on the indexes belonging to the
5032 * unique constraints.
5034 if (foundDep->deptype == DEPENDENCY_NORMAL)
5036 tab->changedConstraintOids =
5037 lcons_oid(foundObject.objectId,
5038 tab->changedConstraintOids);
5039 tab->changedConstraintDefs =
5041 tab->changedConstraintDefs);
5045 tab->changedConstraintOids =
5046 lappend_oid(tab->changedConstraintOids,
5047 foundObject.objectId);
5048 tab->changedConstraintDefs =
5049 lappend(tab->changedConstraintDefs,
5055 case OCLASS_REWRITE:
5056 /* XXX someday see if we can cope with revising views */
5058 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5059 errmsg("cannot alter type of a column used by a view or rule"),
5060 errdetail("%s depends on column \"%s\"",
5061 getObjectDescription(&foundObject),
5065 case OCLASS_DEFAULT:
5068 * Ignore the column's default expression, since we will fix
5071 Assert(defaultexpr);
5077 case OCLASS_CONVERSION:
5078 case OCLASS_LANGUAGE:
5079 case OCLASS_OPERATOR:
5080 case OCLASS_OPCLASS:
5081 case OCLASS_TRIGGER:
5085 * We don't expect any of these sorts of objects to depend on
5088 elog(ERROR, "unexpected object depending on column: %s",
5089 getObjectDescription(&foundObject));
5093 elog(ERROR, "unrecognized object class: %u",
5094 foundObject.classId);
5098 systable_endscan(scan);
5101 * Now scan for dependencies of this column on other things. The only
5102 * thing we should find is the dependency on the column datatype, which we
5105 ScanKeyInit(&key[0],
5106 Anum_pg_depend_classid,
5107 BTEqualStrategyNumber, F_OIDEQ,
5108 ObjectIdGetDatum(RelationRelationId));
5109 ScanKeyInit(&key[1],
5110 Anum_pg_depend_objid,
5111 BTEqualStrategyNumber, F_OIDEQ,
5112 ObjectIdGetDatum(RelationGetRelid(rel)));
5113 ScanKeyInit(&key[2],
5114 Anum_pg_depend_objsubid,
5115 BTEqualStrategyNumber, F_INT4EQ,
5116 Int32GetDatum((int32) attnum));
5118 scan = systable_beginscan(depRel, DependDependerIndexId, true,
5119 SnapshotNow, 3, key);
5121 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5123 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5125 if (foundDep->deptype != DEPENDENCY_NORMAL)
5126 elog(ERROR, "found unexpected dependency type '%c'",
5128 if (foundDep->refclassid != TypeRelationId ||
5129 foundDep->refobjid != attTup->atttypid)
5130 elog(ERROR, "found unexpected dependency for column");
5132 simple_heap_delete(depRel, &depTup->t_self);
5135 systable_endscan(scan);
5137 heap_close(depRel, RowExclusiveLock);
5140 * Here we go --- change the recorded column type. (Note heapTup is a
5141 * copy of the syscache entry, so okay to scribble on.)
5143 attTup->atttypid = targettype;
5144 attTup->atttypmod = targettypmod;
5145 attTup->attndims = list_length(typename->arrayBounds);
5146 attTup->attlen = tform->typlen;
5147 attTup->attbyval = tform->typbyval;
5148 attTup->attalign = tform->typalign;
5149 attTup->attstorage = tform->typstorage;
5151 ReleaseSysCache(typeTuple);
5153 simple_heap_update(attrelation, &heapTup->t_self, heapTup);
5155 /* keep system catalog indexes current */
5156 CatalogUpdateIndexes(attrelation, heapTup);
5158 heap_close(attrelation, RowExclusiveLock);
5160 /* Install dependency on new datatype */
5161 add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
5164 * Drop any pg_statistic entry for the column, since it's now wrong type
5166 RemoveStatistics(RelationGetRelid(rel), attnum);
5169 * Update the default, if present, by brute force --- remove and re-add
5170 * the default. Probably unsafe to take shortcuts, since the new version
5171 * may well have additional dependencies. (It's okay to do this now,
5172 * rather than after other ALTER TYPE commands, since the default won't
5173 * depend on other column types.)
5177 /* Must make new row visible since it will be updated again */
5178 CommandCounterIncrement();
5181 * We use RESTRICT here for safety, but at present we do not expect
5182 * anything to depend on the default.
5184 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true);
5186 StoreAttrDefault(rel, attnum, nodeToString(defaultexpr));
5190 heap_freetuple(heapTup);
5194 * Cleanup after we've finished all the ALTER TYPE operations for a
5195 * particular relation. We have to drop and recreate all the indexes
5196 * and constraints that depend on the altered columns.
5199 ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab)
5205 * Re-parse the index and constraint definitions, and attach them to the
5206 * appropriate work queue entries. We do this before dropping because in
5207 * the case of a FOREIGN KEY constraint, we might not yet have exclusive
5208 * lock on the table the constraint is attached to, and we need to get
5209 * that before dropping. It's safe because the parser won't actually look
5210 * at the catalogs to detect the existing entry.
5212 foreach(l, tab->changedIndexDefs)
5213 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
5214 foreach(l, tab->changedConstraintDefs)
5215 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
5218 * Now we can drop the existing constraints and indexes --- constraints
5219 * first, since some of them might depend on the indexes. In fact, we
5220 * have to delete FOREIGN KEY constraints before UNIQUE constraints, but
5221 * we already ordered the constraint list to ensure that would happen. It
5222 * should be okay to use DROP_RESTRICT here, since nothing else should be
5223 * depending on these objects.
5225 foreach(l, tab->changedConstraintOids)
5227 obj.classId = ConstraintRelationId;
5228 obj.objectId = lfirst_oid(l);
5229 obj.objectSubId = 0;
5230 performDeletion(&obj, DROP_RESTRICT);
5233 foreach(l, tab->changedIndexOids)
5235 obj.classId = RelationRelationId;
5236 obj.objectId = lfirst_oid(l);
5237 obj.objectSubId = 0;
5238 performDeletion(&obj, DROP_RESTRICT);
5242 * The objects will get recreated during subsequent passes over the work
5248 ATPostAlterTypeParse(char *cmd, List **wqueue)
5250 List *raw_parsetree_list;
5251 List *querytree_list;
5252 ListCell *list_item;
5255 * We expect that we will get only ALTER TABLE and CREATE INDEX statements.
5256 * Hence, there is no need to pass them through parse_analyze() or the
5257 * rewriter, but instead we need to pass them through parse_utilcmd.c
5258 * to make them ready for execution.
5260 raw_parsetree_list = raw_parser(cmd);
5261 querytree_list = NIL;
5262 foreach(list_item, raw_parsetree_list)
5264 Node *stmt = (Node *) lfirst(list_item);
5266 if (IsA(stmt, IndexStmt))
5267 querytree_list = lappend(querytree_list,
5268 transformIndexStmt((IndexStmt *) stmt,
5270 else if (IsA(stmt, AlterTableStmt))
5271 querytree_list = list_concat(querytree_list,
5272 transformAlterTableStmt((AlterTableStmt *) stmt,
5275 querytree_list = lappend(querytree_list, stmt);
5279 * Attach each generated command to the proper place in the work queue.
5280 * Note this could result in creation of entirely new work-queue entries.
5282 foreach(list_item, querytree_list)
5284 Node *stm = (Node *) lfirst(list_item);
5286 AlteredTableInfo *tab;
5288 switch (nodeTag(stm))
5292 IndexStmt *stmt = (IndexStmt *) stm;
5293 AlterTableCmd *newcmd;
5295 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
5296 tab = ATGetQueueEntry(wqueue, rel);
5297 newcmd = makeNode(AlterTableCmd);
5298 newcmd->subtype = AT_ReAddIndex;
5299 newcmd->def = (Node *) stmt;
5300 tab->subcmds[AT_PASS_OLD_INDEX] =
5301 lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
5302 relation_close(rel, NoLock);
5305 case T_AlterTableStmt:
5307 AlterTableStmt *stmt = (AlterTableStmt *) stm;
5310 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
5311 tab = ATGetQueueEntry(wqueue, rel);
5312 foreach(lcmd, stmt->cmds)
5314 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
5316 switch (cmd->subtype)
5319 cmd->subtype = AT_ReAddIndex;
5320 tab->subcmds[AT_PASS_OLD_INDEX] =
5321 lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
5323 case AT_AddConstraint:
5324 tab->subcmds[AT_PASS_OLD_CONSTR] =
5325 lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
5328 elog(ERROR, "unexpected statement type: %d",
5329 (int) cmd->subtype);
5332 relation_close(rel, NoLock);
5336 elog(ERROR, "unexpected statement type: %d",
5337 (int) nodeTag(stm));
5346 * recursing is true if we are recursing from a table to its indexes,
5347 * sequences, or toast table. We don't allow the ownership of those things to
5348 * be changed separately from the parent table. Also, we can skip permission
5349 * checks (this is necessary not just an optimization, else we'd fail to
5350 * handle toast tables properly).
5352 * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
5353 * free-standing composite type.
5356 ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing)
5358 Relation target_rel;
5361 Form_pg_class tuple_class;
5364 * Get exclusive lock till end of transaction on the target table. Use
5365 * relation_open so that we can work on indexes and sequences.
5367 target_rel = relation_open(relationOid, AccessExclusiveLock);
5369 /* Get its pg_class tuple, too */
5370 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
5372 tuple = SearchSysCache(RELOID,
5373 ObjectIdGetDatum(relationOid),
5375 if (!HeapTupleIsValid(tuple))
5376 elog(ERROR, "cache lookup failed for relation %u", relationOid);
5377 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
5379 /* Can we change the ownership of this tuple? */
5380 switch (tuple_class->relkind)
5382 case RELKIND_RELATION:
5384 /* ok to change owner */
5390 * Because ALTER INDEX OWNER used to be allowed, and in fact
5391 * is generated by old versions of pg_dump, we give a warning
5392 * and do nothing rather than erroring out. Also, to avoid
5393 * unnecessary chatter while restoring those old dumps, say
5394 * nothing at all if the command would be a no-op anyway.
5396 if (tuple_class->relowner != newOwnerId)
5398 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5399 errmsg("cannot change owner of index \"%s\"",
5400 NameStr(tuple_class->relname)),
5401 errhint("Change the ownership of the index's table, instead.")));
5402 /* quick hack to exit via the no-op path */
5403 newOwnerId = tuple_class->relowner;
5406 case RELKIND_SEQUENCE:
5408 tuple_class->relowner != newOwnerId)
5410 /* if it's an owned sequence, disallow changing it by itself */
5414 if (sequenceIsOwned(relationOid, &tableId, &colId))
5416 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5417 errmsg("cannot change owner of sequence \"%s\"",
5418 NameStr(tuple_class->relname)),
5419 errdetail("Sequence \"%s\" is linked to table \"%s\".",
5420 NameStr(tuple_class->relname),
5421 get_rel_name(tableId))));
5424 case RELKIND_TOASTVALUE:
5425 case RELKIND_COMPOSITE_TYPE:
5431 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5432 errmsg("\"%s\" is not a table, view, or sequence",
5433 NameStr(tuple_class->relname))));
5437 * If the new owner is the same as the existing owner, consider the
5438 * command to have succeeded. This is for dump restoration purposes.
5440 if (tuple_class->relowner != newOwnerId)
5442 Datum repl_val[Natts_pg_class];
5443 char repl_null[Natts_pg_class];
5444 char repl_repl[Natts_pg_class];
5450 /* skip permission checks when recursing to index or toast table */
5453 /* Superusers can always do it */
5456 Oid namespaceOid = tuple_class->relnamespace;
5457 AclResult aclresult;
5459 /* Otherwise, must be owner of the existing object */
5460 if (!pg_class_ownercheck(relationOid, GetUserId()))
5461 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
5462 RelationGetRelationName(target_rel));
5464 /* Must be able to become new owner */
5465 check_is_member_of_role(GetUserId(), newOwnerId);
5467 /* New owner must have CREATE privilege on namespace */
5468 aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
5470 if (aclresult != ACLCHECK_OK)
5471 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
5472 get_namespace_name(namespaceOid));
5476 memset(repl_null, ' ', sizeof(repl_null));
5477 memset(repl_repl, ' ', sizeof(repl_repl));
5479 repl_repl[Anum_pg_class_relowner - 1] = 'r';
5480 repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
5483 * Determine the modified ACL for the new owner. This is only
5484 * necessary when the ACL is non-null.
5486 aclDatum = SysCacheGetAttr(RELOID, tuple,
5487 Anum_pg_class_relacl,
5491 newAcl = aclnewowner(DatumGetAclP(aclDatum),
5492 tuple_class->relowner, newOwnerId);
5493 repl_repl[Anum_pg_class_relacl - 1] = 'r';
5494 repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
5497 newtuple = heap_modifytuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
5499 simple_heap_update(class_rel, &newtuple->t_self, newtuple);
5500 CatalogUpdateIndexes(class_rel, newtuple);
5502 heap_freetuple(newtuple);
5505 * Update owner dependency reference, if any. A composite type has
5506 * none, because it's tracked for the pg_type entry instead of here;
5507 * indexes and TOAST tables don't have their own entries either.
5509 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
5510 tuple_class->relkind != RELKIND_INDEX &&
5511 tuple_class->relkind != RELKIND_TOASTVALUE)
5512 changeDependencyOnOwner(RelationRelationId, relationOid,
5516 * Also change the ownership of the table's rowtype, if it has one
5518 if (tuple_class->relkind != RELKIND_INDEX)
5519 AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId,
5520 tuple_class->relkind == RELKIND_COMPOSITE_TYPE);
5523 * If we are operating on a table, also change the ownership of any
5524 * indexes and sequences that belong to the table, as well as the
5525 * table's toast table (if it has one)
5527 if (tuple_class->relkind == RELKIND_RELATION ||
5528 tuple_class->relkind == RELKIND_TOASTVALUE)
5530 List *index_oid_list;
5533 /* Find all the indexes belonging to this relation */
5534 index_oid_list = RelationGetIndexList(target_rel);
5536 /* For each index, recursively change its ownership */
5537 foreach(i, index_oid_list)
5538 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true);
5540 list_free(index_oid_list);
5543 if (tuple_class->relkind == RELKIND_RELATION)
5545 /* If it has a toast table, recurse to change its ownership */
5546 if (tuple_class->reltoastrelid != InvalidOid)
5547 ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
5550 /* If it has dependent sequences, recurse to change them too */
5551 change_owner_recurse_to_sequences(relationOid, newOwnerId);
5555 ReleaseSysCache(tuple);
5556 heap_close(class_rel, RowExclusiveLock);
5557 relation_close(target_rel, NoLock);
5561 * change_owner_recurse_to_sequences
5563 * Helper function for ATExecChangeOwner. Examines pg_depend searching
5564 * for sequences that are dependent on serial columns, and changes their
5568 change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId)
5576 * SERIAL sequences are those having an auto dependency on one of the
5577 * table's columns (we don't care *which* column, exactly).
5579 depRel = heap_open(DependRelationId, AccessShareLock);
5581 ScanKeyInit(&key[0],
5582 Anum_pg_depend_refclassid,
5583 BTEqualStrategyNumber, F_OIDEQ,
5584 ObjectIdGetDatum(RelationRelationId));
5585 ScanKeyInit(&key[1],
5586 Anum_pg_depend_refobjid,
5587 BTEqualStrategyNumber, F_OIDEQ,
5588 ObjectIdGetDatum(relationOid));
5589 /* we leave refobjsubid unspecified */
5591 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
5592 SnapshotNow, 2, key);
5594 while (HeapTupleIsValid(tup = systable_getnext(scan)))
5596 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
5599 /* skip dependencies other than auto dependencies on columns */
5600 if (depForm->refobjsubid == 0 ||
5601 depForm->classid != RelationRelationId ||
5602 depForm->objsubid != 0 ||
5603 depForm->deptype != DEPENDENCY_AUTO)
5606 /* Use relation_open just in case it's an index */
5607 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
5609 /* skip non-sequence relations */
5610 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
5612 /* No need to keep the lock */
5613 relation_close(seqRel, AccessExclusiveLock);
5617 /* We don't need to close the sequence while we alter it. */
5618 ATExecChangeOwner(depForm->objid, newOwnerId, true);
5620 /* Now we can close it. Keep the lock till end of transaction. */
5621 relation_close(seqRel, NoLock);
5624 systable_endscan(scan);
5626 relation_close(depRel, AccessShareLock);
5630 * ALTER TABLE CLUSTER ON
5632 * The only thing we have to do is to change the indisclustered bits.
5635 ATExecClusterOn(Relation rel, const char *indexName)
5639 indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
5641 if (!OidIsValid(indexOid))
5643 (errcode(ERRCODE_UNDEFINED_OBJECT),
5644 errmsg("index \"%s\" for table \"%s\" does not exist",
5645 indexName, RelationGetRelationName(rel))));
5647 /* Check index is valid to cluster on */
5648 check_index_is_clusterable(rel, indexOid, false);
5650 /* And do the work */
5651 mark_index_clustered(rel, indexOid);
5655 * ALTER TABLE SET WITHOUT CLUSTER
5657 * We have to find any indexes on the table that have indisclustered bit
5658 * set and turn it off.
5661 ATExecDropCluster(Relation rel)
5663 mark_index_clustered(rel, InvalidOid);
5667 * ALTER TABLE SET TABLESPACE
5670 ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, char *tablespacename)
5673 AclResult aclresult;
5675 /* Check that the tablespace exists */
5676 tablespaceId = get_tablespace_oid(tablespacename);
5677 if (!OidIsValid(tablespaceId))
5679 (errcode(ERRCODE_UNDEFINED_OBJECT),
5680 errmsg("tablespace \"%s\" does not exist", tablespacename)));
5682 /* Check its permissions */
5683 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(), ACL_CREATE);
5684 if (aclresult != ACLCHECK_OK)
5685 aclcheck_error(aclresult, ACL_KIND_TABLESPACE, tablespacename);
5687 /* Save info for Phase 3 to do the real work */
5688 if (OidIsValid(tab->newTableSpace))
5690 (errcode(ERRCODE_SYNTAX_ERROR),
5691 errmsg("cannot have multiple SET TABLESPACE subcommands")));
5692 tab->newTableSpace = tablespaceId;
5696 * ALTER TABLE/INDEX SET (...) or RESET (...)
5699 ATExecSetRelOptions(Relation rel, List *defList, bool isReset)
5708 Datum repl_val[Natts_pg_class];
5709 char repl_null[Natts_pg_class];
5710 char repl_repl[Natts_pg_class];
5713 return; /* nothing to do */
5715 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
5717 /* Get the old reloptions */
5718 relid = RelationGetRelid(rel);
5719 tuple = SearchSysCache(RELOID,
5720 ObjectIdGetDatum(relid),
5722 if (!HeapTupleIsValid(tuple))
5723 elog(ERROR, "cache lookup failed for relation %u", relid);
5725 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions, &isnull);
5727 /* Generate new proposed reloptions (text array) */
5728 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
5729 defList, false, isReset);
5732 switch (rel->rd_rel->relkind)
5734 case RELKIND_RELATION:
5735 case RELKIND_TOASTVALUE:
5736 (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
5739 (void) index_reloptions(rel->rd_am->amoptions, newOptions, true);
5743 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5744 errmsg("\"%s\" is not a table, index, or TOAST table",
5745 RelationGetRelationName(rel))));
5750 * All we need do here is update the pg_class row; the new options will be
5751 * propagated into relcaches during post-commit cache inval.
5753 memset(repl_val, 0, sizeof(repl_val));
5754 memset(repl_null, ' ', sizeof(repl_null));
5755 memset(repl_repl, ' ', sizeof(repl_repl));
5757 if (newOptions != (Datum) 0)
5758 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
5760 repl_null[Anum_pg_class_reloptions - 1] = 'n';
5762 repl_repl[Anum_pg_class_reloptions - 1] = 'r';
5764 newtuple = heap_modifytuple(tuple, RelationGetDescr(pgclass),
5765 repl_val, repl_null, repl_repl);
5767 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
5769 CatalogUpdateIndexes(pgclass, newtuple);
5771 heap_freetuple(newtuple);
5773 ReleaseSysCache(tuple);
5775 heap_close(pgclass, RowExclusiveLock);
5779 * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
5780 * rewriting to be done, so we just want to copy the data as fast as possible.
5783 ATExecSetTableSpace(Oid tableOid, Oid newTableSpace)
5789 RelFileNode newrnode;
5790 SMgrRelation dstrel;
5793 Form_pg_class rd_rel;
5796 * Need lock here in case we are recursing to toast table or index
5798 rel = relation_open(tableOid, AccessExclusiveLock);
5801 * We can never allow moving of shared or nailed-in-cache relations,
5802 * because we can't support changing their reltablespace values.
5804 if (rel->rd_rel->relisshared || rel->rd_isnailed)
5806 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5807 errmsg("cannot move system relation \"%s\"",
5808 RelationGetRelationName(rel))));
5811 * Don't allow moving temp tables of other backends ... their local buffer
5812 * manager is not going to cope.
5814 if (isOtherTempNamespace(RelationGetNamespace(rel)))
5816 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5817 errmsg("cannot move temporary tables of other sessions")));
5820 * No work if no change in tablespace.
5822 oldTableSpace = rel->rd_rel->reltablespace;
5823 if (newTableSpace == oldTableSpace ||
5824 (newTableSpace == MyDatabaseTableSpace && oldTableSpace == 0))
5826 relation_close(rel, NoLock);
5830 reltoastrelid = rel->rd_rel->reltoastrelid;
5831 reltoastidxid = rel->rd_rel->reltoastidxid;
5833 /* Get a modifiable copy of the relation's pg_class row */
5834 pg_class = heap_open(RelationRelationId, RowExclusiveLock);
5836 tuple = SearchSysCacheCopy(RELOID,
5837 ObjectIdGetDatum(tableOid),
5839 if (!HeapTupleIsValid(tuple))
5840 elog(ERROR, "cache lookup failed for relation %u", tableOid);
5841 rd_rel = (Form_pg_class) GETSTRUCT(tuple);
5843 /* create another storage file. Is it a little ugly ? */
5844 /* NOTE: any conflict in relfilenode value will be caught here */
5845 newrnode = rel->rd_node;
5846 newrnode.spcNode = newTableSpace;
5848 dstrel = smgropen(newrnode);
5849 smgrcreate(dstrel, rel->rd_istemp, false);
5851 /* copy relation data to the new physical file */
5852 copy_relation_data(rel, dstrel);
5854 /* schedule unlinking old physical file */
5855 RelationOpenSmgr(rel);
5856 smgrscheduleunlink(rel->rd_smgr, rel->rd_istemp);
5859 * Now drop smgr references. The source was already dropped by
5860 * smgrscheduleunlink.
5864 /* update the pg_class row */
5865 rd_rel->reltablespace = (newTableSpace == MyDatabaseTableSpace) ? InvalidOid : newTableSpace;
5866 simple_heap_update(pg_class, &tuple->t_self, tuple);
5867 CatalogUpdateIndexes(pg_class, tuple);
5869 heap_freetuple(tuple);
5871 heap_close(pg_class, RowExclusiveLock);
5873 relation_close(rel, NoLock);
5875 /* Make sure the reltablespace change is visible */
5876 CommandCounterIncrement();
5878 /* Move associated toast relation and/or index, too */
5879 if (OidIsValid(reltoastrelid))
5880 ATExecSetTableSpace(reltoastrelid, newTableSpace);
5881 if (OidIsValid(reltoastidxid))
5882 ATExecSetTableSpace(reltoastidxid, newTableSpace);
5886 * Copy data, block by block
5889 copy_relation_data(Relation rel, SMgrRelation dst)
5893 BlockNumber nblocks;
5896 Page page = (Page) buf;
5899 * Since we copy the file directly without looking at the shared buffers,
5900 * we'd better first flush out any pages of the source relation that are
5901 * in shared buffers. We assume no new changes will be made while we are
5902 * holding exclusive lock on the rel.
5904 FlushRelationBuffers(rel);
5907 * We need to log the copied data in WAL iff WAL archiving is enabled AND
5908 * it's not a temp rel.
5910 use_wal = XLogArchivingActive() && !rel->rd_istemp;
5912 nblocks = RelationGetNumberOfBlocks(rel);
5913 /* RelationGetNumberOfBlocks will certainly have opened rd_smgr */
5916 for (blkno = 0; blkno < nblocks; blkno++)
5918 smgrread(src, blkno, buf);
5922 log_newpage(&dst->smgr_rnode, blkno, page);
5925 * Now write the page. We say isTemp = true even if it's not a temp
5926 * rel, because there's no need for smgr to schedule an fsync for this
5927 * write; we'll do it ourselves below.
5929 smgrextend(dst, blkno, buf, true);
5933 * If the rel isn't temp, we must fsync it down to disk before it's safe
5934 * to commit the transaction. (For a temp rel we don't care since the rel
5935 * will be uninteresting after a crash anyway.)
5937 * It's obvious that we must do this when not WAL-logging the copy. It's
5938 * less obvious that we have to do it even if we did WAL-log the copied
5939 * pages. The reason is that since we're copying outside shared buffers, a
5940 * CHECKPOINT occurring during the copy has no way to flush the previously
5941 * written data to disk (indeed it won't know the new rel even exists). A
5942 * crash later on would replay WAL from the checkpoint, therefore it
5943 * wouldn't replay our earlier WAL entries. If we do not fsync those pages
5944 * here, they might still not be on disk when the crash occurs.
5946 if (!rel->rd_istemp)
5951 * ALTER TABLE ENABLE/DISABLE TRIGGER
5953 * We just pass this off to trigger.c.
5956 ATExecEnableDisableTrigger(Relation rel, char *trigname,
5957 char fires_when, bool skip_system)
5959 EnableDisableTrigger(rel, trigname, fires_when, skip_system);
5963 * ALTER TABLE ENABLE/DISABLE RULE
5965 * We just pass this off to rewriteDefine.c.
5968 ATExecEnableDisableRule(Relation rel, char *trigname,
5971 EnableDisableRule(rel, trigname, fires_when);
5975 * ALTER TABLE INHERIT
5977 * Add a parent to the child's parents. This verifies that all the columns and
5978 * check constraints of the parent appear in the child and that they have the
5979 * same data types and expressions.
5982 ATExecAddInherit(Relation child_rel, RangeVar *parent)
5984 Relation parent_rel,
5988 HeapTuple inheritsTuple;
5993 * AccessShareLock on the parent is what's obtained during normal CREATE
5994 * TABLE ... INHERITS ..., so should be enough here.
5996 parent_rel = heap_openrv(parent, AccessShareLock);
5999 * Must be owner of both parent and child -- child was checked by
6000 * ATSimplePermissions call in ATPrepCmd
6002 ATSimplePermissions(parent_rel, false);
6004 /* Permanent rels cannot inherit from temporary ones */
6005 if (!isTempNamespace(RelationGetNamespace(child_rel)) &&
6006 isTempNamespace(RelationGetNamespace(parent_rel)))
6008 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6009 errmsg("cannot inherit from temporary relation \"%s\"",
6010 RelationGetRelationName(parent_rel))));
6013 * Check for duplicates in the list of parents, and determine the highest
6014 * inhseqno already present; we'll use the next one for the new parent.
6015 * (Note: get RowExclusiveLock because we will write pg_inherits below.)
6017 * Note: we do not reject the case where the child already inherits from
6018 * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
6020 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
6022 Anum_pg_inherits_inhrelid,
6023 BTEqualStrategyNumber, F_OIDEQ,
6024 ObjectIdGetDatum(RelationGetRelid(child_rel)));
6025 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
6026 true, SnapshotNow, 1, &key);
6028 /* inhseqno sequences start at 1 */
6030 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
6032 Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
6034 if (inh->inhparent == RelationGetRelid(parent_rel))
6036 (errcode(ERRCODE_DUPLICATE_TABLE),
6037 errmsg("relation \"%s\" would be inherited from more than once",
6038 RelationGetRelationName(parent_rel))));
6039 if (inh->inhseqno > inhseqno)
6040 inhseqno = inh->inhseqno;
6042 systable_endscan(scan);
6045 * Prevent circularity by seeing if proposed parent inherits from child.
6046 * (In particular, this disallows making a rel inherit from itself.)
6048 * This is not completely bulletproof because of race conditions: in
6049 * multi-level inheritance trees, someone else could concurrently
6050 * be making another inheritance link that closes the loop but does
6051 * not join either of the rels we have locked. Preventing that seems
6052 * to require exclusive locks on the entire inheritance tree, which is
6053 * a cure worse than the disease. find_all_inheritors() will cope with
6054 * circularity anyway, so don't sweat it too much.
6056 children = find_all_inheritors(RelationGetRelid(child_rel));
6058 if (list_member_oid(children, RelationGetRelid(parent_rel)))
6060 (errcode(ERRCODE_DUPLICATE_TABLE),
6061 errmsg("circular inheritance not allowed"),
6062 errdetail("\"%s\" is already a child of \"%s\".",
6064 RelationGetRelationName(child_rel))));
6066 /* If parent has OIDs then child must have OIDs */
6067 if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
6069 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6070 errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
6071 RelationGetRelationName(child_rel),
6072 RelationGetRelationName(parent_rel))));
6074 /* Match up the columns and bump attinhcount and attislocal */
6075 MergeAttributesIntoExisting(child_rel, parent_rel);
6077 /* Match up the constraints and make sure they're present in child */
6078 MergeConstraintsIntoExisting(child_rel, parent_rel);
6081 * OK, it looks valid. Make the catalog entries that show inheritance.
6083 StoreCatalogInheritance1(RelationGetRelid(child_rel),
6084 RelationGetRelid(parent_rel),
6088 /* Now we're done with pg_inherits */
6089 heap_close(catalogRelation, RowExclusiveLock);
6091 /* keep our lock on the parent relation until commit */
6092 heap_close(parent_rel, NoLock);
6096 * Obtain the source-text form of the constraint expression for a check
6097 * constraint, given its pg_constraint tuple
6100 decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
6102 Form_pg_constraint con;
6107 con = (Form_pg_constraint) GETSTRUCT(contup);
6108 attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
6110 elog(ERROR, "null conbin for constraint %u", HeapTupleGetOid(contup));
6112 expr = DirectFunctionCall2(pg_get_expr, attr,
6113 ObjectIdGetDatum(con->conrelid));
6114 return DatumGetCString(DirectFunctionCall1(textout, expr));
6118 * Check columns in child table match up with columns in parent, and increment
6119 * their attinhcount.
6121 * Called by ATExecAddInherit
6123 * Currently all parent columns must be found in child. Missing columns are an
6124 * error. One day we might consider creating new columns like CREATE TABLE
6125 * does. However, that is widely unpopular --- in the common use case of
6126 * partitioned tables it's a foot-gun.
6128 * The data type must match exactly. If the parent column is NOT NULL then
6129 * the child must be as well. Defaults are not compared, however.
6132 MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel)
6135 AttrNumber parent_attno;
6137 TupleDesc tupleDesc;
6138 TupleConstr *constr;
6141 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
6143 tupleDesc = RelationGetDescr(parent_rel);
6144 parent_natts = tupleDesc->natts;
6145 constr = tupleDesc->constr;
6147 for (parent_attno = 1; parent_attno <= parent_natts; parent_attno++)
6149 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
6150 char *attributeName = NameStr(attribute->attname);
6152 /* Ignore dropped columns in the parent. */
6153 if (attribute->attisdropped)
6156 /* Find same column in child (matching on column name). */
6157 tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel),
6159 if (HeapTupleIsValid(tuple))
6161 /* Check they are same type and typmod */
6162 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
6164 if (attribute->atttypid != childatt->atttypid ||
6165 attribute->atttypmod != childatt->atttypmod)
6167 (errcode(ERRCODE_DATATYPE_MISMATCH),
6168 errmsg("child table \"%s\" has different type for column \"%s\"",
6169 RelationGetRelationName(child_rel),
6172 if (attribute->attnotnull && !childatt->attnotnull)
6174 (errcode(ERRCODE_DATATYPE_MISMATCH),
6175 errmsg("column \"%s\" in child table must be marked NOT NULL",
6179 * OK, bump the child column's inheritance count. (If we fail
6180 * later on, this change will just roll back.)
6182 childatt->attinhcount++;
6183 simple_heap_update(attrrel, &tuple->t_self, tuple);
6184 CatalogUpdateIndexes(attrrel, tuple);
6185 heap_freetuple(tuple);
6190 (errcode(ERRCODE_DATATYPE_MISMATCH),
6191 errmsg("child table is missing column \"%s\"",
6196 heap_close(attrrel, RowExclusiveLock);
6200 * Check constraints in child table match up with constraints in parent
6202 * Called by ATExecAddInherit
6204 * Currently all constraints in parent must be present in the child. One day we
6205 * may consider adding new constraints like CREATE TABLE does. We may also want
6206 * to allow an optional flag on parent table constraints indicating they are
6207 * intended to ONLY apply to the master table, not to the children. That would
6208 * make it possible to ensure no records are mistakenly inserted into the
6209 * master in partitioned tables rather than the appropriate child.
6211 * XXX This is O(N^2) which may be an issue with tables with hundreds of
6212 * constraints. As long as tables have more like 10 constraints it shouldn't be
6213 * a problem though. Even 100 constraints ought not be the end of the world.
6216 MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
6218 Relation catalogRelation;
6219 TupleDesc tupleDesc;
6222 HeapTuple constraintTuple;
6226 /* First gather up the child's constraint definitions */
6227 catalogRelation = heap_open(ConstraintRelationId, AccessShareLock);
6228 tupleDesc = RelationGetDescr(catalogRelation);
6231 Anum_pg_constraint_conrelid,
6232 BTEqualStrategyNumber, F_OIDEQ,
6233 ObjectIdGetDatum(RelationGetRelid(child_rel)));
6234 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
6235 true, SnapshotNow, 1, &key);
6238 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
6240 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
6242 if (con->contype != CONSTRAINT_CHECK)
6245 constraints = lappend(constraints, heap_copytuple(constraintTuple));
6248 systable_endscan(scan);
6250 /* Then scan through the parent's constraints looking for matches */
6252 Anum_pg_constraint_conrelid,
6253 BTEqualStrategyNumber, F_OIDEQ,
6254 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
6255 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId, true,
6256 SnapshotNow, 1, &key);
6258 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
6260 Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
6262 Form_pg_constraint child_con = NULL;
6263 HeapTuple child_contuple = NULL;
6265 if (parent_con->contype != CONSTRAINT_CHECK)
6268 foreach(elem, constraints)
6270 child_contuple = (HeapTuple) lfirst(elem);
6271 child_con = (Form_pg_constraint) GETSTRUCT(child_contuple);
6272 if (strcmp(NameStr(parent_con->conname),
6273 NameStr(child_con->conname)) == 0)
6282 (errcode(ERRCODE_DATATYPE_MISMATCH),
6283 errmsg("child table is missing constraint \"%s\"",
6284 NameStr(parent_con->conname))));
6286 if (parent_con->condeferrable != child_con->condeferrable ||
6287 parent_con->condeferred != child_con->condeferred ||
6288 strcmp(decompile_conbin(constraintTuple, tupleDesc),
6289 decompile_conbin(child_contuple, tupleDesc)) != 0)
6291 (errcode(ERRCODE_DATATYPE_MISMATCH),
6292 errmsg("constraint definition for check constraint \"%s\" does not match",
6293 NameStr(parent_con->conname))));
6296 * TODO: add conislocal,coninhcount to constraints. This is where we
6297 * would have to bump them just like attributes
6301 systable_endscan(scan);
6302 heap_close(catalogRelation, AccessShareLock);
6306 * ALTER TABLE NO INHERIT
6308 * Drop a parent from the child's parents. This just adjusts the attinhcount
6309 * and attislocal of the columns and removes the pg_inherit and pg_depend
6312 * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
6313 * up attislocal stays true, which means if a child is ever removed from a
6314 * parent then its columns will never be automatically dropped which may
6315 * surprise. But at least we'll never surprise by dropping columns someone
6316 * isn't expecting to be dropped which would actually mean data loss.
6319 ATExecDropInherit(Relation rel, RangeVar *parent)
6321 Relation parent_rel;
6322 Relation catalogRelation;
6325 HeapTuple inheritsTuple,
6331 * AccessShareLock on the parent is probably enough, seeing that DROP TABLE
6332 * doesn't lock parent tables at all. We need some lock since we'll be
6333 * inspecting the parent's schema.
6335 parent_rel = heap_openrv(parent, AccessShareLock);
6338 * We don't bother to check ownership of the parent table --- ownership
6339 * of the child is presumed enough rights.
6343 * Find and destroy the pg_inherits entry linking the two, or error out
6346 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
6347 ScanKeyInit(&key[0],
6348 Anum_pg_inherits_inhrelid,
6349 BTEqualStrategyNumber, F_OIDEQ,
6350 ObjectIdGetDatum(RelationGetRelid(rel)));
6351 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
6352 true, SnapshotNow, 1, key);
6354 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
6358 inhparent = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
6359 if (inhparent == RelationGetRelid(parent_rel))
6361 simple_heap_delete(catalogRelation, &inheritsTuple->t_self);
6367 systable_endscan(scan);
6368 heap_close(catalogRelation, RowExclusiveLock);
6372 (errcode(ERRCODE_UNDEFINED_TABLE),
6373 errmsg("relation \"%s\" is not a parent of relation \"%s\"",
6374 RelationGetRelationName(parent_rel),
6375 RelationGetRelationName(rel))));
6378 * Search through child columns looking for ones matching parent rel
6380 catalogRelation = heap_open(AttributeRelationId, RowExclusiveLock);
6381 ScanKeyInit(&key[0],
6382 Anum_pg_attribute_attrelid,
6383 BTEqualStrategyNumber, F_OIDEQ,
6384 ObjectIdGetDatum(RelationGetRelid(rel)));
6385 scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
6386 true, SnapshotNow, 1, key);
6387 while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
6389 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
6391 /* Ignore if dropped or not inherited */
6392 if (att->attisdropped)
6394 if (att->attinhcount <= 0)
6397 if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
6398 NameStr(att->attname)))
6400 /* Decrement inhcount and possibly set islocal to true */
6401 HeapTuple copyTuple = heap_copytuple(attributeTuple);
6402 Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
6404 copy_att->attinhcount--;
6405 if (copy_att->attinhcount == 0)
6406 copy_att->attislocal = true;
6408 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
6409 CatalogUpdateIndexes(catalogRelation, copyTuple);
6410 heap_freetuple(copyTuple);
6413 systable_endscan(scan);
6414 heap_close(catalogRelation, RowExclusiveLock);
6417 * Drop the dependency
6419 * There's no convenient way to do this, so go trawling through pg_depend
6421 catalogRelation = heap_open(DependRelationId, RowExclusiveLock);
6423 ScanKeyInit(&key[0],
6424 Anum_pg_depend_classid,
6425 BTEqualStrategyNumber, F_OIDEQ,
6426 ObjectIdGetDatum(RelationRelationId));
6427 ScanKeyInit(&key[1],
6428 Anum_pg_depend_objid,
6429 BTEqualStrategyNumber, F_OIDEQ,
6430 ObjectIdGetDatum(RelationGetRelid(rel)));
6431 ScanKeyInit(&key[2],
6432 Anum_pg_depend_objsubid,
6433 BTEqualStrategyNumber, F_INT4EQ,
6436 scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
6437 SnapshotNow, 3, key);
6439 while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
6441 Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
6443 if (dep->refclassid == RelationRelationId &&
6444 dep->refobjid == RelationGetRelid(parent_rel) &&
6445 dep->refobjsubid == 0 &&
6446 dep->deptype == DEPENDENCY_NORMAL)
6447 simple_heap_delete(catalogRelation, &depTuple->t_self);
6450 systable_endscan(scan);
6451 heap_close(catalogRelation, RowExclusiveLock);
6453 /* keep our lock on the parent relation until commit */
6454 heap_close(parent_rel, NoLock);
6459 * Execute ALTER TABLE SET SCHEMA
6461 * Note: caller must have checked ownership of the relation already
6464 AlterTableNamespace(RangeVar *relation, const char *newschema)
6472 rel = heap_openrv(relation, AccessExclusiveLock);
6474 relid = RelationGetRelid(rel);
6475 oldNspOid = RelationGetNamespace(rel);
6477 /* heap_openrv allows TOAST, but we don't want to */
6478 if (rel->rd_rel->relkind == RELKIND_TOASTVALUE)
6480 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6481 errmsg("\"%s\" is a TOAST relation",
6482 RelationGetRelationName(rel))));
6484 /* if it's an owned sequence, disallow moving it by itself */
6485 if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
6490 if (sequenceIsOwned(relid, &tableId, &colId))
6492 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6493 errmsg("cannot move an owned sequence into another schema"),
6494 errdetail("Sequence \"%s\" is linked to table \"%s\".",
6495 RelationGetRelationName(rel),
6496 get_rel_name(tableId))));
6499 /* get schema OID and check its permissions */
6500 nspOid = LookupCreationNamespace(newschema);
6502 if (oldNspOid == nspOid)
6504 (errcode(ERRCODE_DUPLICATE_TABLE),
6505 errmsg("relation \"%s\" is already in schema \"%s\"",
6506 RelationGetRelationName(rel),
6509 /* disallow renaming into or out of temp schemas */
6510 if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
6512 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6513 errmsg("cannot move objects into or out of temporary schemas")));
6515 /* same for TOAST schema */
6516 if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
6518 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6519 errmsg("cannot move objects into or out of TOAST schema")));
6521 /* OK, modify the pg_class row and pg_depend entry */
6522 classRel = heap_open(RelationRelationId, RowExclusiveLock);
6524 AlterRelationNamespaceInternal(classRel, relid, oldNspOid, nspOid, true);
6526 /* Fix the table's rowtype too */
6527 AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid, false, false);
6529 /* Fix other dependent stuff */
6530 if (rel->rd_rel->relkind == RELKIND_RELATION)
6532 AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid);
6533 AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid, newschema);
6534 AlterConstraintNamespaces(relid, oldNspOid, nspOid, false);
6537 heap_close(classRel, RowExclusiveLock);
6539 /* close rel, but keep lock until commit */
6540 relation_close(rel, NoLock);
6544 * The guts of relocating a relation to another namespace: fix the pg_class
6545 * entry, and the pg_depend entry if any. Caller must already have
6546 * opened and write-locked pg_class.
6549 AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
6550 Oid oldNspOid, Oid newNspOid,
6551 bool hasDependEntry)
6554 Form_pg_class classForm;
6556 classTup = SearchSysCacheCopy(RELOID,
6557 ObjectIdGetDatum(relOid),
6559 if (!HeapTupleIsValid(classTup))
6560 elog(ERROR, "cache lookup failed for relation %u", relOid);
6561 classForm = (Form_pg_class) GETSTRUCT(classTup);
6563 Assert(classForm->relnamespace == oldNspOid);
6565 /* check for duplicate name (more friendly than unique-index failure) */
6566 if (get_relname_relid(NameStr(classForm->relname),
6567 newNspOid) != InvalidOid)
6569 (errcode(ERRCODE_DUPLICATE_TABLE),
6570 errmsg("relation \"%s\" already exists in schema \"%s\"",
6571 NameStr(classForm->relname),
6572 get_namespace_name(newNspOid))));
6574 /* classTup is a copy, so OK to scribble on */
6575 classForm->relnamespace = newNspOid;
6577 simple_heap_update(classRel, &classTup->t_self, classTup);
6578 CatalogUpdateIndexes(classRel, classTup);
6580 /* Update dependency on schema if caller said so */
6581 if (hasDependEntry &&
6582 changeDependencyFor(RelationRelationId, relOid,
6583 NamespaceRelationId, oldNspOid, newNspOid) != 1)
6584 elog(ERROR, "failed to change schema dependency for relation \"%s\"",
6585 NameStr(classForm->relname));
6587 heap_freetuple(classTup);
6591 * Move all indexes for the specified relation to another namespace.
6593 * Note: we assume adequate permission checking was done by the caller,
6594 * and that the caller has a suitable lock on the owning relation.
6597 AlterIndexNamespaces(Relation classRel, Relation rel,
6598 Oid oldNspOid, Oid newNspOid)
6603 indexList = RelationGetIndexList(rel);
6605 foreach(l, indexList)
6607 Oid indexOid = lfirst_oid(l);
6610 * Note: currently, the index will not have its own dependency on the
6611 * namespace, so we don't need to do changeDependencyFor(). There's no
6612 * rowtype in pg_type, either.
6614 AlterRelationNamespaceInternal(classRel, indexOid,
6615 oldNspOid, newNspOid,
6619 list_free(indexList);
6623 * Move all SERIAL-column sequences of the specified relation to another
6626 * Note: we assume adequate permission checking was done by the caller,
6627 * and that the caller has a suitable lock on the owning relation.
6630 AlterSeqNamespaces(Relation classRel, Relation rel,
6631 Oid oldNspOid, Oid newNspOid, const char *newNspName)
6639 * SERIAL sequences are those having an auto dependency on one of the
6640 * table's columns (we don't care *which* column, exactly).
6642 depRel = heap_open(DependRelationId, AccessShareLock);
6644 ScanKeyInit(&key[0],
6645 Anum_pg_depend_refclassid,
6646 BTEqualStrategyNumber, F_OIDEQ,
6647 ObjectIdGetDatum(RelationRelationId));
6648 ScanKeyInit(&key[1],
6649 Anum_pg_depend_refobjid,
6650 BTEqualStrategyNumber, F_OIDEQ,
6651 ObjectIdGetDatum(RelationGetRelid(rel)));
6652 /* we leave refobjsubid unspecified */
6654 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
6655 SnapshotNow, 2, key);
6657 while (HeapTupleIsValid(tup = systable_getnext(scan)))
6659 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
6662 /* skip dependencies other than auto dependencies on columns */
6663 if (depForm->refobjsubid == 0 ||
6664 depForm->classid != RelationRelationId ||
6665 depForm->objsubid != 0 ||
6666 depForm->deptype != DEPENDENCY_AUTO)
6669 /* Use relation_open just in case it's an index */
6670 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
6672 /* skip non-sequence relations */
6673 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
6675 /* No need to keep the lock */
6676 relation_close(seqRel, AccessExclusiveLock);
6680 /* Fix the pg_class and pg_depend entries */
6681 AlterRelationNamespaceInternal(classRel, depForm->objid,
6682 oldNspOid, newNspOid,
6686 * Sequences have entries in pg_type. We need to be careful to move
6687 * them to the new namespace, too.
6689 AlterTypeNamespaceInternal(RelationGetForm(seqRel)->reltype,
6690 newNspOid, false, false);
6692 /* Now we can close it. Keep the lock till end of transaction. */
6693 relation_close(seqRel, NoLock);
6696 systable_endscan(scan);
6698 relation_close(depRel, AccessShareLock);
6703 * This code supports
6704 * CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
6706 * Because we only support this for TEMP tables, it's sufficient to remember
6707 * the state in a backend-local data structure.
6711 * Register a newly-created relation's ON COMMIT action.
6714 register_on_commit_action(Oid relid, OnCommitAction action)
6717 MemoryContext oldcxt;
6720 * We needn't bother registering the relation unless there is an ON COMMIT
6721 * action we need to take.
6723 if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
6726 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
6728 oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
6730 oc->oncommit = action;
6731 oc->creating_subid = GetCurrentSubTransactionId();
6732 oc->deleting_subid = InvalidSubTransactionId;
6734 on_commits = lcons(oc, on_commits);
6736 MemoryContextSwitchTo(oldcxt);
6740 * Unregister any ON COMMIT action when a relation is deleted.
6742 * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
6745 remove_on_commit_action(Oid relid)
6749 foreach(l, on_commits)
6751 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
6753 if (oc->relid == relid)
6755 oc->deleting_subid = GetCurrentSubTransactionId();
6762 * Perform ON COMMIT actions.
6764 * This is invoked just before actually committing, since it's possible
6765 * to encounter errors.
6768 PreCommit_on_commit_actions(void)
6771 List *oids_to_truncate = NIL;
6773 foreach(l, on_commits)
6775 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
6777 /* Ignore entry if already dropped in this xact */
6778 if (oc->deleting_subid != InvalidSubTransactionId)
6781 switch (oc->oncommit)
6784 case ONCOMMIT_PRESERVE_ROWS:
6785 /* Do nothing (there shouldn't be such entries, actually) */
6787 case ONCOMMIT_DELETE_ROWS:
6788 oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
6792 ObjectAddress object;
6794 object.classId = RelationRelationId;
6795 object.objectId = oc->relid;
6796 object.objectSubId = 0;
6797 performDeletion(&object, DROP_CASCADE);
6800 * Note that table deletion will call
6801 * remove_on_commit_action, so the entry should get marked
6804 Assert(oc->deleting_subid != InvalidSubTransactionId);
6809 if (oids_to_truncate != NIL)
6811 heap_truncate(oids_to_truncate);
6812 CommandCounterIncrement(); /* XXX needed? */
6817 * Post-commit or post-abort cleanup for ON COMMIT management.
6819 * All we do here is remove no-longer-needed OnCommitItem entries.
6821 * During commit, remove entries that were deleted during this transaction;
6822 * during abort, remove those created during this transaction.
6825 AtEOXact_on_commit_actions(bool isCommit)
6828 ListCell *prev_item;
6831 cur_item = list_head(on_commits);
6833 while (cur_item != NULL)
6835 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
6837 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
6838 oc->creating_subid != InvalidSubTransactionId)
6840 /* cur_item must be removed */
6841 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
6844 cur_item = lnext(prev_item);
6846 cur_item = list_head(on_commits);
6850 /* cur_item must be preserved */
6851 oc->creating_subid = InvalidSubTransactionId;
6852 oc->deleting_subid = InvalidSubTransactionId;
6853 prev_item = cur_item;
6854 cur_item = lnext(prev_item);
6860 * Post-subcommit or post-subabort cleanup for ON COMMIT management.
6862 * During subabort, we can immediately remove entries created during this
6863 * subtransaction. During subcommit, just relabel entries marked during
6864 * this subtransaction as being the parent's responsibility.
6867 AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
6868 SubTransactionId parentSubid)
6871 ListCell *prev_item;
6874 cur_item = list_head(on_commits);
6876 while (cur_item != NULL)
6878 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
6880 if (!isCommit && oc->creating_subid == mySubid)
6882 /* cur_item must be removed */
6883 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
6886 cur_item = lnext(prev_item);
6888 cur_item = list_head(on_commits);
6892 /* cur_item must be preserved */
6893 if (oc->creating_subid == mySubid)
6894 oc->creating_subid = parentSubid;
6895 if (oc->deleting_subid == mySubid)
6896 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
6897 prev_item = cur_item;
6898 cur_item = lnext(prev_item);