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.234 2007/10/12 18:55:12 tgl Exp $
13 *-------------------------------------------------------------------------
17 #include "access/genam.h"
18 #include "access/heapam.h"
19 #include "access/reloptions.h"
20 #include "access/xact.h"
21 #include "catalog/catalog.h"
22 #include "catalog/dependency.h"
23 #include "catalog/heap.h"
24 #include "catalog/index.h"
25 #include "catalog/indexing.h"
26 #include "catalog/namespace.h"
27 #include "catalog/pg_constraint.h"
28 #include "catalog/pg_depend.h"
29 #include "catalog/pg_inherits.h"
30 #include "catalog/pg_namespace.h"
31 #include "catalog/pg_opclass.h"
32 #include "catalog/pg_tablespace.h"
33 #include "catalog/pg_trigger.h"
34 #include "catalog/pg_type.h"
35 #include "catalog/toasting.h"
36 #include "commands/cluster.h"
37 #include "commands/defrem.h"
38 #include "commands/tablecmds.h"
39 #include "commands/tablespace.h"
40 #include "commands/trigger.h"
41 #include "commands/typecmds.h"
42 #include "executor/executor.h"
43 #include "miscadmin.h"
44 #include "nodes/makefuncs.h"
45 #include "nodes/parsenodes.h"
46 #include "optimizer/clauses.h"
47 #include "optimizer/plancat.h"
48 #include "optimizer/prep.h"
49 #include "parser/gramparse.h"
50 #include "parser/parse_clause.h"
51 #include "parser/parse_coerce.h"
52 #include "parser/parse_expr.h"
53 #include "parser/parse_oper.h"
54 #include "parser/parse_relation.h"
55 #include "parser/parse_type.h"
56 #include "parser/parse_utilcmd.h"
57 #include "parser/parser.h"
58 #include "rewrite/rewriteDefine.h"
59 #include "rewrite/rewriteHandler.h"
60 #include "storage/smgr.h"
61 #include "utils/acl.h"
62 #include "utils/builtins.h"
63 #include "utils/fmgroids.h"
64 #include "utils/inval.h"
65 #include "utils/lsyscache.h"
66 #include "utils/memutils.h"
67 #include "utils/relcache.h"
68 #include "utils/syscache.h"
72 * ON COMMIT action list
74 typedef struct OnCommitItem
76 Oid relid; /* relid of relation */
77 OnCommitAction oncommit; /* what to do at end of xact */
80 * If this entry was created during the current transaction,
81 * creating_subid is the ID of the creating subxact; if created in a prior
82 * transaction, creating_subid is zero. If deleted during the current
83 * transaction, deleting_subid is the ID of the deleting subxact; if no
84 * deletion request is pending, deleting_subid is zero.
86 SubTransactionId creating_subid;
87 SubTransactionId deleting_subid;
90 static List *on_commits = NIL;
94 * State information for ALTER TABLE
96 * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
97 * structs, one for each table modified by the operation (the named table
98 * plus any child tables that are affected). We save lists of subcommands
99 * to apply to this table (possibly modified by parse transformation steps);
100 * these lists will be executed in Phase 2. If a Phase 3 step is needed,
101 * necessary information is stored in the constraints and newvals lists.
103 * Phase 2 is divided into multiple passes; subcommands are executed in
104 * a pass determined by subcommand type.
107 #define AT_PASS_DROP 0 /* DROP (all flavors) */
108 #define AT_PASS_ALTER_TYPE 1 /* ALTER COLUMN TYPE */
109 #define AT_PASS_OLD_INDEX 2 /* re-add existing indexes */
110 #define AT_PASS_OLD_CONSTR 3 /* re-add existing constraints */
111 #define AT_PASS_COL_ATTRS 4 /* set other column attributes */
112 /* We could support a RENAME COLUMN pass here, but not currently used */
113 #define AT_PASS_ADD_COL 5 /* ADD COLUMN */
114 #define AT_PASS_ADD_INDEX 6 /* ADD indexes */
115 #define AT_PASS_ADD_CONSTR 7 /* ADD constraints, defaults */
116 #define AT_PASS_MISC 8 /* other stuff */
117 #define AT_NUM_PASSES 9
119 typedef struct AlteredTableInfo
121 /* Information saved before any work commences: */
122 Oid relid; /* Relation to work on */
123 char relkind; /* Its relkind */
124 TupleDesc oldDesc; /* Pre-modification tuple descriptor */
125 /* Information saved by Phase 1 for Phase 2: */
126 List *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
127 /* Information saved by Phases 1/2 for Phase 3: */
128 List *constraints; /* List of NewConstraint */
129 List *newvals; /* List of NewColumnValue */
130 bool new_notnull; /* T if we added new NOT NULL constraints */
131 Oid newTableSpace; /* new tablespace; 0 means no change */
132 /* Objects to rebuild after completing ALTER TYPE operations */
133 List *changedConstraintOids; /* OIDs of constraints to rebuild */
134 List *changedConstraintDefs; /* string definitions of same */
135 List *changedIndexOids; /* OIDs of indexes to rebuild */
136 List *changedIndexDefs; /* string definitions of same */
139 /* Struct describing one new constraint to check in Phase 3 scan */
140 /* Note: new NOT NULL constraints are handled elsewhere */
141 typedef struct NewConstraint
143 char *name; /* Constraint name, or NULL if none */
144 ConstrType contype; /* CHECK or FOREIGN */
145 Oid refrelid; /* PK rel, if FOREIGN */
146 Oid conid; /* OID of pg_constraint entry, if FOREIGN */
147 Node *qual; /* Check expr or FkConstraint struct */
148 List *qualstate; /* Execution state for CHECK */
152 * Struct describing one new column value that needs to be computed during
153 * Phase 3 copy (this could be either a new column with a non-null default, or
154 * a column that we're changing the type of). Columns without such an entry
155 * are just copied from the old table during ATRewriteTable. Note that the
156 * expr is an expression over *old* table values.
158 typedef struct NewColumnValue
160 AttrNumber attnum; /* which column */
161 Expr *expr; /* expression to compute */
162 ExprState *exprstate; /* execution state */
166 static void truncate_check_rel(Relation rel);
167 static List *MergeAttributes(List *schema, List *supers, bool istemp,
168 List **supOids, List **supconstr, int *supOidCount);
169 static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
170 static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel);
171 static void add_nonduplicate_constraint(Constraint *cdef,
172 ConstrCheck *check, int *ncheck);
173 static bool change_varattnos_walker(Node *node, const AttrNumber *newattno);
174 static void StoreCatalogInheritance(Oid relationId, List *supers);
175 static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
176 int16 seqNumber, Relation inhRelation);
177 static int findAttrByName(const char *attributeName, List *schema);
178 static void setRelhassubclassInRelation(Oid relationId, bool relhassubclass);
179 static void AlterIndexNamespaces(Relation classRel, Relation rel,
180 Oid oldNspOid, Oid newNspOid);
181 static void AlterSeqNamespaces(Relation classRel, Relation rel,
182 Oid oldNspOid, Oid newNspOid,
183 const char *newNspName);
184 static int transformColumnNameList(Oid relId, List *colList,
185 int16 *attnums, Oid *atttypids);
186 static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
188 int16 *attnums, Oid *atttypids,
190 static Oid transformFkeyCheckAttrs(Relation pkrel,
191 int numattrs, int16 *attnums,
193 static void validateForeignKeyConstraint(FkConstraint *fkconstraint,
194 Relation rel, Relation pkrel, Oid constraintOid);
195 static void createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
197 static void ATController(Relation rel, List *cmds, bool recurse);
198 static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
199 bool recurse, bool recursing);
200 static void ATRewriteCatalogs(List **wqueue);
201 static void ATExecCmd(AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd);
202 static void ATRewriteTables(List **wqueue);
203 static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap);
204 static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
205 static void ATSimplePermissions(Relation rel, bool allowView);
206 static void ATSimplePermissionsRelationOrIndex(Relation rel);
207 static void ATSimpleRecursion(List **wqueue, Relation rel,
208 AlterTableCmd *cmd, bool recurse);
209 static void ATOneLevelRecursion(List **wqueue, Relation rel,
211 static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
213 static void ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
215 static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
216 static void ATExecDropNotNull(Relation rel, const char *colName);
217 static void ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
218 const char *colName);
219 static void ATExecColumnDefault(Relation rel, const char *colName,
221 static void ATPrepSetStatistics(Relation rel, const char *colName,
223 static void ATExecSetStatistics(Relation rel, const char *colName,
225 static void ATExecSetStorage(Relation rel, const char *colName,
227 static void ATExecDropColumn(Relation rel, const char *colName,
228 DropBehavior behavior,
229 bool recurse, bool recursing);
230 static void ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
231 IndexStmt *stmt, bool is_rebuild);
232 static void ATExecAddConstraint(AlteredTableInfo *tab, Relation rel,
233 Node *newConstraint);
234 static void ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
235 FkConstraint *fkconstraint);
236 static void ATPrepDropConstraint(List **wqueue, Relation rel,
237 bool recurse, AlterTableCmd *cmd);
238 static void ATExecDropConstraint(Relation rel, const char *constrName,
239 DropBehavior behavior, bool quiet);
240 static void ATPrepAlterColumnType(List **wqueue,
241 AlteredTableInfo *tab, Relation rel,
242 bool recurse, bool recursing,
244 static void ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
245 const char *colName, TypeName *typename);
246 static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab);
247 static void ATPostAlterTypeParse(char *cmd, List **wqueue);
248 static void change_owner_recurse_to_sequences(Oid relationOid,
250 static void ATExecClusterOn(Relation rel, const char *indexName);
251 static void ATExecDropCluster(Relation rel);
252 static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
253 char *tablespacename);
254 static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace);
255 static void ATExecSetRelOptions(Relation rel, List *defList, bool isReset);
256 static void ATExecEnableDisableTrigger(Relation rel, char *trigname,
257 char fires_when, bool skip_system);
258 static void ATExecEnableDisableRule(Relation rel, char *rulename,
260 static void ATExecAddInherit(Relation rel, RangeVar *parent);
261 static void ATExecDropInherit(Relation rel, RangeVar *parent);
262 static void copy_relation_data(Relation rel, SMgrRelation dst);
265 /* ----------------------------------------------------------------
267 * Creates a new relation.
269 * If successful, returns the OID of the new relation.
270 * ----------------------------------------------------------------
273 DefineRelation(CreateStmt *stmt, char relkind)
275 char relname[NAMEDATALEN];
277 List *schema = stmt->tableElts;
281 TupleDesc descriptor;
283 List *old_constraints;
292 * Truncate relname to appropriate length (probably a waste of time, as
293 * parser should have done this already).
295 StrNCpy(relname, stmt->relation->relname, NAMEDATALEN);
298 * Check consistency of arguments
300 if (stmt->oncommit != ONCOMMIT_NOOP && !stmt->relation->istemp)
302 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
303 errmsg("ON COMMIT can only be used on temporary tables")));
306 * Look up the namespace in which we are supposed to create the relation.
307 * Check we have permission to create there. Skip check if bootstrapping,
308 * since permissions machinery may not be working yet.
310 namespaceId = RangeVarGetCreationNamespace(stmt->relation);
312 if (!IsBootstrapProcessingMode())
316 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
318 if (aclresult != ACLCHECK_OK)
319 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
320 get_namespace_name(namespaceId));
324 * Select tablespace to use. If not specified, use default tablespace
325 * (which may in turn default to database's default).
327 if (stmt->tablespacename)
329 tablespaceId = get_tablespace_oid(stmt->tablespacename);
330 if (!OidIsValid(tablespaceId))
332 (errcode(ERRCODE_UNDEFINED_OBJECT),
333 errmsg("tablespace \"%s\" does not exist",
334 stmt->tablespacename)));
338 tablespaceId = GetDefaultTablespace(stmt->relation->istemp);
339 /* note InvalidOid is OK in this case */
342 /* Check permissions except when using database's default */
343 if (OidIsValid(tablespaceId))
347 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
349 if (aclresult != ACLCHECK_OK)
350 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
351 get_tablespace_name(tablespaceId));
355 * Parse and validate reloptions, if any.
357 reloptions = transformRelOptions((Datum) 0, stmt->options, true, false);
359 (void) heap_reloptions(relkind, reloptions, true);
362 * Look up inheritance ancestors and generate relation schema, including
363 * inherited attributes.
365 schema = MergeAttributes(schema, stmt->inhRelations,
366 stmt->relation->istemp,
367 &inheritOids, &old_constraints, &parentOidCount);
370 * Create a relation descriptor from the relation schema and create the
371 * relation. Note that in this stage only inherited (pre-cooked) defaults
372 * and constraints will be included into the new relation.
373 * (BuildDescForRelation takes care of the inherited defaults, but we have
374 * to copy inherited constraints here.)
376 descriptor = BuildDescForRelation(schema);
378 localHasOids = interpretOidsOption(stmt->options);
379 descriptor->tdhasoid = (localHasOids || parentOidCount > 0);
381 if (old_constraints || stmt->constraints)
386 /* make array that's certainly big enough */
387 check = (ConstrCheck *)
388 palloc((list_length(old_constraints) +
389 list_length(stmt->constraints)) * sizeof(ConstrCheck));
390 /* deal with constraints from MergeAttributes */
391 foreach(listptr, old_constraints)
393 Constraint *cdef = (Constraint *) lfirst(listptr);
395 if (cdef->contype == CONSTR_CHECK)
396 add_nonduplicate_constraint(cdef, check, &ncheck);
399 * parse_utilcmd.c might have passed some precooked constraints too,
400 * due to LIKE tab INCLUDING CONSTRAINTS
402 foreach(listptr, stmt->constraints)
404 Constraint *cdef = (Constraint *) lfirst(listptr);
406 if (cdef->contype == CONSTR_CHECK && cdef->cooked_expr != NULL)
407 add_nonduplicate_constraint(cdef, check, &ncheck);
409 /* if we found any, insert 'em into the descriptor */
412 if (descriptor->constr == NULL)
414 descriptor->constr = (TupleConstr *) palloc(sizeof(TupleConstr));
415 descriptor->constr->defval = NULL;
416 descriptor->constr->num_defval = 0;
417 descriptor->constr->has_not_null = false;
419 descriptor->constr->num_check = ncheck;
420 descriptor->constr->check = check;
424 relationId = heap_create_with_catalog(relname,
436 allowSystemTableMods);
438 StoreCatalogInheritance(relationId, inheritOids);
441 * We must bump the command counter to make the newly-created relation
442 * tuple visible for opening.
444 CommandCounterIncrement();
447 * Open the new relation and acquire exclusive lock on it. This isn't
448 * really necessary for locking out other backends (since they can't see
449 * the new rel anyway until we commit), but it keeps the lock manager from
450 * complaining about deadlock risks.
452 rel = relation_open(relationId, AccessExclusiveLock);
455 * Now add any newly specified column default values and CHECK constraints
456 * to the new relation. These are passed to us in the form of raw
457 * parsetrees; we need to transform them to executable expression trees
458 * before they can be added. The most convenient way to do that is to
459 * apply the parser's transformExpr routine, but transformExpr doesn't
460 * work unless we have a pre-existing relation. So, the transformation has
461 * to be postponed to this final step of CREATE TABLE.
463 * First, scan schema to find new column defaults.
468 foreach(listptr, schema)
470 ColumnDef *colDef = lfirst(listptr);
474 if (colDef->raw_default != NULL)
476 RawColumnDefault *rawEnt;
478 Assert(colDef->cooked_default == NULL);
480 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
481 rawEnt->attnum = attnum;
482 rawEnt->raw_default = colDef->raw_default;
483 rawDefaults = lappend(rawDefaults, rawEnt);
488 * Parse and add the defaults/constraints, if any.
490 if (rawDefaults || stmt->constraints)
491 AddRelationRawConstraints(rel, rawDefaults, stmt->constraints);
494 * Clean up. We keep lock on new relation (although it shouldn't be
495 * visible to anyone else anyway, until commit).
497 relation_close(rel, NoLock);
504 * Deletes a relation.
507 RemoveRelation(const RangeVar *relation, DropBehavior behavior)
510 ObjectAddress object;
512 relOid = RangeVarGetRelid(relation, false);
514 object.classId = RelationRelationId;
515 object.objectId = relOid;
516 object.objectSubId = 0;
518 performDeletion(&object, behavior);
523 * Executes a TRUNCATE command.
525 * This is a multi-relation truncate. We first open and grab exclusive
526 * lock on all relations involved, checking permissions and otherwise
527 * verifying that the relation is OK for truncation. In CASCADE mode,
528 * relations having FK references to the targeted relations are automatically
529 * added to the group; in RESTRICT mode, we check that all FK references are
530 * internal to the group that's being truncated. Finally all the relations
531 * are truncated and reindexed.
534 ExecuteTruncate(TruncateStmt *stmt)
541 * Open, exclusive-lock, and check all the explicitly-specified relations
543 foreach(cell, stmt->relations)
545 RangeVar *rv = lfirst(cell);
548 rel = heap_openrv(rv, AccessExclusiveLock);
549 truncate_check_rel(rel);
550 rels = lappend(rels, rel);
551 relids = lappend_oid(relids, RelationGetRelid(rel));
555 * In CASCADE mode, suck in all referencing relations as well. This
556 * requires multiple iterations to find indirectly-dependent relations. At
557 * each phase, we need to exclusive-lock new rels before looking for their
558 * dependencies, else we might miss something. Also, we check each rel as
559 * soon as we open it, to avoid a faux pas such as holding lock for a long
560 * time on a rel we have no permissions for.
562 if (stmt->behavior == DROP_CASCADE)
568 newrelids = heap_truncate_find_FKs(relids);
569 if (newrelids == NIL)
570 break; /* nothing else to add */
572 foreach(cell, newrelids)
574 Oid relid = lfirst_oid(cell);
577 rel = heap_open(relid, AccessExclusiveLock);
579 (errmsg("truncate cascades to table \"%s\"",
580 RelationGetRelationName(rel))));
581 truncate_check_rel(rel);
582 rels = lappend(rels, rel);
583 relids = lappend_oid(relids, relid);
589 * Check foreign key references. In CASCADE mode, this should be
590 * unnecessary since we just pulled in all the references; but as a
591 * cross-check, do it anyway if in an Assert-enabled build.
593 #ifdef USE_ASSERT_CHECKING
594 heap_truncate_check_FKs(rels, false);
596 if (stmt->behavior == DROP_RESTRICT)
597 heap_truncate_check_FKs(rels, false);
601 * Also check for pending AFTER trigger events on the target relations. We
602 * can't just leave those be, since they will try to fetch tuples that the
605 AfterTriggerCheckTruncate(relids);
608 * OK, truncate each table.
612 Relation rel = (Relation) lfirst(cell);
617 * Create a new empty storage file for the relation, and assign it as
618 * the relfilenode value. The old storage file is scheduled for
619 * deletion at commit.
621 setNewRelfilenode(rel, RecentXmin);
623 heap_relid = RelationGetRelid(rel);
624 toast_relid = rel->rd_rel->reltoastrelid;
626 heap_close(rel, NoLock);
629 * The same for the toast table, if any.
631 if (OidIsValid(toast_relid))
633 rel = relation_open(toast_relid, AccessExclusiveLock);
634 setNewRelfilenode(rel, RecentXmin);
635 heap_close(rel, NoLock);
639 * Reconstruct the indexes to match, and we're done.
641 reindex_relation(heap_relid, true);
646 * Check that a given rel is safe to truncate. Subroutine for ExecuteTruncate
649 truncate_check_rel(Relation rel)
651 /* Only allow truncate on regular tables */
652 if (rel->rd_rel->relkind != RELKIND_RELATION)
654 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
655 errmsg("\"%s\" is not a table",
656 RelationGetRelationName(rel))));
658 /* Permissions checks */
659 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
660 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
661 RelationGetRelationName(rel));
663 if (!allowSystemTableMods && IsSystemRelation(rel))
665 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
666 errmsg("permission denied: \"%s\" is a system catalog",
667 RelationGetRelationName(rel))));
670 * We can never allow truncation of shared or nailed-in-cache relations,
671 * because we can't support changing their relfilenode values.
673 if (rel->rd_rel->relisshared || rel->rd_isnailed)
675 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
676 errmsg("cannot truncate system relation \"%s\"",
677 RelationGetRelationName(rel))));
680 * Don't allow truncate on temp tables of other backends ... their local
681 * buffer manager is not going to cope.
683 if (isOtherTempNamespace(RelationGetNamespace(rel)))
685 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
686 errmsg("cannot truncate temporary tables of other sessions")));
691 * Returns new schema given initial schema and superclasses.
694 * 'schema' is the column/attribute definition for the table. (It's a list
695 * of ColumnDef's.) It is destructively changed.
696 * 'supers' is a list of names (as RangeVar nodes) of parent relations.
697 * 'istemp' is TRUE if we are creating a temp relation.
700 * 'supOids' receives a list of the OIDs of the parent relations.
701 * 'supconstr' receives a list of constraints belonging to the parents,
702 * updated as necessary to be valid for the child.
703 * 'supOidCount' is set to the number of parents that have OID columns.
706 * Completed schema list.
709 * The order in which the attributes are inherited is very important.
710 * Intuitively, the inherited attributes should come first. If a table
711 * inherits from multiple parents, the order of those attributes are
712 * according to the order of the parents specified in CREATE TABLE.
716 * create table person (name text, age int4, location point);
717 * create table emp (salary int4, manager text) inherits(person);
718 * create table student (gpa float8) inherits (person);
719 * create table stud_emp (percent int4) inherits (emp, student);
721 * The order of the attributes of stud_emp is:
723 * person {1:name, 2:age, 3:location}
725 * {6:gpa} student emp {4:salary, 5:manager}
727 * stud_emp {7:percent}
729 * If the same attribute name appears multiple times, then it appears
730 * in the result table in the proper location for its first appearance.
732 * Constraints (including NOT NULL constraints) for the child table
733 * are the union of all relevant constraints, from both the child schema
736 * The default value for a child column is defined as:
737 * (1) If the child schema specifies a default, that value is used.
738 * (2) If neither the child nor any parent specifies a default, then
739 * the column will not have a default.
740 * (3) If conflicting defaults are inherited from different parents
741 * (and not overridden by the child), an error is raised.
742 * (4) Otherwise the inherited default is used.
743 * Rule (3) is new in Postgres 7.1; in earlier releases you got a
744 * rather arbitrary choice of which parent default to use.
748 MergeAttributes(List *schema, List *supers, bool istemp,
749 List **supOids, List **supconstr, int *supOidCount)
752 List *inhSchema = NIL;
753 List *parentOids = NIL;
754 List *constraints = NIL;
755 int parentsWithOids = 0;
756 bool have_bogus_defaults = false;
757 char *bogus_marker = "Bogus!"; /* marks conflicting defaults */
761 * Check for and reject tables with too many columns. We perform this
762 * check relatively early for two reasons: (a) we don't run the risk of
763 * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
764 * okay if we're processing <= 1600 columns, but could take minutes to
765 * execute if the user attempts to create a table with hundreds of
766 * thousands of columns.
768 * Note that we also need to check that any we do not exceed this figure
769 * after including columns from inherited relations.
771 if (list_length(schema) > MaxHeapAttributeNumber)
773 (errcode(ERRCODE_TOO_MANY_COLUMNS),
774 errmsg("tables can have at most %d columns",
775 MaxHeapAttributeNumber)));
778 * Check for duplicate names in the explicit list of attributes.
780 * Although we might consider merging such entries in the same way that we
781 * handle name conflicts for inherited attributes, it seems to make more
782 * sense to assume such conflicts are errors.
784 foreach(entry, schema)
786 ColumnDef *coldef = lfirst(entry);
789 for_each_cell(rest, lnext(entry))
791 ColumnDef *restdef = lfirst(rest);
793 if (strcmp(coldef->colname, restdef->colname) == 0)
795 (errcode(ERRCODE_DUPLICATE_COLUMN),
796 errmsg("column \"%s\" specified more than once",
802 * Scan the parents left-to-right, and merge their attributes to form a
803 * list of inherited attributes (inhSchema). Also check to see if we need
804 * to inherit an OID column.
807 foreach(entry, supers)
809 RangeVar *parent = (RangeVar *) lfirst(entry);
813 AttrNumber *newattno;
814 AttrNumber parent_attno;
816 relation = heap_openrv(parent, AccessShareLock);
818 if (relation->rd_rel->relkind != RELKIND_RELATION)
820 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
821 errmsg("inherited relation \"%s\" is not a table",
823 /* Permanent rels cannot inherit from temporary ones */
824 if (!istemp && isTempNamespace(RelationGetNamespace(relation)))
826 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
827 errmsg("cannot inherit from temporary relation \"%s\"",
831 * We should have an UNDER permission flag for this, but for now,
832 * demand that creator of a child table own the parent.
834 if (!pg_class_ownercheck(RelationGetRelid(relation), GetUserId()))
835 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
836 RelationGetRelationName(relation));
839 * Reject duplications in the list of parents.
841 if (list_member_oid(parentOids, RelationGetRelid(relation)))
843 (errcode(ERRCODE_DUPLICATE_TABLE),
844 errmsg("relation \"%s\" would be inherited from more than once",
847 parentOids = lappend_oid(parentOids, RelationGetRelid(relation));
849 if (relation->rd_rel->relhasoids)
852 tupleDesc = RelationGetDescr(relation);
853 constr = tupleDesc->constr;
856 * newattno[] will contain the child-table attribute numbers for the
857 * attributes of this parent table. (They are not the same for
858 * parents after the first one, nor if we have dropped columns.)
860 newattno = (AttrNumber *)
861 palloc(tupleDesc->natts * sizeof(AttrNumber));
863 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
866 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
867 char *attributeName = NameStr(attribute->attname);
872 * Ignore dropped columns in the parent.
874 if (attribute->attisdropped)
877 * change_varattnos_of_a_node asserts that this is greater
878 * than zero, so if anything tries to use it, we should find
881 newattno[parent_attno - 1] = 0;
886 * Does it conflict with some previously inherited column?
888 exist_attno = findAttrByName(attributeName, inhSchema);
895 * Yes, try to merge the two column definitions. They must
896 * have the same type and typmod.
899 (errmsg("merging multiple inherited definitions of column \"%s\"",
901 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
902 defTypeId = typenameTypeId(NULL, def->typename);
903 deftypmod = typenameTypeMod(NULL, def->typename, defTypeId);
904 if (defTypeId != attribute->atttypid ||
905 deftypmod != attribute->atttypmod)
907 (errcode(ERRCODE_DATATYPE_MISMATCH),
908 errmsg("inherited column \"%s\" has a type conflict",
910 errdetail("%s versus %s",
911 TypeNameToString(def->typename),
912 format_type_be(attribute->atttypid))));
914 /* Merge of NOT NULL constraints = OR 'em together */
915 def->is_not_null |= attribute->attnotnull;
916 /* Default and other constraints are handled below */
917 newattno[parent_attno - 1] = exist_attno;
922 * No, create a new inherited column
924 def = makeNode(ColumnDef);
925 def->colname = pstrdup(attributeName);
926 def->typename = makeTypeNameFromOid(attribute->atttypid,
927 attribute->atttypmod);
929 def->is_local = false;
930 def->is_not_null = attribute->attnotnull;
931 def->raw_default = NULL;
932 def->cooked_default = NULL;
933 def->constraints = NIL;
934 inhSchema = lappend(inhSchema, def);
935 newattno[parent_attno - 1] = ++child_attno;
939 * Copy default if any
941 if (attribute->atthasdef)
943 char *this_default = NULL;
944 AttrDefault *attrdef;
947 /* Find default in constraint structure */
948 Assert(constr != NULL);
949 attrdef = constr->defval;
950 for (i = 0; i < constr->num_defval; i++)
952 if (attrdef[i].adnum == parent_attno)
954 this_default = attrdef[i].adbin;
958 Assert(this_default != NULL);
961 * If default expr could contain any vars, we'd need to fix
962 * 'em, but it can't; so default is ready to apply to child.
964 * If we already had a default from some prior parent, check
965 * to see if they are the same. If so, no problem; if not,
966 * mark the column as having a bogus default. Below, we will
967 * complain if the bogus default isn't overridden by the child
970 Assert(def->raw_default == NULL);
971 if (def->cooked_default == NULL)
972 def->cooked_default = pstrdup(this_default);
973 else if (strcmp(def->cooked_default, this_default) != 0)
975 def->cooked_default = bogus_marker;
976 have_bogus_defaults = true;
982 * Now copy the constraints of this parent, adjusting attnos using the
983 * completed newattno[] map
985 if (constr && constr->num_check > 0)
987 ConstrCheck *check = constr->check;
990 for (i = 0; i < constr->num_check; i++)
992 Constraint *cdef = makeNode(Constraint);
995 cdef->contype = CONSTR_CHECK;
996 cdef->name = pstrdup(check[i].ccname);
997 cdef->raw_expr = NULL;
998 /* adjust varattnos of ccbin here */
999 expr = stringToNode(check[i].ccbin);
1000 change_varattnos_of_a_node(expr, newattno);
1001 cdef->cooked_expr = nodeToString(expr);
1002 constraints = lappend(constraints, cdef);
1009 * Close the parent rel, but keep our AccessShareLock on it until xact
1010 * commit. That will prevent someone else from deleting or ALTERing
1011 * the parent before the child is committed.
1013 heap_close(relation, NoLock);
1017 * If we had no inherited attributes, the result schema is just the
1018 * explicitly declared columns. Otherwise, we need to merge the declared
1019 * columns into the inherited schema list.
1021 if (inhSchema != NIL)
1023 foreach(entry, schema)
1025 ColumnDef *newdef = lfirst(entry);
1026 char *attributeName = newdef->colname;
1030 * Does it conflict with some previously inherited column?
1032 exist_attno = findAttrByName(attributeName, inhSchema);
1033 if (exist_attno > 0)
1036 Oid defTypeId, newTypeId;
1037 int32 deftypmod, newtypmod;
1040 * Yes, try to merge the two column definitions. They must
1041 * have the same type and typmod.
1044 (errmsg("merging column \"%s\" with inherited definition",
1046 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1047 defTypeId = typenameTypeId(NULL, def->typename);
1048 deftypmod = typenameTypeMod(NULL, def->typename, defTypeId);
1049 newTypeId = typenameTypeId(NULL, newdef->typename);
1050 newtypmod = typenameTypeMod(NULL, newdef->typename, newTypeId);
1051 if (defTypeId != newTypeId || deftypmod != newtypmod)
1053 (errcode(ERRCODE_DATATYPE_MISMATCH),
1054 errmsg("column \"%s\" has a type conflict",
1056 errdetail("%s versus %s",
1057 TypeNameToString(def->typename),
1058 TypeNameToString(newdef->typename))));
1059 /* Mark the column as locally defined */
1060 def->is_local = true;
1061 /* Merge of NOT NULL constraints = OR 'em together */
1062 def->is_not_null |= newdef->is_not_null;
1063 /* If new def has a default, override previous default */
1064 if (newdef->raw_default != NULL)
1066 def->raw_default = newdef->raw_default;
1067 def->cooked_default = newdef->cooked_default;
1073 * No, attach new column to result schema
1075 inhSchema = lappend(inhSchema, newdef);
1082 * Check that we haven't exceeded the legal # of columns after merging
1083 * in inherited columns.
1085 if (list_length(schema) > MaxHeapAttributeNumber)
1087 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1088 errmsg("tables can have at most %d columns",
1089 MaxHeapAttributeNumber)));
1093 * If we found any conflicting parent default values, check to make sure
1094 * they were overridden by the child.
1096 if (have_bogus_defaults)
1098 foreach(entry, schema)
1100 ColumnDef *def = lfirst(entry);
1102 if (def->cooked_default == bogus_marker)
1104 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
1105 errmsg("column \"%s\" inherits conflicting default values",
1107 errhint("To resolve the conflict, specify a default explicitly.")));
1111 *supOids = parentOids;
1112 *supconstr = constraints;
1113 *supOidCount = parentsWithOids;
1119 * In multiple-inheritance situations, it's possible to inherit
1120 * the same grandparent constraint through multiple parents.
1121 * Hence, we want to discard inherited constraints that match as to
1122 * both name and expression. Otherwise, gripe if there are conflicting
1123 * names. Nonconflicting constraints are added to the array check[]
1124 * of length *ncheck ... caller must ensure there is room!
1127 add_nonduplicate_constraint(Constraint *cdef, ConstrCheck *check, int *ncheck)
1131 /* Should only see precooked constraints here */
1132 Assert(cdef->contype == CONSTR_CHECK);
1133 Assert(cdef->name != NULL);
1134 Assert(cdef->raw_expr == NULL && cdef->cooked_expr != NULL);
1136 for (i = 0; i < *ncheck; i++)
1138 if (strcmp(check[i].ccname, cdef->name) != 0)
1140 if (strcmp(check[i].ccbin, cdef->cooked_expr) == 0)
1141 return; /* duplicate constraint, so ignore it */
1143 (errcode(ERRCODE_DUPLICATE_OBJECT),
1144 errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
1147 /* No match on name, so add it to array */
1148 check[*ncheck].ccname = cdef->name;
1149 check[*ncheck].ccbin = pstrdup(cdef->cooked_expr);
1155 * Replace varattno values in an expression tree according to the given
1156 * map array, that is, varattno N is replaced by newattno[N-1]. It is
1157 * caller's responsibility to ensure that the array is long enough to
1158 * define values for all user varattnos present in the tree. System column
1159 * attnos remain unchanged.
1161 * Note that the passed node tree is modified in-place!
1164 change_varattnos_of_a_node(Node *node, const AttrNumber *newattno)
1166 /* no setup needed, so away we go */
1167 (void) change_varattnos_walker(node, newattno);
1171 change_varattnos_walker(Node *node, const AttrNumber *newattno)
1177 Var *var = (Var *) node;
1179 if (var->varlevelsup == 0 && var->varno == 1 &&
1183 * ??? the following may be a problem when the node is multiply
1184 * referenced though stringToNode() doesn't create such a node
1187 Assert(newattno[var->varattno - 1] > 0);
1188 var->varattno = newattno[var->varattno - 1];
1192 return expression_tree_walker(node, change_varattnos_walker,
1197 * Generate a map for change_varattnos_of_a_node from old and new TupleDesc's,
1198 * matching according to column name.
1201 varattnos_map(TupleDesc old, TupleDesc new)
1207 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * old->natts);
1208 for (i = 1; i <= old->natts; i++)
1210 if (old->attrs[i - 1]->attisdropped)
1211 continue; /* leave the entry as zero */
1213 for (j = 1; j <= new->natts; j++)
1215 if (strcmp(NameStr(old->attrs[i - 1]->attname),
1216 NameStr(new->attrs[j - 1]->attname)) == 0)
1227 * Generate a map for change_varattnos_of_a_node from a TupleDesc and a list
1231 varattnos_map_schema(TupleDesc old, List *schema)
1236 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * old->natts);
1237 for (i = 1; i <= old->natts; i++)
1239 if (old->attrs[i - 1]->attisdropped)
1240 continue; /* leave the entry as zero */
1242 attmap[i - 1] = findAttrByName(NameStr(old->attrs[i - 1]->attname),
1250 * StoreCatalogInheritance
1251 * Updates the system catalogs with proper inheritance information.
1253 * supers is a list of the OIDs of the new relation's direct ancestors.
1256 StoreCatalogInheritance(Oid relationId, List *supers)
1265 AssertArg(OidIsValid(relationId));
1271 * Store INHERITS information in pg_inherits using direct ancestors only.
1272 * Also enter dependencies on the direct ancestors, and make sure they are
1273 * marked with relhassubclass = true.
1275 * (Once upon a time, both direct and indirect ancestors were found here
1276 * and then entered into pg_ipl. Since that catalog doesn't exist
1277 * anymore, there's no need to look for indirect ancestors.)
1279 relation = heap_open(InheritsRelationId, RowExclusiveLock);
1282 foreach(entry, supers)
1284 Oid parentOid = lfirst_oid(entry);
1286 StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation);
1290 heap_close(relation, RowExclusiveLock);
1294 * Make catalog entries showing relationId as being an inheritance child
1295 * of parentOid. inhRelation is the already-opened pg_inherits catalog.
1298 StoreCatalogInheritance1(Oid relationId, Oid parentOid,
1299 int16 seqNumber, Relation inhRelation)
1301 TupleDesc desc = RelationGetDescr(inhRelation);
1302 Datum datum[Natts_pg_inherits];
1303 char nullarr[Natts_pg_inherits];
1304 ObjectAddress childobject,
1309 * Make the pg_inherits entry
1311 datum[0] = ObjectIdGetDatum(relationId); /* inhrelid */
1312 datum[1] = ObjectIdGetDatum(parentOid); /* inhparent */
1313 datum[2] = Int16GetDatum(seqNumber); /* inhseqno */
1319 tuple = heap_formtuple(desc, datum, nullarr);
1321 simple_heap_insert(inhRelation, tuple);
1323 CatalogUpdateIndexes(inhRelation, tuple);
1325 heap_freetuple(tuple);
1328 * Store a dependency too
1330 parentobject.classId = RelationRelationId;
1331 parentobject.objectId = parentOid;
1332 parentobject.objectSubId = 0;
1333 childobject.classId = RelationRelationId;
1334 childobject.objectId = relationId;
1335 childobject.objectSubId = 0;
1337 recordDependencyOn(&childobject, &parentobject, DEPENDENCY_NORMAL);
1340 * Mark the parent as having subclasses.
1342 setRelhassubclassInRelation(parentOid, true);
1346 * Look for an existing schema entry with the given name.
1348 * Returns the index (starting with 1) if attribute already exists in schema,
1352 findAttrByName(const char *attributeName, List *schema)
1359 ColumnDef *def = lfirst(s);
1361 if (strcmp(attributeName, def->colname) == 0)
1370 * Update a relation's pg_class.relhassubclass entry to the given value
1373 setRelhassubclassInRelation(Oid relationId, bool relhassubclass)
1375 Relation relationRelation;
1377 Form_pg_class classtuple;
1380 * Fetch a modifiable copy of the tuple, modify it, update pg_class.
1382 * If the tuple already has the right relhassubclass setting, we don't
1383 * need to update it, but we still need to issue an SI inval message.
1385 relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
1386 tuple = SearchSysCacheCopy(RELOID,
1387 ObjectIdGetDatum(relationId),
1389 if (!HeapTupleIsValid(tuple))
1390 elog(ERROR, "cache lookup failed for relation %u", relationId);
1391 classtuple = (Form_pg_class) GETSTRUCT(tuple);
1393 if (classtuple->relhassubclass != relhassubclass)
1395 classtuple->relhassubclass = relhassubclass;
1396 simple_heap_update(relationRelation, &tuple->t_self, tuple);
1398 /* keep the catalog indexes up to date */
1399 CatalogUpdateIndexes(relationRelation, tuple);
1403 /* no need to change tuple, but force relcache rebuild anyway */
1404 CacheInvalidateRelcacheByTuple(tuple);
1407 heap_freetuple(tuple);
1408 heap_close(relationRelation, RowExclusiveLock);
1413 * renameatt - changes the name of a attribute in a relation
1415 * Attname attribute is changed in attribute catalog.
1416 * No record of the previous attname is kept (correct?).
1418 * get proper relrelation from relation catalog (if not arg)
1419 * scan attribute catalog
1420 * for name conflict (within rel)
1421 * for original attribute (if not arg)
1422 * modify attname in attribute tuple
1423 * insert modified attribute in attribute catalog
1424 * delete original attribute from attribute catalog
1427 renameatt(Oid myrelid,
1428 const char *oldattname,
1429 const char *newattname,
1433 Relation targetrelation;
1434 Relation attrelation;
1436 Form_pg_attribute attform;
1439 ListCell *indexoidscan;
1442 * Grab an exclusive lock on the target table, which we will NOT release
1443 * until end of transaction.
1445 targetrelation = relation_open(myrelid, AccessExclusiveLock);
1448 * permissions checking. this would normally be done in utility.c, but
1449 * this particular routine is recursive.
1451 * normally, only the owner of a class can change its schema.
1453 if (!pg_class_ownercheck(myrelid, GetUserId()))
1454 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1455 RelationGetRelationName(targetrelation));
1456 if (!allowSystemTableMods && IsSystemRelation(targetrelation))
1458 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1459 errmsg("permission denied: \"%s\" is a system catalog",
1460 RelationGetRelationName(targetrelation))));
1463 * if the 'recurse' flag is set then we are supposed to rename this
1464 * attribute in all classes that inherit from 'relname' (as well as in
1467 * any permissions or problems with duplicate attributes will cause the
1468 * whole transaction to abort, which is what we want -- all or nothing.
1475 /* this routine is actually in the planner */
1476 children = find_all_inheritors(myrelid);
1479 * find_all_inheritors does the recursive search of the inheritance
1480 * hierarchy, so all we have to do is process all of the relids in the
1481 * list that it returns.
1483 foreach(child, children)
1485 Oid childrelid = lfirst_oid(child);
1487 if (childrelid == myrelid)
1489 /* note we need not recurse again */
1490 renameatt(childrelid, oldattname, newattname, false, true);
1496 * If we are told not to recurse, there had better not be any child
1497 * tables; else the rename would put them out of step.
1500 find_inheritance_children(myrelid) != NIL)
1502 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1503 errmsg("inherited column \"%s\" must be renamed in child tables too",
1507 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
1509 atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
1510 if (!HeapTupleIsValid(atttup))
1512 (errcode(ERRCODE_UNDEFINED_COLUMN),
1513 errmsg("column \"%s\" does not exist",
1515 attform = (Form_pg_attribute) GETSTRUCT(atttup);
1517 attnum = attform->attnum;
1520 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1521 errmsg("cannot rename system column \"%s\"",
1525 * if the attribute is inherited, forbid the renaming, unless we are
1526 * already inside a recursive rename.
1528 if (attform->attinhcount > 0 && !recursing)
1530 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1531 errmsg("cannot rename inherited column \"%s\"",
1534 /* should not already exist */
1535 /* this test is deliberately not attisdropped-aware */
1536 if (SearchSysCacheExists(ATTNAME,
1537 ObjectIdGetDatum(myrelid),
1538 PointerGetDatum(newattname),
1541 (errcode(ERRCODE_DUPLICATE_COLUMN),
1542 errmsg("column \"%s\" of relation \"%s\" already exists",
1543 newattname, RelationGetRelationName(targetrelation))));
1545 namestrcpy(&(attform->attname), newattname);
1547 simple_heap_update(attrelation, &atttup->t_self, atttup);
1549 /* keep system catalog indexes current */
1550 CatalogUpdateIndexes(attrelation, atttup);
1552 heap_freetuple(atttup);
1555 * Update column names of indexes that refer to the column being renamed.
1557 indexoidlist = RelationGetIndexList(targetrelation);
1559 foreach(indexoidscan, indexoidlist)
1561 Oid indexoid = lfirst_oid(indexoidscan);
1563 Form_pg_index indexform;
1567 * Scan through index columns to see if there's any simple index
1568 * entries for this attribute. We ignore expressional entries.
1570 indextup = SearchSysCache(INDEXRELID,
1571 ObjectIdGetDatum(indexoid),
1573 if (!HeapTupleIsValid(indextup))
1574 elog(ERROR, "cache lookup failed for index %u", indexoid);
1575 indexform = (Form_pg_index) GETSTRUCT(indextup);
1577 for (i = 0; i < indexform->indnatts; i++)
1579 if (attnum != indexform->indkey.values[i])
1583 * Found one, rename it.
1585 atttup = SearchSysCacheCopy(ATTNUM,
1586 ObjectIdGetDatum(indexoid),
1587 Int16GetDatum(i + 1),
1589 if (!HeapTupleIsValid(atttup))
1590 continue; /* should we raise an error? */
1593 * Update the (copied) attribute tuple.
1595 namestrcpy(&(((Form_pg_attribute) GETSTRUCT(atttup))->attname),
1598 simple_heap_update(attrelation, &atttup->t_self, atttup);
1600 /* keep system catalog indexes current */
1601 CatalogUpdateIndexes(attrelation, atttup);
1603 heap_freetuple(atttup);
1606 ReleaseSysCache(indextup);
1609 list_free(indexoidlist);
1611 heap_close(attrelation, RowExclusiveLock);
1613 relation_close(targetrelation, NoLock); /* close rel but keep lock */
1617 * renamerel - change the name of a relation
1619 * XXX - When renaming sequences, we don't bother to modify the
1620 * sequence name that is stored within the sequence itself
1621 * (this would cause problems with MVCC). In the future,
1622 * the sequence name should probably be removed from the
1623 * sequence, AFAIK there's no need for it to be there.
1626 renamerel(Oid myrelid, const char *newrelname, ObjectType reltype)
1628 Relation targetrelation;
1629 Relation relrelation; /* for RELATION relation */
1631 Form_pg_class relform;
1635 bool relhastriggers;
1638 * Grab an exclusive lock on the target table, index, sequence or
1639 * view, which we will NOT release until end of transaction.
1641 targetrelation = relation_open(myrelid, AccessExclusiveLock);
1643 oldrelname = pstrdup(RelationGetRelationName(targetrelation));
1644 namespaceId = RelationGetNamespace(targetrelation);
1646 if (!allowSystemTableMods && IsSystemRelation(targetrelation))
1648 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1649 errmsg("permission denied: \"%s\" is a system catalog",
1650 RelationGetRelationName(targetrelation))));
1653 * For compatibility with prior releases, we don't complain if
1654 * ALTER TABLE or ALTER INDEX is used to rename a sequence or
1657 relkind = targetrelation->rd_rel->relkind;
1658 if (reltype == OBJECT_SEQUENCE && relkind != 'S')
1660 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1661 errmsg("\"%s\" is not a sequence",
1662 RelationGetRelationName(targetrelation))));
1664 if (reltype == OBJECT_VIEW && relkind != 'v')
1666 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1667 errmsg("\"%s\" is not a view",
1668 RelationGetRelationName(targetrelation))));
1670 relhastriggers = (targetrelation->rd_rel->reltriggers > 0);
1673 * Find relation's pg_class tuple, and make sure newrelname isn't in use.
1675 relrelation = heap_open(RelationRelationId, RowExclusiveLock);
1677 reltup = SearchSysCacheCopy(RELOID,
1678 ObjectIdGetDatum(myrelid),
1680 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
1681 elog(ERROR, "cache lookup failed for relation %u", myrelid);
1682 relform = (Form_pg_class) GETSTRUCT(reltup);
1684 if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
1686 (errcode(ERRCODE_DUPLICATE_TABLE),
1687 errmsg("relation \"%s\" already exists",
1691 * Update pg_class tuple with new relname. (Scribbling on reltup is OK
1692 * because it's a copy...)
1694 namestrcpy(&(relform->relname), newrelname);
1696 simple_heap_update(relrelation, &reltup->t_self, reltup);
1698 /* keep the system catalog indexes current */
1699 CatalogUpdateIndexes(relrelation, reltup);
1701 heap_freetuple(reltup);
1702 heap_close(relrelation, RowExclusiveLock);
1705 * Also rename the associated type, if any.
1707 if (OidIsValid(targetrelation->rd_rel->reltype))
1708 TypeRename(targetrelation->rd_rel->reltype, newrelname, namespaceId);
1711 * Close rel, but keep exclusive lock!
1713 relation_close(targetrelation, NoLock);
1718 * Execute ALTER TABLE, which can be a list of subcommands
1720 * ALTER TABLE is performed in three phases:
1721 * 1. Examine subcommands and perform pre-transformation checking.
1722 * 2. Update system catalogs.
1723 * 3. Scan table(s) to check new constraints, and optionally recopy
1724 * the data into new table(s).
1725 * Phase 3 is not performed unless one or more of the subcommands requires
1726 * it. The intention of this design is to allow multiple independent
1727 * updates of the table schema to be performed with only one pass over the
1730 * ATPrepCmd performs phase 1. A "work queue" entry is created for
1731 * each table to be affected (there may be multiple affected tables if the
1732 * commands traverse a table inheritance hierarchy). Also we do preliminary
1733 * validation of the subcommands, including parse transformation of those
1734 * expressions that need to be evaluated with respect to the old table
1737 * ATRewriteCatalogs performs phase 2 for each affected table (note that
1738 * phases 2 and 3 do no explicit recursion, since phase 1 already did it).
1739 * Certain subcommands need to be performed before others to avoid
1740 * unnecessary conflicts; for example, DROP COLUMN should come before
1741 * ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
1742 * lists, one for each logical "pass" of phase 2.
1744 * ATRewriteTables performs phase 3 for those tables that need it.
1746 * Thanks to the magic of MVCC, an error anywhere along the way rolls back
1747 * the whole operation; we don't have to do anything special to clean up.
1750 AlterTable(AlterTableStmt *stmt)
1752 Relation rel = relation_openrv(stmt->relation, AccessExclusiveLock);
1753 int expected_refcnt;
1756 * Disallow ALTER TABLE when the current backend has any open reference
1757 * to it besides the one we just got (such as an open cursor or active
1758 * plan); our AccessExclusiveLock doesn't protect us against stomping on
1759 * our own foot, only other people's feet!
1761 * Note: the only case known to cause serious trouble is ALTER COLUMN TYPE,
1762 * and some changes are obviously pretty benign, so this could possibly
1763 * be relaxed to only error out for certain types of alterations. But
1764 * the use-case for allowing any of these things is not obvious, so we
1765 * won't work hard at it for now.
1767 expected_refcnt = rel->rd_isnailed ? 2 : 1;
1768 if (rel->rd_refcnt != expected_refcnt)
1770 (errcode(ERRCODE_OBJECT_IN_USE),
1771 errmsg("relation \"%s\" is being used by active queries in this session",
1772 RelationGetRelationName(rel))));
1774 ATController(rel, stmt->cmds, interpretInhOption(stmt->relation->inhOpt));
1778 * AlterTableInternal
1780 * ALTER TABLE with target specified by OID
1782 * We do not reject if the relation is already open, because it's quite
1783 * likely that one or more layers of caller have it open. That means it
1784 * is unsafe to use this entry point for alterations that could break
1785 * existing query plans.
1788 AlterTableInternal(Oid relid, List *cmds, bool recurse)
1790 Relation rel = relation_open(relid, AccessExclusiveLock);
1792 ATController(rel, cmds, recurse);
1796 ATController(Relation rel, List *cmds, bool recurse)
1801 /* Phase 1: preliminary examination of commands, create work queue */
1804 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
1806 ATPrepCmd(&wqueue, rel, cmd, recurse, false);
1809 /* Close the relation, but keep lock until commit */
1810 relation_close(rel, NoLock);
1812 /* Phase 2: update system catalogs */
1813 ATRewriteCatalogs(&wqueue);
1815 /* Phase 3: scan/rewrite tables as needed */
1816 ATRewriteTables(&wqueue);
1822 * Traffic cop for ALTER TABLE Phase 1 operations, including simple
1823 * recursion and permission checks.
1825 * Caller must have acquired AccessExclusiveLock on relation already.
1826 * This lock should be held until commit.
1829 ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
1830 bool recurse, bool recursing)
1832 AlteredTableInfo *tab;
1835 /* Find or create work queue entry for this table */
1836 tab = ATGetQueueEntry(wqueue, rel);
1839 * Copy the original subcommand for each table. This avoids conflicts
1840 * when different child tables need to make different parse
1841 * transformations (for example, the same column may have different column
1842 * numbers in different children).
1844 cmd = copyObject(cmd);
1847 * Do permissions checking, recursion to child tables if needed, and any
1848 * additional phase-1 processing needed.
1850 switch (cmd->subtype)
1852 case AT_AddColumn: /* ADD COLUMN */
1853 ATSimplePermissions(rel, false);
1854 /* Performs own recursion */
1855 ATPrepAddColumn(wqueue, rel, recurse, cmd);
1856 pass = AT_PASS_ADD_COL;
1858 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
1861 * We allow defaults on views so that INSERT into a view can have
1862 * default-ish behavior. This works because the rewriter
1863 * substitutes default values into INSERTs before it expands
1866 ATSimplePermissions(rel, true);
1867 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1868 /* No command-specific prep needed */
1869 pass = cmd->def ? AT_PASS_ADD_CONSTR : AT_PASS_DROP;
1871 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
1872 ATSimplePermissions(rel, false);
1873 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1874 /* No command-specific prep needed */
1875 pass = AT_PASS_DROP;
1877 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
1878 ATSimplePermissions(rel, false);
1879 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1880 /* No command-specific prep needed */
1881 pass = AT_PASS_ADD_CONSTR;
1883 case AT_SetStatistics: /* ALTER COLUMN STATISTICS */
1884 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1885 /* Performs own permission checks */
1886 ATPrepSetStatistics(rel, cmd->name, cmd->def);
1887 pass = AT_PASS_COL_ATTRS;
1889 case AT_SetStorage: /* ALTER COLUMN STORAGE */
1890 ATSimplePermissions(rel, false);
1891 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1892 /* No command-specific prep needed */
1893 pass = AT_PASS_COL_ATTRS;
1895 case AT_DropColumn: /* DROP COLUMN */
1896 ATSimplePermissions(rel, false);
1897 /* Recursion occurs during execution phase */
1898 /* No command-specific prep needed except saving recurse flag */
1900 cmd->subtype = AT_DropColumnRecurse;
1901 pass = AT_PASS_DROP;
1903 case AT_AddIndex: /* ADD INDEX */
1904 ATSimplePermissions(rel, false);
1905 /* This command never recurses */
1906 /* No command-specific prep needed */
1907 pass = AT_PASS_ADD_INDEX;
1909 case AT_AddConstraint: /* ADD CONSTRAINT */
1910 ATSimplePermissions(rel, false);
1913 * Currently we recurse only for CHECK constraints, never for
1914 * foreign-key constraints. UNIQUE/PKEY constraints won't be seen
1917 if (IsA(cmd->def, Constraint))
1918 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1919 /* No command-specific prep needed */
1920 pass = AT_PASS_ADD_CONSTR;
1922 case AT_DropConstraint: /* DROP CONSTRAINT */
1923 ATSimplePermissions(rel, false);
1924 /* Performs own recursion */
1925 ATPrepDropConstraint(wqueue, rel, recurse, cmd);
1926 pass = AT_PASS_DROP;
1928 case AT_DropConstraintQuietly: /* DROP CONSTRAINT for child */
1929 ATSimplePermissions(rel, false);
1930 ATSimpleRecursion(wqueue, rel, cmd, recurse);
1931 /* No command-specific prep needed */
1932 pass = AT_PASS_DROP;
1934 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
1935 ATSimplePermissions(rel, false);
1936 /* Performs own recursion */
1937 ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd);
1938 pass = AT_PASS_ALTER_TYPE;
1940 case AT_ChangeOwner: /* ALTER OWNER */
1941 /* This command never recurses */
1942 /* No command-specific prep needed */
1943 pass = AT_PASS_MISC;
1945 case AT_ClusterOn: /* CLUSTER ON */
1946 case AT_DropCluster: /* SET WITHOUT CLUSTER */
1947 ATSimplePermissions(rel, false);
1948 /* These commands never recurse */
1949 /* No command-specific prep needed */
1950 pass = AT_PASS_MISC;
1952 case AT_DropOids: /* SET WITHOUT OIDS */
1953 ATSimplePermissions(rel, false);
1954 /* Performs own recursion */
1955 if (rel->rd_rel->relhasoids)
1957 AlterTableCmd *dropCmd = makeNode(AlterTableCmd);
1959 dropCmd->subtype = AT_DropColumn;
1960 dropCmd->name = pstrdup("oid");
1961 dropCmd->behavior = cmd->behavior;
1962 ATPrepCmd(wqueue, rel, dropCmd, recurse, false);
1964 pass = AT_PASS_DROP;
1966 case AT_SetTableSpace: /* SET TABLESPACE */
1967 ATSimplePermissionsRelationOrIndex(rel);
1968 /* This command never recurses */
1969 ATPrepSetTableSpace(tab, rel, cmd->name);
1970 pass = AT_PASS_MISC; /* doesn't actually matter */
1972 case AT_SetRelOptions: /* SET (...) */
1973 case AT_ResetRelOptions: /* RESET (...) */
1974 ATSimplePermissionsRelationOrIndex(rel);
1975 /* This command never recurses */
1976 /* No command-specific prep needed */
1977 pass = AT_PASS_MISC;
1979 case AT_EnableTrig: /* ENABLE TRIGGER variants */
1980 case AT_EnableAlwaysTrig:
1981 case AT_EnableReplicaTrig:
1982 case AT_EnableTrigAll:
1983 case AT_EnableTrigUser:
1984 case AT_DisableTrig: /* DISABLE TRIGGER variants */
1985 case AT_DisableTrigAll:
1986 case AT_DisableTrigUser:
1987 case AT_EnableRule: /* ENABLE/DISABLE RULE variants */
1988 case AT_EnableAlwaysRule:
1989 case AT_EnableReplicaRule:
1990 case AT_DisableRule:
1991 case AT_AddInherit: /* INHERIT / NO INHERIT */
1992 case AT_DropInherit:
1993 ATSimplePermissions(rel, false);
1994 /* These commands never recurse */
1995 /* No command-specific prep needed */
1996 pass = AT_PASS_MISC;
1999 elog(ERROR, "unrecognized alter table type: %d",
2000 (int) cmd->subtype);
2001 pass = 0; /* keep compiler quiet */
2005 /* Add the subcommand to the appropriate list for phase 2 */
2006 tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
2012 * Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
2013 * dispatched in a "safe" execution order (designed to avoid unnecessary
2017 ATRewriteCatalogs(List **wqueue)
2023 * We process all the tables "in parallel", one pass at a time. This is
2024 * needed because we may have to propagate work from one table to another
2025 * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
2026 * re-adding of the foreign key constraint to the other table). Work can
2027 * only be propagated into later passes, however.
2029 for (pass = 0; pass < AT_NUM_PASSES; pass++)
2031 /* Go through each table that needs to be processed */
2032 foreach(ltab, *wqueue)
2034 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2035 List *subcmds = tab->subcmds[pass];
2043 * Exclusive lock was obtained by phase 1, needn't get it again
2045 rel = relation_open(tab->relid, NoLock);
2047 foreach(lcmd, subcmds)
2048 ATExecCmd(tab, rel, (AlterTableCmd *) lfirst(lcmd));
2051 * After the ALTER TYPE pass, do cleanup work (this is not done in
2052 * ATExecAlterColumnType since it should be done only once if
2053 * multiple columns of a table are altered).
2055 if (pass == AT_PASS_ALTER_TYPE)
2056 ATPostAlterTypeCleanup(wqueue, tab);
2058 relation_close(rel, NoLock);
2063 * Check to see if a toast table must be added, if we executed any
2064 * subcommands that might have added a column or changed column storage.
2066 foreach(ltab, *wqueue)
2068 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2070 if (tab->relkind == RELKIND_RELATION &&
2071 (tab->subcmds[AT_PASS_ADD_COL] ||
2072 tab->subcmds[AT_PASS_ALTER_TYPE] ||
2073 tab->subcmds[AT_PASS_COL_ATTRS]))
2074 AlterTableCreateToastTable(tab->relid);
2079 * ATExecCmd: dispatch a subcommand to appropriate execution routine
2082 ATExecCmd(AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd)
2084 switch (cmd->subtype)
2086 case AT_AddColumn: /* ADD COLUMN */
2087 ATExecAddColumn(tab, rel, (ColumnDef *) cmd->def);
2089 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
2090 ATExecColumnDefault(rel, cmd->name, cmd->def);
2092 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
2093 ATExecDropNotNull(rel, cmd->name);
2095 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
2096 ATExecSetNotNull(tab, rel, cmd->name);
2098 case AT_SetStatistics: /* ALTER COLUMN STATISTICS */
2099 ATExecSetStatistics(rel, cmd->name, cmd->def);
2101 case AT_SetStorage: /* ALTER COLUMN STORAGE */
2102 ATExecSetStorage(rel, cmd->name, cmd->def);
2104 case AT_DropColumn: /* DROP COLUMN */
2105 ATExecDropColumn(rel, cmd->name, cmd->behavior, false, false);
2107 case AT_DropColumnRecurse: /* DROP COLUMN with recursion */
2108 ATExecDropColumn(rel, cmd->name, cmd->behavior, true, false);
2110 case AT_AddIndex: /* ADD INDEX */
2111 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false);
2113 case AT_ReAddIndex: /* ADD INDEX */
2114 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true);
2116 case AT_AddConstraint: /* ADD CONSTRAINT */
2117 ATExecAddConstraint(tab, rel, cmd->def);
2119 case AT_DropConstraint: /* DROP CONSTRAINT */
2120 ATExecDropConstraint(rel, cmd->name, cmd->behavior, false);
2122 case AT_DropConstraintQuietly: /* DROP CONSTRAINT for child */
2123 ATExecDropConstraint(rel, cmd->name, cmd->behavior, true);
2125 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
2126 ATExecAlterColumnType(tab, rel, cmd->name, (TypeName *) cmd->def);
2128 case AT_ChangeOwner: /* ALTER OWNER */
2129 ATExecChangeOwner(RelationGetRelid(rel),
2130 get_roleid_checked(cmd->name),
2133 case AT_ClusterOn: /* CLUSTER ON */
2134 ATExecClusterOn(rel, cmd->name);
2136 case AT_DropCluster: /* SET WITHOUT CLUSTER */
2137 ATExecDropCluster(rel);
2139 case AT_DropOids: /* SET WITHOUT OIDS */
2142 * Nothing to do here; we'll have generated a DropColumn
2143 * subcommand to do the real work
2146 case AT_SetTableSpace: /* SET TABLESPACE */
2149 * Nothing to do here; Phase 3 does the work
2152 case AT_SetRelOptions: /* SET (...) */
2153 ATExecSetRelOptions(rel, (List *) cmd->def, false);
2155 case AT_ResetRelOptions: /* RESET (...) */
2156 ATExecSetRelOptions(rel, (List *) cmd->def, true);
2159 case AT_EnableTrig: /* ENABLE TRIGGER name */
2160 ATExecEnableDisableTrigger(rel, cmd->name,
2161 TRIGGER_FIRES_ON_ORIGIN, false);
2163 case AT_EnableAlwaysTrig: /* ENABLE ALWAYS TRIGGER name */
2164 ATExecEnableDisableTrigger(rel, cmd->name,
2165 TRIGGER_FIRES_ALWAYS, false);
2167 case AT_EnableReplicaTrig: /* ENABLE REPLICA TRIGGER name */
2168 ATExecEnableDisableTrigger(rel, cmd->name,
2169 TRIGGER_FIRES_ON_REPLICA, false);
2171 case AT_DisableTrig: /* DISABLE TRIGGER name */
2172 ATExecEnableDisableTrigger(rel, cmd->name,
2173 TRIGGER_DISABLED, false);
2175 case AT_EnableTrigAll: /* ENABLE TRIGGER ALL */
2176 ATExecEnableDisableTrigger(rel, NULL,
2177 TRIGGER_FIRES_ON_ORIGIN, false);
2179 case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
2180 ATExecEnableDisableTrigger(rel, NULL,
2181 TRIGGER_DISABLED, false);
2183 case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
2184 ATExecEnableDisableTrigger(rel, NULL,
2185 TRIGGER_FIRES_ON_ORIGIN, true);
2187 case AT_DisableTrigUser: /* DISABLE TRIGGER USER */
2188 ATExecEnableDisableTrigger(rel, NULL,
2189 TRIGGER_DISABLED, true);
2192 case AT_EnableRule: /* ENABLE RULE name */
2193 ATExecEnableDisableRule(rel, cmd->name,
2194 RULE_FIRES_ON_ORIGIN);
2196 case AT_EnableAlwaysRule: /* ENABLE ALWAYS RULE name */
2197 ATExecEnableDisableRule(rel, cmd->name,
2200 case AT_EnableReplicaRule: /* ENABLE REPLICA RULE name */
2201 ATExecEnableDisableRule(rel, cmd->name,
2202 RULE_FIRES_ON_REPLICA);
2204 case AT_DisableRule: /* DISABLE RULE name */
2205 ATExecEnableDisableRule(rel, cmd->name,
2210 ATExecAddInherit(rel, (RangeVar *) cmd->def);
2212 case AT_DropInherit:
2213 ATExecDropInherit(rel, (RangeVar *) cmd->def);
2216 elog(ERROR, "unrecognized alter table type: %d",
2217 (int) cmd->subtype);
2222 * Bump the command counter to ensure the next subcommand in the sequence
2223 * can see the changes so far
2225 CommandCounterIncrement();
2229 * ATRewriteTables: ALTER TABLE phase 3
2232 ATRewriteTables(List **wqueue)
2236 /* Go through each table that needs to be checked or rewritten */
2237 foreach(ltab, *wqueue)
2239 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2242 * We only need to rewrite the table if at least one column needs to
2245 if (tab->newvals != NIL)
2247 /* Build a temporary relation and copy data */
2249 char NewHeapName[NAMEDATALEN];
2252 ObjectAddress object;
2254 OldHeap = heap_open(tab->relid, NoLock);
2257 * We can never allow rewriting of shared or nailed-in-cache
2258 * relations, because we can't support changing their relfilenode
2261 if (OldHeap->rd_rel->relisshared || OldHeap->rd_isnailed)
2263 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2264 errmsg("cannot rewrite system relation \"%s\"",
2265 RelationGetRelationName(OldHeap))));
2268 * Don't allow rewrite on temp tables of other backends ... their
2269 * local buffer manager is not going to cope.
2271 if (isOtherTempNamespace(RelationGetNamespace(OldHeap)))
2273 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2274 errmsg("cannot rewrite temporary tables of other sessions")));
2277 * Select destination tablespace (same as original unless user
2278 * requested a change)
2280 if (tab->newTableSpace)
2281 NewTableSpace = tab->newTableSpace;
2283 NewTableSpace = OldHeap->rd_rel->reltablespace;
2285 heap_close(OldHeap, NoLock);
2288 * Create the new heap, using a temporary name in the same
2289 * namespace as the existing table. NOTE: there is some risk of
2290 * collision with user relnames. Working around this seems more
2291 * trouble than it's worth; in particular, we can't create the new
2292 * heap in a different namespace from the old, or we will have
2293 * problems with the TEMP status of temp tables.
2295 snprintf(NewHeapName, sizeof(NewHeapName),
2296 "pg_temp_%u", tab->relid);
2298 OIDNewHeap = make_new_heap(tab->relid, NewHeapName, NewTableSpace);
2301 * Copy the heap data into the new table with the desired
2302 * modifications, and test the current data within the table
2303 * against new constraints generated by ALTER TABLE commands.
2305 ATRewriteTable(tab, OIDNewHeap);
2308 * Swap the physical files of the old and new heaps. Since we are
2309 * generating a new heap, we can use RecentXmin for the table's new
2310 * relfrozenxid because we rewrote all the tuples on
2311 * ATRewriteTable, so no older Xid remains on the table.
2313 swap_relation_files(tab->relid, OIDNewHeap, RecentXmin);
2315 CommandCounterIncrement();
2317 /* Destroy new heap with old filenode */
2318 object.classId = RelationRelationId;
2319 object.objectId = OIDNewHeap;
2320 object.objectSubId = 0;
2323 * The new relation is local to our transaction and we know
2324 * nothing depends on it, so DROP_RESTRICT should be OK.
2326 performDeletion(&object, DROP_RESTRICT);
2327 /* performDeletion does CommandCounterIncrement at end */
2330 * Rebuild each index on the relation (but not the toast table,
2331 * which is all-new anyway). We do not need
2332 * CommandCounterIncrement() because reindex_relation does it.
2334 reindex_relation(tab->relid, false);
2339 * Test the current data within the table against new constraints
2340 * generated by ALTER TABLE commands, but don't rebuild data.
2342 if (tab->constraints != NIL || tab->new_notnull)
2343 ATRewriteTable(tab, InvalidOid);
2346 * If we had SET TABLESPACE but no reason to reconstruct tuples,
2347 * just do a block-by-block copy.
2349 if (tab->newTableSpace)
2350 ATExecSetTableSpace(tab->relid, tab->newTableSpace);
2355 * Foreign key constraints are checked in a final pass, since (a) it's
2356 * generally best to examine each one separately, and (b) it's at least
2357 * theoretically possible that we have changed both relations of the
2358 * foreign key, and we'd better have finished both rewrites before we try
2359 * to read the tables.
2361 foreach(ltab, *wqueue)
2363 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2364 Relation rel = NULL;
2367 foreach(lcon, tab->constraints)
2369 NewConstraint *con = lfirst(lcon);
2371 if (con->contype == CONSTR_FOREIGN)
2373 FkConstraint *fkconstraint = (FkConstraint *) con->qual;
2378 /* Long since locked, no need for another */
2379 rel = heap_open(tab->relid, NoLock);
2382 refrel = heap_open(con->refrelid, RowShareLock);
2384 validateForeignKeyConstraint(fkconstraint, rel, refrel,
2387 heap_close(refrel, NoLock);
2392 heap_close(rel, NoLock);
2397 * ATRewriteTable: scan or rewrite one table
2399 * OIDNewHeap is InvalidOid if we don't need to rewrite
2402 ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap)
2406 TupleDesc oldTupDesc;
2407 TupleDesc newTupDesc;
2408 bool needscan = false;
2409 List *notnull_attrs;
2415 * Open the relation(s). We have surely already locked the existing
2418 oldrel = heap_open(tab->relid, NoLock);
2419 oldTupDesc = tab->oldDesc;
2420 newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
2422 if (OidIsValid(OIDNewHeap))
2423 newrel = heap_open(OIDNewHeap, AccessExclusiveLock);
2428 * If we need to rewrite the table, the operation has to be propagated to
2429 * tables that use this table's rowtype as a column type.
2431 * (Eventually this will probably become true for scans as well, but at
2432 * the moment a composite type does not enforce any constraints, so it's
2433 * not necessary/appropriate to enforce them just during ALTER.)
2436 find_composite_type_dependencies(oldrel->rd_rel->reltype,
2437 RelationGetRelationName(oldrel),
2441 * Generate the constraint and default execution states
2444 estate = CreateExecutorState();
2446 /* Build the needed expression execution states */
2447 foreach(l, tab->constraints)
2449 NewConstraint *con = lfirst(l);
2451 switch (con->contype)
2455 con->qualstate = (List *)
2456 ExecPrepareExpr((Expr *) con->qual, estate);
2458 case CONSTR_FOREIGN:
2459 /* Nothing to do here */
2462 elog(ERROR, "unrecognized constraint type: %d",
2463 (int) con->contype);
2467 foreach(l, tab->newvals)
2469 NewColumnValue *ex = lfirst(l);
2473 ex->exprstate = ExecPrepareExpr((Expr *) ex->expr, estate);
2476 notnull_attrs = NIL;
2477 if (newrel || tab->new_notnull)
2480 * If we are rebuilding the tuples OR if we added any new NOT NULL
2481 * constraints, check all not-null constraints. This is a bit of
2482 * overkill but it minimizes risk of bugs, and heap_attisnull is a
2483 * pretty cheap test anyway.
2485 for (i = 0; i < newTupDesc->natts; i++)
2487 if (newTupDesc->attrs[i]->attnotnull &&
2488 !newTupDesc->attrs[i]->attisdropped)
2489 notnull_attrs = lappend_int(notnull_attrs, i);
2497 ExprContext *econtext;
2500 TupleTableSlot *oldslot;
2501 TupleTableSlot *newslot;
2504 MemoryContext oldCxt;
2505 List *dropped_attrs = NIL;
2508 econtext = GetPerTupleExprContext(estate);
2511 * Make tuple slots for old and new tuples. Note that even when the
2512 * tuples are the same, the tupDescs might not be (consider ADD COLUMN
2513 * without a default).
2515 oldslot = MakeSingleTupleTableSlot(oldTupDesc);
2516 newslot = MakeSingleTupleTableSlot(newTupDesc);
2518 /* Preallocate values/isnull arrays */
2519 i = Max(newTupDesc->natts, oldTupDesc->natts);
2520 values = (Datum *) palloc(i * sizeof(Datum));
2521 isnull = (bool *) palloc(i * sizeof(bool));
2522 memset(values, 0, i * sizeof(Datum));
2523 memset(isnull, true, i * sizeof(bool));
2526 * Any attributes that are dropped according to the new tuple
2527 * descriptor can be set to NULL. We precompute the list of dropped
2528 * attributes to avoid needing to do so in the per-tuple loop.
2530 for (i = 0; i < newTupDesc->natts; i++)
2532 if (newTupDesc->attrs[i]->attisdropped)
2533 dropped_attrs = lappend_int(dropped_attrs, i);
2537 * Scan through the rows, generating a new row if needed and then
2538 * checking all the constraints.
2540 scan = heap_beginscan(oldrel, SnapshotNow, 0, NULL);
2543 * Switch to per-tuple memory context and reset it for each tuple
2544 * produced, so we don't leak memory.
2546 oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
2548 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2552 Oid tupOid = InvalidOid;
2554 /* Extract data from old tuple */
2555 heap_deform_tuple(tuple, oldTupDesc, values, isnull);
2556 if (oldTupDesc->tdhasoid)
2557 tupOid = HeapTupleGetOid(tuple);
2559 /* Set dropped attributes to null in new tuple */
2560 foreach(lc, dropped_attrs)
2561 isnull[lfirst_int(lc)] = true;
2564 * Process supplied expressions to replace selected columns.
2565 * Expression inputs come from the old tuple.
2567 ExecStoreTuple(tuple, oldslot, InvalidBuffer, false);
2568 econtext->ecxt_scantuple = oldslot;
2570 foreach(l, tab->newvals)
2572 NewColumnValue *ex = lfirst(l);
2574 values[ex->attnum - 1] = ExecEvalExpr(ex->exprstate,
2576 &isnull[ex->attnum - 1],
2581 * Form the new tuple. Note that we don't explicitly pfree it,
2582 * since the per-tuple memory context will be reset shortly.
2584 tuple = heap_form_tuple(newTupDesc, values, isnull);
2586 /* Preserve OID, if any */
2587 if (newTupDesc->tdhasoid)
2588 HeapTupleSetOid(tuple, tupOid);
2591 /* Now check any constraints on the possibly-changed tuple */
2592 ExecStoreTuple(tuple, newslot, InvalidBuffer, false);
2593 econtext->ecxt_scantuple = newslot;
2595 foreach(l, notnull_attrs)
2597 int attn = lfirst_int(l);
2599 if (heap_attisnull(tuple, attn + 1))
2601 (errcode(ERRCODE_NOT_NULL_VIOLATION),
2602 errmsg("column \"%s\" contains null values",
2603 NameStr(newTupDesc->attrs[attn]->attname))));
2606 foreach(l, tab->constraints)
2608 NewConstraint *con = lfirst(l);
2610 switch (con->contype)
2613 if (!ExecQual(con->qualstate, econtext, true))
2615 (errcode(ERRCODE_CHECK_VIOLATION),
2616 errmsg("check constraint \"%s\" is violated by some row",
2619 case CONSTR_FOREIGN:
2620 /* Nothing to do here */
2623 elog(ERROR, "unrecognized constraint type: %d",
2624 (int) con->contype);
2628 /* Write the tuple out to the new relation */
2630 simple_heap_insert(newrel, tuple);
2632 ResetExprContext(econtext);
2634 CHECK_FOR_INTERRUPTS();
2637 MemoryContextSwitchTo(oldCxt);
2640 ExecDropSingleTupleTableSlot(oldslot);
2641 ExecDropSingleTupleTableSlot(newslot);
2644 FreeExecutorState(estate);
2646 heap_close(oldrel, NoLock);
2648 heap_close(newrel, NoLock);
2652 * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
2654 static AlteredTableInfo *
2655 ATGetQueueEntry(List **wqueue, Relation rel)
2657 Oid relid = RelationGetRelid(rel);
2658 AlteredTableInfo *tab;
2661 foreach(ltab, *wqueue)
2663 tab = (AlteredTableInfo *) lfirst(ltab);
2664 if (tab->relid == relid)
2669 * Not there, so add it. Note that we make a copy of the relation's
2670 * existing descriptor before anything interesting can happen to it.
2672 tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
2674 tab->relkind = rel->rd_rel->relkind;
2675 tab->oldDesc = CreateTupleDescCopy(RelationGetDescr(rel));
2677 *wqueue = lappend(*wqueue, tab);
2683 * ATSimplePermissions
2685 * - Ensure that it is a relation (or possibly a view)
2686 * - Ensure this user is the owner
2687 * - Ensure that it is not a system table
2690 ATSimplePermissions(Relation rel, bool allowView)
2692 if (rel->rd_rel->relkind != RELKIND_RELATION)
2696 if (rel->rd_rel->relkind != RELKIND_VIEW)
2698 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2699 errmsg("\"%s\" is not a table or view",
2700 RelationGetRelationName(rel))));
2704 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2705 errmsg("\"%s\" is not a table",
2706 RelationGetRelationName(rel))));
2709 /* Permissions checks */
2710 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
2711 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
2712 RelationGetRelationName(rel));
2714 if (!allowSystemTableMods && IsSystemRelation(rel))
2716 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2717 errmsg("permission denied: \"%s\" is a system catalog",
2718 RelationGetRelationName(rel))));
2722 * ATSimplePermissionsRelationOrIndex
2724 * - Ensure that it is a relation or an index
2725 * - Ensure this user is the owner
2726 * - Ensure that it is not a system table
2729 ATSimplePermissionsRelationOrIndex(Relation rel)
2731 if (rel->rd_rel->relkind != RELKIND_RELATION &&
2732 rel->rd_rel->relkind != RELKIND_INDEX)
2734 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2735 errmsg("\"%s\" is not a table or index",
2736 RelationGetRelationName(rel))));
2738 /* Permissions checks */
2739 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
2740 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
2741 RelationGetRelationName(rel));
2743 if (!allowSystemTableMods && IsSystemRelation(rel))
2745 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2746 errmsg("permission denied: \"%s\" is a system catalog",
2747 RelationGetRelationName(rel))));
2753 * Simple table recursion sufficient for most ALTER TABLE operations.
2754 * All direct and indirect children are processed in an unspecified order.
2755 * Note that if a child inherits from the original table via multiple
2756 * inheritance paths, it will be visited just once.
2759 ATSimpleRecursion(List **wqueue, Relation rel,
2760 AlterTableCmd *cmd, bool recurse)
2763 * Propagate to children if desired. Non-table relations never have
2764 * children, so no need to search in that case.
2766 if (recurse && rel->rd_rel->relkind == RELKIND_RELATION)
2768 Oid relid = RelationGetRelid(rel);
2772 /* this routine is actually in the planner */
2773 children = find_all_inheritors(relid);
2776 * find_all_inheritors does the recursive search of the inheritance
2777 * hierarchy, so all we have to do is process all of the relids in the
2778 * list that it returns.
2780 foreach(child, children)
2782 Oid childrelid = lfirst_oid(child);
2785 if (childrelid == relid)
2787 childrel = relation_open(childrelid, AccessExclusiveLock);
2788 /* check for child relation in use in this session */
2789 if (childrel->rd_refcnt != 1)
2791 (errcode(ERRCODE_OBJECT_IN_USE),
2792 errmsg("relation \"%s\" is being used by active queries in this session",
2793 RelationGetRelationName(childrel))));
2794 ATPrepCmd(wqueue, childrel, cmd, false, true);
2795 relation_close(childrel, NoLock);
2801 * ATOneLevelRecursion
2803 * Here, we visit only direct inheritance children. It is expected that
2804 * the command's prep routine will recurse again to find indirect children.
2805 * When using this technique, a multiply-inheriting child will be visited
2809 ATOneLevelRecursion(List **wqueue, Relation rel,
2812 Oid relid = RelationGetRelid(rel);
2816 /* this routine is actually in the planner */
2817 children = find_inheritance_children(relid);
2819 foreach(child, children)
2821 Oid childrelid = lfirst_oid(child);
2824 childrel = relation_open(childrelid, AccessExclusiveLock);
2825 /* check for child relation in use in this session */
2826 if (childrel->rd_refcnt != 1)
2828 (errcode(ERRCODE_OBJECT_IN_USE),
2829 errmsg("relation \"%s\" is being used by active queries in this session",
2830 RelationGetRelationName(childrel))));
2831 ATPrepCmd(wqueue, childrel, cmd, true, true);
2832 relation_close(childrel, NoLock);
2838 * find_composite_type_dependencies
2840 * Check to see if a composite type is being used as a column in some
2841 * other table (possibly nested several levels deep in composite types!).
2842 * Eventually, we'd like to propagate the check or rewrite operation
2843 * into other such tables, but for now, just error out if we find any.
2845 * Caller should provide either a table name or a type name (not both) to
2846 * report in the error message, if any.
2848 * We assume that functions and views depending on the type are not reasons
2849 * to reject the ALTER. (How safe is this really?)
2852 find_composite_type_dependencies(Oid typeOid,
2853 const char *origTblName,
2854 const char *origTypeName)
2858 SysScanDesc depScan;
2863 * We scan pg_depend to find those things that depend on the rowtype. (We
2864 * assume we can ignore refobjsubid for a rowtype.)
2866 depRel = heap_open(DependRelationId, AccessShareLock);
2868 ScanKeyInit(&key[0],
2869 Anum_pg_depend_refclassid,
2870 BTEqualStrategyNumber, F_OIDEQ,
2871 ObjectIdGetDatum(TypeRelationId));
2872 ScanKeyInit(&key[1],
2873 Anum_pg_depend_refobjid,
2874 BTEqualStrategyNumber, F_OIDEQ,
2875 ObjectIdGetDatum(typeOid));
2877 depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
2878 SnapshotNow, 2, key);
2880 while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
2882 Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
2884 Form_pg_attribute att;
2886 /* Ignore dependees that aren't user columns of relations */
2887 /* (we assume system columns are never of rowtypes) */
2888 if (pg_depend->classid != RelationRelationId ||
2889 pg_depend->objsubid <= 0)
2892 rel = relation_open(pg_depend->objid, AccessShareLock);
2893 att = rel->rd_att->attrs[pg_depend->objsubid - 1];
2895 if (rel->rd_rel->relkind == RELKIND_RELATION)
2899 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2900 errmsg("cannot alter table \"%s\" because column \"%s\".\"%s\" uses its rowtype",
2902 RelationGetRelationName(rel),
2903 NameStr(att->attname))));
2906 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2907 errmsg("cannot alter type \"%s\" because column \"%s\".\"%s\" uses it",
2909 RelationGetRelationName(rel),
2910 NameStr(att->attname))));
2912 else if (OidIsValid(rel->rd_rel->reltype))
2915 * A view or composite type itself isn't a problem, but we must
2916 * recursively check for indirect dependencies via its rowtype.
2918 find_composite_type_dependencies(rel->rd_rel->reltype,
2919 origTblName, origTypeName);
2922 relation_close(rel, AccessShareLock);
2925 systable_endscan(depScan);
2927 relation_close(depRel, AccessShareLock);
2930 * If there's an array type for the rowtype, must check for uses of it,
2933 arrayOid = get_array_type(typeOid);
2934 if (OidIsValid(arrayOid))
2935 find_composite_type_dependencies(arrayOid, origTblName, origTypeName);
2940 * ALTER TABLE ADD COLUMN
2942 * Adds an additional attribute to a relation making the assumption that
2943 * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
2944 * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
2948 ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
2952 * Recurse to add the column to child classes, if requested.
2954 * We must recurse one level at a time, so that multiply-inheriting
2955 * children are visited the right number of times and end up with the
2956 * right attinhcount.
2960 AlterTableCmd *childCmd = copyObject(cmd);
2961 ColumnDef *colDefChild = (ColumnDef *) childCmd->def;
2963 /* Child should see column as singly inherited */
2964 colDefChild->inhcount = 1;
2965 colDefChild->is_local = false;
2967 ATOneLevelRecursion(wqueue, rel, childCmd);
2972 * If we are told not to recurse, there had better not be any child
2973 * tables; else the addition would put them out of step.
2975 if (find_inheritance_children(RelationGetRelid(rel)) != NIL)
2977 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2978 errmsg("column must be added to child tables too")));
2983 ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
2986 Oid myrelid = RelationGetRelid(rel);
2990 HeapTuple attributeTuple;
2991 Form_pg_attribute attribute;
2992 FormData_pg_attribute attributeD;
2996 HeapTuple typeTuple;
3002 attrdesc = heap_open(AttributeRelationId, RowExclusiveLock);
3005 * Are we adding the column to a recursion child? If so, check whether to
3006 * merge with an existing definition for the column.
3008 if (colDef->inhcount > 0)
3012 /* Does child already have a column by this name? */
3013 tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
3014 if (HeapTupleIsValid(tuple))
3016 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
3020 /* Okay if child matches by type */
3021 ctypeId = typenameTypeId(NULL, colDef->typename);
3022 ctypmod = typenameTypeMod(NULL, colDef->typename, ctypeId);
3023 if (ctypeId != childatt->atttypid ||
3024 ctypmod != childatt->atttypmod)
3026 (errcode(ERRCODE_DATATYPE_MISMATCH),
3027 errmsg("child table \"%s\" has different type for column \"%s\"",
3028 RelationGetRelationName(rel), colDef->colname)));
3030 /* Bump the existing child att's inhcount */
3031 childatt->attinhcount++;
3032 simple_heap_update(attrdesc, &tuple->t_self, tuple);
3033 CatalogUpdateIndexes(attrdesc, tuple);
3035 heap_freetuple(tuple);
3037 /* Inform the user about the merge */
3039 (errmsg("merging definition of column \"%s\" for child \"%s\"",
3040 colDef->colname, RelationGetRelationName(rel))));
3042 heap_close(attrdesc, RowExclusiveLock);
3047 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
3049 reltup = SearchSysCacheCopy(RELOID,
3050 ObjectIdGetDatum(myrelid),
3052 if (!HeapTupleIsValid(reltup))
3053 elog(ERROR, "cache lookup failed for relation %u", myrelid);
3056 * this test is deliberately not attisdropped-aware, since if one tries to
3057 * add a column matching a dropped column name, it's gonna fail anyway.
3059 if (SearchSysCacheExists(ATTNAME,
3060 ObjectIdGetDatum(myrelid),
3061 PointerGetDatum(colDef->colname),
3064 (errcode(ERRCODE_DUPLICATE_COLUMN),
3065 errmsg("column \"%s\" of relation \"%s\" already exists",
3066 colDef->colname, RelationGetRelationName(rel))));
3068 minattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts;
3069 maxatts = minattnum + 1;
3070 if (maxatts > MaxHeapAttributeNumber)
3072 (errcode(ERRCODE_TOO_MANY_COLUMNS),
3073 errmsg("tables can have at most %d columns",
3074 MaxHeapAttributeNumber)));
3077 typeTuple = typenameType(NULL, colDef->typename);
3078 tform = (Form_pg_type) GETSTRUCT(typeTuple);
3079 typeOid = HeapTupleGetOid(typeTuple);
3080 typmod = typenameTypeMod(NULL, colDef->typename, typeOid);
3082 /* make sure datatype is legal for a column */
3083 CheckAttributeType(colDef->colname, typeOid);
3085 attributeTuple = heap_addheader(Natts_pg_attribute,
3087 ATTRIBUTE_TUPLE_SIZE,
3088 (void *) &attributeD);
3090 attribute = (Form_pg_attribute) GETSTRUCT(attributeTuple);
3092 attribute->attrelid = myrelid;
3093 namestrcpy(&(attribute->attname), colDef->colname);
3094 attribute->atttypid = typeOid;
3095 attribute->attstattarget = -1;
3096 attribute->attlen = tform->typlen;
3097 attribute->attcacheoff = -1;
3098 attribute->atttypmod = typmod;
3099 attribute->attnum = i;
3100 attribute->attbyval = tform->typbyval;
3101 attribute->attndims = list_length(colDef->typename->arrayBounds);
3102 attribute->attstorage = tform->typstorage;
3103 attribute->attalign = tform->typalign;
3104 attribute->attnotnull = colDef->is_not_null;
3105 attribute->atthasdef = false;
3106 attribute->attisdropped = false;
3107 attribute->attislocal = colDef->is_local;
3108 attribute->attinhcount = colDef->inhcount;
3110 ReleaseSysCache(typeTuple);
3112 simple_heap_insert(attrdesc, attributeTuple);
3114 /* Update indexes on pg_attribute */
3115 CatalogUpdateIndexes(attrdesc, attributeTuple);
3117 heap_close(attrdesc, RowExclusiveLock);
3120 * Update number of attributes in pg_class tuple
3122 ((Form_pg_class) GETSTRUCT(reltup))->relnatts = maxatts;
3124 simple_heap_update(pgclass, &reltup->t_self, reltup);
3126 /* keep catalog indexes current */
3127 CatalogUpdateIndexes(pgclass, reltup);
3129 heap_freetuple(reltup);
3131 heap_close(pgclass, RowExclusiveLock);
3133 /* Make the attribute's catalog entry visible */
3134 CommandCounterIncrement();
3137 * Store the DEFAULT, if any, in the catalogs
3139 if (colDef->raw_default)
3141 RawColumnDefault *rawEnt;
3143 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3144 rawEnt->attnum = attribute->attnum;
3145 rawEnt->raw_default = copyObject(colDef->raw_default);
3148 * This function is intended for CREATE TABLE, so it processes a
3149 * _list_ of defaults, but we just do one.
3151 AddRelationRawConstraints(rel, list_make1(rawEnt), NIL);
3153 /* Make the additional catalog changes visible */
3154 CommandCounterIncrement();
3158 * Tell Phase 3 to fill in the default expression, if there is one.
3160 * If there is no default, Phase 3 doesn't have to do anything, because
3161 * that effectively means that the default is NULL. The heap tuple access
3162 * routines always check for attnum > # of attributes in tuple, and return
3163 * NULL if so, so without any modification of the tuple data we will get
3164 * the effect of NULL values in the new column.
3166 * An exception occurs when the new column is of a domain type: the domain
3167 * might have a NOT NULL constraint, or a check constraint that indirectly
3168 * rejects nulls. If there are any domain constraints then we construct
3169 * an explicit NULL default value that will be passed through
3170 * CoerceToDomain processing. (This is a tad inefficient, since it causes
3171 * rewriting the table which we really don't have to do, but the present
3172 * design of domain processing doesn't offer any simple way of checking
3173 * the constraints more directly.)
3175 * Note: we use build_column_default, and not just the cooked default
3176 * returned by AddRelationRawConstraints, so that the right thing happens
3177 * when a datatype's default applies.
3179 defval = (Expr *) build_column_default(rel, attribute->attnum);
3181 if (!defval && GetDomainConstraints(typeOid) != NIL)
3186 baseTypeMod = typmod;
3187 baseTypeId = getBaseTypeAndTypmod(typeOid, &baseTypeMod);
3188 defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod);
3189 defval = (Expr *) coerce_to_target_type(NULL,
3194 COERCION_ASSIGNMENT,
3195 COERCE_IMPLICIT_CAST);
3196 if (defval == NULL) /* should not happen */
3197 elog(ERROR, "failed to coerce base type to domain");
3202 NewColumnValue *newval;
3204 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
3205 newval->attnum = attribute->attnum;
3206 newval->expr = defval;
3208 tab->newvals = lappend(tab->newvals, newval);
3212 * Add needed dependency entries for the new column.
3214 add_column_datatype_dependency(myrelid, i, attribute->atttypid);
3218 * Install a column's dependency on its datatype.
3221 add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
3223 ObjectAddress myself,
3226 myself.classId = RelationRelationId;
3227 myself.objectId = relid;
3228 myself.objectSubId = attnum;
3229 referenced.classId = TypeRelationId;
3230 referenced.objectId = typid;
3231 referenced.objectSubId = 0;
3232 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
3236 * ALTER TABLE ALTER COLUMN DROP NOT NULL
3239 ATExecDropNotNull(Relation rel, const char *colName)
3245 ListCell *indexoidscan;
3248 * lookup the attribute
3250 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3252 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3254 if (!HeapTupleIsValid(tuple))
3256 (errcode(ERRCODE_UNDEFINED_COLUMN),
3257 errmsg("column \"%s\" of relation \"%s\" does not exist",
3258 colName, RelationGetRelationName(rel))));
3260 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3262 /* Prevent them from altering a system attribute */
3265 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3266 errmsg("cannot alter system column \"%s\"",
3270 * Check that the attribute is not in a primary key
3273 /* Loop over all indexes on the relation */
3274 indexoidlist = RelationGetIndexList(rel);
3276 foreach(indexoidscan, indexoidlist)
3278 Oid indexoid = lfirst_oid(indexoidscan);
3279 HeapTuple indexTuple;
3280 Form_pg_index indexStruct;
3283 indexTuple = SearchSysCache(INDEXRELID,
3284 ObjectIdGetDatum(indexoid),
3286 if (!HeapTupleIsValid(indexTuple))
3287 elog(ERROR, "cache lookup failed for index %u", indexoid);
3288 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
3290 /* If the index is not a primary key, skip the check */
3291 if (indexStruct->indisprimary)
3294 * Loop over each attribute in the primary key and see if it
3295 * matches the to-be-altered attribute
3297 for (i = 0; i < indexStruct->indnatts; i++)
3299 if (indexStruct->indkey.values[i] == attnum)
3301 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3302 errmsg("column \"%s\" is in a primary key",
3307 ReleaseSysCache(indexTuple);
3310 list_free(indexoidlist);
3313 * Okay, actually perform the catalog change ... if needed
3315 if (((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3317 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = FALSE;
3319 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3321 /* keep the system catalog indexes current */
3322 CatalogUpdateIndexes(attr_rel, tuple);
3325 heap_close(attr_rel, RowExclusiveLock);
3329 * ALTER TABLE ALTER COLUMN SET NOT NULL
3332 ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
3333 const char *colName)
3340 * lookup the attribute
3342 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3344 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3346 if (!HeapTupleIsValid(tuple))
3348 (errcode(ERRCODE_UNDEFINED_COLUMN),
3349 errmsg("column \"%s\" of relation \"%s\" does not exist",
3350 colName, RelationGetRelationName(rel))));
3352 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3354 /* Prevent them from altering a system attribute */
3357 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3358 errmsg("cannot alter system column \"%s\"",
3362 * Okay, actually perform the catalog change ... if needed
3364 if (!((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3366 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = TRUE;
3368 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3370 /* keep the system catalog indexes current */
3371 CatalogUpdateIndexes(attr_rel, tuple);
3373 /* Tell Phase 3 it needs to test the constraint */
3374 tab->new_notnull = true;
3377 heap_close(attr_rel, RowExclusiveLock);
3381 * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
3384 ATExecColumnDefault(Relation rel, const char *colName,
3390 * get the number of the attribute
3392 attnum = get_attnum(RelationGetRelid(rel), colName);
3393 if (attnum == InvalidAttrNumber)
3395 (errcode(ERRCODE_UNDEFINED_COLUMN),
3396 errmsg("column \"%s\" of relation \"%s\" does not exist",
3397 colName, RelationGetRelationName(rel))));
3399 /* Prevent them from altering a system attribute */
3402 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3403 errmsg("cannot alter system column \"%s\"",
3407 * Remove any old default for the column. We use RESTRICT here for
3408 * safety, but at present we do not expect anything to depend on the
3411 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false);
3416 RawColumnDefault *rawEnt;
3418 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3419 rawEnt->attnum = attnum;
3420 rawEnt->raw_default = newDefault;
3423 * This function is intended for CREATE TABLE, so it processes a
3424 * _list_ of defaults, but we just do one.
3426 AddRelationRawConstraints(rel, list_make1(rawEnt), NIL);
3431 * ALTER TABLE ALTER COLUMN SET STATISTICS
3434 ATPrepSetStatistics(Relation rel, const char *colName, Node *flagValue)
3437 * We do our own permission checking because (a) we want to allow SET
3438 * STATISTICS on indexes (for expressional index columns), and (b) we want
3439 * to allow SET STATISTICS on system catalogs without requiring
3440 * allowSystemTableMods to be turned on.
3442 if (rel->rd_rel->relkind != RELKIND_RELATION &&
3443 rel->rd_rel->relkind != RELKIND_INDEX)
3445 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3446 errmsg("\"%s\" is not a table or index",
3447 RelationGetRelationName(rel))));
3449 /* Permissions checks */
3450 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3451 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3452 RelationGetRelationName(rel));
3456 ATExecSetStatistics(Relation rel, const char *colName, Node *newValue)
3459 Relation attrelation;
3461 Form_pg_attribute attrtuple;
3463 Assert(IsA(newValue, Integer));
3464 newtarget = intVal(newValue);
3467 * Limit target to a sane range
3472 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3473 errmsg("statistics target %d is too low",
3476 else if (newtarget > 1000)
3480 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3481 errmsg("lowering statistics target to %d",
3485 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
3487 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3489 if (!HeapTupleIsValid(tuple))
3491 (errcode(ERRCODE_UNDEFINED_COLUMN),
3492 errmsg("column \"%s\" of relation \"%s\" does not exist",
3493 colName, RelationGetRelationName(rel))));
3494 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
3496 if (attrtuple->attnum <= 0)
3498 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3499 errmsg("cannot alter system column \"%s\"",
3502 attrtuple->attstattarget = newtarget;
3504 simple_heap_update(attrelation, &tuple->t_self, tuple);
3506 /* keep system catalog indexes current */
3507 CatalogUpdateIndexes(attrelation, tuple);
3509 heap_freetuple(tuple);
3511 heap_close(attrelation, RowExclusiveLock);
3515 * ALTER TABLE ALTER COLUMN SET STORAGE
3518 ATExecSetStorage(Relation rel, const char *colName, Node *newValue)
3522 Relation attrelation;
3524 Form_pg_attribute attrtuple;
3526 Assert(IsA(newValue, String));
3527 storagemode = strVal(newValue);
3529 if (pg_strcasecmp(storagemode, "plain") == 0)
3531 else if (pg_strcasecmp(storagemode, "external") == 0)
3533 else if (pg_strcasecmp(storagemode, "extended") == 0)
3535 else if (pg_strcasecmp(storagemode, "main") == 0)
3540 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3541 errmsg("invalid storage type \"%s\"",
3543 newstorage = 0; /* keep compiler quiet */
3546 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
3548 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3550 if (!HeapTupleIsValid(tuple))
3552 (errcode(ERRCODE_UNDEFINED_COLUMN),
3553 errmsg("column \"%s\" of relation \"%s\" does not exist",
3554 colName, RelationGetRelationName(rel))));
3555 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
3557 if (attrtuple->attnum <= 0)
3559 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3560 errmsg("cannot alter system column \"%s\"",
3564 * safety check: do not allow toasted storage modes unless column datatype
3567 if (newstorage == 'p' || TypeIsToastable(attrtuple->atttypid))
3568 attrtuple->attstorage = newstorage;
3571 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3572 errmsg("column data type %s can only have storage PLAIN",
3573 format_type_be(attrtuple->atttypid))));
3575 simple_heap_update(attrelation, &tuple->t_self, tuple);
3577 /* keep system catalog indexes current */
3578 CatalogUpdateIndexes(attrelation, tuple);
3580 heap_freetuple(tuple);
3582 heap_close(attrelation, RowExclusiveLock);
3587 * ALTER TABLE DROP COLUMN
3589 * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
3590 * because we have to decide at runtime whether to recurse or not depending
3591 * on whether attinhcount goes to zero or not. (We can't check this in a
3592 * static pre-pass because it won't handle multiple inheritance situations
3593 * correctly.) Since DROP COLUMN doesn't need to create any work queue
3594 * entries for Phase 3, it's okay to recurse internally in this routine
3595 * without considering the work queue.
3598 ATExecDropColumn(Relation rel, const char *colName,
3599 DropBehavior behavior,
3600 bool recurse, bool recursing)
3603 Form_pg_attribute targetatt;
3606 ObjectAddress object;
3608 /* At top level, permission check was done in ATPrepCmd, else do it */
3610 ATSimplePermissions(rel, false);
3613 * get the number of the attribute
3615 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
3616 if (!HeapTupleIsValid(tuple))
3618 (errcode(ERRCODE_UNDEFINED_COLUMN),
3619 errmsg("column \"%s\" of relation \"%s\" does not exist",
3620 colName, RelationGetRelationName(rel))));
3621 targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
3623 attnum = targetatt->attnum;
3625 /* Can't drop a system attribute, except OID */
3626 if (attnum <= 0 && attnum != ObjectIdAttributeNumber)
3628 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3629 errmsg("cannot drop system column \"%s\"",
3632 /* Don't drop inherited columns */
3633 if (targetatt->attinhcount > 0 && !recursing)
3635 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3636 errmsg("cannot drop inherited column \"%s\"",
3639 ReleaseSysCache(tuple);
3642 * Propagate to children as appropriate. Unlike most other ALTER
3643 * routines, we have to do this one level of recursion at a time; we can't
3644 * use find_all_inheritors to do it in one pass.
3646 children = find_inheritance_children(RelationGetRelid(rel));
3653 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3654 foreach(child, children)
3656 Oid childrelid = lfirst_oid(child);
3658 Form_pg_attribute childatt;
3660 childrel = heap_open(childrelid, AccessExclusiveLock);
3661 /* check for child relation in use in this session */
3662 if (childrel->rd_refcnt != 1)
3664 (errcode(ERRCODE_OBJECT_IN_USE),
3665 errmsg("relation \"%s\" is being used by active queries in this session",
3666 RelationGetRelationName(childrel))));
3668 tuple = SearchSysCacheCopyAttName(childrelid, colName);
3669 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
3670 elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
3671 colName, childrelid);
3672 childatt = (Form_pg_attribute) GETSTRUCT(tuple);
3674 if (childatt->attinhcount <= 0) /* shouldn't happen */
3675 elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
3676 childrelid, colName);
3681 * If the child column has other definition sources, just
3682 * decrement its inheritance count; if not, recurse to delete
3685 if (childatt->attinhcount == 1 && !childatt->attislocal)
3687 /* Time to delete this child column, too */
3688 ATExecDropColumn(childrel, colName, behavior, true, true);
3692 /* Child column must survive my deletion */
3693 childatt->attinhcount--;
3695 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3697 /* keep the system catalog indexes current */
3698 CatalogUpdateIndexes(attr_rel, tuple);
3700 /* Make update visible */
3701 CommandCounterIncrement();
3707 * If we were told to drop ONLY in this table (no recursion),
3708 * we need to mark the inheritors' attribute as locally
3709 * defined rather than inherited.
3711 childatt->attinhcount--;
3712 childatt->attislocal = true;
3714 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3716 /* keep the system catalog indexes current */
3717 CatalogUpdateIndexes(attr_rel, tuple);
3719 /* Make update visible */
3720 CommandCounterIncrement();
3723 heap_freetuple(tuple);
3725 heap_close(childrel, NoLock);
3727 heap_close(attr_rel, RowExclusiveLock);
3731 * Perform the actual column deletion
3733 object.classId = RelationRelationId;
3734 object.objectId = RelationGetRelid(rel);
3735 object.objectSubId = attnum;
3737 performDeletion(&object, behavior);
3740 * If we dropped the OID column, must adjust pg_class.relhasoids
3742 if (attnum == ObjectIdAttributeNumber)
3745 Form_pg_class tuple_class;
3747 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
3749 tuple = SearchSysCacheCopy(RELOID,
3750 ObjectIdGetDatum(RelationGetRelid(rel)),
3752 if (!HeapTupleIsValid(tuple))
3753 elog(ERROR, "cache lookup failed for relation %u",
3754 RelationGetRelid(rel));
3755 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
3757 tuple_class->relhasoids = false;
3758 simple_heap_update(class_rel, &tuple->t_self, tuple);
3760 /* Keep the catalog indexes up to date */
3761 CatalogUpdateIndexes(class_rel, tuple);
3763 heap_close(class_rel, RowExclusiveLock);
3768 * ALTER TABLE ADD INDEX
3770 * There is no such command in the grammar, but parse_utilcmd.c converts
3771 * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands. This lets
3772 * us schedule creation of the index at the appropriate time during ALTER.
3775 ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
3776 IndexStmt *stmt, bool is_rebuild)
3782 Assert(IsA(stmt, IndexStmt));
3784 /* suppress schema rights check when rebuilding existing index */
3785 check_rights = !is_rebuild;
3786 /* skip index build if phase 3 will have to rewrite table anyway */
3787 skip_build = (tab->newvals != NIL);
3788 /* suppress notices when rebuilding existing index */
3791 /* The IndexStmt has already been through transformIndexStmt */
3793 DefineIndex(stmt->relation, /* relation */
3794 stmt->idxname, /* index name */
3795 InvalidOid, /* no predefined OID */
3796 stmt->accessMethod, /* am name */
3798 stmt->indexParams, /* parameters */
3799 (Expr *) stmt->whereClause,
3805 true, /* is_alter_table */
3813 * ALTER TABLE ADD CONSTRAINT
3816 ATExecAddConstraint(AlteredTableInfo *tab, Relation rel, Node *newConstraint)
3818 switch (nodeTag(newConstraint))
3822 Constraint *constr = (Constraint *) newConstraint;
3825 * Currently, we only expect to see CONSTR_CHECK nodes
3826 * arriving here (see the preprocessing done in
3827 * parse_utilcmd.c). Use a switch anyway to make it easier
3828 * to add more code later.
3830 switch (constr->contype)
3838 * Call AddRelationRawConstraints to do the work.
3839 * It returns a list of cooked constraints.
3841 newcons = AddRelationRawConstraints(rel, NIL,
3842 list_make1(constr));
3843 /* Add each constraint to Phase 3's queue */
3844 foreach(lcon, newcons)
3846 CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
3847 NewConstraint *newcon;
3849 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
3850 newcon->name = ccon->name;
3851 newcon->contype = ccon->contype;
3852 /* ExecQual wants implicit-AND format */
3853 newcon->qual = (Node *)
3854 make_ands_implicit((Expr *) ccon->expr);
3856 tab->constraints = lappend(tab->constraints,
3862 elog(ERROR, "unrecognized constraint type: %d",
3863 (int) constr->contype);
3867 case T_FkConstraint:
3869 FkConstraint *fkconstraint = (FkConstraint *) newConstraint;
3872 * Assign or validate constraint name
3874 if (fkconstraint->constr_name)
3876 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
3877 RelationGetRelid(rel),
3878 RelationGetNamespace(rel),
3879 fkconstraint->constr_name))
3881 (errcode(ERRCODE_DUPLICATE_OBJECT),
3882 errmsg("constraint \"%s\" for relation \"%s\" already exists",
3883 fkconstraint->constr_name,
3884 RelationGetRelationName(rel))));
3887 fkconstraint->constr_name =
3888 ChooseConstraintName(RelationGetRelationName(rel),
3889 strVal(linitial(fkconstraint->fk_attrs)),
3891 RelationGetNamespace(rel),
3894 ATAddForeignKeyConstraint(tab, rel, fkconstraint);
3899 elog(ERROR, "unrecognized node type: %d",
3900 (int) nodeTag(newConstraint));
3905 * Add a foreign-key constraint to a single table
3907 * Subroutine for ATExecAddConstraint. Must already hold exclusive
3908 * lock on the rel, and have done appropriate validity/permissions checks
3912 ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
3913 FkConstraint *fkconstraint)
3916 AclResult aclresult;
3917 int16 pkattnum[INDEX_MAX_KEYS];
3918 int16 fkattnum[INDEX_MAX_KEYS];
3919 Oid pktypoid[INDEX_MAX_KEYS];
3920 Oid fktypoid[INDEX_MAX_KEYS];
3921 Oid opclasses[INDEX_MAX_KEYS];
3922 Oid pfeqoperators[INDEX_MAX_KEYS];
3923 Oid ppeqoperators[INDEX_MAX_KEYS];
3924 Oid ffeqoperators[INDEX_MAX_KEYS];
3932 * Grab an exclusive lock on the pk table, so that someone doesn't delete
3933 * rows out from under us. (Although a lesser lock would do for that
3934 * purpose, we'll need exclusive lock anyway to add triggers to the pk
3935 * table; trying to start with a lesser lock will just create a risk of
3938 pkrel = heap_openrv(fkconstraint->pktable, AccessExclusiveLock);
3941 * Validity and permissions checks
3943 * Note: REFERENCES permissions checks are redundant with CREATE TRIGGER,
3944 * but we may as well error out sooner instead of later.
3946 if (pkrel->rd_rel->relkind != RELKIND_RELATION)
3948 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3949 errmsg("referenced relation \"%s\" is not a table",
3950 RelationGetRelationName(pkrel))));
3952 aclresult = pg_class_aclcheck(RelationGetRelid(pkrel), GetUserId(),
3954 if (aclresult != ACLCHECK_OK)
3955 aclcheck_error(aclresult, ACL_KIND_CLASS,
3956 RelationGetRelationName(pkrel));
3958 if (!allowSystemTableMods && IsSystemRelation(pkrel))
3960 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3961 errmsg("permission denied: \"%s\" is a system catalog",
3962 RelationGetRelationName(pkrel))));
3964 aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
3966 if (aclresult != ACLCHECK_OK)
3967 aclcheck_error(aclresult, ACL_KIND_CLASS,
3968 RelationGetRelationName(rel));
3971 * Disallow reference from permanent table to temp table or vice versa.
3972 * (The ban on perm->temp is for fairly obvious reasons. The ban on
3973 * temp->perm is because other backends might need to run the RI triggers
3974 * on the perm table, but they can't reliably see tuples the owning
3975 * backend has created in the temp table, because non-shared buffers are
3976 * used for temp tables.)
3978 if (isTempNamespace(RelationGetNamespace(pkrel)))
3980 if (!isTempNamespace(RelationGetNamespace(rel)))
3982 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3983 errmsg("cannot reference temporary table from permanent table constraint")));
3987 if (isTempNamespace(RelationGetNamespace(rel)))
3989 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3990 errmsg("cannot reference permanent table from temporary table constraint")));
3994 * Look up the referencing attributes to make sure they exist, and record
3995 * their attnums and type OIDs.
3997 MemSet(pkattnum, 0, sizeof(pkattnum));
3998 MemSet(fkattnum, 0, sizeof(fkattnum));
3999 MemSet(pktypoid, 0, sizeof(pktypoid));
4000 MemSet(fktypoid, 0, sizeof(fktypoid));
4001 MemSet(opclasses, 0, sizeof(opclasses));
4002 MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
4003 MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
4004 MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
4006 numfks = transformColumnNameList(RelationGetRelid(rel),
4007 fkconstraint->fk_attrs,
4008 fkattnum, fktypoid);
4011 * If the attribute list for the referenced table was omitted, lookup the
4012 * definition of the primary key and use it. Otherwise, validate the
4013 * supplied attribute list. In either case, discover the index OID and
4014 * index opclasses, and the attnums and type OIDs of the attributes.
4016 if (fkconstraint->pk_attrs == NIL)
4018 numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
4019 &fkconstraint->pk_attrs,
4025 numpks = transformColumnNameList(RelationGetRelid(pkrel),
4026 fkconstraint->pk_attrs,
4027 pkattnum, pktypoid);
4028 /* Look for an index matching the column list */
4029 indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
4034 * Look up the equality operators to use in the constraint.
4036 * Note that we have to be careful about the difference between the actual
4037 * PK column type and the opclass' declared input type, which might be
4038 * only binary-compatible with it. The declared opcintype is the right
4039 * thing to probe pg_amop with.
4041 if (numfks != numpks)
4043 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4044 errmsg("number of referencing and referenced columns for foreign key disagree")));
4046 for (i = 0; i < numpks; i++)
4048 Oid pktype = pktypoid[i];
4049 Oid fktype = fktypoid[i];
4052 Form_pg_opclass cla_tup;
4061 /* We need several fields out of the pg_opclass entry */
4062 cla_ht = SearchSysCache(CLAOID,
4063 ObjectIdGetDatum(opclasses[i]),
4065 if (!HeapTupleIsValid(cla_ht))
4066 elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
4067 cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
4068 amid = cla_tup->opcmethod;
4069 opfamily = cla_tup->opcfamily;
4070 opcintype = cla_tup->opcintype;
4071 ReleaseSysCache(cla_ht);
4074 * Check it's a btree; currently this can never fail since no other
4075 * index AMs support unique indexes. If we ever did have other
4076 * types of unique indexes, we'd need a way to determine which
4077 * operator strategy number is equality. (Is it reasonable to
4078 * insist that every such index AM use btree's number for equality?)
4080 if (amid != BTREE_AM_OID)
4081 elog(ERROR, "only b-tree indexes are supported for foreign keys");
4082 eqstrategy = BTEqualStrategyNumber;
4085 * There had better be a primary equality operator for the index.
4086 * We'll use it for PK = PK comparisons.
4088 ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
4091 if (!OidIsValid(ppeqop))
4092 elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
4093 eqstrategy, opcintype, opcintype, opfamily);
4096 * Are there equality operators that take exactly the FK type?
4097 * Assume we should look through any domain here.
4099 fktyped = getBaseType(fktype);
4101 pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
4103 if (OidIsValid(pfeqop))
4104 ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
4107 ffeqop = InvalidOid; /* keep compiler quiet */
4109 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4112 * Otherwise, look for an implicit cast from the FK type to
4113 * the opcintype, and if found, use the primary equality operator.
4114 * This is a bit tricky because opcintype might be a generic type
4115 * such as ANYARRAY, and so what we have to test is whether the
4116 * two actual column types can be concurrently cast to that type.
4117 * (Otherwise, we'd fail to reject combinations such as int[] and
4120 Oid input_typeids[2];
4121 Oid target_typeids[2];
4123 input_typeids[0] = pktype;
4124 input_typeids[1] = fktype;
4125 target_typeids[0] = opcintype;
4126 target_typeids[1] = opcintype;
4127 if (can_coerce_type(2, input_typeids, target_typeids,
4129 pfeqop = ffeqop = ppeqop;
4132 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4134 (errcode(ERRCODE_DATATYPE_MISMATCH),
4135 errmsg("foreign key constraint \"%s\" "
4136 "cannot be implemented",
4137 fkconstraint->constr_name),
4138 errdetail("Key columns \"%s\" and \"%s\" "
4139 "are of incompatible types: %s and %s.",
4140 strVal(list_nth(fkconstraint->fk_attrs, i)),
4141 strVal(list_nth(fkconstraint->pk_attrs, i)),
4142 format_type_be(fktype),
4143 format_type_be(pktype))));
4145 pfeqoperators[i] = pfeqop;
4146 ppeqoperators[i] = ppeqop;
4147 ffeqoperators[i] = ffeqop;
4151 * Record the FK constraint in pg_constraint.
4153 constrOid = CreateConstraintEntry(fkconstraint->constr_name,
4154 RelationGetNamespace(rel),
4156 fkconstraint->deferrable,
4157 fkconstraint->initdeferred,
4158 RelationGetRelid(rel),
4161 InvalidOid, /* not a domain
4163 RelationGetRelid(pkrel),
4169 fkconstraint->fk_upd_action,
4170 fkconstraint->fk_del_action,
4171 fkconstraint->fk_matchtype,
4173 NULL, /* no check constraint */
4178 * Create the triggers that will enforce the constraint.
4180 createForeignKeyTriggers(rel, fkconstraint, constrOid);
4183 * Tell Phase 3 to check that the constraint is satisfied by existing rows
4184 * (we can skip this during table creation).
4186 if (!fkconstraint->skip_validation)
4188 NewConstraint *newcon;
4190 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
4191 newcon->name = fkconstraint->constr_name;
4192 newcon->contype = CONSTR_FOREIGN;
4193 newcon->refrelid = RelationGetRelid(pkrel);
4194 newcon->conid = constrOid;
4195 newcon->qual = (Node *) fkconstraint;
4197 tab->constraints = lappend(tab->constraints, newcon);
4201 * Close pk table, but keep lock until we've committed.
4203 heap_close(pkrel, NoLock);
4208 * transformColumnNameList - transform list of column names
4210 * Lookup each name and return its attnum and type OID
4213 transformColumnNameList(Oid relId, List *colList,
4214 int16 *attnums, Oid *atttypids)
4222 char *attname = strVal(lfirst(l));
4225 atttuple = SearchSysCacheAttName(relId, attname);
4226 if (!HeapTupleIsValid(atttuple))
4228 (errcode(ERRCODE_UNDEFINED_COLUMN),
4229 errmsg("column \"%s\" referenced in foreign key constraint does not exist",
4231 if (attnum >= INDEX_MAX_KEYS)
4233 (errcode(ERRCODE_TOO_MANY_COLUMNS),
4234 errmsg("cannot have more than %d keys in a foreign key",
4236 attnums[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->attnum;
4237 atttypids[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->atttypid;
4238 ReleaseSysCache(atttuple);
4246 * transformFkeyGetPrimaryKey -
4248 * Look up the names, attnums, and types of the primary key attributes
4249 * for the pkrel. Also return the index OID and index opclasses of the
4250 * index supporting the primary key.
4252 * All parameters except pkrel are output parameters. Also, the function
4253 * return value is the number of attributes in the primary key.
4255 * Used when the column list in the REFERENCES specification is omitted.
4258 transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
4260 int16 *attnums, Oid *atttypids,
4264 ListCell *indexoidscan;
4265 HeapTuple indexTuple = NULL;
4266 Form_pg_index indexStruct = NULL;
4267 Datum indclassDatum;
4269 oidvector *indclass;
4273 * Get the list of index OIDs for the table from the relcache, and look up
4274 * each one in the pg_index syscache until we find one marked primary key
4275 * (hopefully there isn't more than one such).
4277 *indexOid = InvalidOid;
4279 indexoidlist = RelationGetIndexList(pkrel);
4281 foreach(indexoidscan, indexoidlist)
4283 Oid indexoid = lfirst_oid(indexoidscan);
4285 indexTuple = SearchSysCache(INDEXRELID,
4286 ObjectIdGetDatum(indexoid),
4288 if (!HeapTupleIsValid(indexTuple))
4289 elog(ERROR, "cache lookup failed for index %u", indexoid);
4290 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4291 if (indexStruct->indisprimary)
4293 *indexOid = indexoid;
4296 ReleaseSysCache(indexTuple);
4299 list_free(indexoidlist);
4302 * Check that we found it
4304 if (!OidIsValid(*indexOid))
4306 (errcode(ERRCODE_UNDEFINED_OBJECT),
4307 errmsg("there is no primary key for referenced table \"%s\"",
4308 RelationGetRelationName(pkrel))));
4310 /* Must get indclass the hard way */
4311 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4312 Anum_pg_index_indclass, &isnull);
4314 indclass = (oidvector *) DatumGetPointer(indclassDatum);
4317 * Now build the list of PK attributes from the indkey definition (we
4318 * assume a primary key cannot have expressional elements)
4321 for (i = 0; i < indexStruct->indnatts; i++)
4323 int pkattno = indexStruct->indkey.values[i];
4325 attnums[i] = pkattno;
4326 atttypids[i] = attnumTypeId(pkrel, pkattno);
4327 opclasses[i] = indclass->values[i];
4328 *attnamelist = lappend(*attnamelist,
4329 makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
4332 ReleaseSysCache(indexTuple);
4338 * transformFkeyCheckAttrs -
4340 * Make sure that the attributes of a referenced table belong to a unique
4341 * (or primary key) constraint. Return the OID of the index supporting
4342 * the constraint, as well as the opclasses associated with the index
4346 transformFkeyCheckAttrs(Relation pkrel,
4347 int numattrs, int16 *attnums,
4348 Oid *opclasses) /* output parameter */
4350 Oid indexoid = InvalidOid;
4353 ListCell *indexoidscan;
4356 * Get the list of index OIDs for the table from the relcache, and look up
4357 * each one in the pg_index syscache, and match unique indexes to the list
4358 * of attnums we are given.
4360 indexoidlist = RelationGetIndexList(pkrel);
4362 foreach(indexoidscan, indexoidlist)
4364 HeapTuple indexTuple;
4365 Form_pg_index indexStruct;
4369 indexoid = lfirst_oid(indexoidscan);
4370 indexTuple = SearchSysCache(INDEXRELID,
4371 ObjectIdGetDatum(indexoid),
4373 if (!HeapTupleIsValid(indexTuple))
4374 elog(ERROR, "cache lookup failed for index %u", indexoid);
4375 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4378 * Must have the right number of columns; must be unique and not a
4379 * partial index; forget it if there are any expressions, too
4381 if (indexStruct->indnatts == numattrs &&
4382 indexStruct->indisunique &&
4383 heap_attisnull(indexTuple, Anum_pg_index_indpred) &&
4384 heap_attisnull(indexTuple, Anum_pg_index_indexprs))
4386 /* Must get indclass the hard way */
4387 Datum indclassDatum;
4389 oidvector *indclass;
4391 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4392 Anum_pg_index_indclass, &isnull);
4394 indclass = (oidvector *) DatumGetPointer(indclassDatum);
4397 * The given attnum list may match the index columns in any order.
4398 * Check that each list is a subset of the other.
4400 for (i = 0; i < numattrs; i++)
4403 for (j = 0; j < numattrs; j++)
4405 if (attnums[i] == indexStruct->indkey.values[j])
4416 for (i = 0; i < numattrs; i++)
4419 for (j = 0; j < numattrs; j++)
4421 if (attnums[j] == indexStruct->indkey.values[i])
4423 opclasses[j] = indclass->values[i];
4433 ReleaseSysCache(indexTuple);
4440 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4441 errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
4442 RelationGetRelationName(pkrel))));
4444 list_free(indexoidlist);
4450 * Scan the existing rows in a table to verify they meet a proposed FK
4453 * Caller must have opened and locked both relations.
4456 validateForeignKeyConstraint(FkConstraint *fkconstraint,
4466 * Build a trigger call structure; we'll need it either way.
4468 MemSet(&trig, 0, sizeof(trig));
4469 trig.tgoid = InvalidOid;
4470 trig.tgname = fkconstraint->constr_name;
4471 trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
4472 trig.tgisconstraint = TRUE;
4473 trig.tgconstrrelid = RelationGetRelid(pkrel);
4474 trig.tgconstraint = constraintOid;
4475 trig.tgdeferrable = FALSE;
4476 trig.tginitdeferred = FALSE;
4477 /* we needn't fill in tgargs */
4480 * See if we can do it with a single LEFT JOIN query. A FALSE result
4481 * indicates we must proceed with the fire-the-trigger method.
4483 if (RI_Initial_Check(&trig, rel, pkrel))
4487 * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
4488 * if that tuple had just been inserted. If any of those fail, it should
4489 * ereport(ERROR) and that's that.
4491 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
4493 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
4495 FunctionCallInfoData fcinfo;
4496 TriggerData trigdata;
4499 * Make a call to the trigger function
4501 * No parameters are passed, but we do set a context
4503 MemSet(&fcinfo, 0, sizeof(fcinfo));
4506 * We assume RI_FKey_check_ins won't look at flinfo...
4508 trigdata.type = T_TriggerData;
4509 trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
4510 trigdata.tg_relation = rel;
4511 trigdata.tg_trigtuple = tuple;
4512 trigdata.tg_newtuple = NULL;
4513 trigdata.tg_trigger = &trig;
4514 trigdata.tg_trigtuplebuf = scan->rs_cbuf;
4515 trigdata.tg_newtuplebuf = InvalidBuffer;
4517 fcinfo.context = (Node *) &trigdata;
4519 RI_FKey_check_ins(&fcinfo);
4526 CreateFKCheckTrigger(RangeVar *myRel, FkConstraint *fkconstraint,
4527 Oid constraintOid, bool on_insert)
4529 CreateTrigStmt *fk_trigger;
4531 fk_trigger = makeNode(CreateTrigStmt);
4532 fk_trigger->trigname = fkconstraint->constr_name;
4533 fk_trigger->relation = myRel;
4534 fk_trigger->before = false;
4535 fk_trigger->row = true;
4537 /* Either ON INSERT or ON UPDATE */
4540 fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
4541 fk_trigger->actions[0] = 'i';
4545 fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
4546 fk_trigger->actions[0] = 'u';
4548 fk_trigger->actions[1] = '\0';
4550 fk_trigger->isconstraint = true;
4551 fk_trigger->deferrable = fkconstraint->deferrable;
4552 fk_trigger->initdeferred = fkconstraint->initdeferred;
4553 fk_trigger->constrrel = fkconstraint->pktable;
4554 fk_trigger->args = NIL;
4556 (void) CreateTrigger(fk_trigger, constraintOid);
4558 /* Make changes-so-far visible */
4559 CommandCounterIncrement();
4563 * Create the triggers that implement an FK constraint.
4566 createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
4570 CreateTrigStmt *fk_trigger;
4573 * Reconstruct a RangeVar for my relation (not passed in, unfortunately).
4575 myRel = makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
4576 pstrdup(RelationGetRelationName(rel)));
4578 /* Make changes-so-far visible */
4579 CommandCounterIncrement();
4582 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the CHECK
4583 * action for both INSERTs and UPDATEs on the referencing table.
4585 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, true);
4586 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, false);
4589 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
4590 * DELETE action on the referenced table.
4592 fk_trigger = makeNode(CreateTrigStmt);
4593 fk_trigger->trigname = fkconstraint->constr_name;
4594 fk_trigger->relation = fkconstraint->pktable;
4595 fk_trigger->before = false;
4596 fk_trigger->row = true;
4597 fk_trigger->actions[0] = 'd';
4598 fk_trigger->actions[1] = '\0';
4600 fk_trigger->isconstraint = true;
4601 fk_trigger->constrrel = myRel;
4602 switch (fkconstraint->fk_del_action)
4604 case FKCONSTR_ACTION_NOACTION:
4605 fk_trigger->deferrable = fkconstraint->deferrable;
4606 fk_trigger->initdeferred = fkconstraint->initdeferred;
4607 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
4609 case FKCONSTR_ACTION_RESTRICT:
4610 fk_trigger->deferrable = false;
4611 fk_trigger->initdeferred = false;
4612 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
4614 case FKCONSTR_ACTION_CASCADE:
4615 fk_trigger->deferrable = false;
4616 fk_trigger->initdeferred = false;
4617 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
4619 case FKCONSTR_ACTION_SETNULL:
4620 fk_trigger->deferrable = false;
4621 fk_trigger->initdeferred = false;
4622 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
4624 case FKCONSTR_ACTION_SETDEFAULT:
4625 fk_trigger->deferrable = false;
4626 fk_trigger->initdeferred = false;
4627 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
4630 elog(ERROR, "unrecognized FK action type: %d",
4631 (int) fkconstraint->fk_del_action);
4634 fk_trigger->args = NIL;
4636 (void) CreateTrigger(fk_trigger, constraintOid);
4638 /* Make changes-so-far visible */
4639 CommandCounterIncrement();
4642 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
4643 * UPDATE action on the referenced table.
4645 fk_trigger = makeNode(CreateTrigStmt);
4646 fk_trigger->trigname = fkconstraint->constr_name;
4647 fk_trigger->relation = fkconstraint->pktable;
4648 fk_trigger->before = false;
4649 fk_trigger->row = true;
4650 fk_trigger->actions[0] = 'u';
4651 fk_trigger->actions[1] = '\0';
4652 fk_trigger->isconstraint = true;
4653 fk_trigger->constrrel = myRel;
4654 switch (fkconstraint->fk_upd_action)
4656 case FKCONSTR_ACTION_NOACTION:
4657 fk_trigger->deferrable = fkconstraint->deferrable;
4658 fk_trigger->initdeferred = fkconstraint->initdeferred;
4659 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
4661 case FKCONSTR_ACTION_RESTRICT:
4662 fk_trigger->deferrable = false;
4663 fk_trigger->initdeferred = false;
4664 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
4666 case FKCONSTR_ACTION_CASCADE:
4667 fk_trigger->deferrable = false;
4668 fk_trigger->initdeferred = false;
4669 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
4671 case FKCONSTR_ACTION_SETNULL:
4672 fk_trigger->deferrable = false;
4673 fk_trigger->initdeferred = false;
4674 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
4676 case FKCONSTR_ACTION_SETDEFAULT:
4677 fk_trigger->deferrable = false;
4678 fk_trigger->initdeferred = false;
4679 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
4682 elog(ERROR, "unrecognized FK action type: %d",
4683 (int) fkconstraint->fk_upd_action);
4686 fk_trigger->args = NIL;
4688 (void) CreateTrigger(fk_trigger, constraintOid);
4692 * ALTER TABLE DROP CONSTRAINT
4695 ATPrepDropConstraint(List **wqueue, Relation rel,
4696 bool recurse, AlterTableCmd *cmd)
4699 * We don't want errors or noise from child tables, so we have to pass
4700 * down a modified command.
4704 AlterTableCmd *childCmd = copyObject(cmd);
4706 childCmd->subtype = AT_DropConstraintQuietly;
4707 ATSimpleRecursion(wqueue, rel, childCmd, recurse);
4712 ATExecDropConstraint(Relation rel, const char *constrName,
4713 DropBehavior behavior, bool quiet)
4717 deleted = RemoveRelConstraints(rel, constrName, behavior);
4721 /* If zero constraints deleted, complain */
4724 (errcode(ERRCODE_UNDEFINED_OBJECT),
4725 errmsg("constraint \"%s\" does not exist",
4727 /* Otherwise if more than one constraint deleted, notify */
4728 else if (deleted > 1)
4730 (errmsg("multiple constraints named \"%s\" were dropped",
4739 ATPrepAlterColumnType(List **wqueue,
4740 AlteredTableInfo *tab, Relation rel,
4741 bool recurse, bool recursing,
4744 char *colName = cmd->name;
4745 TypeName *typename = (TypeName *) cmd->def;
4747 Form_pg_attribute attTup;
4752 NewColumnValue *newval;
4753 ParseState *pstate = make_parsestate(NULL);
4755 /* lookup the attribute so we can check inheritance status */
4756 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
4757 if (!HeapTupleIsValid(tuple))
4759 (errcode(ERRCODE_UNDEFINED_COLUMN),
4760 errmsg("column \"%s\" of relation \"%s\" does not exist",
4761 colName, RelationGetRelationName(rel))));
4762 attTup = (Form_pg_attribute) GETSTRUCT(tuple);
4763 attnum = attTup->attnum;
4765 /* Can't alter a system attribute */
4768 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4769 errmsg("cannot alter system column \"%s\"",
4772 /* Don't alter inherited columns */
4773 if (attTup->attinhcount > 0 && !recursing)
4775 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4776 errmsg("cannot alter inherited column \"%s\"",
4779 /* Look up the target type */
4780 targettype = typenameTypeId(NULL, typename);
4781 targettypmod = typenameTypeMod(NULL, typename, targettype);
4783 /* make sure datatype is legal for a column */
4784 CheckAttributeType(colName, targettype);
4787 * Set up an expression to transform the old data value to the new type.
4788 * If a USING option was given, transform and use that expression, else
4789 * just take the old value and try to coerce it. We do this first so that
4790 * type incompatibility can be detected before we waste effort, and
4791 * because we need the expression to be parsed against the original table
4798 /* Expression must be able to access vars of old table */
4799 rte = addRangeTableEntryForRelation(pstate,
4804 addRTEtoQuery(pstate, rte, false, true, true);
4806 transform = transformExpr(pstate, cmd->transform);
4808 /* It can't return a set */
4809 if (expression_returns_set(transform))
4811 (errcode(ERRCODE_DATATYPE_MISMATCH),
4812 errmsg("transform expression must not return a set")));
4814 /* No subplans or aggregates, either... */
4815 if (pstate->p_hasSubLinks)
4817 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4818 errmsg("cannot use subquery in transform expression")));
4819 if (pstate->p_hasAggs)
4821 (errcode(ERRCODE_GROUPING_ERROR),
4822 errmsg("cannot use aggregate function in transform expression")));
4826 transform = (Node *) makeVar(1, attnum,
4827 attTup->atttypid, attTup->atttypmod,
4831 transform = coerce_to_target_type(pstate,
4832 transform, exprType(transform),
4833 targettype, targettypmod,
4834 COERCION_ASSIGNMENT,
4835 COERCE_IMPLICIT_CAST);
4836 if (transform == NULL)
4838 (errcode(ERRCODE_DATATYPE_MISMATCH),
4839 errmsg("column \"%s\" cannot be cast to type \"%s\"",
4840 colName, TypeNameToString(typename))));
4843 * Add a work queue item to make ATRewriteTable update the column
4846 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
4847 newval->attnum = attnum;
4848 newval->expr = (Expr *) transform;
4850 tab->newvals = lappend(tab->newvals, newval);
4852 ReleaseSysCache(tuple);
4855 * The recursion case is handled by ATSimpleRecursion. However, if we are
4856 * told not to recurse, there had better not be any child tables; else the
4857 * alter would put them out of step.
4860 ATSimpleRecursion(wqueue, rel, cmd, recurse);
4861 else if (!recursing &&
4862 find_inheritance_children(RelationGetRelid(rel)) != NIL)
4864 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4865 errmsg("type of inherited column \"%s\" must be changed in child tables too",
4870 ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
4871 const char *colName, TypeName *typename)
4874 Form_pg_attribute attTup;
4876 HeapTuple typeTuple;
4881 Relation attrelation;
4887 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
4889 /* Look up the target column */
4890 heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4891 if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
4893 (errcode(ERRCODE_UNDEFINED_COLUMN),
4894 errmsg("column \"%s\" of relation \"%s\" does not exist",
4895 colName, RelationGetRelationName(rel))));
4896 attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
4897 attnum = attTup->attnum;
4899 /* Check for multiple ALTER TYPE on same column --- can't cope */
4900 if (attTup->atttypid != tab->oldDesc->attrs[attnum - 1]->atttypid ||
4901 attTup->atttypmod != tab->oldDesc->attrs[attnum - 1]->atttypmod)
4903 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4904 errmsg("cannot alter type of column \"%s\" twice",
4907 /* Look up the target type (should not fail, since prep found it) */
4908 typeTuple = typenameType(NULL, typename);
4909 tform = (Form_pg_type) GETSTRUCT(typeTuple);
4910 targettype = HeapTupleGetOid(typeTuple);
4911 targettypmod = typenameTypeMod(NULL, typename, targettype);
4914 * If there is a default expression for the column, get it and ensure we
4915 * can coerce it to the new datatype. (We must do this before changing
4916 * the column type, because build_column_default itself will try to
4917 * coerce, and will not issue the error message we want if it fails.)
4919 * We remove any implicit coercion steps at the top level of the old
4920 * default expression; this has been agreed to satisfy the principle of
4921 * least surprise. (The conversion to the new column type should act like
4922 * it started from what the user sees as the stored expression, and the
4923 * implicit coercions aren't going to be shown.)
4925 if (attTup->atthasdef)
4927 defaultexpr = build_column_default(rel, attnum);
4928 Assert(defaultexpr);
4929 defaultexpr = strip_implicit_coercions(defaultexpr);
4930 defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
4931 defaultexpr, exprType(defaultexpr),
4932 targettype, targettypmod,
4933 COERCION_ASSIGNMENT,
4934 COERCE_IMPLICIT_CAST);
4935 if (defaultexpr == NULL)
4937 (errcode(ERRCODE_DATATYPE_MISMATCH),
4938 errmsg("default for column \"%s\" cannot be cast to type \"%s\"",
4939 colName, TypeNameToString(typename))));
4945 * Find everything that depends on the column (constraints, indexes, etc),
4946 * and record enough information to let us recreate the objects.
4948 * The actual recreation does not happen here, but only after we have
4949 * performed all the individual ALTER TYPE operations. We have to save
4950 * the info before executing ALTER TYPE, though, else the deparser will
4953 * There could be multiple entries for the same object, so we must check
4954 * to ensure we process each one only once. Note: we assume that an index
4955 * that implements a constraint will not show a direct dependency on the
4958 depRel = heap_open(DependRelationId, RowExclusiveLock);
4960 ScanKeyInit(&key[0],
4961 Anum_pg_depend_refclassid,
4962 BTEqualStrategyNumber, F_OIDEQ,
4963 ObjectIdGetDatum(RelationRelationId));
4964 ScanKeyInit(&key[1],
4965 Anum_pg_depend_refobjid,
4966 BTEqualStrategyNumber, F_OIDEQ,
4967 ObjectIdGetDatum(RelationGetRelid(rel)));
4968 ScanKeyInit(&key[2],
4969 Anum_pg_depend_refobjsubid,
4970 BTEqualStrategyNumber, F_INT4EQ,
4971 Int32GetDatum((int32) attnum));
4973 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
4974 SnapshotNow, 3, key);
4976 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
4978 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
4979 ObjectAddress foundObject;
4981 /* We don't expect any PIN dependencies on columns */
4982 if (foundDep->deptype == DEPENDENCY_PIN)
4983 elog(ERROR, "cannot alter type of a pinned column");
4985 foundObject.classId = foundDep->classid;
4986 foundObject.objectId = foundDep->objid;
4987 foundObject.objectSubId = foundDep->objsubid;
4989 switch (getObjectClass(&foundObject))
4993 char relKind = get_rel_relkind(foundObject.objectId);
4995 if (relKind == RELKIND_INDEX)
4997 Assert(foundObject.objectSubId == 0);
4998 if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
5000 tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
5001 foundObject.objectId);
5002 tab->changedIndexDefs = lappend(tab->changedIndexDefs,
5003 pg_get_indexdef_string(foundObject.objectId));
5006 else if (relKind == RELKIND_SEQUENCE)
5009 * This must be a SERIAL column's sequence. We need
5010 * not do anything to it.
5012 Assert(foundObject.objectSubId == 0);
5016 /* Not expecting any other direct dependencies... */
5017 elog(ERROR, "unexpected object depending on column: %s",
5018 getObjectDescription(&foundObject));
5023 case OCLASS_CONSTRAINT:
5024 Assert(foundObject.objectSubId == 0);
5025 if (!list_member_oid(tab->changedConstraintOids,
5026 foundObject.objectId))
5028 char *defstring = pg_get_constraintdef_string(foundObject.objectId);
5031 * Put NORMAL dependencies at the front of the list and
5032 * AUTO dependencies at the back. This makes sure that
5033 * foreign-key constraints depending on this column will
5034 * be dropped before unique or primary-key constraints of
5035 * the column; which we must have because the FK
5036 * constraints depend on the indexes belonging to the
5037 * unique constraints.
5039 if (foundDep->deptype == DEPENDENCY_NORMAL)
5041 tab->changedConstraintOids =
5042 lcons_oid(foundObject.objectId,
5043 tab->changedConstraintOids);
5044 tab->changedConstraintDefs =
5046 tab->changedConstraintDefs);
5050 tab->changedConstraintOids =
5051 lappend_oid(tab->changedConstraintOids,
5052 foundObject.objectId);
5053 tab->changedConstraintDefs =
5054 lappend(tab->changedConstraintDefs,
5060 case OCLASS_REWRITE:
5061 /* XXX someday see if we can cope with revising views */
5063 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5064 errmsg("cannot alter type of a column used by a view or rule"),
5065 errdetail("%s depends on column \"%s\"",
5066 getObjectDescription(&foundObject),
5070 case OCLASS_DEFAULT:
5073 * Ignore the column's default expression, since we will fix
5076 Assert(defaultexpr);
5082 case OCLASS_CONVERSION:
5083 case OCLASS_LANGUAGE:
5084 case OCLASS_OPERATOR:
5085 case OCLASS_OPCLASS:
5086 case OCLASS_OPFAMILY:
5087 case OCLASS_TRIGGER:
5089 case OCLASS_TSPARSER:
5091 case OCLASS_TSTEMPLATE:
5092 case OCLASS_TSCONFIG:
5095 * We don't expect any of these sorts of objects to depend on
5098 elog(ERROR, "unexpected object depending on column: %s",
5099 getObjectDescription(&foundObject));
5103 elog(ERROR, "unrecognized object class: %u",
5104 foundObject.classId);
5108 systable_endscan(scan);
5111 * Now scan for dependencies of this column on other things. The only
5112 * thing we should find is the dependency on the column datatype, which we
5115 ScanKeyInit(&key[0],
5116 Anum_pg_depend_classid,
5117 BTEqualStrategyNumber, F_OIDEQ,
5118 ObjectIdGetDatum(RelationRelationId));
5119 ScanKeyInit(&key[1],
5120 Anum_pg_depend_objid,
5121 BTEqualStrategyNumber, F_OIDEQ,
5122 ObjectIdGetDatum(RelationGetRelid(rel)));
5123 ScanKeyInit(&key[2],
5124 Anum_pg_depend_objsubid,
5125 BTEqualStrategyNumber, F_INT4EQ,
5126 Int32GetDatum((int32) attnum));
5128 scan = systable_beginscan(depRel, DependDependerIndexId, true,
5129 SnapshotNow, 3, key);
5131 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5133 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5135 if (foundDep->deptype != DEPENDENCY_NORMAL)
5136 elog(ERROR, "found unexpected dependency type '%c'",
5138 if (foundDep->refclassid != TypeRelationId ||
5139 foundDep->refobjid != attTup->atttypid)
5140 elog(ERROR, "found unexpected dependency for column");
5142 simple_heap_delete(depRel, &depTup->t_self);
5145 systable_endscan(scan);
5147 heap_close(depRel, RowExclusiveLock);
5150 * Here we go --- change the recorded column type. (Note heapTup is a
5151 * copy of the syscache entry, so okay to scribble on.)
5153 attTup->atttypid = targettype;
5154 attTup->atttypmod = targettypmod;
5155 attTup->attndims = list_length(typename->arrayBounds);
5156 attTup->attlen = tform->typlen;
5157 attTup->attbyval = tform->typbyval;
5158 attTup->attalign = tform->typalign;
5159 attTup->attstorage = tform->typstorage;
5161 ReleaseSysCache(typeTuple);
5163 simple_heap_update(attrelation, &heapTup->t_self, heapTup);
5165 /* keep system catalog indexes current */
5166 CatalogUpdateIndexes(attrelation, heapTup);
5168 heap_close(attrelation, RowExclusiveLock);
5170 /* Install dependency on new datatype */
5171 add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
5174 * Drop any pg_statistic entry for the column, since it's now wrong type
5176 RemoveStatistics(RelationGetRelid(rel), attnum);
5179 * Update the default, if present, by brute force --- remove and re-add
5180 * the default. Probably unsafe to take shortcuts, since the new version
5181 * may well have additional dependencies. (It's okay to do this now,
5182 * rather than after other ALTER TYPE commands, since the default won't
5183 * depend on other column types.)
5187 /* Must make new row visible since it will be updated again */
5188 CommandCounterIncrement();
5191 * We use RESTRICT here for safety, but at present we do not expect
5192 * anything to depend on the default.
5194 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true);
5196 StoreAttrDefault(rel, attnum, nodeToString(defaultexpr));
5200 heap_freetuple(heapTup);
5204 * Cleanup after we've finished all the ALTER TYPE operations for a
5205 * particular relation. We have to drop and recreate all the indexes
5206 * and constraints that depend on the altered columns.
5209 ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab)
5215 * Re-parse the index and constraint definitions, and attach them to the
5216 * appropriate work queue entries. We do this before dropping because in
5217 * the case of a FOREIGN KEY constraint, we might not yet have exclusive
5218 * lock on the table the constraint is attached to, and we need to get
5219 * that before dropping. It's safe because the parser won't actually look
5220 * at the catalogs to detect the existing entry.
5222 foreach(l, tab->changedIndexDefs)
5223 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
5224 foreach(l, tab->changedConstraintDefs)
5225 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
5228 * Now we can drop the existing constraints and indexes --- constraints
5229 * first, since some of them might depend on the indexes. In fact, we
5230 * have to delete FOREIGN KEY constraints before UNIQUE constraints, but
5231 * we already ordered the constraint list to ensure that would happen. It
5232 * should be okay to use DROP_RESTRICT here, since nothing else should be
5233 * depending on these objects.
5235 foreach(l, tab->changedConstraintOids)
5237 obj.classId = ConstraintRelationId;
5238 obj.objectId = lfirst_oid(l);
5239 obj.objectSubId = 0;
5240 performDeletion(&obj, DROP_RESTRICT);
5243 foreach(l, tab->changedIndexOids)
5245 obj.classId = RelationRelationId;
5246 obj.objectId = lfirst_oid(l);
5247 obj.objectSubId = 0;
5248 performDeletion(&obj, DROP_RESTRICT);
5252 * The objects will get recreated during subsequent passes over the work
5258 ATPostAlterTypeParse(char *cmd, List **wqueue)
5260 List *raw_parsetree_list;
5261 List *querytree_list;
5262 ListCell *list_item;
5265 * We expect that we will get only ALTER TABLE and CREATE INDEX statements.
5266 * Hence, there is no need to pass them through parse_analyze() or the
5267 * rewriter, but instead we need to pass them through parse_utilcmd.c
5268 * to make them ready for execution.
5270 raw_parsetree_list = raw_parser(cmd);
5271 querytree_list = NIL;
5272 foreach(list_item, raw_parsetree_list)
5274 Node *stmt = (Node *) lfirst(list_item);
5276 if (IsA(stmt, IndexStmt))
5277 querytree_list = lappend(querytree_list,
5278 transformIndexStmt((IndexStmt *) stmt,
5280 else if (IsA(stmt, AlterTableStmt))
5281 querytree_list = list_concat(querytree_list,
5282 transformAlterTableStmt((AlterTableStmt *) stmt,
5285 querytree_list = lappend(querytree_list, stmt);
5289 * Attach each generated command to the proper place in the work queue.
5290 * Note this could result in creation of entirely new work-queue entries.
5292 foreach(list_item, querytree_list)
5294 Node *stm = (Node *) lfirst(list_item);
5296 AlteredTableInfo *tab;
5298 switch (nodeTag(stm))
5302 IndexStmt *stmt = (IndexStmt *) stm;
5303 AlterTableCmd *newcmd;
5305 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
5306 tab = ATGetQueueEntry(wqueue, rel);
5307 newcmd = makeNode(AlterTableCmd);
5308 newcmd->subtype = AT_ReAddIndex;
5309 newcmd->def = (Node *) stmt;
5310 tab->subcmds[AT_PASS_OLD_INDEX] =
5311 lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
5312 relation_close(rel, NoLock);
5315 case T_AlterTableStmt:
5317 AlterTableStmt *stmt = (AlterTableStmt *) stm;
5320 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
5321 tab = ATGetQueueEntry(wqueue, rel);
5322 foreach(lcmd, stmt->cmds)
5324 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
5326 switch (cmd->subtype)
5329 cmd->subtype = AT_ReAddIndex;
5330 tab->subcmds[AT_PASS_OLD_INDEX] =
5331 lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
5333 case AT_AddConstraint:
5334 tab->subcmds[AT_PASS_OLD_CONSTR] =
5335 lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
5338 elog(ERROR, "unexpected statement type: %d",
5339 (int) cmd->subtype);
5342 relation_close(rel, NoLock);
5346 elog(ERROR, "unexpected statement type: %d",
5347 (int) nodeTag(stm));
5356 * recursing is true if we are recursing from a table to its indexes,
5357 * sequences, or toast table. We don't allow the ownership of those things to
5358 * be changed separately from the parent table. Also, we can skip permission
5359 * checks (this is necessary not just an optimization, else we'd fail to
5360 * handle toast tables properly).
5362 * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
5363 * free-standing composite type.
5366 ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing)
5368 Relation target_rel;
5371 Form_pg_class tuple_class;
5374 * Get exclusive lock till end of transaction on the target table. Use
5375 * relation_open so that we can work on indexes and sequences.
5377 target_rel = relation_open(relationOid, AccessExclusiveLock);
5379 /* Get its pg_class tuple, too */
5380 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
5382 tuple = SearchSysCache(RELOID,
5383 ObjectIdGetDatum(relationOid),
5385 if (!HeapTupleIsValid(tuple))
5386 elog(ERROR, "cache lookup failed for relation %u", relationOid);
5387 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
5389 /* Can we change the ownership of this tuple? */
5390 switch (tuple_class->relkind)
5392 case RELKIND_RELATION:
5394 /* ok to change owner */
5400 * Because ALTER INDEX OWNER used to be allowed, and in fact
5401 * is generated by old versions of pg_dump, we give a warning
5402 * and do nothing rather than erroring out. Also, to avoid
5403 * unnecessary chatter while restoring those old dumps, say
5404 * nothing at all if the command would be a no-op anyway.
5406 if (tuple_class->relowner != newOwnerId)
5408 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5409 errmsg("cannot change owner of index \"%s\"",
5410 NameStr(tuple_class->relname)),
5411 errhint("Change the ownership of the index's table, instead.")));
5412 /* quick hack to exit via the no-op path */
5413 newOwnerId = tuple_class->relowner;
5416 case RELKIND_SEQUENCE:
5418 tuple_class->relowner != newOwnerId)
5420 /* if it's an owned sequence, disallow changing it by itself */
5424 if (sequenceIsOwned(relationOid, &tableId, &colId))
5426 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5427 errmsg("cannot change owner of sequence \"%s\"",
5428 NameStr(tuple_class->relname)),
5429 errdetail("Sequence \"%s\" is linked to table \"%s\".",
5430 NameStr(tuple_class->relname),
5431 get_rel_name(tableId))));
5434 case RELKIND_COMPOSITE_TYPE:
5438 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5439 errmsg("\"%s\" is a composite type",
5440 NameStr(tuple_class->relname)),
5441 errhint("Use ALTER TYPE instead.")));
5443 case RELKIND_TOASTVALUE:
5449 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5450 errmsg("\"%s\" is not a table, view, or sequence",
5451 NameStr(tuple_class->relname))));
5455 * If the new owner is the same as the existing owner, consider the
5456 * command to have succeeded. This is for dump restoration purposes.
5458 if (tuple_class->relowner != newOwnerId)
5460 Datum repl_val[Natts_pg_class];
5461 char repl_null[Natts_pg_class];
5462 char repl_repl[Natts_pg_class];
5468 /* skip permission checks when recursing to index or toast table */
5471 /* Superusers can always do it */
5474 Oid namespaceOid = tuple_class->relnamespace;
5475 AclResult aclresult;
5477 /* Otherwise, must be owner of the existing object */
5478 if (!pg_class_ownercheck(relationOid, GetUserId()))
5479 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
5480 RelationGetRelationName(target_rel));
5482 /* Must be able to become new owner */
5483 check_is_member_of_role(GetUserId(), newOwnerId);
5485 /* New owner must have CREATE privilege on namespace */
5486 aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
5488 if (aclresult != ACLCHECK_OK)
5489 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
5490 get_namespace_name(namespaceOid));
5494 memset(repl_null, ' ', sizeof(repl_null));
5495 memset(repl_repl, ' ', sizeof(repl_repl));
5497 repl_repl[Anum_pg_class_relowner - 1] = 'r';
5498 repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
5501 * Determine the modified ACL for the new owner. This is only
5502 * necessary when the ACL is non-null.
5504 aclDatum = SysCacheGetAttr(RELOID, tuple,
5505 Anum_pg_class_relacl,
5509 newAcl = aclnewowner(DatumGetAclP(aclDatum),
5510 tuple_class->relowner, newOwnerId);
5511 repl_repl[Anum_pg_class_relacl - 1] = 'r';
5512 repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
5515 newtuple = heap_modifytuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
5517 simple_heap_update(class_rel, &newtuple->t_self, newtuple);
5518 CatalogUpdateIndexes(class_rel, newtuple);
5520 heap_freetuple(newtuple);
5523 * Update owner dependency reference, if any. A composite type has
5524 * none, because it's tracked for the pg_type entry instead of here;
5525 * indexes and TOAST tables don't have their own entries either.
5527 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
5528 tuple_class->relkind != RELKIND_INDEX &&
5529 tuple_class->relkind != RELKIND_TOASTVALUE)
5530 changeDependencyOnOwner(RelationRelationId, relationOid,
5534 * Also change the ownership of the table's rowtype, if it has one
5536 if (tuple_class->relkind != RELKIND_INDEX)
5537 AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId,
5538 tuple_class->relkind == RELKIND_COMPOSITE_TYPE);
5541 * If we are operating on a table, also change the ownership of any
5542 * indexes and sequences that belong to the table, as well as the
5543 * table's toast table (if it has one)
5545 if (tuple_class->relkind == RELKIND_RELATION ||
5546 tuple_class->relkind == RELKIND_TOASTVALUE)
5548 List *index_oid_list;
5551 /* Find all the indexes belonging to this relation */
5552 index_oid_list = RelationGetIndexList(target_rel);
5554 /* For each index, recursively change its ownership */
5555 foreach(i, index_oid_list)
5556 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true);
5558 list_free(index_oid_list);
5561 if (tuple_class->relkind == RELKIND_RELATION)
5563 /* If it has a toast table, recurse to change its ownership */
5564 if (tuple_class->reltoastrelid != InvalidOid)
5565 ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
5568 /* If it has dependent sequences, recurse to change them too */
5569 change_owner_recurse_to_sequences(relationOid, newOwnerId);
5573 ReleaseSysCache(tuple);
5574 heap_close(class_rel, RowExclusiveLock);
5575 relation_close(target_rel, NoLock);
5579 * change_owner_recurse_to_sequences
5581 * Helper function for ATExecChangeOwner. Examines pg_depend searching
5582 * for sequences that are dependent on serial columns, and changes their
5586 change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId)
5594 * SERIAL sequences are those having an auto dependency on one of the
5595 * table's columns (we don't care *which* column, exactly).
5597 depRel = heap_open(DependRelationId, AccessShareLock);
5599 ScanKeyInit(&key[0],
5600 Anum_pg_depend_refclassid,
5601 BTEqualStrategyNumber, F_OIDEQ,
5602 ObjectIdGetDatum(RelationRelationId));
5603 ScanKeyInit(&key[1],
5604 Anum_pg_depend_refobjid,
5605 BTEqualStrategyNumber, F_OIDEQ,
5606 ObjectIdGetDatum(relationOid));
5607 /* we leave refobjsubid unspecified */
5609 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
5610 SnapshotNow, 2, key);
5612 while (HeapTupleIsValid(tup = systable_getnext(scan)))
5614 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
5617 /* skip dependencies other than auto dependencies on columns */
5618 if (depForm->refobjsubid == 0 ||
5619 depForm->classid != RelationRelationId ||
5620 depForm->objsubid != 0 ||
5621 depForm->deptype != DEPENDENCY_AUTO)
5624 /* Use relation_open just in case it's an index */
5625 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
5627 /* skip non-sequence relations */
5628 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
5630 /* No need to keep the lock */
5631 relation_close(seqRel, AccessExclusiveLock);
5635 /* We don't need to close the sequence while we alter it. */
5636 ATExecChangeOwner(depForm->objid, newOwnerId, true);
5638 /* Now we can close it. Keep the lock till end of transaction. */
5639 relation_close(seqRel, NoLock);
5642 systable_endscan(scan);
5644 relation_close(depRel, AccessShareLock);
5648 * ALTER TABLE CLUSTER ON
5650 * The only thing we have to do is to change the indisclustered bits.
5653 ATExecClusterOn(Relation rel, const char *indexName)
5657 indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
5659 if (!OidIsValid(indexOid))
5661 (errcode(ERRCODE_UNDEFINED_OBJECT),
5662 errmsg("index \"%s\" for table \"%s\" does not exist",
5663 indexName, RelationGetRelationName(rel))));
5665 /* Check index is valid to cluster on */
5666 check_index_is_clusterable(rel, indexOid, false);
5668 /* And do the work */
5669 mark_index_clustered(rel, indexOid);
5673 * ALTER TABLE SET WITHOUT CLUSTER
5675 * We have to find any indexes on the table that have indisclustered bit
5676 * set and turn it off.
5679 ATExecDropCluster(Relation rel)
5681 mark_index_clustered(rel, InvalidOid);
5685 * ALTER TABLE SET TABLESPACE
5688 ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, char *tablespacename)
5691 AclResult aclresult;
5693 /* Check that the tablespace exists */
5694 tablespaceId = get_tablespace_oid(tablespacename);
5695 if (!OidIsValid(tablespaceId))
5697 (errcode(ERRCODE_UNDEFINED_OBJECT),
5698 errmsg("tablespace \"%s\" does not exist", tablespacename)));
5700 /* Check its permissions */
5701 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(), ACL_CREATE);
5702 if (aclresult != ACLCHECK_OK)
5703 aclcheck_error(aclresult, ACL_KIND_TABLESPACE, tablespacename);
5705 /* Save info for Phase 3 to do the real work */
5706 if (OidIsValid(tab->newTableSpace))
5708 (errcode(ERRCODE_SYNTAX_ERROR),
5709 errmsg("cannot have multiple SET TABLESPACE subcommands")));
5710 tab->newTableSpace = tablespaceId;
5714 * ALTER TABLE/INDEX SET (...) or RESET (...)
5717 ATExecSetRelOptions(Relation rel, List *defList, bool isReset)
5726 Datum repl_val[Natts_pg_class];
5727 char repl_null[Natts_pg_class];
5728 char repl_repl[Natts_pg_class];
5731 return; /* nothing to do */
5733 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
5735 /* Get the old reloptions */
5736 relid = RelationGetRelid(rel);
5737 tuple = SearchSysCache(RELOID,
5738 ObjectIdGetDatum(relid),
5740 if (!HeapTupleIsValid(tuple))
5741 elog(ERROR, "cache lookup failed for relation %u", relid);
5743 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions, &isnull);
5745 /* Generate new proposed reloptions (text array) */
5746 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
5747 defList, false, isReset);
5750 switch (rel->rd_rel->relkind)
5752 case RELKIND_RELATION:
5753 case RELKIND_TOASTVALUE:
5754 (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
5757 (void) index_reloptions(rel->rd_am->amoptions, newOptions, true);
5761 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5762 errmsg("\"%s\" is not a table, index, or TOAST table",
5763 RelationGetRelationName(rel))));
5768 * All we need do here is update the pg_class row; the new options will be
5769 * propagated into relcaches during post-commit cache inval.
5771 memset(repl_val, 0, sizeof(repl_val));
5772 memset(repl_null, ' ', sizeof(repl_null));
5773 memset(repl_repl, ' ', sizeof(repl_repl));
5775 if (newOptions != (Datum) 0)
5776 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
5778 repl_null[Anum_pg_class_reloptions - 1] = 'n';
5780 repl_repl[Anum_pg_class_reloptions - 1] = 'r';
5782 newtuple = heap_modifytuple(tuple, RelationGetDescr(pgclass),
5783 repl_val, repl_null, repl_repl);
5785 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
5787 CatalogUpdateIndexes(pgclass, newtuple);
5789 heap_freetuple(newtuple);
5791 ReleaseSysCache(tuple);
5793 heap_close(pgclass, RowExclusiveLock);
5797 * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
5798 * rewriting to be done, so we just want to copy the data as fast as possible.
5801 ATExecSetTableSpace(Oid tableOid, Oid newTableSpace)
5807 RelFileNode newrnode;
5808 SMgrRelation dstrel;
5811 Form_pg_class rd_rel;
5814 * Need lock here in case we are recursing to toast table or index
5816 rel = relation_open(tableOid, AccessExclusiveLock);
5819 * We can never allow moving of shared or nailed-in-cache relations,
5820 * because we can't support changing their reltablespace values.
5822 if (rel->rd_rel->relisshared || rel->rd_isnailed)
5824 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5825 errmsg("cannot move system relation \"%s\"",
5826 RelationGetRelationName(rel))));
5828 /* Can't move a non-shared relation into pg_global */
5829 if (newTableSpace == GLOBALTABLESPACE_OID)
5831 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5832 errmsg("only shared relations can be placed in pg_global tablespace")));
5835 * Don't allow moving temp tables of other backends ... their local buffer
5836 * manager is not going to cope.
5838 if (isOtherTempNamespace(RelationGetNamespace(rel)))
5840 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5841 errmsg("cannot move temporary tables of other sessions")));
5844 * No work if no change in tablespace.
5846 oldTableSpace = rel->rd_rel->reltablespace;
5847 if (newTableSpace == oldTableSpace ||
5848 (newTableSpace == MyDatabaseTableSpace && oldTableSpace == 0))
5850 relation_close(rel, NoLock);
5854 reltoastrelid = rel->rd_rel->reltoastrelid;
5855 reltoastidxid = rel->rd_rel->reltoastidxid;
5857 /* Get a modifiable copy of the relation's pg_class row */
5858 pg_class = heap_open(RelationRelationId, RowExclusiveLock);
5860 tuple = SearchSysCacheCopy(RELOID,
5861 ObjectIdGetDatum(tableOid),
5863 if (!HeapTupleIsValid(tuple))
5864 elog(ERROR, "cache lookup failed for relation %u", tableOid);
5865 rd_rel = (Form_pg_class) GETSTRUCT(tuple);
5867 /* create another storage file. Is it a little ugly ? */
5868 /* NOTE: any conflict in relfilenode value will be caught here */
5869 newrnode = rel->rd_node;
5870 newrnode.spcNode = newTableSpace;
5872 dstrel = smgropen(newrnode);
5873 smgrcreate(dstrel, rel->rd_istemp, false);
5875 /* copy relation data to the new physical file */
5876 copy_relation_data(rel, dstrel);
5878 /* schedule unlinking old physical file */
5879 RelationOpenSmgr(rel);
5880 smgrscheduleunlink(rel->rd_smgr, rel->rd_istemp);
5883 * Now drop smgr references. The source was already dropped by
5884 * smgrscheduleunlink.
5888 /* update the pg_class row */
5889 rd_rel->reltablespace = (newTableSpace == MyDatabaseTableSpace) ? InvalidOid : newTableSpace;
5890 simple_heap_update(pg_class, &tuple->t_self, tuple);
5891 CatalogUpdateIndexes(pg_class, tuple);
5893 heap_freetuple(tuple);
5895 heap_close(pg_class, RowExclusiveLock);
5897 relation_close(rel, NoLock);
5899 /* Make sure the reltablespace change is visible */
5900 CommandCounterIncrement();
5902 /* Move associated toast relation and/or index, too */
5903 if (OidIsValid(reltoastrelid))
5904 ATExecSetTableSpace(reltoastrelid, newTableSpace);
5905 if (OidIsValid(reltoastidxid))
5906 ATExecSetTableSpace(reltoastidxid, newTableSpace);
5910 * Copy data, block by block
5913 copy_relation_data(Relation rel, SMgrRelation dst)
5917 BlockNumber nblocks;
5920 Page page = (Page) buf;
5923 * Since we copy the file directly without looking at the shared buffers,
5924 * we'd better first flush out any pages of the source relation that are
5925 * in shared buffers. We assume no new changes will be made while we are
5926 * holding exclusive lock on the rel.
5928 FlushRelationBuffers(rel);
5931 * We need to log the copied data in WAL iff WAL archiving is enabled AND
5932 * it's not a temp rel.
5934 use_wal = XLogArchivingActive() && !rel->rd_istemp;
5936 nblocks = RelationGetNumberOfBlocks(rel);
5937 /* RelationGetNumberOfBlocks will certainly have opened rd_smgr */
5940 for (blkno = 0; blkno < nblocks; blkno++)
5942 smgrread(src, blkno, buf);
5946 log_newpage(&dst->smgr_rnode, blkno, page);
5949 * Now write the page. We say isTemp = true even if it's not a temp
5950 * rel, because there's no need for smgr to schedule an fsync for this
5951 * write; we'll do it ourselves below.
5953 smgrextend(dst, blkno, buf, true);
5957 * If the rel isn't temp, we must fsync it down to disk before it's safe
5958 * to commit the transaction. (For a temp rel we don't care since the rel
5959 * will be uninteresting after a crash anyway.)
5961 * It's obvious that we must do this when not WAL-logging the copy. It's
5962 * less obvious that we have to do it even if we did WAL-log the copied
5963 * pages. The reason is that since we're copying outside shared buffers, a
5964 * CHECKPOINT occurring during the copy has no way to flush the previously
5965 * written data to disk (indeed it won't know the new rel even exists). A
5966 * crash later on would replay WAL from the checkpoint, therefore it
5967 * wouldn't replay our earlier WAL entries. If we do not fsync those pages
5968 * here, they might still not be on disk when the crash occurs.
5970 if (!rel->rd_istemp)
5975 * ALTER TABLE ENABLE/DISABLE TRIGGER
5977 * We just pass this off to trigger.c.
5980 ATExecEnableDisableTrigger(Relation rel, char *trigname,
5981 char fires_when, bool skip_system)
5983 EnableDisableTrigger(rel, trigname, fires_when, skip_system);
5987 * ALTER TABLE ENABLE/DISABLE RULE
5989 * We just pass this off to rewriteDefine.c.
5992 ATExecEnableDisableRule(Relation rel, char *trigname,
5995 EnableDisableRule(rel, trigname, fires_when);
5999 * ALTER TABLE INHERIT
6001 * Add a parent to the child's parents. This verifies that all the columns and
6002 * check constraints of the parent appear in the child and that they have the
6003 * same data types and expressions.
6006 ATExecAddInherit(Relation child_rel, RangeVar *parent)
6008 Relation parent_rel,
6012 HeapTuple inheritsTuple;
6017 * AccessShareLock on the parent is what's obtained during normal CREATE
6018 * TABLE ... INHERITS ..., so should be enough here.
6020 parent_rel = heap_openrv(parent, AccessShareLock);
6023 * Must be owner of both parent and child -- child was checked by
6024 * ATSimplePermissions call in ATPrepCmd
6026 ATSimplePermissions(parent_rel, false);
6028 /* Permanent rels cannot inherit from temporary ones */
6029 if (!isTempNamespace(RelationGetNamespace(child_rel)) &&
6030 isTempNamespace(RelationGetNamespace(parent_rel)))
6032 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6033 errmsg("cannot inherit from temporary relation \"%s\"",
6034 RelationGetRelationName(parent_rel))));
6037 * Check for duplicates in the list of parents, and determine the highest
6038 * inhseqno already present; we'll use the next one for the new parent.
6039 * (Note: get RowExclusiveLock because we will write pg_inherits below.)
6041 * Note: we do not reject the case where the child already inherits from
6042 * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
6044 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
6046 Anum_pg_inherits_inhrelid,
6047 BTEqualStrategyNumber, F_OIDEQ,
6048 ObjectIdGetDatum(RelationGetRelid(child_rel)));
6049 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
6050 true, SnapshotNow, 1, &key);
6052 /* inhseqno sequences start at 1 */
6054 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
6056 Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
6058 if (inh->inhparent == RelationGetRelid(parent_rel))
6060 (errcode(ERRCODE_DUPLICATE_TABLE),
6061 errmsg("relation \"%s\" would be inherited from more than once",
6062 RelationGetRelationName(parent_rel))));
6063 if (inh->inhseqno > inhseqno)
6064 inhseqno = inh->inhseqno;
6066 systable_endscan(scan);
6069 * Prevent circularity by seeing if proposed parent inherits from child.
6070 * (In particular, this disallows making a rel inherit from itself.)
6072 * This is not completely bulletproof because of race conditions: in
6073 * multi-level inheritance trees, someone else could concurrently
6074 * be making another inheritance link that closes the loop but does
6075 * not join either of the rels we have locked. Preventing that seems
6076 * to require exclusive locks on the entire inheritance tree, which is
6077 * a cure worse than the disease. find_all_inheritors() will cope with
6078 * circularity anyway, so don't sweat it too much.
6080 children = find_all_inheritors(RelationGetRelid(child_rel));
6082 if (list_member_oid(children, RelationGetRelid(parent_rel)))
6084 (errcode(ERRCODE_DUPLICATE_TABLE),
6085 errmsg("circular inheritance not allowed"),
6086 errdetail("\"%s\" is already a child of \"%s\".",
6088 RelationGetRelationName(child_rel))));
6090 /* If parent has OIDs then child must have OIDs */
6091 if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
6093 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6094 errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
6095 RelationGetRelationName(child_rel),
6096 RelationGetRelationName(parent_rel))));
6098 /* Match up the columns and bump attinhcount and attislocal */
6099 MergeAttributesIntoExisting(child_rel, parent_rel);
6101 /* Match up the constraints and make sure they're present in child */
6102 MergeConstraintsIntoExisting(child_rel, parent_rel);
6105 * OK, it looks valid. Make the catalog entries that show inheritance.
6107 StoreCatalogInheritance1(RelationGetRelid(child_rel),
6108 RelationGetRelid(parent_rel),
6112 /* Now we're done with pg_inherits */
6113 heap_close(catalogRelation, RowExclusiveLock);
6115 /* keep our lock on the parent relation until commit */
6116 heap_close(parent_rel, NoLock);
6120 * Obtain the source-text form of the constraint expression for a check
6121 * constraint, given its pg_constraint tuple
6124 decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
6126 Form_pg_constraint con;
6131 con = (Form_pg_constraint) GETSTRUCT(contup);
6132 attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
6134 elog(ERROR, "null conbin for constraint %u", HeapTupleGetOid(contup));
6136 expr = DirectFunctionCall2(pg_get_expr, attr,
6137 ObjectIdGetDatum(con->conrelid));
6138 return DatumGetCString(DirectFunctionCall1(textout, expr));
6142 * Check columns in child table match up with columns in parent, and increment
6143 * their attinhcount.
6145 * Called by ATExecAddInherit
6147 * Currently all parent columns must be found in child. Missing columns are an
6148 * error. One day we might consider creating new columns like CREATE TABLE
6149 * does. However, that is widely unpopular --- in the common use case of
6150 * partitioned tables it's a foot-gun.
6152 * The data type must match exactly. If the parent column is NOT NULL then
6153 * the child must be as well. Defaults are not compared, however.
6156 MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel)
6159 AttrNumber parent_attno;
6161 TupleDesc tupleDesc;
6162 TupleConstr *constr;
6165 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
6167 tupleDesc = RelationGetDescr(parent_rel);
6168 parent_natts = tupleDesc->natts;
6169 constr = tupleDesc->constr;
6171 for (parent_attno = 1; parent_attno <= parent_natts; parent_attno++)
6173 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
6174 char *attributeName = NameStr(attribute->attname);
6176 /* Ignore dropped columns in the parent. */
6177 if (attribute->attisdropped)
6180 /* Find same column in child (matching on column name). */
6181 tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel),
6183 if (HeapTupleIsValid(tuple))
6185 /* Check they are same type and typmod */
6186 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
6188 if (attribute->atttypid != childatt->atttypid ||
6189 attribute->atttypmod != childatt->atttypmod)
6191 (errcode(ERRCODE_DATATYPE_MISMATCH),
6192 errmsg("child table \"%s\" has different type for column \"%s\"",
6193 RelationGetRelationName(child_rel),
6196 if (attribute->attnotnull && !childatt->attnotnull)
6198 (errcode(ERRCODE_DATATYPE_MISMATCH),
6199 errmsg("column \"%s\" in child table must be marked NOT NULL",
6203 * OK, bump the child column's inheritance count. (If we fail
6204 * later on, this change will just roll back.)
6206 childatt->attinhcount++;
6207 simple_heap_update(attrrel, &tuple->t_self, tuple);
6208 CatalogUpdateIndexes(attrrel, tuple);
6209 heap_freetuple(tuple);
6214 (errcode(ERRCODE_DATATYPE_MISMATCH),
6215 errmsg("child table is missing column \"%s\"",
6220 heap_close(attrrel, RowExclusiveLock);
6224 * Check constraints in child table match up with constraints in parent
6226 * Called by ATExecAddInherit
6228 * Currently all constraints in parent must be present in the child. One day we
6229 * may consider adding new constraints like CREATE TABLE does. We may also want
6230 * to allow an optional flag on parent table constraints indicating they are
6231 * intended to ONLY apply to the master table, not to the children. That would
6232 * make it possible to ensure no records are mistakenly inserted into the
6233 * master in partitioned tables rather than the appropriate child.
6235 * XXX This is O(N^2) which may be an issue with tables with hundreds of
6236 * constraints. As long as tables have more like 10 constraints it shouldn't be
6237 * a problem though. Even 100 constraints ought not be the end of the world.
6240 MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
6242 Relation catalogRelation;
6243 TupleDesc tupleDesc;
6246 HeapTuple constraintTuple;
6250 /* First gather up the child's constraint definitions */
6251 catalogRelation = heap_open(ConstraintRelationId, AccessShareLock);
6252 tupleDesc = RelationGetDescr(catalogRelation);
6255 Anum_pg_constraint_conrelid,
6256 BTEqualStrategyNumber, F_OIDEQ,
6257 ObjectIdGetDatum(RelationGetRelid(child_rel)));
6258 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
6259 true, SnapshotNow, 1, &key);
6262 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
6264 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
6266 if (con->contype != CONSTRAINT_CHECK)
6269 constraints = lappend(constraints, heap_copytuple(constraintTuple));
6272 systable_endscan(scan);
6274 /* Then scan through the parent's constraints looking for matches */
6276 Anum_pg_constraint_conrelid,
6277 BTEqualStrategyNumber, F_OIDEQ,
6278 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
6279 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId, true,
6280 SnapshotNow, 1, &key);
6282 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
6284 Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
6286 Form_pg_constraint child_con = NULL;
6287 HeapTuple child_contuple = NULL;
6289 if (parent_con->contype != CONSTRAINT_CHECK)
6292 foreach(elem, constraints)
6294 child_contuple = (HeapTuple) lfirst(elem);
6295 child_con = (Form_pg_constraint) GETSTRUCT(child_contuple);
6296 if (strcmp(NameStr(parent_con->conname),
6297 NameStr(child_con->conname)) == 0)
6306 (errcode(ERRCODE_DATATYPE_MISMATCH),
6307 errmsg("child table is missing constraint \"%s\"",
6308 NameStr(parent_con->conname))));
6310 if (parent_con->condeferrable != child_con->condeferrable ||
6311 parent_con->condeferred != child_con->condeferred ||
6312 strcmp(decompile_conbin(constraintTuple, tupleDesc),
6313 decompile_conbin(child_contuple, tupleDesc)) != 0)
6315 (errcode(ERRCODE_DATATYPE_MISMATCH),
6316 errmsg("constraint definition for check constraint \"%s\" does not match",
6317 NameStr(parent_con->conname))));
6320 * TODO: add conislocal,coninhcount to constraints. This is where we
6321 * would have to bump them just like attributes
6325 systable_endscan(scan);
6326 heap_close(catalogRelation, AccessShareLock);
6330 * ALTER TABLE NO INHERIT
6332 * Drop a parent from the child's parents. This just adjusts the attinhcount
6333 * and attislocal of the columns and removes the pg_inherit and pg_depend
6336 * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
6337 * up attislocal stays true, which means if a child is ever removed from a
6338 * parent then its columns will never be automatically dropped which may
6339 * surprise. But at least we'll never surprise by dropping columns someone
6340 * isn't expecting to be dropped which would actually mean data loss.
6343 ATExecDropInherit(Relation rel, RangeVar *parent)
6345 Relation parent_rel;
6346 Relation catalogRelation;
6349 HeapTuple inheritsTuple,
6355 * AccessShareLock on the parent is probably enough, seeing that DROP TABLE
6356 * doesn't lock parent tables at all. We need some lock since we'll be
6357 * inspecting the parent's schema.
6359 parent_rel = heap_openrv(parent, AccessShareLock);
6362 * We don't bother to check ownership of the parent table --- ownership
6363 * of the child is presumed enough rights.
6367 * Find and destroy the pg_inherits entry linking the two, or error out
6370 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
6371 ScanKeyInit(&key[0],
6372 Anum_pg_inherits_inhrelid,
6373 BTEqualStrategyNumber, F_OIDEQ,
6374 ObjectIdGetDatum(RelationGetRelid(rel)));
6375 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
6376 true, SnapshotNow, 1, key);
6378 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
6382 inhparent = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
6383 if (inhparent == RelationGetRelid(parent_rel))
6385 simple_heap_delete(catalogRelation, &inheritsTuple->t_self);
6391 systable_endscan(scan);
6392 heap_close(catalogRelation, RowExclusiveLock);
6396 (errcode(ERRCODE_UNDEFINED_TABLE),
6397 errmsg("relation \"%s\" is not a parent of relation \"%s\"",
6398 RelationGetRelationName(parent_rel),
6399 RelationGetRelationName(rel))));
6402 * Search through child columns looking for ones matching parent rel
6404 catalogRelation = heap_open(AttributeRelationId, RowExclusiveLock);
6405 ScanKeyInit(&key[0],
6406 Anum_pg_attribute_attrelid,
6407 BTEqualStrategyNumber, F_OIDEQ,
6408 ObjectIdGetDatum(RelationGetRelid(rel)));
6409 scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
6410 true, SnapshotNow, 1, key);
6411 while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
6413 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
6415 /* Ignore if dropped or not inherited */
6416 if (att->attisdropped)
6418 if (att->attinhcount <= 0)
6421 if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
6422 NameStr(att->attname)))
6424 /* Decrement inhcount and possibly set islocal to true */
6425 HeapTuple copyTuple = heap_copytuple(attributeTuple);
6426 Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
6428 copy_att->attinhcount--;
6429 if (copy_att->attinhcount == 0)
6430 copy_att->attislocal = true;
6432 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
6433 CatalogUpdateIndexes(catalogRelation, copyTuple);
6434 heap_freetuple(copyTuple);
6437 systable_endscan(scan);
6438 heap_close(catalogRelation, RowExclusiveLock);
6441 * Drop the dependency
6443 * There's no convenient way to do this, so go trawling through pg_depend
6445 catalogRelation = heap_open(DependRelationId, RowExclusiveLock);
6447 ScanKeyInit(&key[0],
6448 Anum_pg_depend_classid,
6449 BTEqualStrategyNumber, F_OIDEQ,
6450 ObjectIdGetDatum(RelationRelationId));
6451 ScanKeyInit(&key[1],
6452 Anum_pg_depend_objid,
6453 BTEqualStrategyNumber, F_OIDEQ,
6454 ObjectIdGetDatum(RelationGetRelid(rel)));
6455 ScanKeyInit(&key[2],
6456 Anum_pg_depend_objsubid,
6457 BTEqualStrategyNumber, F_INT4EQ,
6460 scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
6461 SnapshotNow, 3, key);
6463 while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
6465 Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
6467 if (dep->refclassid == RelationRelationId &&
6468 dep->refobjid == RelationGetRelid(parent_rel) &&
6469 dep->refobjsubid == 0 &&
6470 dep->deptype == DEPENDENCY_NORMAL)
6471 simple_heap_delete(catalogRelation, &depTuple->t_self);
6474 systable_endscan(scan);
6475 heap_close(catalogRelation, RowExclusiveLock);
6477 /* keep our lock on the parent relation until commit */
6478 heap_close(parent_rel, NoLock);
6483 * Execute ALTER TABLE SET SCHEMA
6485 * Note: caller must have checked ownership of the relation already
6488 AlterTableNamespace(RangeVar *relation, const char *newschema)
6496 rel = relation_openrv(relation, AccessExclusiveLock);
6498 relid = RelationGetRelid(rel);
6499 oldNspOid = RelationGetNamespace(rel);
6501 /* Can we change the schema of this tuple? */
6502 switch (rel->rd_rel->relkind)
6504 case RELKIND_RELATION:
6506 /* ok to change schema */
6508 case RELKIND_SEQUENCE:
6510 /* if it's an owned sequence, disallow moving it by itself */
6514 if (sequenceIsOwned(relid, &tableId, &colId))
6516 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6517 errmsg("cannot move an owned sequence into another schema"),
6518 errdetail("Sequence \"%s\" is linked to table \"%s\".",
6519 RelationGetRelationName(rel),
6520 get_rel_name(tableId))));
6523 case RELKIND_COMPOSITE_TYPE:
6525 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6526 errmsg("\"%s\" is a composite type",
6527 RelationGetRelationName(rel)),
6528 errhint("Use ALTER TYPE instead.")));
6531 case RELKIND_TOASTVALUE:
6535 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6536 errmsg("\"%s\" is not a table, view, or sequence",
6537 RelationGetRelationName(rel))));
6540 /* get schema OID and check its permissions */
6541 nspOid = LookupCreationNamespace(newschema);
6543 if (oldNspOid == nspOid)
6545 (errcode(ERRCODE_DUPLICATE_TABLE),
6546 errmsg("relation \"%s\" is already in schema \"%s\"",
6547 RelationGetRelationName(rel),
6550 /* disallow renaming into or out of temp schemas */
6551 if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
6553 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6554 errmsg("cannot move objects into or out of temporary schemas")));
6556 /* same for TOAST schema */
6557 if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
6559 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6560 errmsg("cannot move objects into or out of TOAST schema")));
6562 /* OK, modify the pg_class row and pg_depend entry */
6563 classRel = heap_open(RelationRelationId, RowExclusiveLock);
6565 AlterRelationNamespaceInternal(classRel, relid, oldNspOid, nspOid, true);
6567 /* Fix the table's rowtype too */
6568 AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid, false, false);
6570 /* Fix other dependent stuff */
6571 if (rel->rd_rel->relkind == RELKIND_RELATION)
6573 AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid);
6574 AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid, newschema);
6575 AlterConstraintNamespaces(relid, oldNspOid, nspOid, false);
6578 heap_close(classRel, RowExclusiveLock);
6580 /* close rel, but keep lock until commit */
6581 relation_close(rel, NoLock);
6585 * The guts of relocating a relation to another namespace: fix the pg_class
6586 * entry, and the pg_depend entry if any. Caller must already have
6587 * opened and write-locked pg_class.
6590 AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
6591 Oid oldNspOid, Oid newNspOid,
6592 bool hasDependEntry)
6595 Form_pg_class classForm;
6597 classTup = SearchSysCacheCopy(RELOID,
6598 ObjectIdGetDatum(relOid),
6600 if (!HeapTupleIsValid(classTup))
6601 elog(ERROR, "cache lookup failed for relation %u", relOid);
6602 classForm = (Form_pg_class) GETSTRUCT(classTup);
6604 Assert(classForm->relnamespace == oldNspOid);
6606 /* check for duplicate name (more friendly than unique-index failure) */
6607 if (get_relname_relid(NameStr(classForm->relname),
6608 newNspOid) != InvalidOid)
6610 (errcode(ERRCODE_DUPLICATE_TABLE),
6611 errmsg("relation \"%s\" already exists in schema \"%s\"",
6612 NameStr(classForm->relname),
6613 get_namespace_name(newNspOid))));
6615 /* classTup is a copy, so OK to scribble on */
6616 classForm->relnamespace = newNspOid;
6618 simple_heap_update(classRel, &classTup->t_self, classTup);
6619 CatalogUpdateIndexes(classRel, classTup);
6621 /* Update dependency on schema if caller said so */
6622 if (hasDependEntry &&
6623 changeDependencyFor(RelationRelationId, relOid,
6624 NamespaceRelationId, oldNspOid, newNspOid) != 1)
6625 elog(ERROR, "failed to change schema dependency for relation \"%s\"",
6626 NameStr(classForm->relname));
6628 heap_freetuple(classTup);
6632 * Move all indexes for the specified relation to another namespace.
6634 * Note: we assume adequate permission checking was done by the caller,
6635 * and that the caller has a suitable lock on the owning relation.
6638 AlterIndexNamespaces(Relation classRel, Relation rel,
6639 Oid oldNspOid, Oid newNspOid)
6644 indexList = RelationGetIndexList(rel);
6646 foreach(l, indexList)
6648 Oid indexOid = lfirst_oid(l);
6651 * Note: currently, the index will not have its own dependency on the
6652 * namespace, so we don't need to do changeDependencyFor(). There's no
6653 * rowtype in pg_type, either.
6655 AlterRelationNamespaceInternal(classRel, indexOid,
6656 oldNspOid, newNspOid,
6660 list_free(indexList);
6664 * Move all SERIAL-column sequences of the specified relation to another
6667 * Note: we assume adequate permission checking was done by the caller,
6668 * and that the caller has a suitable lock on the owning relation.
6671 AlterSeqNamespaces(Relation classRel, Relation rel,
6672 Oid oldNspOid, Oid newNspOid, const char *newNspName)
6680 * SERIAL sequences are those having an auto dependency on one of the
6681 * table's columns (we don't care *which* column, exactly).
6683 depRel = heap_open(DependRelationId, AccessShareLock);
6685 ScanKeyInit(&key[0],
6686 Anum_pg_depend_refclassid,
6687 BTEqualStrategyNumber, F_OIDEQ,
6688 ObjectIdGetDatum(RelationRelationId));
6689 ScanKeyInit(&key[1],
6690 Anum_pg_depend_refobjid,
6691 BTEqualStrategyNumber, F_OIDEQ,
6692 ObjectIdGetDatum(RelationGetRelid(rel)));
6693 /* we leave refobjsubid unspecified */
6695 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
6696 SnapshotNow, 2, key);
6698 while (HeapTupleIsValid(tup = systable_getnext(scan)))
6700 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
6703 /* skip dependencies other than auto dependencies on columns */
6704 if (depForm->refobjsubid == 0 ||
6705 depForm->classid != RelationRelationId ||
6706 depForm->objsubid != 0 ||
6707 depForm->deptype != DEPENDENCY_AUTO)
6710 /* Use relation_open just in case it's an index */
6711 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
6713 /* skip non-sequence relations */
6714 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
6716 /* No need to keep the lock */
6717 relation_close(seqRel, AccessExclusiveLock);
6721 /* Fix the pg_class and pg_depend entries */
6722 AlterRelationNamespaceInternal(classRel, depForm->objid,
6723 oldNspOid, newNspOid,
6727 * Sequences have entries in pg_type. We need to be careful to move
6728 * them to the new namespace, too.
6730 AlterTypeNamespaceInternal(RelationGetForm(seqRel)->reltype,
6731 newNspOid, false, false);
6733 /* Now we can close it. Keep the lock till end of transaction. */
6734 relation_close(seqRel, NoLock);
6737 systable_endscan(scan);
6739 relation_close(depRel, AccessShareLock);
6744 * This code supports
6745 * CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
6747 * Because we only support this for TEMP tables, it's sufficient to remember
6748 * the state in a backend-local data structure.
6752 * Register a newly-created relation's ON COMMIT action.
6755 register_on_commit_action(Oid relid, OnCommitAction action)
6758 MemoryContext oldcxt;
6761 * We needn't bother registering the relation unless there is an ON COMMIT
6762 * action we need to take.
6764 if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
6767 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
6769 oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
6771 oc->oncommit = action;
6772 oc->creating_subid = GetCurrentSubTransactionId();
6773 oc->deleting_subid = InvalidSubTransactionId;
6775 on_commits = lcons(oc, on_commits);
6777 MemoryContextSwitchTo(oldcxt);
6781 * Unregister any ON COMMIT action when a relation is deleted.
6783 * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
6786 remove_on_commit_action(Oid relid)
6790 foreach(l, on_commits)
6792 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
6794 if (oc->relid == relid)
6796 oc->deleting_subid = GetCurrentSubTransactionId();
6803 * Perform ON COMMIT actions.
6805 * This is invoked just before actually committing, since it's possible
6806 * to encounter errors.
6809 PreCommit_on_commit_actions(void)
6812 List *oids_to_truncate = NIL;
6814 foreach(l, on_commits)
6816 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
6818 /* Ignore entry if already dropped in this xact */
6819 if (oc->deleting_subid != InvalidSubTransactionId)
6822 switch (oc->oncommit)
6825 case ONCOMMIT_PRESERVE_ROWS:
6826 /* Do nothing (there shouldn't be such entries, actually) */
6828 case ONCOMMIT_DELETE_ROWS:
6829 oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
6833 ObjectAddress object;
6835 object.classId = RelationRelationId;
6836 object.objectId = oc->relid;
6837 object.objectSubId = 0;
6838 performDeletion(&object, DROP_CASCADE);
6841 * Note that table deletion will call
6842 * remove_on_commit_action, so the entry should get marked
6845 Assert(oc->deleting_subid != InvalidSubTransactionId);
6850 if (oids_to_truncate != NIL)
6852 heap_truncate(oids_to_truncate);
6853 CommandCounterIncrement(); /* XXX needed? */
6858 * Post-commit or post-abort cleanup for ON COMMIT management.
6860 * All we do here is remove no-longer-needed OnCommitItem entries.
6862 * During commit, remove entries that were deleted during this transaction;
6863 * during abort, remove those created during this transaction.
6866 AtEOXact_on_commit_actions(bool isCommit)
6869 ListCell *prev_item;
6872 cur_item = list_head(on_commits);
6874 while (cur_item != NULL)
6876 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
6878 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
6879 oc->creating_subid != InvalidSubTransactionId)
6881 /* cur_item must be removed */
6882 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
6885 cur_item = lnext(prev_item);
6887 cur_item = list_head(on_commits);
6891 /* cur_item must be preserved */
6892 oc->creating_subid = InvalidSubTransactionId;
6893 oc->deleting_subid = InvalidSubTransactionId;
6894 prev_item = cur_item;
6895 cur_item = lnext(prev_item);
6901 * Post-subcommit or post-subabort cleanup for ON COMMIT management.
6903 * During subabort, we can immediately remove entries created during this
6904 * subtransaction. During subcommit, just relabel entries marked during
6905 * this subtransaction as being the parent's responsibility.
6908 AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
6909 SubTransactionId parentSubid)
6912 ListCell *prev_item;
6915 cur_item = list_head(on_commits);
6917 while (cur_item != NULL)
6919 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
6921 if (!isCommit && oc->creating_subid == mySubid)
6923 /* cur_item must be removed */
6924 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
6927 cur_item = lnext(prev_item);
6929 cur_item = list_head(on_commits);
6933 /* cur_item must be preserved */
6934 if (oc->creating_subid == mySubid)
6935 oc->creating_subid = parentSubid;
6936 if (oc->deleting_subid == mySubid)
6937 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
6938 prev_item = cur_item;
6939 cur_item = lnext(prev_item);