1 /*-------------------------------------------------------------------------
4 * Commands for creating and altering table structures and settings
6 * Portions Copyright (c) 1996-2006, 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.207 2006/12/23 00:43:09 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_trigger.h"
32 #include "catalog/pg_type.h"
33 #include "catalog/toasting.h"
34 #include "commands/cluster.h"
35 #include "commands/defrem.h"
36 #include "commands/tablecmds.h"
37 #include "commands/tablespace.h"
38 #include "commands/trigger.h"
39 #include "commands/typecmds.h"
40 #include "executor/executor.h"
41 #include "miscadmin.h"
42 #include "nodes/makefuncs.h"
43 #include "optimizer/clauses.h"
44 #include "optimizer/plancat.h"
45 #include "optimizer/prep.h"
46 #include "parser/analyze.h"
47 #include "parser/gramparse.h"
48 #include "parser/parse_clause.h"
49 #include "parser/parse_coerce.h"
50 #include "parser/parse_expr.h"
51 #include "parser/parse_oper.h"
52 #include "parser/parse_relation.h"
53 #include "parser/parse_type.h"
54 #include "parser/parser.h"
55 #include "rewrite/rewriteHandler.h"
56 #include "storage/smgr.h"
57 #include "utils/acl.h"
58 #include "utils/builtins.h"
59 #include "utils/fmgroids.h"
60 #include "utils/inval.h"
61 #include "utils/lsyscache.h"
62 #include "utils/memutils.h"
63 #include "utils/relcache.h"
64 #include "utils/syscache.h"
68 * ON COMMIT action list
70 typedef struct OnCommitItem
72 Oid relid; /* relid of relation */
73 OnCommitAction oncommit; /* what to do at end of xact */
76 * If this entry was created during the current transaction,
77 * creating_subid is the ID of the creating subxact; if created in a prior
78 * transaction, creating_subid is zero. If deleted during the current
79 * transaction, deleting_subid is the ID of the deleting subxact; if no
80 * deletion request is pending, deleting_subid is zero.
82 SubTransactionId creating_subid;
83 SubTransactionId deleting_subid;
86 static List *on_commits = NIL;
90 * State information for ALTER TABLE
92 * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
93 * structs, one for each table modified by the operation (the named table
94 * plus any child tables that are affected). We save lists of subcommands
95 * to apply to this table (possibly modified by parse transformation steps);
96 * these lists will be executed in Phase 2. If a Phase 3 step is needed,
97 * necessary information is stored in the constraints and newvals lists.
99 * Phase 2 is divided into multiple passes; subcommands are executed in
100 * a pass determined by subcommand type.
103 #define AT_PASS_DROP 0 /* DROP (all flavors) */
104 #define AT_PASS_ALTER_TYPE 1 /* ALTER COLUMN TYPE */
105 #define AT_PASS_OLD_INDEX 2 /* re-add existing indexes */
106 #define AT_PASS_OLD_CONSTR 3 /* re-add existing constraints */
107 #define AT_PASS_COL_ATTRS 4 /* set other column attributes */
108 /* We could support a RENAME COLUMN pass here, but not currently used */
109 #define AT_PASS_ADD_COL 5 /* ADD COLUMN */
110 #define AT_PASS_ADD_INDEX 6 /* ADD indexes */
111 #define AT_PASS_ADD_CONSTR 7 /* ADD constraints, defaults */
112 #define AT_PASS_MISC 8 /* other stuff */
113 #define AT_NUM_PASSES 9
115 typedef struct AlteredTableInfo
117 /* Information saved before any work commences: */
118 Oid relid; /* Relation to work on */
119 char relkind; /* Its relkind */
120 TupleDesc oldDesc; /* Pre-modification tuple descriptor */
121 /* Information saved by Phase 1 for Phase 2: */
122 List *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
123 /* Information saved by Phases 1/2 for Phase 3: */
124 List *constraints; /* List of NewConstraint */
125 List *newvals; /* List of NewColumnValue */
126 bool new_notnull; /* T if we added new NOT NULL constraints */
127 Oid newTableSpace; /* new tablespace; 0 means no change */
128 /* Objects to rebuild after completing ALTER TYPE operations */
129 List *changedConstraintOids; /* OIDs of constraints to rebuild */
130 List *changedConstraintDefs; /* string definitions of same */
131 List *changedIndexOids; /* OIDs of indexes to rebuild */
132 List *changedIndexDefs; /* string definitions of same */
135 /* Struct describing one new constraint to check in Phase 3 scan */
136 /* Note: new NOT NULL constraints are handled elsewhere */
137 typedef struct NewConstraint
139 char *name; /* Constraint name, or NULL if none */
140 ConstrType contype; /* CHECK or FOREIGN */
141 Oid refrelid; /* PK rel, if FOREIGN */
142 Node *qual; /* Check expr or FkConstraint struct */
143 List *qualstate; /* Execution state for CHECK */
147 * Struct describing one new column value that needs to be computed during
148 * Phase 3 copy (this could be either a new column with a non-null default, or
149 * a column that we're changing the type of). Columns without such an entry
150 * are just copied from the old table during ATRewriteTable. Note that the
151 * expr is an expression over *old* table values.
153 typedef struct NewColumnValue
155 AttrNumber attnum; /* which column */
156 Expr *expr; /* expression to compute */
157 ExprState *exprstate; /* execution state */
161 static void truncate_check_rel(Relation rel);
162 static List *MergeAttributes(List *schema, List *supers, bool istemp,
163 List **supOids, List **supconstr, int *supOidCount);
164 static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
165 static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel);
166 static void add_nonduplicate_constraint(Constraint *cdef,
167 ConstrCheck *check, int *ncheck);
168 static bool change_varattnos_walker(Node *node, const AttrNumber *newattno);
169 static void StoreCatalogInheritance(Oid relationId, List *supers);
170 static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
171 int16 seqNumber, Relation inhRelation);
172 static int findAttrByName(const char *attributeName, List *schema);
173 static void setRelhassubclassInRelation(Oid relationId, bool relhassubclass);
174 static void AlterIndexNamespaces(Relation classRel, Relation rel,
175 Oid oldNspOid, Oid newNspOid);
176 static void AlterSeqNamespaces(Relation classRel, Relation rel,
177 Oid oldNspOid, Oid newNspOid,
178 const char *newNspName);
179 static int transformColumnNameList(Oid relId, List *colList,
180 int16 *attnums, Oid *atttypids);
181 static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
183 int16 *attnums, Oid *atttypids,
185 static Oid transformFkeyCheckAttrs(Relation pkrel,
186 int numattrs, int16 *attnums,
188 static void validateForeignKeyConstraint(FkConstraint *fkconstraint,
189 Relation rel, Relation pkrel);
190 static void createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
192 static char *fkMatchTypeToString(char match_type);
193 static void ATController(Relation rel, List *cmds, bool recurse);
194 static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
195 bool recurse, bool recursing);
196 static void ATRewriteCatalogs(List **wqueue);
197 static void ATExecCmd(AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd);
198 static void ATRewriteTables(List **wqueue);
199 static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap);
200 static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
201 static void ATSimplePermissions(Relation rel, bool allowView);
202 static void ATSimplePermissionsRelationOrIndex(Relation rel);
203 static void ATSimpleRecursion(List **wqueue, Relation rel,
204 AlterTableCmd *cmd, bool recurse);
205 static void ATOneLevelRecursion(List **wqueue, Relation rel,
207 static void find_composite_type_dependencies(Oid typeOid,
208 const char *origTblName);
209 static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
211 static void ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
213 static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
214 static void ATExecDropNotNull(Relation rel, const char *colName);
215 static void ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
216 const char *colName);
217 static void ATExecColumnDefault(Relation rel, const char *colName,
219 static void ATPrepSetStatistics(Relation rel, const char *colName,
221 static void ATExecSetStatistics(Relation rel, const char *colName,
223 static void ATExecSetStorage(Relation rel, const char *colName,
225 static void ATExecDropColumn(Relation rel, const char *colName,
226 DropBehavior behavior,
227 bool recurse, bool recursing);
228 static void ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
229 IndexStmt *stmt, bool is_rebuild);
230 static void ATExecAddConstraint(AlteredTableInfo *tab, Relation rel,
231 Node *newConstraint);
232 static void ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
233 FkConstraint *fkconstraint);
234 static void ATPrepDropConstraint(List **wqueue, Relation rel,
235 bool recurse, AlterTableCmd *cmd);
236 static void ATExecDropConstraint(Relation rel, const char *constrName,
237 DropBehavior behavior, bool quiet);
238 static void ATPrepAlterColumnType(List **wqueue,
239 AlteredTableInfo *tab, Relation rel,
240 bool recurse, bool recursing,
242 static void ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
243 const char *colName, TypeName *typename);
244 static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab);
245 static void ATPostAlterTypeParse(char *cmd, List **wqueue);
246 static void change_owner_recurse_to_sequences(Oid relationOid,
248 static void ATExecClusterOn(Relation rel, const char *indexName);
249 static void ATExecDropCluster(Relation rel);
250 static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
251 char *tablespacename);
252 static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace);
253 static void ATExecSetRelOptions(Relation rel, List *defList, bool isReset);
254 static void ATExecEnableDisableTrigger(Relation rel, char *trigname,
255 bool enable, bool skip_system);
256 static void ATExecAddInherit(Relation rel, RangeVar *parent);
257 static void ATExecDropInherit(Relation rel, RangeVar *parent);
258 static void copy_relation_data(Relation rel, SMgrRelation dst);
259 static void update_ri_trigger_args(Oid relid,
263 bool update_relname);
266 /* ----------------------------------------------------------------
268 * Creates a new relation.
270 * If successful, returns the OID of the new relation.
271 * ----------------------------------------------------------------
274 DefineRelation(CreateStmt *stmt, char relkind)
276 char relname[NAMEDATALEN];
278 List *schema = stmt->tableElts;
282 TupleDesc descriptor;
284 List *old_constraints;
293 * Truncate relname to appropriate length (probably a waste of time, as
294 * parser should have done this already).
296 StrNCpy(relname, stmt->relation->relname, NAMEDATALEN);
299 * Check consistency of arguments
301 if (stmt->oncommit != ONCOMMIT_NOOP && !stmt->relation->istemp)
303 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
304 errmsg("ON COMMIT can only be used on temporary tables")));
307 * Look up the namespace in which we are supposed to create the relation.
308 * Check we have permission to create there. Skip check if bootstrapping,
309 * since permissions machinery may not be working yet.
311 namespaceId = RangeVarGetCreationNamespace(stmt->relation);
313 if (!IsBootstrapProcessingMode())
317 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
319 if (aclresult != ACLCHECK_OK)
320 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
321 get_namespace_name(namespaceId));
325 * Select tablespace to use. If not specified, use default_tablespace
326 * (which may in turn default to database's default).
328 if (stmt->tablespacename)
330 tablespaceId = get_tablespace_oid(stmt->tablespacename);
331 if (!OidIsValid(tablespaceId))
333 (errcode(ERRCODE_UNDEFINED_OBJECT),
334 errmsg("tablespace \"%s\" does not exist",
335 stmt->tablespacename)));
339 tablespaceId = GetDefaultTablespace();
340 /* note InvalidOid is OK in this case */
344 * Parse and validate reloptions, if any.
346 reloptions = transformRelOptions((Datum) 0, stmt->options, true, false);
348 (void) heap_reloptions(relkind, reloptions, true);
350 /* Check permissions except when using database's default */
351 if (OidIsValid(tablespaceId))
355 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
357 if (aclresult != ACLCHECK_OK)
358 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
359 get_tablespace_name(tablespaceId));
363 * Look up inheritance ancestors and generate relation schema, including
364 * inherited attributes.
366 schema = MergeAttributes(schema, stmt->inhRelations,
367 stmt->relation->istemp,
368 &inheritOids, &old_constraints, &parentOidCount);
371 * Create a relation descriptor from the relation schema and create the
372 * relation. Note that in this stage only inherited (pre-cooked) defaults
373 * and constraints will be included into the new relation.
374 * (BuildDescForRelation takes care of the inherited defaults, but we have
375 * to copy inherited constraints here.)
377 descriptor = BuildDescForRelation(schema);
379 localHasOids = interpretOidsOption(stmt->options);
380 descriptor->tdhasoid = (localHasOids || parentOidCount > 0);
382 if (old_constraints || stmt->constraints)
387 /* make array that's certainly big enough */
388 check = (ConstrCheck *)
389 palloc((list_length(old_constraints) +
390 list_length(stmt->constraints)) * sizeof(ConstrCheck));
391 /* deal with constraints from MergeAttributes */
392 foreach(listptr, old_constraints)
394 Constraint *cdef = (Constraint *) lfirst(listptr);
396 if (cdef->contype == CONSTR_CHECK)
397 add_nonduplicate_constraint(cdef, check, &ncheck);
400 * analyze.c might have passed some precooked constraints too,
401 * due to LIKE tab INCLUDING CONSTRAINTS
403 foreach(listptr, stmt->constraints)
405 Constraint *cdef = (Constraint *) lfirst(listptr);
407 if (cdef->contype == CONSTR_CHECK && cdef->cooked_expr != NULL)
408 add_nonduplicate_constraint(cdef, check, &ncheck);
410 /* if we found any, insert 'em into the descriptor */
413 if (descriptor->constr == NULL)
415 descriptor->constr = (TupleConstr *) palloc(sizeof(TupleConstr));
416 descriptor->constr->defval = NULL;
417 descriptor->constr->num_defval = 0;
418 descriptor->constr->has_not_null = false;
420 descriptor->constr->num_check = ncheck;
421 descriptor->constr->check = check;
425 relationId = heap_create_with_catalog(relname,
437 allowSystemTableMods);
439 StoreCatalogInheritance(relationId, inheritOids);
442 * We must bump the command counter to make the newly-created relation
443 * tuple visible for opening.
445 CommandCounterIncrement();
448 * Open the new relation and acquire exclusive lock on it. This isn't
449 * really necessary for locking out other backends (since they can't see
450 * the new rel anyway until we commit), but it keeps the lock manager from
451 * complaining about deadlock risks.
453 rel = relation_open(relationId, AccessExclusiveLock);
456 * Now add any newly specified column default values and CHECK constraints
457 * to the new relation. These are passed to us in the form of raw
458 * parsetrees; we need to transform them to executable expression trees
459 * before they can be added. The most convenient way to do that is to
460 * apply the parser's transformExpr routine, but transformExpr doesn't
461 * work unless we have a pre-existing relation. So, the transformation has
462 * to be postponed to this final step of CREATE TABLE.
464 * First, scan schema to find new column defaults.
469 foreach(listptr, schema)
471 ColumnDef *colDef = lfirst(listptr);
475 if (colDef->raw_default != NULL)
477 RawColumnDefault *rawEnt;
479 Assert(colDef->cooked_default == NULL);
481 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
482 rawEnt->attnum = attnum;
483 rawEnt->raw_default = colDef->raw_default;
484 rawDefaults = lappend(rawDefaults, rawEnt);
489 * Parse and add the defaults/constraints, if any.
491 if (rawDefaults || stmt->constraints)
492 AddRelationRawConstraints(rel, rawDefaults, stmt->constraints);
495 * Clean up. We keep lock on new relation (although it shouldn't be
496 * visible to anyone else anyway, until commit).
498 relation_close(rel, NoLock);
505 * Deletes a relation.
508 RemoveRelation(const RangeVar *relation, DropBehavior behavior)
511 ObjectAddress object;
513 relOid = RangeVarGetRelid(relation, false);
515 object.classId = RelationRelationId;
516 object.objectId = relOid;
517 object.objectSubId = 0;
519 performDeletion(&object, behavior);
524 * Executes a TRUNCATE command.
526 * This is a multi-relation truncate. We first open and grab exclusive
527 * lock on all relations involved, checking permissions and otherwise
528 * verifying that the relation is OK for truncation. In CASCADE mode,
529 * relations having FK references to the targeted relations are automatically
530 * added to the group; in RESTRICT mode, we check that all FK references are
531 * internal to the group that's being truncated. Finally all the relations
532 * are truncated and reindexed.
535 ExecuteTruncate(TruncateStmt *stmt)
542 * Open, exclusive-lock, and check all the explicitly-specified relations
544 foreach(cell, stmt->relations)
546 RangeVar *rv = lfirst(cell);
549 rel = heap_openrv(rv, AccessExclusiveLock);
550 truncate_check_rel(rel);
551 rels = lappend(rels, rel);
552 relids = lappend_oid(relids, RelationGetRelid(rel));
556 * In CASCADE mode, suck in all referencing relations as well. This
557 * requires multiple iterations to find indirectly-dependent relations. At
558 * each phase, we need to exclusive-lock new rels before looking for their
559 * dependencies, else we might miss something. Also, we check each rel as
560 * soon as we open it, to avoid a faux pas such as holding lock for a long
561 * time on a rel we have no permissions for.
563 if (stmt->behavior == DROP_CASCADE)
569 newrelids = heap_truncate_find_FKs(relids);
570 if (newrelids == NIL)
571 break; /* nothing else to add */
573 foreach(cell, newrelids)
575 Oid relid = lfirst_oid(cell);
578 rel = heap_open(relid, AccessExclusiveLock);
580 (errmsg("truncate cascades to table \"%s\"",
581 RelationGetRelationName(rel))));
582 truncate_check_rel(rel);
583 rels = lappend(rels, rel);
584 relids = lappend_oid(relids, relid);
590 * Check foreign key references. In CASCADE mode, this should be
591 * unnecessary since we just pulled in all the references; but as a
592 * cross-check, do it anyway if in an Assert-enabled build.
594 #ifdef USE_ASSERT_CHECKING
595 heap_truncate_check_FKs(rels, false);
597 if (stmt->behavior == DROP_RESTRICT)
598 heap_truncate_check_FKs(rels, false);
602 * Also check for pending AFTER trigger events on the target relations. We
603 * can't just leave those be, since they will try to fetch tuples that the
606 AfterTriggerCheckTruncate(relids);
609 * OK, truncate each table.
613 Relation rel = (Relation) lfirst(cell);
618 * Create a new empty storage file for the relation, and assign it as
619 * the relfilenode value. The old storage file is scheduled for
620 * deletion at commit.
622 setNewRelfilenode(rel);
624 heap_relid = RelationGetRelid(rel);
625 toast_relid = rel->rd_rel->reltoastrelid;
627 heap_close(rel, NoLock);
630 * The same for the toast table, if any.
632 if (OidIsValid(toast_relid))
634 rel = relation_open(toast_relid, AccessExclusiveLock);
635 setNewRelfilenode(rel);
636 heap_close(rel, NoLock);
640 * Reconstruct the indexes to match, and we're done.
642 reindex_relation(heap_relid, true);
647 * Check that a given rel is safe to truncate. Subroutine for ExecuteTruncate
650 truncate_check_rel(Relation rel)
652 /* Only allow truncate on regular tables */
653 if (rel->rd_rel->relkind != RELKIND_RELATION)
655 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
656 errmsg("\"%s\" is not a table",
657 RelationGetRelationName(rel))));
659 /* Permissions checks */
660 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
661 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
662 RelationGetRelationName(rel));
664 if (!allowSystemTableMods && IsSystemRelation(rel))
666 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
667 errmsg("permission denied: \"%s\" is a system catalog",
668 RelationGetRelationName(rel))));
671 * We can never allow truncation of shared or nailed-in-cache relations,
672 * because we can't support changing their relfilenode values.
674 if (rel->rd_rel->relisshared || rel->rd_isnailed)
676 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
677 errmsg("cannot truncate system relation \"%s\"",
678 RelationGetRelationName(rel))));
681 * Don't allow truncate on temp tables of other backends ... their local
682 * buffer manager is not going to cope.
684 if (isOtherTempNamespace(RelationGetNamespace(rel)))
686 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
687 errmsg("cannot truncate temporary tables of other sessions")));
692 * Returns new schema given initial schema and superclasses.
695 * 'schema' is the column/attribute definition for the table. (It's a list
696 * of ColumnDef's.) It is destructively changed.
697 * 'supers' is a list of names (as RangeVar nodes) of parent relations.
698 * 'istemp' is TRUE if we are creating a temp relation.
701 * 'supOids' receives a list of the OIDs of the parent relations.
702 * 'supconstr' receives a list of constraints belonging to the parents,
703 * updated as necessary to be valid for the child.
704 * 'supOidCount' is set to the number of parents that have OID columns.
707 * Completed schema list.
710 * The order in which the attributes are inherited is very important.
711 * Intuitively, the inherited attributes should come first. If a table
712 * inherits from multiple parents, the order of those attributes are
713 * according to the order of the parents specified in CREATE TABLE.
717 * create table person (name text, age int4, location point);
718 * create table emp (salary int4, manager text) inherits(person);
719 * create table student (gpa float8) inherits (person);
720 * create table stud_emp (percent int4) inherits (emp, student);
722 * The order of the attributes of stud_emp is:
724 * person {1:name, 2:age, 3:location}
726 * {6:gpa} student emp {4:salary, 5:manager}
728 * stud_emp {7:percent}
730 * If the same attribute name appears multiple times, then it appears
731 * in the result table in the proper location for its first appearance.
733 * Constraints (including NOT NULL constraints) for the child table
734 * are the union of all relevant constraints, from both the child schema
737 * The default value for a child column is defined as:
738 * (1) If the child schema specifies a default, that value is used.
739 * (2) If neither the child nor any parent specifies a default, then
740 * the column will not have a default.
741 * (3) If conflicting defaults are inherited from different parents
742 * (and not overridden by the child), an error is raised.
743 * (4) Otherwise the inherited default is used.
744 * Rule (3) is new in Postgres 7.1; in earlier releases you got a
745 * rather arbitrary choice of which parent default to use.
749 MergeAttributes(List *schema, List *supers, bool istemp,
750 List **supOids, List **supconstr, int *supOidCount)
753 List *inhSchema = NIL;
754 List *parentOids = NIL;
755 List *constraints = NIL;
756 int parentsWithOids = 0;
757 bool have_bogus_defaults = false;
758 char *bogus_marker = "Bogus!"; /* marks conflicting defaults */
762 * Check for and reject tables with too many columns. We perform this
763 * check relatively early for two reasons: (a) we don't run the risk of
764 * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
765 * okay if we're processing <= 1600 columns, but could take minutes to
766 * execute if the user attempts to create a table with hundreds of
767 * thousands of columns.
769 * Note that we also need to check that any we do not exceed this figure
770 * after including columns from inherited relations.
772 if (list_length(schema) > MaxHeapAttributeNumber)
774 (errcode(ERRCODE_TOO_MANY_COLUMNS),
775 errmsg("tables can have at most %d columns",
776 MaxHeapAttributeNumber)));
779 * Check for duplicate names in the explicit list of attributes.
781 * Although we might consider merging such entries in the same way that we
782 * handle name conflicts for inherited attributes, it seems to make more
783 * sense to assume such conflicts are errors.
785 foreach(entry, schema)
787 ColumnDef *coldef = lfirst(entry);
790 for_each_cell(rest, lnext(entry))
792 ColumnDef *restdef = lfirst(rest);
794 if (strcmp(coldef->colname, restdef->colname) == 0)
796 (errcode(ERRCODE_DUPLICATE_COLUMN),
797 errmsg("column \"%s\" duplicated",
803 * Scan the parents left-to-right, and merge their attributes to form a
804 * list of inherited attributes (inhSchema). Also check to see if we need
805 * to inherit an OID column.
808 foreach(entry, supers)
810 RangeVar *parent = (RangeVar *) lfirst(entry);
814 AttrNumber *newattno;
815 AttrNumber parent_attno;
817 relation = heap_openrv(parent, AccessShareLock);
819 if (relation->rd_rel->relkind != RELKIND_RELATION)
821 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
822 errmsg("inherited relation \"%s\" is not a table",
824 /* Permanent rels cannot inherit from temporary ones */
825 if (!istemp && isTempNamespace(RelationGetNamespace(relation)))
827 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
828 errmsg("cannot inherit from temporary relation \"%s\"",
832 * We should have an UNDER permission flag for this, but for now,
833 * demand that creator of a child table own the parent.
835 if (!pg_class_ownercheck(RelationGetRelid(relation), GetUserId()))
836 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
837 RelationGetRelationName(relation));
840 * Reject duplications in the list of parents.
842 if (list_member_oid(parentOids, RelationGetRelid(relation)))
844 (errcode(ERRCODE_DUPLICATE_TABLE),
845 errmsg("inherited relation \"%s\" duplicated",
848 parentOids = lappend_oid(parentOids, RelationGetRelid(relation));
850 if (relation->rd_rel->relhasoids)
853 tupleDesc = RelationGetDescr(relation);
854 constr = tupleDesc->constr;
857 * newattno[] will contain the child-table attribute numbers for the
858 * attributes of this parent table. (They are not the same for
859 * parents after the first one, nor if we have dropped columns.)
861 newattno = (AttrNumber *)
862 palloc(tupleDesc->natts * sizeof(AttrNumber));
864 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
867 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
868 char *attributeName = NameStr(attribute->attname);
873 * Ignore dropped columns in the parent.
875 if (attribute->attisdropped)
878 * change_varattnos_of_a_node asserts that this is greater
879 * than zero, so if anything tries to use it, we should find
882 newattno[parent_attno - 1] = 0;
887 * Does it conflict with some previously inherited column?
889 exist_attno = findAttrByName(attributeName, inhSchema);
893 * Yes, try to merge the two column definitions. They must
894 * have the same type and typmod.
897 (errmsg("merging multiple inherited definitions of column \"%s\"",
899 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
900 if (typenameTypeId(NULL, def->typename) != attribute->atttypid ||
901 def->typename->typmod != attribute->atttypmod)
903 (errcode(ERRCODE_DATATYPE_MISMATCH),
904 errmsg("inherited column \"%s\" has a type conflict",
906 errdetail("%s versus %s",
907 TypeNameToString(def->typename),
908 format_type_be(attribute->atttypid))));
910 /* Merge of NOT NULL constraints = OR 'em together */
911 def->is_not_null |= attribute->attnotnull;
912 /* Default and other constraints are handled below */
913 newattno[parent_attno - 1] = exist_attno;
918 * No, create a new inherited column
920 def = makeNode(ColumnDef);
921 def->colname = pstrdup(attributeName);
922 def->typename = makeTypeNameFromOid(attribute->atttypid,
923 attribute->atttypmod);
925 def->is_local = false;
926 def->is_not_null = attribute->attnotnull;
927 def->raw_default = NULL;
928 def->cooked_default = NULL;
929 def->constraints = NIL;
930 inhSchema = lappend(inhSchema, def);
931 newattno[parent_attno - 1] = ++child_attno;
935 * Copy default if any
937 if (attribute->atthasdef)
939 char *this_default = NULL;
940 AttrDefault *attrdef;
943 /* Find default in constraint structure */
944 Assert(constr != NULL);
945 attrdef = constr->defval;
946 for (i = 0; i < constr->num_defval; i++)
948 if (attrdef[i].adnum == parent_attno)
950 this_default = attrdef[i].adbin;
954 Assert(this_default != NULL);
957 * If default expr could contain any vars, we'd need to fix
958 * 'em, but it can't; so default is ready to apply to child.
960 * If we already had a default from some prior parent, check
961 * to see if they are the same. If so, no problem; if not,
962 * mark the column as having a bogus default. Below, we will
963 * complain if the bogus default isn't overridden by the child
966 Assert(def->raw_default == NULL);
967 if (def->cooked_default == NULL)
968 def->cooked_default = pstrdup(this_default);
969 else if (strcmp(def->cooked_default, this_default) != 0)
971 def->cooked_default = bogus_marker;
972 have_bogus_defaults = true;
978 * Now copy the constraints of this parent, adjusting attnos using the
979 * completed newattno[] map
981 if (constr && constr->num_check > 0)
983 ConstrCheck *check = constr->check;
986 for (i = 0; i < constr->num_check; i++)
988 Constraint *cdef = makeNode(Constraint);
991 cdef->contype = CONSTR_CHECK;
992 cdef->name = pstrdup(check[i].ccname);
993 cdef->raw_expr = NULL;
994 /* adjust varattnos of ccbin here */
995 expr = stringToNode(check[i].ccbin);
996 change_varattnos_of_a_node(expr, newattno);
997 cdef->cooked_expr = nodeToString(expr);
998 constraints = lappend(constraints, cdef);
1005 * Close the parent rel, but keep our AccessShareLock on it until xact
1006 * commit. That will prevent someone else from deleting or ALTERing
1007 * the parent before the child is committed.
1009 heap_close(relation, NoLock);
1013 * If we had no inherited attributes, the result schema is just the
1014 * explicitly declared columns. Otherwise, we need to merge the declared
1015 * columns into the inherited schema list.
1017 if (inhSchema != NIL)
1019 foreach(entry, schema)
1021 ColumnDef *newdef = lfirst(entry);
1022 char *attributeName = newdef->colname;
1026 * Does it conflict with some previously inherited column?
1028 exist_attno = findAttrByName(attributeName, inhSchema);
1029 if (exist_attno > 0)
1034 * Yes, try to merge the two column definitions. They must
1035 * have the same type and typmod.
1038 (errmsg("merging column \"%s\" with inherited definition",
1040 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1041 if (typenameTypeId(NULL, def->typename) != typenameTypeId(NULL, newdef->typename) ||
1042 def->typename->typmod != newdef->typename->typmod)
1044 (errcode(ERRCODE_DATATYPE_MISMATCH),
1045 errmsg("column \"%s\" has a type conflict",
1047 errdetail("%s versus %s",
1048 TypeNameToString(def->typename),
1049 TypeNameToString(newdef->typename))));
1050 /* Mark the column as locally defined */
1051 def->is_local = true;
1052 /* Merge of NOT NULL constraints = OR 'em together */
1053 def->is_not_null |= newdef->is_not_null;
1054 /* If new def has a default, override previous default */
1055 if (newdef->raw_default != NULL)
1057 def->raw_default = newdef->raw_default;
1058 def->cooked_default = newdef->cooked_default;
1064 * No, attach new column to result schema
1066 inhSchema = lappend(inhSchema, newdef);
1073 * Check that we haven't exceeded the legal # of columns after merging
1074 * in inherited columns.
1076 if (list_length(schema) > MaxHeapAttributeNumber)
1078 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1079 errmsg("tables can have at most %d columns",
1080 MaxHeapAttributeNumber)));
1084 * If we found any conflicting parent default values, check to make sure
1085 * they were overridden by the child.
1087 if (have_bogus_defaults)
1089 foreach(entry, schema)
1091 ColumnDef *def = lfirst(entry);
1093 if (def->cooked_default == bogus_marker)
1095 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
1096 errmsg("column \"%s\" inherits conflicting default values",
1098 errhint("To resolve the conflict, specify a default explicitly.")));
1102 *supOids = parentOids;
1103 *supconstr = constraints;
1104 *supOidCount = parentsWithOids;
1110 * In multiple-inheritance situations, it's possible to inherit
1111 * the same grandparent constraint through multiple parents.
1112 * Hence, we want to discard inherited constraints that match as to
1113 * both name and expression. Otherwise, gripe if there are conflicting
1114 * names. Nonconflicting constraints are added to the array check[]
1115 * of length *ncheck ... caller must ensure there is room!
1118 add_nonduplicate_constraint(Constraint *cdef, ConstrCheck *check, int *ncheck)
1122 /* Should only see precooked constraints here */
1123 Assert(cdef->contype == CONSTR_CHECK);
1124 Assert(cdef->name != NULL);
1125 Assert(cdef->raw_expr == NULL && cdef->cooked_expr != NULL);
1127 for (i = 0; i < *ncheck; i++)
1129 if (strcmp(check[i].ccname, cdef->name) != 0)
1131 if (strcmp(check[i].ccbin, cdef->cooked_expr) == 0)
1132 return; /* duplicate constraint, so ignore it */
1134 (errcode(ERRCODE_DUPLICATE_OBJECT),
1135 errmsg("duplicate check constraint name \"%s\"",
1138 /* No match on name, so add it to array */
1139 check[*ncheck].ccname = cdef->name;
1140 check[*ncheck].ccbin = pstrdup(cdef->cooked_expr);
1146 * Replace varattno values in an expression tree according to the given
1147 * map array, that is, varattno N is replaced by newattno[N-1]. It is
1148 * caller's responsibility to ensure that the array is long enough to
1149 * define values for all user varattnos present in the tree. System column
1150 * attnos remain unchanged.
1152 * Note that the passed node tree is modified in-place!
1155 change_varattnos_of_a_node(Node *node, const AttrNumber *newattno)
1157 /* no setup needed, so away we go */
1158 (void) change_varattnos_walker(node, newattno);
1162 change_varattnos_walker(Node *node, const AttrNumber *newattno)
1168 Var *var = (Var *) node;
1170 if (var->varlevelsup == 0 && var->varno == 1 &&
1174 * ??? the following may be a problem when the node is multiply
1175 * referenced though stringToNode() doesn't create such a node
1178 Assert(newattno[var->varattno - 1] > 0);
1179 var->varattno = newattno[var->varattno - 1];
1183 return expression_tree_walker(node, change_varattnos_walker,
1188 * Generate a map for change_varattnos_of_a_node from old and new TupleDesc's,
1189 * matching according to column name.
1192 varattnos_map(TupleDesc old, TupleDesc new)
1198 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * old->natts);
1199 for (i = 1; i <= old->natts; i++)
1201 if (old->attrs[i - 1]->attisdropped)
1202 continue; /* leave the entry as zero */
1204 for (j = 1; j <= new->natts; j++)
1206 if (strcmp(NameStr(old->attrs[i - 1]->attname),
1207 NameStr(new->attrs[j - 1]->attname)) == 0)
1218 * Generate a map for change_varattnos_of_a_node from a TupleDesc and a list
1222 varattnos_map_schema(TupleDesc old, List *schema)
1227 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * old->natts);
1228 for (i = 1; i <= old->natts; i++)
1230 if (old->attrs[i - 1]->attisdropped)
1231 continue; /* leave the entry as zero */
1233 attmap[i - 1] = findAttrByName(NameStr(old->attrs[i - 1]->attname),
1241 * StoreCatalogInheritance
1242 * Updates the system catalogs with proper inheritance information.
1244 * supers is a list of the OIDs of the new relation's direct ancestors.
1247 StoreCatalogInheritance(Oid relationId, List *supers)
1256 AssertArg(OidIsValid(relationId));
1262 * Store INHERITS information in pg_inherits using direct ancestors only.
1263 * Also enter dependencies on the direct ancestors, and make sure they are
1264 * marked with relhassubclass = true.
1266 * (Once upon a time, both direct and indirect ancestors were found here
1267 * and then entered into pg_ipl. Since that catalog doesn't exist
1268 * anymore, there's no need to look for indirect ancestors.)
1270 relation = heap_open(InheritsRelationId, RowExclusiveLock);
1273 foreach(entry, supers)
1275 Oid parentOid = lfirst_oid(entry);
1277 StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation);
1281 heap_close(relation, RowExclusiveLock);
1285 * Make catalog entries showing relationId as being an inheritance child
1286 * of parentOid. inhRelation is the already-opened pg_inherits catalog.
1289 StoreCatalogInheritance1(Oid relationId, Oid parentOid,
1290 int16 seqNumber, Relation inhRelation)
1292 TupleDesc desc = RelationGetDescr(inhRelation);
1293 Datum datum[Natts_pg_inherits];
1294 char nullarr[Natts_pg_inherits];
1295 ObjectAddress childobject,
1300 * Make the pg_inherits entry
1302 datum[0] = ObjectIdGetDatum(relationId); /* inhrelid */
1303 datum[1] = ObjectIdGetDatum(parentOid); /* inhparent */
1304 datum[2] = Int16GetDatum(seqNumber); /* inhseqno */
1310 tuple = heap_formtuple(desc, datum, nullarr);
1312 simple_heap_insert(inhRelation, tuple);
1314 CatalogUpdateIndexes(inhRelation, tuple);
1316 heap_freetuple(tuple);
1319 * Store a dependency too
1321 parentobject.classId = RelationRelationId;
1322 parentobject.objectId = parentOid;
1323 parentobject.objectSubId = 0;
1324 childobject.classId = RelationRelationId;
1325 childobject.objectId = relationId;
1326 childobject.objectSubId = 0;
1328 recordDependencyOn(&childobject, &parentobject, DEPENDENCY_NORMAL);
1331 * Mark the parent as having subclasses.
1333 setRelhassubclassInRelation(parentOid, true);
1337 * Look for an existing schema entry with the given name.
1339 * Returns the index (starting with 1) if attribute already exists in schema,
1343 findAttrByName(const char *attributeName, List *schema)
1350 ColumnDef *def = lfirst(s);
1352 if (strcmp(attributeName, def->colname) == 0)
1361 * Update a relation's pg_class.relhassubclass entry to the given value
1364 setRelhassubclassInRelation(Oid relationId, bool relhassubclass)
1366 Relation relationRelation;
1368 Form_pg_class classtuple;
1371 * Fetch a modifiable copy of the tuple, modify it, update pg_class.
1373 * If the tuple already has the right relhassubclass setting, we don't
1374 * need to update it, but we still need to issue an SI inval message.
1376 relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
1377 tuple = SearchSysCacheCopy(RELOID,
1378 ObjectIdGetDatum(relationId),
1380 if (!HeapTupleIsValid(tuple))
1381 elog(ERROR, "cache lookup failed for relation %u", relationId);
1382 classtuple = (Form_pg_class) GETSTRUCT(tuple);
1384 if (classtuple->relhassubclass != relhassubclass)
1386 classtuple->relhassubclass = relhassubclass;
1387 simple_heap_update(relationRelation, &tuple->t_self, tuple);
1389 /* keep the catalog indexes up to date */
1390 CatalogUpdateIndexes(relationRelation, tuple);
1394 /* no need to change tuple, but force relcache rebuild anyway */
1395 CacheInvalidateRelcacheByTuple(tuple);
1398 heap_freetuple(tuple);
1399 heap_close(relationRelation, RowExclusiveLock);
1404 * renameatt - changes the name of a attribute in a relation
1406 * Attname attribute is changed in attribute catalog.
1407 * No record of the previous attname is kept (correct?).
1409 * get proper relrelation from relation catalog (if not arg)
1410 * scan attribute catalog
1411 * for name conflict (within rel)
1412 * for original attribute (if not arg)
1413 * modify attname in attribute tuple
1414 * insert modified attribute in attribute catalog
1415 * delete original attribute from attribute catalog
1418 renameatt(Oid myrelid,
1419 const char *oldattname,
1420 const char *newattname,
1424 Relation targetrelation;
1425 Relation attrelation;
1427 Form_pg_attribute attform;
1430 ListCell *indexoidscan;
1433 * Grab an exclusive lock on the target table, which we will NOT release
1434 * until end of transaction.
1436 targetrelation = relation_open(myrelid, AccessExclusiveLock);
1439 * permissions checking. this would normally be done in utility.c, but
1440 * this particular routine is recursive.
1442 * normally, only the owner of a class can change its schema.
1444 if (!pg_class_ownercheck(myrelid, GetUserId()))
1445 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1446 RelationGetRelationName(targetrelation));
1447 if (!allowSystemTableMods && IsSystemRelation(targetrelation))
1449 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1450 errmsg("permission denied: \"%s\" is a system catalog",
1451 RelationGetRelationName(targetrelation))));
1454 * if the 'recurse' flag is set then we are supposed to rename this
1455 * attribute in all classes that inherit from 'relname' (as well as in
1458 * any permissions or problems with duplicate attributes will cause the
1459 * whole transaction to abort, which is what we want -- all or nothing.
1466 /* this routine is actually in the planner */
1467 children = find_all_inheritors(myrelid);
1470 * find_all_inheritors does the recursive search of the inheritance
1471 * hierarchy, so all we have to do is process all of the relids in the
1472 * list that it returns.
1474 foreach(child, children)
1476 Oid childrelid = lfirst_oid(child);
1478 if (childrelid == myrelid)
1480 /* note we need not recurse again */
1481 renameatt(childrelid, oldattname, newattname, false, true);
1487 * If we are told not to recurse, there had better not be any child
1488 * tables; else the rename would put them out of step.
1491 find_inheritance_children(myrelid) != NIL)
1493 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1494 errmsg("inherited column \"%s\" must be renamed in child tables too",
1498 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
1500 atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
1501 if (!HeapTupleIsValid(atttup))
1503 (errcode(ERRCODE_UNDEFINED_COLUMN),
1504 errmsg("column \"%s\" does not exist",
1506 attform = (Form_pg_attribute) GETSTRUCT(atttup);
1508 attnum = attform->attnum;
1511 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1512 errmsg("cannot rename system column \"%s\"",
1516 * if the attribute is inherited, forbid the renaming, unless we are
1517 * already inside a recursive rename.
1519 if (attform->attinhcount > 0 && !recursing)
1521 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1522 errmsg("cannot rename inherited column \"%s\"",
1525 /* should not already exist */
1526 /* this test is deliberately not attisdropped-aware */
1527 if (SearchSysCacheExists(ATTNAME,
1528 ObjectIdGetDatum(myrelid),
1529 PointerGetDatum(newattname),
1532 (errcode(ERRCODE_DUPLICATE_COLUMN),
1533 errmsg("column \"%s\" of relation \"%s\" already exists",
1534 newattname, RelationGetRelationName(targetrelation))));
1536 namestrcpy(&(attform->attname), newattname);
1538 simple_heap_update(attrelation, &atttup->t_self, atttup);
1540 /* keep system catalog indexes current */
1541 CatalogUpdateIndexes(attrelation, atttup);
1543 heap_freetuple(atttup);
1546 * Update column names of indexes that refer to the column being renamed.
1548 indexoidlist = RelationGetIndexList(targetrelation);
1550 foreach(indexoidscan, indexoidlist)
1552 Oid indexoid = lfirst_oid(indexoidscan);
1554 Form_pg_index indexform;
1558 * Scan through index columns to see if there's any simple index
1559 * entries for this attribute. We ignore expressional entries.
1561 indextup = SearchSysCache(INDEXRELID,
1562 ObjectIdGetDatum(indexoid),
1564 if (!HeapTupleIsValid(indextup))
1565 elog(ERROR, "cache lookup failed for index %u", indexoid);
1566 indexform = (Form_pg_index) GETSTRUCT(indextup);
1568 for (i = 0; i < indexform->indnatts; i++)
1570 if (attnum != indexform->indkey.values[i])
1574 * Found one, rename it.
1576 atttup = SearchSysCacheCopy(ATTNUM,
1577 ObjectIdGetDatum(indexoid),
1578 Int16GetDatum(i + 1),
1580 if (!HeapTupleIsValid(atttup))
1581 continue; /* should we raise an error? */
1584 * Update the (copied) attribute tuple.
1586 namestrcpy(&(((Form_pg_attribute) GETSTRUCT(atttup))->attname),
1589 simple_heap_update(attrelation, &atttup->t_self, atttup);
1591 /* keep system catalog indexes current */
1592 CatalogUpdateIndexes(attrelation, atttup);
1594 heap_freetuple(atttup);
1597 ReleaseSysCache(indextup);
1600 list_free(indexoidlist);
1602 heap_close(attrelation, RowExclusiveLock);
1605 * Update att name in any RI triggers associated with the relation.
1607 if (targetrelation->rd_rel->reltriggers > 0)
1609 /* update tgargs column reference where att is primary key */
1610 update_ri_trigger_args(RelationGetRelid(targetrelation),
1611 oldattname, newattname,
1613 /* update tgargs column reference where att is foreign key */
1614 update_ri_trigger_args(RelationGetRelid(targetrelation),
1615 oldattname, newattname,
1619 relation_close(targetrelation, NoLock); /* close rel but keep lock */
1623 * renamerel - change the name of a relation
1625 * XXX - When renaming sequences, we don't bother to modify the
1626 * sequence name that is stored within the sequence itself
1627 * (this would cause problems with MVCC). In the future,
1628 * the sequence name should probably be removed from the
1629 * sequence, AFAIK there's no need for it to be there.
1632 renamerel(Oid myrelid, const char *newrelname)
1634 Relation targetrelation;
1635 Relation relrelation; /* for RELATION relation */
1640 bool relhastriggers;
1643 * Grab an exclusive lock on the target table or index, which we will NOT
1644 * release until end of transaction.
1646 targetrelation = relation_open(myrelid, AccessExclusiveLock);
1648 oldrelname = pstrdup(RelationGetRelationName(targetrelation));
1649 namespaceId = RelationGetNamespace(targetrelation);
1651 if (!allowSystemTableMods && IsSystemRelation(targetrelation))
1653 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1654 errmsg("permission denied: \"%s\" is a system catalog",
1655 RelationGetRelationName(targetrelation))));
1657 relkind = targetrelation->rd_rel->relkind;
1658 relhastriggers = (targetrelation->rd_rel->reltriggers > 0);
1661 * Find relation's pg_class tuple, and make sure newrelname isn't in use.
1663 relrelation = heap_open(RelationRelationId, RowExclusiveLock);
1665 reltup = SearchSysCacheCopy(RELOID,
1666 PointerGetDatum(myrelid),
1668 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
1669 elog(ERROR, "cache lookup failed for relation %u", myrelid);
1671 if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
1673 (errcode(ERRCODE_DUPLICATE_TABLE),
1674 errmsg("relation \"%s\" already exists",
1678 * Update pg_class tuple with new relname. (Scribbling on reltup is OK
1679 * because it's a copy...)
1681 namestrcpy(&(((Form_pg_class) GETSTRUCT(reltup))->relname), newrelname);
1683 simple_heap_update(relrelation, &reltup->t_self, reltup);
1685 /* keep the system catalog indexes current */
1686 CatalogUpdateIndexes(relrelation, reltup);
1688 heap_freetuple(reltup);
1689 heap_close(relrelation, RowExclusiveLock);
1692 * Also rename the associated type, if any.
1694 if (relkind != RELKIND_INDEX)
1695 TypeRename(oldrelname, namespaceId, newrelname);
1698 * Update rel name in any RI triggers associated with the relation.
1702 /* update tgargs where relname is primary key */
1703 update_ri_trigger_args(myrelid,
1707 /* update tgargs where relname is foreign key */
1708 update_ri_trigger_args(myrelid,
1715 * Close rel, but keep exclusive lock!
1717 relation_close(targetrelation, NoLock);
1721 * Scan pg_trigger for RI triggers that are on the specified relation
1722 * (if fk_scan is false) or have it as the tgconstrrel (if fk_scan
1723 * is true). Update RI trigger args fields matching oldname to contain
1724 * newname instead. If update_relname is true, examine the relname
1725 * fields; otherwise examine the attname fields.
1728 update_ri_trigger_args(Oid relid,
1729 const char *oldname,
1730 const char *newname,
1732 bool update_relname)
1735 ScanKeyData skey[1];
1736 SysScanDesc trigscan;
1738 Datum values[Natts_pg_trigger];
1739 char nulls[Natts_pg_trigger];
1740 char replaces[Natts_pg_trigger];
1742 tgrel = heap_open(TriggerRelationId, RowExclusiveLock);
1745 ScanKeyInit(&skey[0],
1746 Anum_pg_trigger_tgconstrrelid,
1747 BTEqualStrategyNumber, F_OIDEQ,
1748 ObjectIdGetDatum(relid));
1749 trigscan = systable_beginscan(tgrel, TriggerConstrRelidIndexId,
1755 ScanKeyInit(&skey[0],
1756 Anum_pg_trigger_tgrelid,
1757 BTEqualStrategyNumber, F_OIDEQ,
1758 ObjectIdGetDatum(relid));
1759 trigscan = systable_beginscan(tgrel, TriggerRelidNameIndexId,
1764 while ((tuple = systable_getnext(trigscan)) != NULL)
1766 Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(tuple);
1776 const char *arga[RI_MAX_ARGUMENTS];
1779 tg_type = RI_FKey_trigger_type(pg_trigger->tgfoid);
1780 if (tg_type == RI_TRIGGER_NONE)
1782 /* Not an RI trigger, forget it */
1787 * It is an RI trigger, so parse the tgargs bytea.
1789 * NB: we assume the field will never be compressed or moved out of
1790 * line; so does trigger.c ...
1792 tgnargs = pg_trigger->tgnargs;
1794 DatumGetPointer(fastgetattr(tuple,
1795 Anum_pg_trigger_tgargs,
1796 tgrel->rd_att, &isnull));
1797 if (isnull || tgnargs < RI_FIRST_ATTNAME_ARGNO ||
1798 tgnargs > RI_MAX_ARGUMENTS)
1800 /* This probably shouldn't happen, but ignore busted triggers */
1803 argp = (const char *) VARDATA(val);
1804 for (i = 0; i < tgnargs; i++)
1807 argp += strlen(argp) + 1;
1811 * Figure out which item(s) to look at. If the trigger is primary-key
1812 * type and attached to my rel, I should look at the PK fields; if it
1813 * is foreign-key type and attached to my rel, I should look at the FK
1814 * fields. But the opposite rule holds when examining triggers found
1815 * by tgconstrrel search.
1817 examine_pk = (tg_type == RI_TRIGGER_PK) == (!fk_scan);
1822 /* Change the relname if needed */
1823 i = examine_pk ? RI_PK_RELNAME_ARGNO : RI_FK_RELNAME_ARGNO;
1824 if (strcmp(arga[i], oldname) == 0)
1832 /* Change attname(s) if needed */
1833 i = examine_pk ? RI_FIRST_ATTNAME_ARGNO + RI_KEYPAIR_PK_IDX :
1834 RI_FIRST_ATTNAME_ARGNO + RI_KEYPAIR_FK_IDX;
1835 for (; i < tgnargs; i += 2)
1837 if (strcmp(arga[i], oldname) == 0)
1847 /* Don't need to update this tuple */
1852 * Construct modified tgargs bytea.
1855 for (i = 0; i < tgnargs; i++)
1856 newlen += strlen(arga[i]) + 1;
1857 newtgargs = (bytea *) palloc(newlen);
1858 VARATT_SIZEP(newtgargs) = newlen;
1860 for (i = 0; i < tgnargs; i++)
1862 strcpy(((char *) newtgargs) + newlen, arga[i]);
1863 newlen += strlen(arga[i]) + 1;
1867 * Build modified tuple.
1869 for (i = 0; i < Natts_pg_trigger; i++)
1871 values[i] = (Datum) 0;
1875 values[Anum_pg_trigger_tgargs - 1] = PointerGetDatum(newtgargs);
1876 replaces[Anum_pg_trigger_tgargs - 1] = 'r';
1878 tuple = heap_modifytuple(tuple, RelationGetDescr(tgrel), values, nulls, replaces);
1881 * Update pg_trigger and its indexes
1883 simple_heap_update(tgrel, &tuple->t_self, tuple);
1885 CatalogUpdateIndexes(tgrel, tuple);
1888 * Invalidate trigger's relation's relcache entry so that other
1889 * backends (and this one too!) are sent SI message to make them
1890 * rebuild relcache entries. (Ideally this should happen
1893 * We can skip this for triggers on relid itself, since that relcache
1894 * flush will happen anyway due to the table or column rename. We
1895 * just need to catch the far ends of RI relationships.
1897 pg_trigger = (Form_pg_trigger) GETSTRUCT(tuple);
1898 if (pg_trigger->tgrelid != relid)
1899 CacheInvalidateRelcacheByRelid(pg_trigger->tgrelid);
1901 /* free up our scratch memory */
1903 heap_freetuple(tuple);
1906 systable_endscan(trigscan);
1908 heap_close(tgrel, RowExclusiveLock);
1911 * Increment cmd counter to make updates visible; this is needed in case
1912 * the same tuple has to be updated again by next pass (can happen in case
1913 * of a self-referential FK relationship).
1915 CommandCounterIncrement();
1920 * Execute ALTER TABLE, which can be a list of subcommands
1922 * ALTER TABLE is performed in three phases:
1923 * 1. Examine subcommands and perform pre-transformation checking.
1924 * 2. Update system catalogs.
1925 * 3. Scan table(s) to check new constraints, and optionally recopy
1926 * the data into new table(s).
1927 * Phase 3 is not performed unless one or more of the subcommands requires
1928 * it. The intention of this design is to allow multiple independent
1929 * updates of the table schema to be performed with only one pass over the
1932 * ATPrepCmd performs phase 1. A "work queue" entry is created for
1933 * each table to be affected (there may be multiple affected tables if the
1934 * commands traverse a table inheritance hierarchy). Also we do preliminary
1935 * validation of the subcommands, including parse transformation of those
1936 * expressions that need to be evaluated with respect to the old table
1939 * ATRewriteCatalogs performs phase 2 for each affected table (note that
1940 * phases 2 and 3 do no explicit recursion, since phase 1 already did it).
1941 * Certain subcommands need to be performed before others to avoid
1942 * unnecessary conflicts; for example, DROP COLUMN should come before
1943 * ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
1944 * lists, one for each logical "pass" of phase 2.
1946 * ATRewriteTables performs phase 3 for those tables that need it.
1948 * Thanks to the magic of MVCC, an error anywhere along the way rolls back
1949 * the whole operation; we don't have to do anything special to clean up.
1952 AlterTable(AlterTableStmt *stmt)
1954 ATController(relation_openrv(stmt->relation, AccessExclusiveLock),
1956 interpretInhOption(stmt->relation->inhOpt));
1960 * AlterTableInternal
1962 * ALTER TABLE with target specified by OID
1965 AlterTableInternal(Oid relid, List *cmds, bool recurse)
1967 ATController(relation_open(relid, AccessExclusiveLock),
1973 ATController(Relation rel, List *cmds, bool recurse)
1978 /* Phase 1: preliminary examination of commands, create work queue */
1981 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
1983 ATPrepCmd(&wqueue, rel, cmd, recurse, false);
1986 /* Close the relation, but keep lock until commit */
1987 relation_close(rel, NoLock);
1989 /* Phase 2: update system catalogs */
1990 ATRewriteCatalogs(&wqueue);
1992 /* Phase 3: scan/rewrite tables as needed */
1993 ATRewriteTables(&wqueue);
1999 * Traffic cop for ALTER TABLE Phase 1 operations, including simple
2000 * recursion and permission checks.
2002 * Caller must have acquired AccessExclusiveLock on relation already.
2003 * This lock should be held until commit.
2006 ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
2007 bool recurse, bool recursing)
2009 AlteredTableInfo *tab;
2012 /* Find or create work queue entry for this table */
2013 tab = ATGetQueueEntry(wqueue, rel);
2016 * Copy the original subcommand for each table. This avoids conflicts
2017 * when different child tables need to make different parse
2018 * transformations (for example, the same column may have different column
2019 * numbers in different children).
2021 cmd = copyObject(cmd);
2024 * Do permissions checking, recursion to child tables if needed, and any
2025 * additional phase-1 processing needed.
2027 switch (cmd->subtype)
2029 case AT_AddColumn: /* ADD COLUMN */
2030 ATSimplePermissions(rel, false);
2031 /* Performs own recursion */
2032 ATPrepAddColumn(wqueue, rel, recurse, cmd);
2033 pass = AT_PASS_ADD_COL;
2035 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
2038 * We allow defaults on views so that INSERT into a view can have
2039 * default-ish behavior. This works because the rewriter
2040 * substitutes default values into INSERTs before it expands
2043 ATSimplePermissions(rel, true);
2044 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2045 /* No command-specific prep needed */
2046 pass = cmd->def ? AT_PASS_ADD_CONSTR : AT_PASS_DROP;
2048 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
2049 ATSimplePermissions(rel, false);
2050 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2051 /* No command-specific prep needed */
2052 pass = AT_PASS_DROP;
2054 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
2055 ATSimplePermissions(rel, false);
2056 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2057 /* No command-specific prep needed */
2058 pass = AT_PASS_ADD_CONSTR;
2060 case AT_SetStatistics: /* ALTER COLUMN STATISTICS */
2061 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2062 /* Performs own permission checks */
2063 ATPrepSetStatistics(rel, cmd->name, cmd->def);
2064 pass = AT_PASS_COL_ATTRS;
2066 case AT_SetStorage: /* ALTER COLUMN STORAGE */
2067 ATSimplePermissions(rel, false);
2068 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2069 /* No command-specific prep needed */
2070 pass = AT_PASS_COL_ATTRS;
2072 case AT_DropColumn: /* DROP COLUMN */
2073 ATSimplePermissions(rel, false);
2074 /* Recursion occurs during execution phase */
2075 /* No command-specific prep needed except saving recurse flag */
2077 cmd->subtype = AT_DropColumnRecurse;
2078 pass = AT_PASS_DROP;
2080 case AT_AddIndex: /* ADD INDEX */
2081 ATSimplePermissions(rel, false);
2082 /* This command never recurses */
2083 /* No command-specific prep needed */
2084 pass = AT_PASS_ADD_INDEX;
2086 case AT_AddConstraint: /* ADD CONSTRAINT */
2087 ATSimplePermissions(rel, false);
2090 * Currently we recurse only for CHECK constraints, never for
2091 * foreign-key constraints. UNIQUE/PKEY constraints won't be seen
2094 if (IsA(cmd->def, Constraint))
2095 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2096 /* No command-specific prep needed */
2097 pass = AT_PASS_ADD_CONSTR;
2099 case AT_DropConstraint: /* DROP CONSTRAINT */
2100 ATSimplePermissions(rel, false);
2101 /* Performs own recursion */
2102 ATPrepDropConstraint(wqueue, rel, recurse, cmd);
2103 pass = AT_PASS_DROP;
2105 case AT_DropConstraintQuietly: /* DROP CONSTRAINT for child */
2106 ATSimplePermissions(rel, false);
2107 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2108 /* No command-specific prep needed */
2109 pass = AT_PASS_DROP;
2111 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
2112 ATSimplePermissions(rel, false);
2113 /* Performs own recursion */
2114 ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd);
2115 pass = AT_PASS_ALTER_TYPE;
2117 case AT_ChangeOwner: /* ALTER OWNER */
2118 /* This command never recurses */
2119 /* No command-specific prep needed */
2120 pass = AT_PASS_MISC;
2122 case AT_ClusterOn: /* CLUSTER ON */
2123 case AT_DropCluster: /* SET WITHOUT CLUSTER */
2124 ATSimplePermissions(rel, false);
2125 /* These commands never recurse */
2126 /* No command-specific prep needed */
2127 pass = AT_PASS_MISC;
2129 case AT_DropOids: /* SET WITHOUT OIDS */
2130 ATSimplePermissions(rel, false);
2131 /* Performs own recursion */
2132 if (rel->rd_rel->relhasoids)
2134 AlterTableCmd *dropCmd = makeNode(AlterTableCmd);
2136 dropCmd->subtype = AT_DropColumn;
2137 dropCmd->name = pstrdup("oid");
2138 dropCmd->behavior = cmd->behavior;
2139 ATPrepCmd(wqueue, rel, dropCmd, recurse, false);
2141 pass = AT_PASS_DROP;
2143 case AT_SetTableSpace: /* SET TABLESPACE */
2144 ATSimplePermissionsRelationOrIndex(rel);
2145 /* This command never recurses */
2146 ATPrepSetTableSpace(tab, rel, cmd->name);
2147 pass = AT_PASS_MISC; /* doesn't actually matter */
2149 case AT_SetRelOptions: /* SET (...) */
2150 case AT_ResetRelOptions: /* RESET (...) */
2151 ATSimplePermissionsRelationOrIndex(rel);
2152 /* This command never recurses */
2153 /* No command-specific prep needed */
2154 pass = AT_PASS_MISC;
2156 case AT_EnableTrig: /* ENABLE TRIGGER variants */
2157 case AT_EnableTrigAll:
2158 case AT_EnableTrigUser:
2159 case AT_DisableTrig: /* DISABLE TRIGGER variants */
2160 case AT_DisableTrigAll:
2161 case AT_DisableTrigUser:
2162 case AT_AddInherit: /* INHERIT / NO INHERIT */
2163 case AT_DropInherit:
2164 ATSimplePermissions(rel, false);
2165 /* These commands never recurse */
2166 /* No command-specific prep needed */
2167 pass = AT_PASS_MISC;
2170 elog(ERROR, "unrecognized alter table type: %d",
2171 (int) cmd->subtype);
2172 pass = 0; /* keep compiler quiet */
2176 /* Add the subcommand to the appropriate list for phase 2 */
2177 tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
2183 * Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
2184 * dispatched in a "safe" execution order (designed to avoid unnecessary
2188 ATRewriteCatalogs(List **wqueue)
2194 * We process all the tables "in parallel", one pass at a time. This is
2195 * needed because we may have to propagate work from one table to another
2196 * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
2197 * re-adding of the foreign key constraint to the other table). Work can
2198 * only be propagated into later passes, however.
2200 for (pass = 0; pass < AT_NUM_PASSES; pass++)
2202 /* Go through each table that needs to be processed */
2203 foreach(ltab, *wqueue)
2205 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2206 List *subcmds = tab->subcmds[pass];
2214 * Exclusive lock was obtained by phase 1, needn't get it again
2216 rel = relation_open(tab->relid, NoLock);
2218 foreach(lcmd, subcmds)
2219 ATExecCmd(tab, rel, (AlterTableCmd *) lfirst(lcmd));
2222 * After the ALTER TYPE pass, do cleanup work (this is not done in
2223 * ATExecAlterColumnType since it should be done only once if
2224 * multiple columns of a table are altered).
2226 if (pass == AT_PASS_ALTER_TYPE)
2227 ATPostAlterTypeCleanup(wqueue, tab);
2229 relation_close(rel, NoLock);
2234 * Check to see if a toast table must be added, if we executed any
2235 * subcommands that might have added a column or changed column storage.
2237 foreach(ltab, *wqueue)
2239 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2241 if (tab->relkind == RELKIND_RELATION &&
2242 (tab->subcmds[AT_PASS_ADD_COL] ||
2243 tab->subcmds[AT_PASS_ALTER_TYPE] ||
2244 tab->subcmds[AT_PASS_COL_ATTRS]))
2245 AlterTableCreateToastTable(tab->relid);
2250 * ATExecCmd: dispatch a subcommand to appropriate execution routine
2253 ATExecCmd(AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd)
2255 switch (cmd->subtype)
2257 case AT_AddColumn: /* ADD COLUMN */
2258 ATExecAddColumn(tab, rel, (ColumnDef *) cmd->def);
2260 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
2261 ATExecColumnDefault(rel, cmd->name, cmd->def);
2263 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
2264 ATExecDropNotNull(rel, cmd->name);
2266 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
2267 ATExecSetNotNull(tab, rel, cmd->name);
2269 case AT_SetStatistics: /* ALTER COLUMN STATISTICS */
2270 ATExecSetStatistics(rel, cmd->name, cmd->def);
2272 case AT_SetStorage: /* ALTER COLUMN STORAGE */
2273 ATExecSetStorage(rel, cmd->name, cmd->def);
2275 case AT_DropColumn: /* DROP COLUMN */
2276 ATExecDropColumn(rel, cmd->name, cmd->behavior, false, false);
2278 case AT_DropColumnRecurse: /* DROP COLUMN with recursion */
2279 ATExecDropColumn(rel, cmd->name, cmd->behavior, true, false);
2281 case AT_AddIndex: /* ADD INDEX */
2282 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false);
2284 case AT_ReAddIndex: /* ADD INDEX */
2285 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true);
2287 case AT_AddConstraint: /* ADD CONSTRAINT */
2288 ATExecAddConstraint(tab, rel, cmd->def);
2290 case AT_DropConstraint: /* DROP CONSTRAINT */
2291 ATExecDropConstraint(rel, cmd->name, cmd->behavior, false);
2293 case AT_DropConstraintQuietly: /* DROP CONSTRAINT for child */
2294 ATExecDropConstraint(rel, cmd->name, cmd->behavior, true);
2296 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
2297 ATExecAlterColumnType(tab, rel, cmd->name, (TypeName *) cmd->def);
2299 case AT_ChangeOwner: /* ALTER OWNER */
2300 ATExecChangeOwner(RelationGetRelid(rel),
2301 get_roleid_checked(cmd->name),
2304 case AT_ClusterOn: /* CLUSTER ON */
2305 ATExecClusterOn(rel, cmd->name);
2307 case AT_DropCluster: /* SET WITHOUT CLUSTER */
2308 ATExecDropCluster(rel);
2310 case AT_DropOids: /* SET WITHOUT OIDS */
2313 * Nothing to do here; we'll have generated a DropColumn
2314 * subcommand to do the real work
2317 case AT_SetTableSpace: /* SET TABLESPACE */
2320 * Nothing to do here; Phase 3 does the work
2323 case AT_SetRelOptions: /* SET (...) */
2324 ATExecSetRelOptions(rel, (List *) cmd->def, false);
2326 case AT_ResetRelOptions: /* RESET (...) */
2327 ATExecSetRelOptions(rel, (List *) cmd->def, true);
2329 case AT_EnableTrig: /* ENABLE TRIGGER name */
2330 ATExecEnableDisableTrigger(rel, cmd->name, true, false);
2332 case AT_DisableTrig: /* DISABLE TRIGGER name */
2333 ATExecEnableDisableTrigger(rel, cmd->name, false, false);
2335 case AT_EnableTrigAll: /* ENABLE TRIGGER ALL */
2336 ATExecEnableDisableTrigger(rel, NULL, true, false);
2338 case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
2339 ATExecEnableDisableTrigger(rel, NULL, false, false);
2341 case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
2342 ATExecEnableDisableTrigger(rel, NULL, true, true);
2344 case AT_DisableTrigUser: /* DISABLE TRIGGER USER */
2345 ATExecEnableDisableTrigger(rel, NULL, false, true);
2348 ATExecAddInherit(rel, (RangeVar *) cmd->def);
2350 case AT_DropInherit:
2351 ATExecDropInherit(rel, (RangeVar *) cmd->def);
2354 elog(ERROR, "unrecognized alter table type: %d",
2355 (int) cmd->subtype);
2360 * Bump the command counter to ensure the next subcommand in the sequence
2361 * can see the changes so far
2363 CommandCounterIncrement();
2367 * ATRewriteTables: ALTER TABLE phase 3
2370 ATRewriteTables(List **wqueue)
2374 /* Go through each table that needs to be checked or rewritten */
2375 foreach(ltab, *wqueue)
2377 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2380 * We only need to rewrite the table if at least one column needs to
2383 if (tab->newvals != NIL)
2385 /* Build a temporary relation and copy data */
2387 char NewHeapName[NAMEDATALEN];
2390 ObjectAddress object;
2392 OldHeap = heap_open(tab->relid, NoLock);
2395 * We can never allow rewriting of shared or nailed-in-cache
2396 * relations, because we can't support changing their relfilenode
2399 if (OldHeap->rd_rel->relisshared || OldHeap->rd_isnailed)
2401 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2402 errmsg("cannot rewrite system relation \"%s\"",
2403 RelationGetRelationName(OldHeap))));
2406 * Don't allow rewrite on temp tables of other backends ... their
2407 * local buffer manager is not going to cope.
2409 if (isOtherTempNamespace(RelationGetNamespace(OldHeap)))
2411 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2412 errmsg("cannot rewrite temporary tables of other sessions")));
2415 * Select destination tablespace (same as original unless user
2416 * requested a change)
2418 if (tab->newTableSpace)
2419 NewTableSpace = tab->newTableSpace;
2421 NewTableSpace = OldHeap->rd_rel->reltablespace;
2423 heap_close(OldHeap, NoLock);
2426 * Create the new heap, using a temporary name in the same
2427 * namespace as the existing table. NOTE: there is some risk of
2428 * collision with user relnames. Working around this seems more
2429 * trouble than it's worth; in particular, we can't create the new
2430 * heap in a different namespace from the old, or we will have
2431 * problems with the TEMP status of temp tables.
2433 snprintf(NewHeapName, sizeof(NewHeapName),
2434 "pg_temp_%u", tab->relid);
2436 OIDNewHeap = make_new_heap(tab->relid, NewHeapName, NewTableSpace);
2439 * Copy the heap data into the new table with the desired
2440 * modifications, and test the current data within the table
2441 * against new constraints generated by ALTER TABLE commands.
2443 ATRewriteTable(tab, OIDNewHeap);
2445 /* Swap the physical files of the old and new heaps. */
2446 swap_relation_files(tab->relid, OIDNewHeap);
2448 CommandCounterIncrement();
2450 /* Destroy new heap with old filenode */
2451 object.classId = RelationRelationId;
2452 object.objectId = OIDNewHeap;
2453 object.objectSubId = 0;
2456 * The new relation is local to our transaction and we know
2457 * nothing depends on it, so DROP_RESTRICT should be OK.
2459 performDeletion(&object, DROP_RESTRICT);
2460 /* performDeletion does CommandCounterIncrement at end */
2463 * Rebuild each index on the relation (but not the toast table,
2464 * which is all-new anyway). We do not need
2465 * CommandCounterIncrement() because reindex_relation does it.
2467 reindex_relation(tab->relid, false);
2472 * Test the current data within the table against new constraints
2473 * generated by ALTER TABLE commands, but don't rebuild data.
2475 if (tab->constraints != NIL || tab->new_notnull)
2476 ATRewriteTable(tab, InvalidOid);
2479 * If we had SET TABLESPACE but no reason to reconstruct tuples,
2480 * just do a block-by-block copy.
2482 if (tab->newTableSpace)
2483 ATExecSetTableSpace(tab->relid, tab->newTableSpace);
2488 * Foreign key constraints are checked in a final pass, since (a) it's
2489 * generally best to examine each one separately, and (b) it's at least
2490 * theoretically possible that we have changed both relations of the
2491 * foreign key, and we'd better have finished both rewrites before we try
2492 * to read the tables.
2494 foreach(ltab, *wqueue)
2496 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2497 Relation rel = NULL;
2500 foreach(lcon, tab->constraints)
2502 NewConstraint *con = lfirst(lcon);
2504 if (con->contype == CONSTR_FOREIGN)
2506 FkConstraint *fkconstraint = (FkConstraint *) con->qual;
2511 /* Long since locked, no need for another */
2512 rel = heap_open(tab->relid, NoLock);
2515 refrel = heap_open(con->refrelid, RowShareLock);
2517 validateForeignKeyConstraint(fkconstraint, rel, refrel);
2519 heap_close(refrel, NoLock);
2524 heap_close(rel, NoLock);
2529 * ATRewriteTable: scan or rewrite one table
2531 * OIDNewHeap is InvalidOid if we don't need to rewrite
2534 ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap)
2538 TupleDesc oldTupDesc;
2539 TupleDesc newTupDesc;
2540 bool needscan = false;
2541 List *notnull_attrs;
2547 * Open the relation(s). We have surely already locked the existing
2550 oldrel = heap_open(tab->relid, NoLock);
2551 oldTupDesc = tab->oldDesc;
2552 newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
2554 if (OidIsValid(OIDNewHeap))
2555 newrel = heap_open(OIDNewHeap, AccessExclusiveLock);
2560 * If we need to rewrite the table, the operation has to be propagated to
2561 * tables that use this table's rowtype as a column type.
2563 * (Eventually this will probably become true for scans as well, but at
2564 * the moment a composite type does not enforce any constraints, so it's
2565 * not necessary/appropriate to enforce them just during ALTER.)
2568 find_composite_type_dependencies(oldrel->rd_rel->reltype,
2569 RelationGetRelationName(oldrel));
2572 * Generate the constraint and default execution states
2575 estate = CreateExecutorState();
2577 /* Build the needed expression execution states */
2578 foreach(l, tab->constraints)
2580 NewConstraint *con = lfirst(l);
2582 switch (con->contype)
2586 con->qualstate = (List *)
2587 ExecPrepareExpr((Expr *) con->qual, estate);
2589 case CONSTR_FOREIGN:
2590 /* Nothing to do here */
2593 elog(ERROR, "unrecognized constraint type: %d",
2594 (int) con->contype);
2598 foreach(l, tab->newvals)
2600 NewColumnValue *ex = lfirst(l);
2604 ex->exprstate = ExecPrepareExpr((Expr *) ex->expr, estate);
2607 notnull_attrs = NIL;
2608 if (newrel || tab->new_notnull)
2611 * If we are rebuilding the tuples OR if we added any new NOT NULL
2612 * constraints, check all not-null constraints. This is a bit of
2613 * overkill but it minimizes risk of bugs, and heap_attisnull is a
2614 * pretty cheap test anyway.
2616 for (i = 0; i < newTupDesc->natts; i++)
2618 if (newTupDesc->attrs[i]->attnotnull &&
2619 !newTupDesc->attrs[i]->attisdropped)
2620 notnull_attrs = lappend_int(notnull_attrs, i);
2628 ExprContext *econtext;
2631 TupleTableSlot *oldslot;
2632 TupleTableSlot *newslot;
2635 MemoryContext oldCxt;
2636 List *dropped_attrs = NIL;
2639 econtext = GetPerTupleExprContext(estate);
2642 * Make tuple slots for old and new tuples. Note that even when the
2643 * tuples are the same, the tupDescs might not be (consider ADD COLUMN
2644 * without a default).
2646 oldslot = MakeSingleTupleTableSlot(oldTupDesc);
2647 newslot = MakeSingleTupleTableSlot(newTupDesc);
2649 /* Preallocate values/isnull arrays */
2650 i = Max(newTupDesc->natts, oldTupDesc->natts);
2651 values = (Datum *) palloc(i * sizeof(Datum));
2652 isnull = (bool *) palloc(i * sizeof(bool));
2653 memset(values, 0, i * sizeof(Datum));
2654 memset(isnull, true, i * sizeof(bool));
2657 * Any attributes that are dropped according to the new tuple
2658 * descriptor can be set to NULL. We precompute the list of dropped
2659 * attributes to avoid needing to do so in the per-tuple loop.
2661 for (i = 0; i < newTupDesc->natts; i++)
2663 if (newTupDesc->attrs[i]->attisdropped)
2664 dropped_attrs = lappend_int(dropped_attrs, i);
2668 * Scan through the rows, generating a new row if needed and then
2669 * checking all the constraints.
2671 scan = heap_beginscan(oldrel, SnapshotNow, 0, NULL);
2674 * Switch to per-tuple memory context and reset it for each tuple
2675 * produced, so we don't leak memory.
2677 oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
2679 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2683 Oid tupOid = InvalidOid;
2685 /* Extract data from old tuple */
2686 heap_deform_tuple(tuple, oldTupDesc, values, isnull);
2687 if (oldTupDesc->tdhasoid)
2688 tupOid = HeapTupleGetOid(tuple);
2690 /* Set dropped attributes to null in new tuple */
2691 foreach(lc, dropped_attrs)
2692 isnull[lfirst_int(lc)] = true;
2695 * Process supplied expressions to replace selected columns.
2696 * Expression inputs come from the old tuple.
2698 ExecStoreTuple(tuple, oldslot, InvalidBuffer, false);
2699 econtext->ecxt_scantuple = oldslot;
2701 foreach(l, tab->newvals)
2703 NewColumnValue *ex = lfirst(l);
2705 values[ex->attnum - 1] = ExecEvalExpr(ex->exprstate,
2707 &isnull[ex->attnum - 1],
2712 * Form the new tuple. Note that we don't explicitly pfree it,
2713 * since the per-tuple memory context will be reset shortly.
2715 tuple = heap_form_tuple(newTupDesc, values, isnull);
2717 /* Preserve OID, if any */
2718 if (newTupDesc->tdhasoid)
2719 HeapTupleSetOid(tuple, tupOid);
2722 /* Now check any constraints on the possibly-changed tuple */
2723 ExecStoreTuple(tuple, newslot, InvalidBuffer, false);
2724 econtext->ecxt_scantuple = newslot;
2726 foreach(l, notnull_attrs)
2728 int attn = lfirst_int(l);
2730 if (heap_attisnull(tuple, attn + 1))
2732 (errcode(ERRCODE_NOT_NULL_VIOLATION),
2733 errmsg("column \"%s\" contains null values",
2734 NameStr(newTupDesc->attrs[attn]->attname))));
2737 foreach(l, tab->constraints)
2739 NewConstraint *con = lfirst(l);
2741 switch (con->contype)
2744 if (!ExecQual(con->qualstate, econtext, true))
2746 (errcode(ERRCODE_CHECK_VIOLATION),
2747 errmsg("check constraint \"%s\" is violated by some row",
2750 case CONSTR_FOREIGN:
2751 /* Nothing to do here */
2754 elog(ERROR, "unrecognized constraint type: %d",
2755 (int) con->contype);
2759 /* Write the tuple out to the new relation */
2761 simple_heap_insert(newrel, tuple);
2763 ResetExprContext(econtext);
2765 CHECK_FOR_INTERRUPTS();
2768 MemoryContextSwitchTo(oldCxt);
2771 ExecDropSingleTupleTableSlot(oldslot);
2772 ExecDropSingleTupleTableSlot(newslot);
2775 FreeExecutorState(estate);
2777 heap_close(oldrel, NoLock);
2779 heap_close(newrel, NoLock);
2783 * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
2785 static AlteredTableInfo *
2786 ATGetQueueEntry(List **wqueue, Relation rel)
2788 Oid relid = RelationGetRelid(rel);
2789 AlteredTableInfo *tab;
2792 foreach(ltab, *wqueue)
2794 tab = (AlteredTableInfo *) lfirst(ltab);
2795 if (tab->relid == relid)
2800 * Not there, so add it. Note that we make a copy of the relation's
2801 * existing descriptor before anything interesting can happen to it.
2803 tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
2805 tab->relkind = rel->rd_rel->relkind;
2806 tab->oldDesc = CreateTupleDescCopy(RelationGetDescr(rel));
2808 *wqueue = lappend(*wqueue, tab);
2814 * ATSimplePermissions
2816 * - Ensure that it is a relation (or possibly a view)
2817 * - Ensure this user is the owner
2818 * - Ensure that it is not a system table
2821 ATSimplePermissions(Relation rel, bool allowView)
2823 if (rel->rd_rel->relkind != RELKIND_RELATION)
2827 if (rel->rd_rel->relkind != RELKIND_VIEW)
2829 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2830 errmsg("\"%s\" is not a table or view",
2831 RelationGetRelationName(rel))));
2835 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2836 errmsg("\"%s\" is not a table",
2837 RelationGetRelationName(rel))));
2840 /* Permissions checks */
2841 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
2842 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
2843 RelationGetRelationName(rel));
2845 if (!allowSystemTableMods && IsSystemRelation(rel))
2847 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2848 errmsg("permission denied: \"%s\" is a system catalog",
2849 RelationGetRelationName(rel))));
2853 * ATSimplePermissionsRelationOrIndex
2855 * - Ensure that it is a relation or an index
2856 * - Ensure this user is the owner
2857 * - Ensure that it is not a system table
2860 ATSimplePermissionsRelationOrIndex(Relation rel)
2862 if (rel->rd_rel->relkind != RELKIND_RELATION &&
2863 rel->rd_rel->relkind != RELKIND_INDEX)
2865 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2866 errmsg("\"%s\" is not a table or index",
2867 RelationGetRelationName(rel))));
2869 /* Permissions checks */
2870 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
2871 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
2872 RelationGetRelationName(rel));
2874 if (!allowSystemTableMods && IsSystemRelation(rel))
2876 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2877 errmsg("permission denied: \"%s\" is a system catalog",
2878 RelationGetRelationName(rel))));
2884 * Simple table recursion sufficient for most ALTER TABLE operations.
2885 * All direct and indirect children are processed in an unspecified order.
2886 * Note that if a child inherits from the original table via multiple
2887 * inheritance paths, it will be visited just once.
2890 ATSimpleRecursion(List **wqueue, Relation rel,
2891 AlterTableCmd *cmd, bool recurse)
2894 * Propagate to children if desired. Non-table relations never have
2895 * children, so no need to search in that case.
2897 if (recurse && rel->rd_rel->relkind == RELKIND_RELATION)
2899 Oid relid = RelationGetRelid(rel);
2903 /* this routine is actually in the planner */
2904 children = find_all_inheritors(relid);
2907 * find_all_inheritors does the recursive search of the inheritance
2908 * hierarchy, so all we have to do is process all of the relids in the
2909 * list that it returns.
2911 foreach(child, children)
2913 Oid childrelid = lfirst_oid(child);
2916 if (childrelid == relid)
2918 childrel = relation_open(childrelid, AccessExclusiveLock);
2919 ATPrepCmd(wqueue, childrel, cmd, false, true);
2920 relation_close(childrel, NoLock);
2926 * ATOneLevelRecursion
2928 * Here, we visit only direct inheritance children. It is expected that
2929 * the command's prep routine will recurse again to find indirect children.
2930 * When using this technique, a multiply-inheriting child will be visited
2934 ATOneLevelRecursion(List **wqueue, Relation rel,
2937 Oid relid = RelationGetRelid(rel);
2941 /* this routine is actually in the planner */
2942 children = find_inheritance_children(relid);
2944 foreach(child, children)
2946 Oid childrelid = lfirst_oid(child);
2949 childrel = relation_open(childrelid, AccessExclusiveLock);
2950 ATPrepCmd(wqueue, childrel, cmd, true, true);
2951 relation_close(childrel, NoLock);
2957 * find_composite_type_dependencies
2959 * Check to see if a table's rowtype is being used as a column in some
2960 * other table (possibly nested several levels deep in composite types!).
2961 * Eventually, we'd like to propagate the check or rewrite operation
2962 * into other such tables, but for now, just error out if we find any.
2964 * We assume that functions and views depending on the type are not reasons
2965 * to reject the ALTER. (How safe is this really?)
2968 find_composite_type_dependencies(Oid typeOid, const char *origTblName)
2972 SysScanDesc depScan;
2976 * We scan pg_depend to find those things that depend on the rowtype. (We
2977 * assume we can ignore refobjsubid for a rowtype.)
2979 depRel = heap_open(DependRelationId, AccessShareLock);
2981 ScanKeyInit(&key[0],
2982 Anum_pg_depend_refclassid,
2983 BTEqualStrategyNumber, F_OIDEQ,
2984 ObjectIdGetDatum(TypeRelationId));
2985 ScanKeyInit(&key[1],
2986 Anum_pg_depend_refobjid,
2987 BTEqualStrategyNumber, F_OIDEQ,
2988 ObjectIdGetDatum(typeOid));
2990 depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
2991 SnapshotNow, 2, key);
2993 while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
2995 Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
2997 Form_pg_attribute att;
2999 /* Ignore dependees that aren't user columns of relations */
3000 /* (we assume system columns are never of rowtypes) */
3001 if (pg_depend->classid != RelationRelationId ||
3002 pg_depend->objsubid <= 0)
3005 rel = relation_open(pg_depend->objid, AccessShareLock);
3006 att = rel->rd_att->attrs[pg_depend->objsubid - 1];
3008 if (rel->rd_rel->relkind == RELKIND_RELATION)
3011 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3012 errmsg("cannot alter table \"%s\" because column \"%s\".\"%s\" uses its rowtype",
3014 RelationGetRelationName(rel),
3015 NameStr(att->attname))));
3017 else if (OidIsValid(rel->rd_rel->reltype))
3020 * A view or composite type itself isn't a problem, but we must
3021 * recursively check for indirect dependencies via its rowtype.
3023 find_composite_type_dependencies(rel->rd_rel->reltype,
3027 relation_close(rel, AccessShareLock);
3030 systable_endscan(depScan);
3032 relation_close(depRel, AccessShareLock);
3037 * ALTER TABLE ADD COLUMN
3039 * Adds an additional attribute to a relation making the assumption that
3040 * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
3041 * AT_AddColumn AlterTableCmd by analyze.c and added as independent
3045 ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
3049 * Recurse to add the column to child classes, if requested.
3051 * We must recurse one level at a time, so that multiply-inheriting
3052 * children are visited the right number of times and end up with the
3053 * right attinhcount.
3057 AlterTableCmd *childCmd = copyObject(cmd);
3058 ColumnDef *colDefChild = (ColumnDef *) childCmd->def;
3060 /* Child should see column as singly inherited */
3061 colDefChild->inhcount = 1;
3062 colDefChild->is_local = false;
3064 ATOneLevelRecursion(wqueue, rel, childCmd);
3069 * If we are told not to recurse, there had better not be any child
3070 * tables; else the addition would put them out of step.
3072 if (find_inheritance_children(RelationGetRelid(rel)) != NIL)
3074 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3075 errmsg("column must be added to child tables too")));
3080 ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
3083 Oid myrelid = RelationGetRelid(rel);
3087 HeapTuple attributeTuple;
3088 Form_pg_attribute attribute;
3089 FormData_pg_attribute attributeD;
3093 HeapTuple typeTuple;
3098 attrdesc = heap_open(AttributeRelationId, RowExclusiveLock);
3101 * Are we adding the column to a recursion child? If so, check whether to
3102 * merge with an existing definition for the column.
3104 if (colDef->inhcount > 0)
3108 /* Does child already have a column by this name? */
3109 tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
3110 if (HeapTupleIsValid(tuple))
3112 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
3114 /* Okay if child matches by type */
3115 if (typenameTypeId(NULL, colDef->typename) != childatt->atttypid ||
3116 colDef->typename->typmod != childatt->atttypmod)
3118 (errcode(ERRCODE_DATATYPE_MISMATCH),
3119 errmsg("child table \"%s\" has different type for column \"%s\"",
3120 RelationGetRelationName(rel), colDef->colname)));
3122 /* Bump the existing child att's inhcount */
3123 childatt->attinhcount++;
3124 simple_heap_update(attrdesc, &tuple->t_self, tuple);
3125 CatalogUpdateIndexes(attrdesc, tuple);
3127 heap_freetuple(tuple);
3129 /* Inform the user about the merge */
3131 (errmsg("merging definition of column \"%s\" for child \"%s\"",
3132 colDef->colname, RelationGetRelationName(rel))));
3134 heap_close(attrdesc, RowExclusiveLock);
3139 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
3141 reltup = SearchSysCacheCopy(RELOID,
3142 ObjectIdGetDatum(myrelid),
3144 if (!HeapTupleIsValid(reltup))
3145 elog(ERROR, "cache lookup failed for relation %u", myrelid);
3148 * this test is deliberately not attisdropped-aware, since if one tries to
3149 * add a column matching a dropped column name, it's gonna fail anyway.
3151 if (SearchSysCacheExists(ATTNAME,
3152 ObjectIdGetDatum(myrelid),
3153 PointerGetDatum(colDef->colname),
3156 (errcode(ERRCODE_DUPLICATE_COLUMN),
3157 errmsg("column \"%s\" of relation \"%s\" already exists",
3158 colDef->colname, RelationGetRelationName(rel))));
3160 minattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts;
3161 maxatts = minattnum + 1;
3162 if (maxatts > MaxHeapAttributeNumber)
3164 (errcode(ERRCODE_TOO_MANY_COLUMNS),
3165 errmsg("tables can have at most %d columns",
3166 MaxHeapAttributeNumber)));
3169 typeTuple = typenameType(NULL, colDef->typename);
3170 tform = (Form_pg_type) GETSTRUCT(typeTuple);
3171 typeOid = HeapTupleGetOid(typeTuple);
3173 /* make sure datatype is legal for a column */
3174 CheckAttributeType(colDef->colname, typeOid);
3176 attributeTuple = heap_addheader(Natts_pg_attribute,
3178 ATTRIBUTE_TUPLE_SIZE,
3179 (void *) &attributeD);
3181 attribute = (Form_pg_attribute) GETSTRUCT(attributeTuple);
3183 attribute->attrelid = myrelid;
3184 namestrcpy(&(attribute->attname), colDef->colname);
3185 attribute->atttypid = typeOid;
3186 attribute->attstattarget = -1;
3187 attribute->attlen = tform->typlen;
3188 attribute->attcacheoff = -1;
3189 attribute->atttypmod = colDef->typename->typmod;
3190 attribute->attnum = i;
3191 attribute->attbyval = tform->typbyval;
3192 attribute->attndims = list_length(colDef->typename->arrayBounds);
3193 attribute->attstorage = tform->typstorage;
3194 attribute->attalign = tform->typalign;
3195 attribute->attnotnull = colDef->is_not_null;
3196 attribute->atthasdef = false;
3197 attribute->attisdropped = false;
3198 attribute->attislocal = colDef->is_local;
3199 attribute->attinhcount = colDef->inhcount;
3201 ReleaseSysCache(typeTuple);
3203 simple_heap_insert(attrdesc, attributeTuple);
3205 /* Update indexes on pg_attribute */
3206 CatalogUpdateIndexes(attrdesc, attributeTuple);
3208 heap_close(attrdesc, RowExclusiveLock);
3211 * Update number of attributes in pg_class tuple
3213 ((Form_pg_class) GETSTRUCT(reltup))->relnatts = maxatts;
3215 simple_heap_update(pgclass, &reltup->t_self, reltup);
3217 /* keep catalog indexes current */
3218 CatalogUpdateIndexes(pgclass, reltup);
3220 heap_freetuple(reltup);
3222 heap_close(pgclass, RowExclusiveLock);
3224 /* Make the attribute's catalog entry visible */
3225 CommandCounterIncrement();
3228 * Store the DEFAULT, if any, in the catalogs
3230 if (colDef->raw_default)
3232 RawColumnDefault *rawEnt;
3234 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3235 rawEnt->attnum = attribute->attnum;
3236 rawEnt->raw_default = copyObject(colDef->raw_default);
3239 * This function is intended for CREATE TABLE, so it processes a
3240 * _list_ of defaults, but we just do one.
3242 AddRelationRawConstraints(rel, list_make1(rawEnt), NIL);
3244 /* Make the additional catalog changes visible */
3245 CommandCounterIncrement();
3249 * Tell Phase 3 to fill in the default expression, if there is one.
3251 * If there is no default, Phase 3 doesn't have to do anything, because
3252 * that effectively means that the default is NULL. The heap tuple access
3253 * routines always check for attnum > # of attributes in tuple, and return
3254 * NULL if so, so without any modification of the tuple data we will get
3255 * the effect of NULL values in the new column.
3257 * An exception occurs when the new column is of a domain type: the domain
3258 * might have a NOT NULL constraint, or a check constraint that indirectly
3259 * rejects nulls. If there are any domain constraints then we construct
3260 * an explicit NULL default value that will be passed through
3261 * CoerceToDomain processing. (This is a tad inefficient, since it causes
3262 * rewriting the table which we really don't have to do, but the present
3263 * design of domain processing doesn't offer any simple way of checking
3264 * the constraints more directly.)
3266 * Note: we use build_column_default, and not just the cooked default
3267 * returned by AddRelationRawConstraints, so that the right thing happens
3268 * when a datatype's default applies.
3270 defval = (Expr *) build_column_default(rel, attribute->attnum);
3272 if (!defval && GetDomainConstraints(typeOid) != NIL)
3274 Oid basetype = getBaseType(typeOid);
3276 defval = (Expr *) makeNullConst(basetype);
3277 defval = (Expr *) coerce_to_target_type(NULL,
3281 colDef->typename->typmod,
3282 COERCION_ASSIGNMENT,
3283 COERCE_IMPLICIT_CAST);
3284 if (defval == NULL) /* should not happen */
3285 elog(ERROR, "failed to coerce base type to domain");
3290 NewColumnValue *newval;
3292 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
3293 newval->attnum = attribute->attnum;
3294 newval->expr = defval;
3296 tab->newvals = lappend(tab->newvals, newval);
3300 * Add needed dependency entries for the new column.
3302 add_column_datatype_dependency(myrelid, i, attribute->atttypid);
3306 * Install a column's dependency on its datatype.
3309 add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
3311 ObjectAddress myself,
3314 myself.classId = RelationRelationId;
3315 myself.objectId = relid;
3316 myself.objectSubId = attnum;
3317 referenced.classId = TypeRelationId;
3318 referenced.objectId = typid;
3319 referenced.objectSubId = 0;
3320 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
3324 * ALTER TABLE ALTER COLUMN DROP NOT NULL
3327 ATExecDropNotNull(Relation rel, const char *colName)
3333 ListCell *indexoidscan;
3336 * lookup the attribute
3338 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3340 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3342 if (!HeapTupleIsValid(tuple))
3344 (errcode(ERRCODE_UNDEFINED_COLUMN),
3345 errmsg("column \"%s\" of relation \"%s\" does not exist",
3346 colName, RelationGetRelationName(rel))));
3348 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3350 /* Prevent them from altering a system attribute */
3353 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3354 errmsg("cannot alter system column \"%s\"",
3358 * Check that the attribute is not in a primary key
3361 /* Loop over all indexes on the relation */
3362 indexoidlist = RelationGetIndexList(rel);
3364 foreach(indexoidscan, indexoidlist)
3366 Oid indexoid = lfirst_oid(indexoidscan);
3367 HeapTuple indexTuple;
3368 Form_pg_index indexStruct;
3371 indexTuple = SearchSysCache(INDEXRELID,
3372 ObjectIdGetDatum(indexoid),
3374 if (!HeapTupleIsValid(indexTuple))
3375 elog(ERROR, "cache lookup failed for index %u", indexoid);
3376 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
3378 /* If the index is not a primary key, skip the check */
3379 if (indexStruct->indisprimary)
3382 * Loop over each attribute in the primary key and see if it
3383 * matches the to-be-altered attribute
3385 for (i = 0; i < indexStruct->indnatts; i++)
3387 if (indexStruct->indkey.values[i] == attnum)
3389 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3390 errmsg("column \"%s\" is in a primary key",
3395 ReleaseSysCache(indexTuple);
3398 list_free(indexoidlist);
3401 * Okay, actually perform the catalog change ... if needed
3403 if (((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3405 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = FALSE;
3407 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3409 /* keep the system catalog indexes current */
3410 CatalogUpdateIndexes(attr_rel, tuple);
3413 heap_close(attr_rel, RowExclusiveLock);
3417 * ALTER TABLE ALTER COLUMN SET NOT NULL
3420 ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
3421 const char *colName)
3428 * lookup the attribute
3430 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3432 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3434 if (!HeapTupleIsValid(tuple))
3436 (errcode(ERRCODE_UNDEFINED_COLUMN),
3437 errmsg("column \"%s\" of relation \"%s\" does not exist",
3438 colName, RelationGetRelationName(rel))));
3440 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3442 /* Prevent them from altering a system attribute */
3445 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3446 errmsg("cannot alter system column \"%s\"",
3450 * Okay, actually perform the catalog change ... if needed
3452 if (!((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3454 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = TRUE;
3456 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3458 /* keep the system catalog indexes current */
3459 CatalogUpdateIndexes(attr_rel, tuple);
3461 /* Tell Phase 3 it needs to test the constraint */
3462 tab->new_notnull = true;
3465 heap_close(attr_rel, RowExclusiveLock);
3469 * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
3472 ATExecColumnDefault(Relation rel, const char *colName,
3478 * get the number of the attribute
3480 attnum = get_attnum(RelationGetRelid(rel), colName);
3481 if (attnum == InvalidAttrNumber)
3483 (errcode(ERRCODE_UNDEFINED_COLUMN),
3484 errmsg("column \"%s\" of relation \"%s\" does not exist",
3485 colName, RelationGetRelationName(rel))));
3487 /* Prevent them from altering a system attribute */
3490 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3491 errmsg("cannot alter system column \"%s\"",
3495 * Remove any old default for the column. We use RESTRICT here for
3496 * safety, but at present we do not expect anything to depend on the
3499 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false);
3504 RawColumnDefault *rawEnt;
3506 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3507 rawEnt->attnum = attnum;
3508 rawEnt->raw_default = newDefault;
3511 * This function is intended for CREATE TABLE, so it processes a
3512 * _list_ of defaults, but we just do one.
3514 AddRelationRawConstraints(rel, list_make1(rawEnt), NIL);
3519 * ALTER TABLE ALTER COLUMN SET STATISTICS
3522 ATPrepSetStatistics(Relation rel, const char *colName, Node *flagValue)
3525 * We do our own permission checking because (a) we want to allow SET
3526 * STATISTICS on indexes (for expressional index columns), and (b) we want
3527 * to allow SET STATISTICS on system catalogs without requiring
3528 * allowSystemTableMods to be turned on.
3530 if (rel->rd_rel->relkind != RELKIND_RELATION &&
3531 rel->rd_rel->relkind != RELKIND_INDEX)
3533 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3534 errmsg("\"%s\" is not a table or index",
3535 RelationGetRelationName(rel))));
3537 /* Permissions checks */
3538 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3539 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3540 RelationGetRelationName(rel));
3544 ATExecSetStatistics(Relation rel, const char *colName, Node *newValue)
3547 Relation attrelation;
3549 Form_pg_attribute attrtuple;
3551 Assert(IsA(newValue, Integer));
3552 newtarget = intVal(newValue);
3555 * Limit target to a sane range
3560 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3561 errmsg("statistics target %d is too low",
3564 else if (newtarget > 1000)
3568 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3569 errmsg("lowering statistics target to %d",
3573 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
3575 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3577 if (!HeapTupleIsValid(tuple))
3579 (errcode(ERRCODE_UNDEFINED_COLUMN),
3580 errmsg("column \"%s\" of relation \"%s\" does not exist",
3581 colName, RelationGetRelationName(rel))));
3582 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
3584 if (attrtuple->attnum <= 0)
3586 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3587 errmsg("cannot alter system column \"%s\"",
3590 attrtuple->attstattarget = newtarget;
3592 simple_heap_update(attrelation, &tuple->t_self, tuple);
3594 /* keep system catalog indexes current */
3595 CatalogUpdateIndexes(attrelation, tuple);
3597 heap_freetuple(tuple);
3599 heap_close(attrelation, RowExclusiveLock);
3603 * ALTER TABLE ALTER COLUMN SET STORAGE
3606 ATExecSetStorage(Relation rel, const char *colName, Node *newValue)
3610 Relation attrelation;
3612 Form_pg_attribute attrtuple;
3614 Assert(IsA(newValue, String));
3615 storagemode = strVal(newValue);
3617 if (pg_strcasecmp(storagemode, "plain") == 0)
3619 else if (pg_strcasecmp(storagemode, "external") == 0)
3621 else if (pg_strcasecmp(storagemode, "extended") == 0)
3623 else if (pg_strcasecmp(storagemode, "main") == 0)
3628 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3629 errmsg("invalid storage type \"%s\"",
3631 newstorage = 0; /* keep compiler quiet */
3634 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
3636 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3638 if (!HeapTupleIsValid(tuple))
3640 (errcode(ERRCODE_UNDEFINED_COLUMN),
3641 errmsg("column \"%s\" of relation \"%s\" does not exist",
3642 colName, RelationGetRelationName(rel))));
3643 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
3645 if (attrtuple->attnum <= 0)
3647 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3648 errmsg("cannot alter system column \"%s\"",
3652 * safety check: do not allow toasted storage modes unless column datatype
3655 if (newstorage == 'p' || TypeIsToastable(attrtuple->atttypid))
3656 attrtuple->attstorage = newstorage;
3659 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3660 errmsg("column data type %s can only have storage PLAIN",
3661 format_type_be(attrtuple->atttypid))));
3663 simple_heap_update(attrelation, &tuple->t_self, tuple);
3665 /* keep system catalog indexes current */
3666 CatalogUpdateIndexes(attrelation, tuple);
3668 heap_freetuple(tuple);
3670 heap_close(attrelation, RowExclusiveLock);
3675 * ALTER TABLE DROP COLUMN
3677 * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
3678 * because we have to decide at runtime whether to recurse or not depending
3679 * on whether attinhcount goes to zero or not. (We can't check this in a
3680 * static pre-pass because it won't handle multiple inheritance situations
3681 * correctly.) Since DROP COLUMN doesn't need to create any work queue
3682 * entries for Phase 3, it's okay to recurse internally in this routine
3683 * without considering the work queue.
3686 ATExecDropColumn(Relation rel, const char *colName,
3687 DropBehavior behavior,
3688 bool recurse, bool recursing)
3691 Form_pg_attribute targetatt;
3694 ObjectAddress object;
3696 /* At top level, permission check was done in ATPrepCmd, else do it */
3698 ATSimplePermissions(rel, false);
3701 * get the number of the attribute
3703 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
3704 if (!HeapTupleIsValid(tuple))
3706 (errcode(ERRCODE_UNDEFINED_COLUMN),
3707 errmsg("column \"%s\" of relation \"%s\" does not exist",
3708 colName, RelationGetRelationName(rel))));
3709 targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
3711 attnum = targetatt->attnum;
3713 /* Can't drop a system attribute, except OID */
3714 if (attnum <= 0 && attnum != ObjectIdAttributeNumber)
3716 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3717 errmsg("cannot drop system column \"%s\"",
3720 /* Don't drop inherited columns */
3721 if (targetatt->attinhcount > 0 && !recursing)
3723 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3724 errmsg("cannot drop inherited column \"%s\"",
3727 ReleaseSysCache(tuple);
3730 * Propagate to children as appropriate. Unlike most other ALTER
3731 * routines, we have to do this one level of recursion at a time; we can't
3732 * use find_all_inheritors to do it in one pass.
3734 children = find_inheritance_children(RelationGetRelid(rel));
3741 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3742 foreach(child, children)
3744 Oid childrelid = lfirst_oid(child);
3746 Form_pg_attribute childatt;
3748 childrel = heap_open(childrelid, AccessExclusiveLock);
3750 tuple = SearchSysCacheCopyAttName(childrelid, colName);
3751 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
3752 elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
3753 colName, childrelid);
3754 childatt = (Form_pg_attribute) GETSTRUCT(tuple);
3756 if (childatt->attinhcount <= 0) /* shouldn't happen */
3757 elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
3758 childrelid, colName);
3763 * If the child column has other definition sources, just
3764 * decrement its inheritance count; if not, recurse to delete
3767 if (childatt->attinhcount == 1 && !childatt->attislocal)
3769 /* Time to delete this child column, too */
3770 ATExecDropColumn(childrel, colName, behavior, true, true);
3774 /* Child column must survive my deletion */
3775 childatt->attinhcount--;
3777 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3779 /* keep the system catalog indexes current */
3780 CatalogUpdateIndexes(attr_rel, tuple);
3782 /* Make update visible */
3783 CommandCounterIncrement();
3789 * If we were told to drop ONLY in this table (no recursion),
3790 * we need to mark the inheritors' attribute as locally
3791 * defined rather than inherited.
3793 childatt->attinhcount--;
3794 childatt->attislocal = true;
3796 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3798 /* keep the system catalog indexes current */
3799 CatalogUpdateIndexes(attr_rel, tuple);
3801 /* Make update visible */
3802 CommandCounterIncrement();
3805 heap_freetuple(tuple);
3807 heap_close(childrel, NoLock);
3809 heap_close(attr_rel, RowExclusiveLock);
3813 * Perform the actual column deletion
3815 object.classId = RelationRelationId;
3816 object.objectId = RelationGetRelid(rel);
3817 object.objectSubId = attnum;
3819 performDeletion(&object, behavior);
3822 * If we dropped the OID column, must adjust pg_class.relhasoids
3824 if (attnum == ObjectIdAttributeNumber)
3827 Form_pg_class tuple_class;
3829 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
3831 tuple = SearchSysCacheCopy(RELOID,
3832 ObjectIdGetDatum(RelationGetRelid(rel)),
3834 if (!HeapTupleIsValid(tuple))
3835 elog(ERROR, "cache lookup failed for relation %u",
3836 RelationGetRelid(rel));
3837 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
3839 tuple_class->relhasoids = false;
3840 simple_heap_update(class_rel, &tuple->t_self, tuple);
3842 /* Keep the catalog indexes up to date */
3843 CatalogUpdateIndexes(class_rel, tuple);
3845 heap_close(class_rel, RowExclusiveLock);
3850 * ALTER TABLE ADD INDEX
3852 * There is no such command in the grammar, but the parser converts UNIQUE
3853 * and PRIMARY KEY constraints into AT_AddIndex subcommands. This lets us
3854 * schedule creation of the index at the appropriate time during ALTER.
3857 ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
3858 IndexStmt *stmt, bool is_rebuild)
3864 Assert(IsA(stmt, IndexStmt));
3866 /* suppress schema rights check when rebuilding existing index */
3867 check_rights = !is_rebuild;
3868 /* skip index build if phase 3 will have to rewrite table anyway */
3869 skip_build = (tab->newvals != NIL);
3870 /* suppress notices when rebuilding existing index */
3873 DefineIndex(stmt->relation, /* relation */
3874 stmt->idxname, /* index name */
3875 InvalidOid, /* no predefined OID */
3876 stmt->accessMethod, /* am name */
3878 stmt->indexParams, /* parameters */
3879 (Expr *) stmt->whereClause,
3885 true, /* is_alter_table */
3893 * ALTER TABLE ADD CONSTRAINT
3896 ATExecAddConstraint(AlteredTableInfo *tab, Relation rel, Node *newConstraint)
3898 switch (nodeTag(newConstraint))
3902 Constraint *constr = (Constraint *) newConstraint;
3905 * Currently, we only expect to see CONSTR_CHECK nodes
3906 * arriving here (see the preprocessing done in
3907 * parser/analyze.c). Use a switch anyway to make it easier
3908 * to add more code later.
3910 switch (constr->contype)
3918 * Call AddRelationRawConstraints to do the work.
3919 * It returns a list of cooked constraints.
3921 newcons = AddRelationRawConstraints(rel, NIL,
3922 list_make1(constr));
3923 /* Add each constraint to Phase 3's queue */
3924 foreach(lcon, newcons)
3926 CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
3927 NewConstraint *newcon;
3929 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
3930 newcon->name = ccon->name;
3931 newcon->contype = ccon->contype;
3932 /* ExecQual wants implicit-AND format */
3933 newcon->qual = (Node *)
3934 make_ands_implicit((Expr *) ccon->expr);
3936 tab->constraints = lappend(tab->constraints,
3942 elog(ERROR, "unrecognized constraint type: %d",
3943 (int) constr->contype);
3947 case T_FkConstraint:
3949 FkConstraint *fkconstraint = (FkConstraint *) newConstraint;
3952 * Assign or validate constraint name
3954 if (fkconstraint->constr_name)
3956 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
3957 RelationGetRelid(rel),
3958 RelationGetNamespace(rel),
3959 fkconstraint->constr_name))
3961 (errcode(ERRCODE_DUPLICATE_OBJECT),
3962 errmsg("constraint \"%s\" for relation \"%s\" already exists",
3963 fkconstraint->constr_name,
3964 RelationGetRelationName(rel))));
3967 fkconstraint->constr_name =
3968 ChooseConstraintName(RelationGetRelationName(rel),
3969 strVal(linitial(fkconstraint->fk_attrs)),
3971 RelationGetNamespace(rel),
3974 ATAddForeignKeyConstraint(tab, rel, fkconstraint);
3979 elog(ERROR, "unrecognized node type: %d",
3980 (int) nodeTag(newConstraint));
3985 * Add a foreign-key constraint to a single table
3987 * Subroutine for ATExecAddConstraint. Must already hold exclusive
3988 * lock on the rel, and have done appropriate validity/permissions checks
3992 ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
3993 FkConstraint *fkconstraint)
3996 AclResult aclresult;
3997 int16 pkattnum[INDEX_MAX_KEYS];
3998 int16 fkattnum[INDEX_MAX_KEYS];
3999 Oid pktypoid[INDEX_MAX_KEYS];
4000 Oid fktypoid[INDEX_MAX_KEYS];
4001 Oid opclasses[INDEX_MAX_KEYS];
4009 * Grab an exclusive lock on the pk table, so that someone doesn't delete
4010 * rows out from under us. (Although a lesser lock would do for that
4011 * purpose, we'll need exclusive lock anyway to add triggers to the pk
4012 * table; trying to start with a lesser lock will just create a risk of
4015 pkrel = heap_openrv(fkconstraint->pktable, AccessExclusiveLock);
4018 * Validity and permissions checks
4020 * Note: REFERENCES permissions checks are redundant with CREATE TRIGGER,
4021 * but we may as well error out sooner instead of later.
4023 if (pkrel->rd_rel->relkind != RELKIND_RELATION)
4025 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4026 errmsg("referenced relation \"%s\" is not a table",
4027 RelationGetRelationName(pkrel))));
4029 aclresult = pg_class_aclcheck(RelationGetRelid(pkrel), GetUserId(),
4031 if (aclresult != ACLCHECK_OK)
4032 aclcheck_error(aclresult, ACL_KIND_CLASS,
4033 RelationGetRelationName(pkrel));
4035 if (!allowSystemTableMods && IsSystemRelation(pkrel))
4037 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4038 errmsg("permission denied: \"%s\" is a system catalog",
4039 RelationGetRelationName(pkrel))));
4041 aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
4043 if (aclresult != ACLCHECK_OK)
4044 aclcheck_error(aclresult, ACL_KIND_CLASS,
4045 RelationGetRelationName(rel));
4048 * Disallow reference from permanent table to temp table or vice versa.
4049 * (The ban on perm->temp is for fairly obvious reasons. The ban on
4050 * temp->perm is because other backends might need to run the RI triggers
4051 * on the perm table, but they can't reliably see tuples the owning
4052 * backend has created in the temp table, because non-shared buffers are
4053 * used for temp tables.)
4055 if (isTempNamespace(RelationGetNamespace(pkrel)))
4057 if (!isTempNamespace(RelationGetNamespace(rel)))
4059 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4060 errmsg("cannot reference temporary table from permanent table constraint")));
4064 if (isTempNamespace(RelationGetNamespace(rel)))
4066 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4067 errmsg("cannot reference permanent table from temporary table constraint")));
4071 * Look up the referencing attributes to make sure they exist, and record
4072 * their attnums and type OIDs.
4074 MemSet(pkattnum, 0, sizeof(pkattnum));
4075 MemSet(fkattnum, 0, sizeof(fkattnum));
4076 MemSet(pktypoid, 0, sizeof(pktypoid));
4077 MemSet(fktypoid, 0, sizeof(fktypoid));
4078 MemSet(opclasses, 0, sizeof(opclasses));
4080 numfks = transformColumnNameList(RelationGetRelid(rel),
4081 fkconstraint->fk_attrs,
4082 fkattnum, fktypoid);
4085 * If the attribute list for the referenced table was omitted, lookup the
4086 * definition of the primary key and use it. Otherwise, validate the
4087 * supplied attribute list. In either case, discover the index OID and
4088 * index opclasses, and the attnums and type OIDs of the attributes.
4090 if (fkconstraint->pk_attrs == NIL)
4092 numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
4093 &fkconstraint->pk_attrs,
4099 numpks = transformColumnNameList(RelationGetRelid(pkrel),
4100 fkconstraint->pk_attrs,
4101 pkattnum, pktypoid);
4102 /* Look for an index matching the column list */
4103 indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
4107 /* Be sure referencing and referenced column types are comparable */
4108 if (numfks != numpks)
4110 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4111 errmsg("number of referencing and referenced columns for foreign key disagree")));
4113 for (i = 0; i < numpks; i++)
4116 * pktypoid[i] is the primary key table's i'th key's type fktypoid[i]
4117 * is the foreign key table's i'th key's type
4119 * Note that we look for an operator with the PK type on the left;
4120 * when the types are different this is critical because the PK index
4121 * will need operators with the indexkey on the left. (Ordinarily both
4122 * commutator operators will exist if either does, but we won't get
4123 * the right answer from the test below on opclass membership unless
4124 * we select the proper operator.)
4126 Operator o = oper(NULL, list_make1(makeString("=")),
4127 pktypoid[i], fktypoid[i],
4132 (errcode(ERRCODE_UNDEFINED_FUNCTION),
4133 errmsg("foreign key constraint \"%s\" "
4134 "cannot be implemented",
4135 fkconstraint->constr_name),
4136 errdetail("Key columns \"%s\" and \"%s\" "
4137 "are of incompatible types: %s and %s.",
4138 strVal(list_nth(fkconstraint->fk_attrs, i)),
4139 strVal(list_nth(fkconstraint->pk_attrs, i)),
4140 format_type_be(fktypoid[i]),
4141 format_type_be(pktypoid[i]))));
4144 * Check that the found operator is compatible with the PK index, and
4145 * generate a warning if not, since otherwise costly seqscans will be
4146 * incurred to check FK validity.
4148 if (!op_in_opfamily(oprid(o), get_opclass_family(opclasses[i])))
4150 (errmsg("foreign key constraint \"%s\" "
4151 "will require costly sequential scans",
4152 fkconstraint->constr_name),
4153 errdetail("Key columns \"%s\" and \"%s\" "
4154 "are of different types: %s and %s.",
4155 strVal(list_nth(fkconstraint->fk_attrs, i)),
4156 strVal(list_nth(fkconstraint->pk_attrs, i)),
4157 format_type_be(fktypoid[i]),
4158 format_type_be(pktypoid[i]))));
4164 * Tell Phase 3 to check that the constraint is satisfied by existing rows
4165 * (we can skip this during table creation).
4167 if (!fkconstraint->skip_validation)
4169 NewConstraint *newcon;
4171 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
4172 newcon->name = fkconstraint->constr_name;
4173 newcon->contype = CONSTR_FOREIGN;
4174 newcon->refrelid = RelationGetRelid(pkrel);
4175 newcon->qual = (Node *) fkconstraint;
4177 tab->constraints = lappend(tab->constraints, newcon);
4181 * Record the FK constraint in pg_constraint.
4183 constrOid = CreateConstraintEntry(fkconstraint->constr_name,
4184 RelationGetNamespace(rel),
4186 fkconstraint->deferrable,
4187 fkconstraint->initdeferred,
4188 RelationGetRelid(rel),
4191 InvalidOid, /* not a domain
4193 RelationGetRelid(pkrel),
4196 fkconstraint->fk_upd_action,
4197 fkconstraint->fk_del_action,
4198 fkconstraint->fk_matchtype,
4200 NULL, /* no check constraint */
4205 * Create the triggers that will enforce the constraint.
4207 createForeignKeyTriggers(rel, fkconstraint, constrOid);
4210 * Close pk table, but keep lock until we've committed.
4212 heap_close(pkrel, NoLock);
4217 * transformColumnNameList - transform list of column names
4219 * Lookup each name and return its attnum and type OID
4222 transformColumnNameList(Oid relId, List *colList,
4223 int16 *attnums, Oid *atttypids)
4231 char *attname = strVal(lfirst(l));
4234 atttuple = SearchSysCacheAttName(relId, attname);
4235 if (!HeapTupleIsValid(atttuple))
4237 (errcode(ERRCODE_UNDEFINED_COLUMN),
4238 errmsg("column \"%s\" referenced in foreign key constraint does not exist",
4240 if (attnum >= INDEX_MAX_KEYS)
4242 (errcode(ERRCODE_TOO_MANY_COLUMNS),
4243 errmsg("cannot have more than %d keys in a foreign key",
4245 attnums[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->attnum;
4246 atttypids[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->atttypid;
4247 ReleaseSysCache(atttuple);
4255 * transformFkeyGetPrimaryKey -
4257 * Look up the names, attnums, and types of the primary key attributes
4258 * for the pkrel. Also return the index OID and index opclasses of the
4259 * index supporting the primary key.
4261 * All parameters except pkrel are output parameters. Also, the function
4262 * return value is the number of attributes in the primary key.
4264 * Used when the column list in the REFERENCES specification is omitted.
4267 transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
4269 int16 *attnums, Oid *atttypids,
4273 ListCell *indexoidscan;
4274 HeapTuple indexTuple = NULL;
4275 Form_pg_index indexStruct = NULL;
4276 Datum indclassDatum;
4278 oidvector *indclass;
4282 * Get the list of index OIDs for the table from the relcache, and look up
4283 * each one in the pg_index syscache until we find one marked primary key
4284 * (hopefully there isn't more than one such).
4286 *indexOid = InvalidOid;
4288 indexoidlist = RelationGetIndexList(pkrel);
4290 foreach(indexoidscan, indexoidlist)
4292 Oid indexoid = lfirst_oid(indexoidscan);
4294 indexTuple = SearchSysCache(INDEXRELID,
4295 ObjectIdGetDatum(indexoid),
4297 if (!HeapTupleIsValid(indexTuple))
4298 elog(ERROR, "cache lookup failed for index %u", indexoid);
4299 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4300 if (indexStruct->indisprimary)
4302 *indexOid = indexoid;
4305 ReleaseSysCache(indexTuple);
4308 list_free(indexoidlist);
4311 * Check that we found it
4313 if (!OidIsValid(*indexOid))
4315 (errcode(ERRCODE_UNDEFINED_OBJECT),
4316 errmsg("there is no primary key for referenced table \"%s\"",
4317 RelationGetRelationName(pkrel))));
4319 /* Must get indclass the hard way */
4320 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4321 Anum_pg_index_indclass, &isnull);
4323 indclass = (oidvector *) DatumGetPointer(indclassDatum);
4326 * Now build the list of PK attributes from the indkey definition (we
4327 * assume a primary key cannot have expressional elements)
4330 for (i = 0; i < indexStruct->indnatts; i++)
4332 int pkattno = indexStruct->indkey.values[i];
4334 attnums[i] = pkattno;
4335 atttypids[i] = attnumTypeId(pkrel, pkattno);
4336 opclasses[i] = indclass->values[i];
4337 *attnamelist = lappend(*attnamelist,
4338 makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
4341 ReleaseSysCache(indexTuple);
4347 * transformFkeyCheckAttrs -
4349 * Make sure that the attributes of a referenced table belong to a unique
4350 * (or primary key) constraint. Return the OID of the index supporting
4351 * the constraint, as well as the opclasses associated with the index
4355 transformFkeyCheckAttrs(Relation pkrel,
4356 int numattrs, int16 *attnums,
4357 Oid *opclasses) /* output parameter */
4359 Oid indexoid = InvalidOid;
4362 ListCell *indexoidscan;
4365 * Get the list of index OIDs for the table from the relcache, and look up
4366 * each one in the pg_index syscache, and match unique indexes to the list
4367 * of attnums we are given.
4369 indexoidlist = RelationGetIndexList(pkrel);
4371 foreach(indexoidscan, indexoidlist)
4373 HeapTuple indexTuple;
4374 Form_pg_index indexStruct;
4378 indexoid = lfirst_oid(indexoidscan);
4379 indexTuple = SearchSysCache(INDEXRELID,
4380 ObjectIdGetDatum(indexoid),
4382 if (!HeapTupleIsValid(indexTuple))
4383 elog(ERROR, "cache lookup failed for index %u", indexoid);
4384 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4387 * Must have the right number of columns; must be unique and not a
4388 * partial index; forget it if there are any expressions, too
4390 if (indexStruct->indnatts == numattrs &&
4391 indexStruct->indisunique &&
4392 heap_attisnull(indexTuple, Anum_pg_index_indpred) &&
4393 heap_attisnull(indexTuple, Anum_pg_index_indexprs))
4395 /* Must get indclass the hard way */
4396 Datum indclassDatum;
4398 oidvector *indclass;
4400 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4401 Anum_pg_index_indclass, &isnull);
4403 indclass = (oidvector *) DatumGetPointer(indclassDatum);
4406 * The given attnum list may match the index columns in any order.
4407 * Check that each list is a subset of the other.
4409 for (i = 0; i < numattrs; i++)
4412 for (j = 0; j < numattrs; j++)
4414 if (attnums[i] == indexStruct->indkey.values[j])
4425 for (i = 0; i < numattrs; i++)
4428 for (j = 0; j < numattrs; j++)
4430 if (attnums[j] == indexStruct->indkey.values[i])
4432 opclasses[j] = indclass->values[i];
4442 ReleaseSysCache(indexTuple);
4449 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4450 errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
4451 RelationGetRelationName(pkrel))));
4453 list_free(indexoidlist);
4459 * Scan the existing rows in a table to verify they meet a proposed FK
4462 * Caller must have opened and locked both relations.
4465 validateForeignKeyConstraint(FkConstraint *fkconstraint,
4476 * See if we can do it with a single LEFT JOIN query. A FALSE result
4477 * indicates we must proceed with the fire-the-trigger method.
4479 if (RI_Initial_Check(fkconstraint, rel, pkrel))
4483 * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
4484 * if that tuple had just been inserted. If any of those fail, it should
4485 * ereport(ERROR) and that's that.
4487 MemSet(&trig, 0, sizeof(trig));
4488 trig.tgoid = InvalidOid;
4489 trig.tgname = fkconstraint->constr_name;
4490 trig.tgenabled = TRUE;
4491 trig.tgisconstraint = TRUE;
4492 trig.tgconstrrelid = RelationGetRelid(pkrel);
4493 trig.tgdeferrable = FALSE;
4494 trig.tginitdeferred = FALSE;
4496 trig.tgargs = (char **) palloc(sizeof(char *) *
4497 (4 + list_length(fkconstraint->fk_attrs)
4498 + list_length(fkconstraint->pk_attrs)));
4500 trig.tgargs[0] = trig.tgname;
4501 trig.tgargs[1] = RelationGetRelationName(rel);
4502 trig.tgargs[2] = RelationGetRelationName(pkrel);
4503 trig.tgargs[3] = fkMatchTypeToString(fkconstraint->fk_matchtype);
4505 foreach(list, fkconstraint->fk_attrs)
4507 char *fk_at = strVal(lfirst(list));
4509 trig.tgargs[count] = fk_at;
4513 foreach(list, fkconstraint->pk_attrs)
4515 char *pk_at = strVal(lfirst(list));
4517 trig.tgargs[count] = pk_at;
4520 trig.tgnargs = count - 1;
4522 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
4524 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
4526 FunctionCallInfoData fcinfo;
4527 TriggerData trigdata;
4530 * Make a call to the trigger function
4532 * No parameters are passed, but we do set a context
4534 MemSet(&fcinfo, 0, sizeof(fcinfo));
4537 * We assume RI_FKey_check_ins won't look at flinfo...
4539 trigdata.type = T_TriggerData;
4540 trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
4541 trigdata.tg_relation = rel;
4542 trigdata.tg_trigtuple = tuple;
4543 trigdata.tg_newtuple = NULL;
4544 trigdata.tg_trigger = &trig;
4545 trigdata.tg_trigtuplebuf = scan->rs_cbuf;
4546 trigdata.tg_newtuplebuf = InvalidBuffer;
4548 fcinfo.context = (Node *) &trigdata;
4550 RI_FKey_check_ins(&fcinfo);
4559 CreateFKCheckTrigger(RangeVar *myRel, FkConstraint *fkconstraint,
4560 ObjectAddress *constrobj, ObjectAddress *trigobj,
4563 CreateTrigStmt *fk_trigger;
4567 fk_trigger = makeNode(CreateTrigStmt);
4568 fk_trigger->trigname = fkconstraint->constr_name;
4569 fk_trigger->relation = myRel;
4570 fk_trigger->before = false;
4571 fk_trigger->row = true;
4573 /* Either ON INSERT or ON UPDATE */
4576 fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
4577 fk_trigger->actions[0] = 'i';
4581 fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
4582 fk_trigger->actions[0] = 'u';
4584 fk_trigger->actions[1] = '\0';
4586 fk_trigger->isconstraint = true;
4587 fk_trigger->deferrable = fkconstraint->deferrable;
4588 fk_trigger->initdeferred = fkconstraint->initdeferred;
4589 fk_trigger->constrrel = fkconstraint->pktable;
4591 fk_trigger->args = NIL;
4592 fk_trigger->args = lappend(fk_trigger->args,
4593 makeString(fkconstraint->constr_name));
4594 fk_trigger->args = lappend(fk_trigger->args,
4595 makeString(myRel->relname));
4596 fk_trigger->args = lappend(fk_trigger->args,
4597 makeString(fkconstraint->pktable->relname));
4598 fk_trigger->args = lappend(fk_trigger->args,
4599 makeString(fkMatchTypeToString(fkconstraint->fk_matchtype)));
4600 if (list_length(fkconstraint->fk_attrs) != list_length(fkconstraint->pk_attrs))
4602 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4603 errmsg("number of referencing and referenced columns for foreign key disagree")));
4605 forboth(fk_attr, fkconstraint->fk_attrs,
4606 pk_attr, fkconstraint->pk_attrs)
4608 fk_trigger->args = lappend(fk_trigger->args, lfirst(fk_attr));
4609 fk_trigger->args = lappend(fk_trigger->args, lfirst(pk_attr));
4612 trigobj->objectId = CreateTrigger(fk_trigger, true);
4614 /* Register dependency from trigger to constraint */
4615 recordDependencyOn(trigobj, constrobj, DEPENDENCY_INTERNAL);
4617 /* Make changes-so-far visible */
4618 CommandCounterIncrement();
4622 * Create the triggers that implement an FK constraint.
4625 createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
4629 CreateTrigStmt *fk_trigger;
4632 ObjectAddress trigobj,
4636 * Reconstruct a RangeVar for my relation (not passed in, unfortunately).
4638 myRel = makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
4639 pstrdup(RelationGetRelationName(rel)));
4642 * Preset objectAddress fields
4644 constrobj.classId = ConstraintRelationId;
4645 constrobj.objectId = constrOid;
4646 constrobj.objectSubId = 0;
4647 trigobj.classId = TriggerRelationId;
4648 trigobj.objectSubId = 0;
4650 /* Make changes-so-far visible */
4651 CommandCounterIncrement();
4654 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the CHECK
4655 * action for both INSERTs and UPDATEs on the referencing table.
4657 CreateFKCheckTrigger(myRel, fkconstraint, &constrobj, &trigobj, true);
4658 CreateFKCheckTrigger(myRel, fkconstraint, &constrobj, &trigobj, false);
4661 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
4662 * DELETE action on the referenced table.
4664 fk_trigger = makeNode(CreateTrigStmt);
4665 fk_trigger->trigname = fkconstraint->constr_name;
4666 fk_trigger->relation = fkconstraint->pktable;
4667 fk_trigger->before = false;
4668 fk_trigger->row = true;
4669 fk_trigger->actions[0] = 'd';
4670 fk_trigger->actions[1] = '\0';
4672 fk_trigger->isconstraint = true;
4673 fk_trigger->constrrel = myRel;
4674 switch (fkconstraint->fk_del_action)
4676 case FKCONSTR_ACTION_NOACTION:
4677 fk_trigger->deferrable = fkconstraint->deferrable;
4678 fk_trigger->initdeferred = fkconstraint->initdeferred;
4679 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
4681 case FKCONSTR_ACTION_RESTRICT:
4682 fk_trigger->deferrable = false;
4683 fk_trigger->initdeferred = false;
4684 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
4686 case FKCONSTR_ACTION_CASCADE:
4687 fk_trigger->deferrable = false;
4688 fk_trigger->initdeferred = false;
4689 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
4691 case FKCONSTR_ACTION_SETNULL:
4692 fk_trigger->deferrable = false;
4693 fk_trigger->initdeferred = false;
4694 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
4696 case FKCONSTR_ACTION_SETDEFAULT:
4697 fk_trigger->deferrable = false;
4698 fk_trigger->initdeferred = false;
4699 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
4702 elog(ERROR, "unrecognized FK action type: %d",
4703 (int) fkconstraint->fk_del_action);
4707 fk_trigger->args = NIL;
4708 fk_trigger->args = lappend(fk_trigger->args,
4709 makeString(fkconstraint->constr_name));
4710 fk_trigger->args = lappend(fk_trigger->args,
4711 makeString(myRel->relname));
4712 fk_trigger->args = lappend(fk_trigger->args,
4713 makeString(fkconstraint->pktable->relname));
4714 fk_trigger->args = lappend(fk_trigger->args,
4715 makeString(fkMatchTypeToString(fkconstraint->fk_matchtype)));
4716 forboth(fk_attr, fkconstraint->fk_attrs,
4717 pk_attr, fkconstraint->pk_attrs)
4719 fk_trigger->args = lappend(fk_trigger->args, lfirst(fk_attr));
4720 fk_trigger->args = lappend(fk_trigger->args, lfirst(pk_attr));
4723 trigobj.objectId = CreateTrigger(fk_trigger, true);
4725 /* Register dependency from trigger to constraint */
4726 recordDependencyOn(&trigobj, &constrobj, DEPENDENCY_INTERNAL);
4728 /* Make changes-so-far visible */
4729 CommandCounterIncrement();
4732 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
4733 * UPDATE action on the referenced table.
4735 fk_trigger = makeNode(CreateTrigStmt);
4736 fk_trigger->trigname = fkconstraint->constr_name;
4737 fk_trigger->relation = fkconstraint->pktable;
4738 fk_trigger->before = false;
4739 fk_trigger->row = true;
4740 fk_trigger->actions[0] = 'u';
4741 fk_trigger->actions[1] = '\0';
4742 fk_trigger->isconstraint = true;
4743 fk_trigger->constrrel = myRel;
4744 switch (fkconstraint->fk_upd_action)
4746 case FKCONSTR_ACTION_NOACTION:
4747 fk_trigger->deferrable = fkconstraint->deferrable;
4748 fk_trigger->initdeferred = fkconstraint->initdeferred;
4749 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
4751 case FKCONSTR_ACTION_RESTRICT:
4752 fk_trigger->deferrable = false;
4753 fk_trigger->initdeferred = false;
4754 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
4756 case FKCONSTR_ACTION_CASCADE:
4757 fk_trigger->deferrable = false;
4758 fk_trigger->initdeferred = false;
4759 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
4761 case FKCONSTR_ACTION_SETNULL:
4762 fk_trigger->deferrable = false;
4763 fk_trigger->initdeferred = false;
4764 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
4766 case FKCONSTR_ACTION_SETDEFAULT:
4767 fk_trigger->deferrable = false;
4768 fk_trigger->initdeferred = false;
4769 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
4772 elog(ERROR, "unrecognized FK action type: %d",
4773 (int) fkconstraint->fk_upd_action);
4777 fk_trigger->args = NIL;
4778 fk_trigger->args = lappend(fk_trigger->args,
4779 makeString(fkconstraint->constr_name));
4780 fk_trigger->args = lappend(fk_trigger->args,
4781 makeString(myRel->relname));
4782 fk_trigger->args = lappend(fk_trigger->args,
4783 makeString(fkconstraint->pktable->relname));
4784 fk_trigger->args = lappend(fk_trigger->args,
4785 makeString(fkMatchTypeToString(fkconstraint->fk_matchtype)));
4786 forboth(fk_attr, fkconstraint->fk_attrs,
4787 pk_attr, fkconstraint->pk_attrs)
4789 fk_trigger->args = lappend(fk_trigger->args, lfirst(fk_attr));
4790 fk_trigger->args = lappend(fk_trigger->args, lfirst(pk_attr));
4793 trigobj.objectId = CreateTrigger(fk_trigger, true);
4795 /* Register dependency from trigger to constraint */
4796 recordDependencyOn(&trigobj, &constrobj, DEPENDENCY_INTERNAL);
4800 * fkMatchTypeToString -
4801 * convert FKCONSTR_MATCH_xxx code to string to use in trigger args
4804 fkMatchTypeToString(char match_type)
4808 case FKCONSTR_MATCH_FULL:
4809 return pstrdup("FULL");
4810 case FKCONSTR_MATCH_PARTIAL:
4811 return pstrdup("PARTIAL");
4812 case FKCONSTR_MATCH_UNSPECIFIED:
4813 return pstrdup("UNSPECIFIED");
4815 elog(ERROR, "unrecognized match type: %d",
4818 return NULL; /* can't get here */
4822 * ALTER TABLE DROP CONSTRAINT
4825 ATPrepDropConstraint(List **wqueue, Relation rel,
4826 bool recurse, AlterTableCmd *cmd)
4829 * We don't want errors or noise from child tables, so we have to pass
4830 * down a modified command.
4834 AlterTableCmd *childCmd = copyObject(cmd);
4836 childCmd->subtype = AT_DropConstraintQuietly;
4837 ATSimpleRecursion(wqueue, rel, childCmd, recurse);
4842 ATExecDropConstraint(Relation rel, const char *constrName,
4843 DropBehavior behavior, bool quiet)
4847 deleted = RemoveRelConstraints(rel, constrName, behavior);
4851 /* If zero constraints deleted, complain */
4854 (errcode(ERRCODE_UNDEFINED_OBJECT),
4855 errmsg("constraint \"%s\" does not exist",
4857 /* Otherwise if more than one constraint deleted, notify */
4858 else if (deleted > 1)
4860 (errmsg("multiple constraints named \"%s\" were dropped",
4869 ATPrepAlterColumnType(List **wqueue,
4870 AlteredTableInfo *tab, Relation rel,
4871 bool recurse, bool recursing,
4874 char *colName = cmd->name;
4875 TypeName *typename = (TypeName *) cmd->def;
4877 Form_pg_attribute attTup;
4881 NewColumnValue *newval;
4882 ParseState *pstate = make_parsestate(NULL);
4884 /* lookup the attribute so we can check inheritance status */
4885 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
4886 if (!HeapTupleIsValid(tuple))
4888 (errcode(ERRCODE_UNDEFINED_COLUMN),
4889 errmsg("column \"%s\" of relation \"%s\" does not exist",
4890 colName, RelationGetRelationName(rel))));
4891 attTup = (Form_pg_attribute) GETSTRUCT(tuple);
4892 attnum = attTup->attnum;
4894 /* Can't alter a system attribute */
4897 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4898 errmsg("cannot alter system column \"%s\"",
4901 /* Don't alter inherited columns */
4902 if (attTup->attinhcount > 0 && !recursing)
4904 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4905 errmsg("cannot alter inherited column \"%s\"",
4908 /* Look up the target type */
4909 targettype = typenameTypeId(NULL, typename);
4911 /* make sure datatype is legal for a column */
4912 CheckAttributeType(colName, targettype);
4915 * Set up an expression to transform the old data value to the new type.
4916 * If a USING option was given, transform and use that expression, else
4917 * just take the old value and try to coerce it. We do this first so that
4918 * type incompatibility can be detected before we waste effort, and
4919 * because we need the expression to be parsed against the original table
4926 /* Expression must be able to access vars of old table */
4927 rte = addRangeTableEntryForRelation(pstate,
4932 addRTEtoQuery(pstate, rte, false, true, true);
4934 transform = transformExpr(pstate, cmd->transform);
4936 /* It can't return a set */
4937 if (expression_returns_set(transform))
4939 (errcode(ERRCODE_DATATYPE_MISMATCH),
4940 errmsg("transform expression must not return a set")));
4942 /* No subplans or aggregates, either... */
4943 if (pstate->p_hasSubLinks)
4945 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4946 errmsg("cannot use subquery in transform expression")));
4947 if (pstate->p_hasAggs)
4949 (errcode(ERRCODE_GROUPING_ERROR),
4950 errmsg("cannot use aggregate function in transform expression")));
4954 transform = (Node *) makeVar(1, attnum,
4955 attTup->atttypid, attTup->atttypmod,
4959 transform = coerce_to_target_type(pstate,
4960 transform, exprType(transform),
4961 targettype, typename->typmod,
4962 COERCION_ASSIGNMENT,
4963 COERCE_IMPLICIT_CAST);
4964 if (transform == NULL)
4966 (errcode(ERRCODE_DATATYPE_MISMATCH),
4967 errmsg("column \"%s\" cannot be cast to type \"%s\"",
4968 colName, TypeNameToString(typename))));
4971 * Add a work queue item to make ATRewriteTable update the column
4974 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
4975 newval->attnum = attnum;
4976 newval->expr = (Expr *) transform;
4978 tab->newvals = lappend(tab->newvals, newval);
4980 ReleaseSysCache(tuple);
4983 * The recursion case is handled by ATSimpleRecursion. However, if we are
4984 * told not to recurse, there had better not be any child tables; else the
4985 * alter would put them out of step.
4988 ATSimpleRecursion(wqueue, rel, cmd, recurse);
4989 else if (!recursing &&
4990 find_inheritance_children(RelationGetRelid(rel)) != NIL)
4992 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4993 errmsg("type of inherited column \"%s\" must be changed in child tables too",
4998 ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
4999 const char *colName, TypeName *typename)
5002 Form_pg_attribute attTup;
5004 HeapTuple typeTuple;
5008 Relation attrelation;
5014 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
5016 /* Look up the target column */
5017 heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5018 if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
5020 (errcode(ERRCODE_UNDEFINED_COLUMN),
5021 errmsg("column \"%s\" of relation \"%s\" does not exist",
5022 colName, RelationGetRelationName(rel))));
5023 attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
5024 attnum = attTup->attnum;
5026 /* Check for multiple ALTER TYPE on same column --- can't cope */
5027 if (attTup->atttypid != tab->oldDesc->attrs[attnum - 1]->atttypid ||
5028 attTup->atttypmod != tab->oldDesc->attrs[attnum - 1]->atttypmod)
5030 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5031 errmsg("cannot alter type of column \"%s\" twice",
5034 /* Look up the target type (should not fail, since prep found it) */
5035 typeTuple = typenameType(NULL, typename);
5036 tform = (Form_pg_type) GETSTRUCT(typeTuple);
5037 targettype = HeapTupleGetOid(typeTuple);
5040 * If there is a default expression for the column, get it and ensure we
5041 * can coerce it to the new datatype. (We must do this before changing
5042 * the column type, because build_column_default itself will try to
5043 * coerce, and will not issue the error message we want if it fails.)
5045 * We remove any implicit coercion steps at the top level of the old
5046 * default expression; this has been agreed to satisfy the principle of
5047 * least surprise. (The conversion to the new column type should act like
5048 * it started from what the user sees as the stored expression, and the
5049 * implicit coercions aren't going to be shown.)
5051 if (attTup->atthasdef)
5053 defaultexpr = build_column_default(rel, attnum);
5054 Assert(defaultexpr);
5055 defaultexpr = strip_implicit_coercions(defaultexpr);
5056 defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
5057 defaultexpr, exprType(defaultexpr),
5058 targettype, typename->typmod,
5059 COERCION_ASSIGNMENT,
5060 COERCE_IMPLICIT_CAST);
5061 if (defaultexpr == NULL)
5063 (errcode(ERRCODE_DATATYPE_MISMATCH),
5064 errmsg("default for column \"%s\" cannot be cast to type \"%s\"",
5065 colName, TypeNameToString(typename))));
5071 * Find everything that depends on the column (constraints, indexes, etc),
5072 * and record enough information to let us recreate the objects.
5074 * The actual recreation does not happen here, but only after we have
5075 * performed all the individual ALTER TYPE operations. We have to save
5076 * the info before executing ALTER TYPE, though, else the deparser will
5079 * There could be multiple entries for the same object, so we must check
5080 * to ensure we process each one only once. Note: we assume that an index
5081 * that implements a constraint will not show a direct dependency on the
5084 depRel = heap_open(DependRelationId, RowExclusiveLock);
5086 ScanKeyInit(&key[0],
5087 Anum_pg_depend_refclassid,
5088 BTEqualStrategyNumber, F_OIDEQ,
5089 ObjectIdGetDatum(RelationRelationId));
5090 ScanKeyInit(&key[1],
5091 Anum_pg_depend_refobjid,
5092 BTEqualStrategyNumber, F_OIDEQ,
5093 ObjectIdGetDatum(RelationGetRelid(rel)));
5094 ScanKeyInit(&key[2],
5095 Anum_pg_depend_refobjsubid,
5096 BTEqualStrategyNumber, F_INT4EQ,
5097 Int32GetDatum((int32) attnum));
5099 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
5100 SnapshotNow, 3, key);
5102 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5104 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5105 ObjectAddress foundObject;
5107 /* We don't expect any PIN dependencies on columns */
5108 if (foundDep->deptype == DEPENDENCY_PIN)
5109 elog(ERROR, "cannot alter type of a pinned column");
5111 foundObject.classId = foundDep->classid;
5112 foundObject.objectId = foundDep->objid;
5113 foundObject.objectSubId = foundDep->objsubid;
5115 switch (getObjectClass(&foundObject))
5119 char relKind = get_rel_relkind(foundObject.objectId);
5121 if (relKind == RELKIND_INDEX)
5123 Assert(foundObject.objectSubId == 0);
5124 if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
5126 tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
5127 foundObject.objectId);
5128 tab->changedIndexDefs = lappend(tab->changedIndexDefs,
5129 pg_get_indexdef_string(foundObject.objectId));
5132 else if (relKind == RELKIND_SEQUENCE)
5135 * This must be a SERIAL column's sequence. We need
5136 * not do anything to it.
5138 Assert(foundObject.objectSubId == 0);
5142 /* Not expecting any other direct dependencies... */
5143 elog(ERROR, "unexpected object depending on column: %s",
5144 getObjectDescription(&foundObject));
5149 case OCLASS_CONSTRAINT:
5150 Assert(foundObject.objectSubId == 0);
5151 if (!list_member_oid(tab->changedConstraintOids,
5152 foundObject.objectId))
5154 char *defstring = pg_get_constraintdef_string(foundObject.objectId);
5157 * Put NORMAL dependencies at the front of the list and
5158 * AUTO dependencies at the back. This makes sure that
5159 * foreign-key constraints depending on this column will
5160 * be dropped before unique or primary-key constraints of
5161 * the column; which we must have because the FK
5162 * constraints depend on the indexes belonging to the
5163 * unique constraints.
5165 if (foundDep->deptype == DEPENDENCY_NORMAL)
5167 tab->changedConstraintOids =
5168 lcons_oid(foundObject.objectId,
5169 tab->changedConstraintOids);
5170 tab->changedConstraintDefs =
5172 tab->changedConstraintDefs);
5176 tab->changedConstraintOids =
5177 lappend_oid(tab->changedConstraintOids,
5178 foundObject.objectId);
5179 tab->changedConstraintDefs =
5180 lappend(tab->changedConstraintDefs,
5186 case OCLASS_REWRITE:
5187 /* XXX someday see if we can cope with revising views */
5189 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5190 errmsg("cannot alter type of a column used by a view or rule"),
5191 errdetail("%s depends on column \"%s\"",
5192 getObjectDescription(&foundObject),
5196 case OCLASS_DEFAULT:
5199 * Ignore the column's default expression, since we will fix
5202 Assert(defaultexpr);
5208 case OCLASS_CONVERSION:
5209 case OCLASS_LANGUAGE:
5210 case OCLASS_OPERATOR:
5211 case OCLASS_OPCLASS:
5212 case OCLASS_TRIGGER:
5216 * We don't expect any of these sorts of objects to depend on
5219 elog(ERROR, "unexpected object depending on column: %s",
5220 getObjectDescription(&foundObject));
5224 elog(ERROR, "unrecognized object class: %u",
5225 foundObject.classId);
5229 systable_endscan(scan);
5232 * Now scan for dependencies of this column on other things. The only
5233 * thing we should find is the dependency on the column datatype, which we
5236 ScanKeyInit(&key[0],
5237 Anum_pg_depend_classid,
5238 BTEqualStrategyNumber, F_OIDEQ,
5239 ObjectIdGetDatum(RelationRelationId));
5240 ScanKeyInit(&key[1],
5241 Anum_pg_depend_objid,
5242 BTEqualStrategyNumber, F_OIDEQ,
5243 ObjectIdGetDatum(RelationGetRelid(rel)));
5244 ScanKeyInit(&key[2],
5245 Anum_pg_depend_objsubid,
5246 BTEqualStrategyNumber, F_INT4EQ,
5247 Int32GetDatum((int32) attnum));
5249 scan = systable_beginscan(depRel, DependDependerIndexId, true,
5250 SnapshotNow, 3, key);
5252 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5254 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5256 if (foundDep->deptype != DEPENDENCY_NORMAL)
5257 elog(ERROR, "found unexpected dependency type '%c'",
5259 if (foundDep->refclassid != TypeRelationId ||
5260 foundDep->refobjid != attTup->atttypid)
5261 elog(ERROR, "found unexpected dependency for column");
5263 simple_heap_delete(depRel, &depTup->t_self);
5266 systable_endscan(scan);
5268 heap_close(depRel, RowExclusiveLock);
5271 * Here we go --- change the recorded column type. (Note heapTup is a
5272 * copy of the syscache entry, so okay to scribble on.)
5274 attTup->atttypid = targettype;
5275 attTup->atttypmod = typename->typmod;
5276 attTup->attndims = list_length(typename->arrayBounds);
5277 attTup->attlen = tform->typlen;
5278 attTup->attbyval = tform->typbyval;
5279 attTup->attalign = tform->typalign;
5280 attTup->attstorage = tform->typstorage;
5282 ReleaseSysCache(typeTuple);
5284 simple_heap_update(attrelation, &heapTup->t_self, heapTup);
5286 /* keep system catalog indexes current */
5287 CatalogUpdateIndexes(attrelation, heapTup);
5289 heap_close(attrelation, RowExclusiveLock);
5291 /* Install dependency on new datatype */
5292 add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
5295 * Drop any pg_statistic entry for the column, since it's now wrong type
5297 RemoveStatistics(RelationGetRelid(rel), attnum);
5300 * Update the default, if present, by brute force --- remove and re-add
5301 * the default. Probably unsafe to take shortcuts, since the new version
5302 * may well have additional dependencies. (It's okay to do this now,
5303 * rather than after other ALTER TYPE commands, since the default won't
5304 * depend on other column types.)
5308 /* Must make new row visible since it will be updated again */
5309 CommandCounterIncrement();
5312 * We use RESTRICT here for safety, but at present we do not expect
5313 * anything to depend on the default.
5315 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true);
5317 StoreAttrDefault(rel, attnum, nodeToString(defaultexpr));
5321 heap_freetuple(heapTup);
5325 * Cleanup after we've finished all the ALTER TYPE operations for a
5326 * particular relation. We have to drop and recreate all the indexes
5327 * and constraints that depend on the altered columns.
5330 ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab)
5336 * Re-parse the index and constraint definitions, and attach them to the
5337 * appropriate work queue entries. We do this before dropping because in
5338 * the case of a FOREIGN KEY constraint, we might not yet have exclusive
5339 * lock on the table the constraint is attached to, and we need to get
5340 * that before dropping. It's safe because the parser won't actually look
5341 * at the catalogs to detect the existing entry.
5343 foreach(l, tab->changedIndexDefs)
5344 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
5345 foreach(l, tab->changedConstraintDefs)
5346 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
5349 * Now we can drop the existing constraints and indexes --- constraints
5350 * first, since some of them might depend on the indexes. In fact, we
5351 * have to delete FOREIGN KEY constraints before UNIQUE constraints, but
5352 * we already ordered the constraint list to ensure that would happen. It
5353 * should be okay to use DROP_RESTRICT here, since nothing else should be
5354 * depending on these objects.
5356 foreach(l, tab->changedConstraintOids)
5358 obj.classId = ConstraintRelationId;
5359 obj.objectId = lfirst_oid(l);
5360 obj.objectSubId = 0;
5361 performDeletion(&obj, DROP_RESTRICT);
5364 foreach(l, tab->changedIndexOids)
5366 obj.classId = RelationRelationId;
5367 obj.objectId = lfirst_oid(l);
5368 obj.objectSubId = 0;
5369 performDeletion(&obj, DROP_RESTRICT);
5373 * The objects will get recreated during subsequent passes over the work
5379 ATPostAlterTypeParse(char *cmd, List **wqueue)
5381 List *raw_parsetree_list;
5382 List *querytree_list;
5383 ListCell *list_item;
5386 * We expect that we only have to do raw parsing and parse analysis, not
5387 * any rule rewriting, since these will all be utility statements.
5389 raw_parsetree_list = raw_parser(cmd);
5390 querytree_list = NIL;
5391 foreach(list_item, raw_parsetree_list)
5393 Node *parsetree = (Node *) lfirst(list_item);
5395 querytree_list = list_concat(querytree_list,
5396 parse_analyze(parsetree, cmd, NULL, 0));
5400 * Attach each generated command to the proper place in the work queue.
5401 * Note this could result in creation of entirely new work-queue entries.
5403 foreach(list_item, querytree_list)
5405 Query *query = (Query *) lfirst(list_item);
5407 AlteredTableInfo *tab;
5409 Assert(IsA(query, Query));
5410 Assert(query->commandType == CMD_UTILITY);
5411 switch (nodeTag(query->utilityStmt))
5415 IndexStmt *stmt = (IndexStmt *) query->utilityStmt;
5416 AlterTableCmd *newcmd;
5418 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
5419 tab = ATGetQueueEntry(wqueue, rel);
5420 newcmd = makeNode(AlterTableCmd);
5421 newcmd->subtype = AT_ReAddIndex;
5422 newcmd->def = (Node *) stmt;
5423 tab->subcmds[AT_PASS_OLD_INDEX] =
5424 lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
5425 relation_close(rel, NoLock);
5428 case T_AlterTableStmt:
5430 AlterTableStmt *stmt = (AlterTableStmt *) query->utilityStmt;
5433 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
5434 tab = ATGetQueueEntry(wqueue, rel);
5435 foreach(lcmd, stmt->cmds)
5437 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
5439 switch (cmd->subtype)
5442 cmd->subtype = AT_ReAddIndex;
5443 tab->subcmds[AT_PASS_OLD_INDEX] =
5444 lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
5446 case AT_AddConstraint:
5447 tab->subcmds[AT_PASS_OLD_CONSTR] =
5448 lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
5451 elog(ERROR, "unexpected statement type: %d",
5452 (int) cmd->subtype);
5455 relation_close(rel, NoLock);
5459 elog(ERROR, "unexpected statement type: %d",
5460 (int) nodeTag(query->utilityStmt));
5469 * recursing is true if we are recursing from a table to its indexes,
5470 * sequences, or toast table. We don't allow the ownership of those things to
5471 * be changed separately from the parent table. Also, we can skip permission
5472 * checks (this is necessary not just an optimization, else we'd fail to
5473 * handle toast tables properly).
5476 ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing)
5478 Relation target_rel;
5481 Form_pg_class tuple_class;
5484 * Get exclusive lock till end of transaction on the target table. Use
5485 * relation_open so that we can work on indexes and sequences.
5487 target_rel = relation_open(relationOid, AccessExclusiveLock);
5489 /* Get its pg_class tuple, too */
5490 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
5492 tuple = SearchSysCache(RELOID,
5493 ObjectIdGetDatum(relationOid),
5495 if (!HeapTupleIsValid(tuple))
5496 elog(ERROR, "cache lookup failed for relation %u", relationOid);
5497 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
5499 /* Can we change the ownership of this tuple? */
5500 switch (tuple_class->relkind)
5502 case RELKIND_RELATION:
5504 /* ok to change owner */
5510 * Because ALTER INDEX OWNER used to be allowed, and in fact
5511 * is generated by old versions of pg_dump, we give a warning
5512 * and do nothing rather than erroring out. Also, to avoid
5513 * unnecessary chatter while restoring those old dumps, say
5514 * nothing at all if the command would be a no-op anyway.
5516 if (tuple_class->relowner != newOwnerId)
5518 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5519 errmsg("cannot change owner of index \"%s\"",
5520 NameStr(tuple_class->relname)),
5521 errhint("Change the ownership of the index's table, instead.")));
5522 /* quick hack to exit via the no-op path */
5523 newOwnerId = tuple_class->relowner;
5526 case RELKIND_SEQUENCE:
5528 tuple_class->relowner != newOwnerId)
5530 /* if it's an owned sequence, disallow changing it by itself */
5534 if (sequenceIsOwned(relationOid, &tableId, &colId))
5536 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5537 errmsg("cannot change owner of sequence \"%s\"",
5538 NameStr(tuple_class->relname)),
5539 errdetail("Sequence \"%s\" is linked to table \"%s\".",
5540 NameStr(tuple_class->relname),
5541 get_rel_name(tableId))));
5544 case RELKIND_TOASTVALUE:
5550 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5551 errmsg("\"%s\" is not a table, view, or sequence",
5552 NameStr(tuple_class->relname))));
5556 * If the new owner is the same as the existing owner, consider the
5557 * command to have succeeded. This is for dump restoration purposes.
5559 if (tuple_class->relowner != newOwnerId)
5561 Datum repl_val[Natts_pg_class];
5562 char repl_null[Natts_pg_class];
5563 char repl_repl[Natts_pg_class];
5569 /* skip permission checks when recursing to index or toast table */
5572 /* Superusers can always do it */
5575 Oid namespaceOid = tuple_class->relnamespace;
5576 AclResult aclresult;
5578 /* Otherwise, must be owner of the existing object */
5579 if (!pg_class_ownercheck(relationOid, GetUserId()))
5580 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
5581 RelationGetRelationName(target_rel));
5583 /* Must be able to become new owner */
5584 check_is_member_of_role(GetUserId(), newOwnerId);
5586 /* New owner must have CREATE privilege on namespace */
5587 aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
5589 if (aclresult != ACLCHECK_OK)
5590 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
5591 get_namespace_name(namespaceOid));
5595 memset(repl_null, ' ', sizeof(repl_null));
5596 memset(repl_repl, ' ', sizeof(repl_repl));
5598 repl_repl[Anum_pg_class_relowner - 1] = 'r';
5599 repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
5602 * Determine the modified ACL for the new owner. This is only
5603 * necessary when the ACL is non-null.
5605 aclDatum = SysCacheGetAttr(RELOID, tuple,
5606 Anum_pg_class_relacl,
5610 newAcl = aclnewowner(DatumGetAclP(aclDatum),
5611 tuple_class->relowner, newOwnerId);
5612 repl_repl[Anum_pg_class_relacl - 1] = 'r';
5613 repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
5616 newtuple = heap_modifytuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
5618 simple_heap_update(class_rel, &newtuple->t_self, newtuple);
5619 CatalogUpdateIndexes(class_rel, newtuple);
5621 heap_freetuple(newtuple);
5623 /* Update owner dependency reference */
5624 changeDependencyOnOwner(RelationRelationId, relationOid, newOwnerId);
5627 * Also change the ownership of the table's rowtype, if it has one
5629 if (tuple_class->relkind != RELKIND_INDEX)
5630 AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId);
5633 * If we are operating on a table, also change the ownership of any
5634 * indexes and sequences that belong to the table, as well as the
5635 * table's toast table (if it has one)
5637 if (tuple_class->relkind == RELKIND_RELATION ||
5638 tuple_class->relkind == RELKIND_TOASTVALUE)
5640 List *index_oid_list;
5643 /* Find all the indexes belonging to this relation */
5644 index_oid_list = RelationGetIndexList(target_rel);
5646 /* For each index, recursively change its ownership */
5647 foreach(i, index_oid_list)
5648 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true);
5650 list_free(index_oid_list);
5653 if (tuple_class->relkind == RELKIND_RELATION)
5655 /* If it has a toast table, recurse to change its ownership */
5656 if (tuple_class->reltoastrelid != InvalidOid)
5657 ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
5660 /* If it has dependent sequences, recurse to change them too */
5661 change_owner_recurse_to_sequences(relationOid, newOwnerId);
5665 ReleaseSysCache(tuple);
5666 heap_close(class_rel, RowExclusiveLock);
5667 relation_close(target_rel, NoLock);
5671 * change_owner_recurse_to_sequences
5673 * Helper function for ATExecChangeOwner. Examines pg_depend searching
5674 * for sequences that are dependent on serial columns, and changes their
5678 change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId)
5686 * SERIAL sequences are those having an auto dependency on one of the
5687 * table's columns (we don't care *which* column, exactly).
5689 depRel = heap_open(DependRelationId, AccessShareLock);
5691 ScanKeyInit(&key[0],
5692 Anum_pg_depend_refclassid,
5693 BTEqualStrategyNumber, F_OIDEQ,
5694 ObjectIdGetDatum(RelationRelationId));
5695 ScanKeyInit(&key[1],
5696 Anum_pg_depend_refobjid,
5697 BTEqualStrategyNumber, F_OIDEQ,
5698 ObjectIdGetDatum(relationOid));
5699 /* we leave refobjsubid unspecified */
5701 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
5702 SnapshotNow, 2, key);
5704 while (HeapTupleIsValid(tup = systable_getnext(scan)))
5706 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
5709 /* skip dependencies other than auto dependencies on columns */
5710 if (depForm->refobjsubid == 0 ||
5711 depForm->classid != RelationRelationId ||
5712 depForm->objsubid != 0 ||
5713 depForm->deptype != DEPENDENCY_AUTO)
5716 /* Use relation_open just in case it's an index */
5717 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
5719 /* skip non-sequence relations */
5720 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
5722 /* No need to keep the lock */
5723 relation_close(seqRel, AccessExclusiveLock);
5727 /* We don't need to close the sequence while we alter it. */
5728 ATExecChangeOwner(depForm->objid, newOwnerId, true);
5730 /* Now we can close it. Keep the lock till end of transaction. */
5731 relation_close(seqRel, NoLock);
5734 systable_endscan(scan);
5736 relation_close(depRel, AccessShareLock);
5740 * ALTER TABLE CLUSTER ON
5742 * The only thing we have to do is to change the indisclustered bits.
5745 ATExecClusterOn(Relation rel, const char *indexName)
5749 indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
5751 if (!OidIsValid(indexOid))
5753 (errcode(ERRCODE_UNDEFINED_OBJECT),
5754 errmsg("index \"%s\" for table \"%s\" does not exist",
5755 indexName, RelationGetRelationName(rel))));
5757 /* Check index is valid to cluster on */
5758 check_index_is_clusterable(rel, indexOid, false);
5760 /* And do the work */
5761 mark_index_clustered(rel, indexOid);
5765 * ALTER TABLE SET WITHOUT CLUSTER
5767 * We have to find any indexes on the table that have indisclustered bit
5768 * set and turn it off.
5771 ATExecDropCluster(Relation rel)
5773 mark_index_clustered(rel, InvalidOid);
5777 * ALTER TABLE SET TABLESPACE
5780 ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, char *tablespacename)
5783 AclResult aclresult;
5785 /* Check that the tablespace exists */
5786 tablespaceId = get_tablespace_oid(tablespacename);
5787 if (!OidIsValid(tablespaceId))
5789 (errcode(ERRCODE_UNDEFINED_OBJECT),
5790 errmsg("tablespace \"%s\" does not exist", tablespacename)));
5792 /* Check its permissions */
5793 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(), ACL_CREATE);
5794 if (aclresult != ACLCHECK_OK)
5795 aclcheck_error(aclresult, ACL_KIND_TABLESPACE, tablespacename);
5797 /* Save info for Phase 3 to do the real work */
5798 if (OidIsValid(tab->newTableSpace))
5800 (errcode(ERRCODE_SYNTAX_ERROR),
5801 errmsg("cannot have multiple SET TABLESPACE subcommands")));
5802 tab->newTableSpace = tablespaceId;
5806 * ALTER TABLE/INDEX SET (...) or RESET (...)
5809 ATExecSetRelOptions(Relation rel, List *defList, bool isReset)
5818 Datum repl_val[Natts_pg_class];
5819 char repl_null[Natts_pg_class];
5820 char repl_repl[Natts_pg_class];
5823 return; /* nothing to do */
5825 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
5827 /* Get the old reloptions */
5828 relid = RelationGetRelid(rel);
5829 tuple = SearchSysCache(RELOID,
5830 ObjectIdGetDatum(relid),
5832 if (!HeapTupleIsValid(tuple))
5833 elog(ERROR, "cache lookup failed for relation %u", relid);
5835 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions, &isnull);
5837 /* Generate new proposed reloptions (text array) */
5838 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
5839 defList, false, isReset);
5842 switch (rel->rd_rel->relkind)
5844 case RELKIND_RELATION:
5845 case RELKIND_TOASTVALUE:
5846 (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
5849 (void) index_reloptions(rel->rd_am->amoptions, newOptions, true);
5853 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5854 errmsg("\"%s\" is not a table, index, or TOAST table",
5855 RelationGetRelationName(rel))));
5860 * All we need do here is update the pg_class row; the new options will be
5861 * propagated into relcaches during post-commit cache inval.
5863 memset(repl_val, 0, sizeof(repl_val));
5864 memset(repl_null, ' ', sizeof(repl_null));
5865 memset(repl_repl, ' ', sizeof(repl_repl));
5867 if (newOptions != (Datum) 0)
5868 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
5870 repl_null[Anum_pg_class_reloptions - 1] = 'n';
5872 repl_repl[Anum_pg_class_reloptions - 1] = 'r';
5874 newtuple = heap_modifytuple(tuple, RelationGetDescr(pgclass),
5875 repl_val, repl_null, repl_repl);
5877 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
5879 CatalogUpdateIndexes(pgclass, newtuple);
5881 heap_freetuple(newtuple);
5883 ReleaseSysCache(tuple);
5885 heap_close(pgclass, RowExclusiveLock);
5889 * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
5890 * rewriting to be done, so we just want to copy the data as fast as possible.
5893 ATExecSetTableSpace(Oid tableOid, Oid newTableSpace)
5899 RelFileNode newrnode;
5900 SMgrRelation dstrel;
5903 Form_pg_class rd_rel;
5906 * Need lock here in case we are recursing to toast table or index
5908 rel = relation_open(tableOid, AccessExclusiveLock);
5911 * We can never allow moving of shared or nailed-in-cache relations,
5912 * because we can't support changing their reltablespace values.
5914 if (rel->rd_rel->relisshared || rel->rd_isnailed)
5916 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5917 errmsg("cannot move system relation \"%s\"",
5918 RelationGetRelationName(rel))));
5921 * Don't allow moving temp tables of other backends ... their local buffer
5922 * manager is not going to cope.
5924 if (isOtherTempNamespace(RelationGetNamespace(rel)))
5926 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5927 errmsg("cannot move temporary tables of other sessions")));
5930 * No work if no change in tablespace.
5932 oldTableSpace = rel->rd_rel->reltablespace;
5933 if (newTableSpace == oldTableSpace ||
5934 (newTableSpace == MyDatabaseTableSpace && oldTableSpace == 0))
5936 relation_close(rel, NoLock);
5940 reltoastrelid = rel->rd_rel->reltoastrelid;
5941 reltoastidxid = rel->rd_rel->reltoastidxid;
5943 /* Get a modifiable copy of the relation's pg_class row */
5944 pg_class = heap_open(RelationRelationId, RowExclusiveLock);
5946 tuple = SearchSysCacheCopy(RELOID,
5947 ObjectIdGetDatum(tableOid),
5949 if (!HeapTupleIsValid(tuple))
5950 elog(ERROR, "cache lookup failed for relation %u", tableOid);
5951 rd_rel = (Form_pg_class) GETSTRUCT(tuple);
5953 /* create another storage file. Is it a little ugly ? */
5954 /* NOTE: any conflict in relfilenode value will be caught here */
5955 newrnode = rel->rd_node;
5956 newrnode.spcNode = newTableSpace;
5958 dstrel = smgropen(newrnode);
5959 smgrcreate(dstrel, rel->rd_istemp, false);
5961 /* copy relation data to the new physical file */
5962 copy_relation_data(rel, dstrel);
5964 /* schedule unlinking old physical file */
5965 RelationOpenSmgr(rel);
5966 smgrscheduleunlink(rel->rd_smgr, rel->rd_istemp);
5969 * Now drop smgr references. The source was already dropped by
5970 * smgrscheduleunlink.
5974 /* update the pg_class row */
5975 rd_rel->reltablespace = (newTableSpace == MyDatabaseTableSpace) ? InvalidOid : newTableSpace;
5976 simple_heap_update(pg_class, &tuple->t_self, tuple);
5977 CatalogUpdateIndexes(pg_class, tuple);
5979 heap_freetuple(tuple);
5981 heap_close(pg_class, RowExclusiveLock);
5983 relation_close(rel, NoLock);
5985 /* Make sure the reltablespace change is visible */
5986 CommandCounterIncrement();
5988 /* Move associated toast relation and/or index, too */
5989 if (OidIsValid(reltoastrelid))
5990 ATExecSetTableSpace(reltoastrelid, newTableSpace);
5991 if (OidIsValid(reltoastidxid))
5992 ATExecSetTableSpace(reltoastidxid, newTableSpace);
5996 * Copy data, block by block
5999 copy_relation_data(Relation rel, SMgrRelation dst)
6003 BlockNumber nblocks;
6006 Page page = (Page) buf;
6009 * Since we copy the file directly without looking at the shared buffers,
6010 * we'd better first flush out any pages of the source relation that are
6011 * in shared buffers. We assume no new changes will be made while we are
6012 * holding exclusive lock on the rel.
6014 FlushRelationBuffers(rel);
6017 * We need to log the copied data in WAL iff WAL archiving is enabled AND
6018 * it's not a temp rel.
6020 use_wal = XLogArchivingActive() && !rel->rd_istemp;
6022 nblocks = RelationGetNumberOfBlocks(rel);
6023 /* RelationGetNumberOfBlocks will certainly have opened rd_smgr */
6026 for (blkno = 0; blkno < nblocks; blkno++)
6028 smgrread(src, blkno, buf);
6033 xl_heap_newpage xlrec;
6035 XLogRecData rdata[2];
6037 /* NO ELOG(ERROR) from here till newpage op is logged */
6038 START_CRIT_SECTION();
6040 xlrec.node = dst->smgr_rnode;
6041 xlrec.blkno = blkno;
6043 rdata[0].data = (char *) &xlrec;
6044 rdata[0].len = SizeOfHeapNewpage;
6045 rdata[0].buffer = InvalidBuffer;
6046 rdata[0].next = &(rdata[1]);
6048 rdata[1].data = (char *) page;
6049 rdata[1].len = BLCKSZ;
6050 rdata[1].buffer = InvalidBuffer;
6051 rdata[1].next = NULL;
6053 recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_NEWPAGE, rdata);
6055 PageSetLSN(page, recptr);
6056 PageSetTLI(page, ThisTimeLineID);
6062 * Now write the page. We say isTemp = true even if it's not a temp
6063 * rel, because there's no need for smgr to schedule an fsync for this
6064 * write; we'll do it ourselves below.
6066 smgrwrite(dst, blkno, buf, true);
6070 * If the rel isn't temp, we must fsync it down to disk before it's safe
6071 * to commit the transaction. (For a temp rel we don't care since the rel
6072 * will be uninteresting after a crash anyway.)
6074 * It's obvious that we must do this when not WAL-logging the copy. It's
6075 * less obvious that we have to do it even if we did WAL-log the copied
6076 * pages. The reason is that since we're copying outside shared buffers, a
6077 * CHECKPOINT occurring during the copy has no way to flush the previously
6078 * written data to disk (indeed it won't know the new rel even exists). A
6079 * crash later on would replay WAL from the checkpoint, therefore it
6080 * wouldn't replay our earlier WAL entries. If we do not fsync those pages
6081 * here, they might still not be on disk when the crash occurs.
6083 if (!rel->rd_istemp)
6088 * ALTER TABLE ENABLE/DISABLE TRIGGER
6090 * We just pass this off to trigger.c.
6093 ATExecEnableDisableTrigger(Relation rel, char *trigname,
6094 bool enable, bool skip_system)
6096 EnableDisableTrigger(rel, trigname, enable, skip_system);
6100 * ALTER TABLE INHERIT
6102 * Add a parent to the child's parents. This verifies that all the columns and
6103 * check constraints of the parent appear in the child and that they have the
6104 * same data types and expressions.
6107 ATExecAddInherit(Relation child_rel, RangeVar *parent)
6109 Relation parent_rel,
6113 HeapTuple inheritsTuple;
6118 * AccessShareLock on the parent is what's obtained during normal CREATE
6119 * TABLE ... INHERITS ..., so should be enough here.
6121 parent_rel = heap_openrv(parent, AccessShareLock);
6124 * Must be owner of both parent and child -- child was checked by
6125 * ATSimplePermissions call in ATPrepCmd
6127 ATSimplePermissions(parent_rel, false);
6129 /* Permanent rels cannot inherit from temporary ones */
6130 if (!isTempNamespace(RelationGetNamespace(child_rel)) &&
6131 isTempNamespace(RelationGetNamespace(parent_rel)))
6133 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6134 errmsg("cannot inherit from temporary relation \"%s\"",
6135 RelationGetRelationName(parent_rel))));
6138 * Check for duplicates in the list of parents, and determine the highest
6139 * inhseqno already present; we'll use the next one for the new parent.
6140 * (Note: get RowExclusiveLock because we will write pg_inherits below.)
6142 * Note: we do not reject the case where the child already inherits from
6143 * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
6145 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
6147 Anum_pg_inherits_inhrelid,
6148 BTEqualStrategyNumber, F_OIDEQ,
6149 ObjectIdGetDatum(RelationGetRelid(child_rel)));
6150 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
6151 true, SnapshotNow, 1, &key);
6153 /* inhseqno sequences start at 1 */
6155 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
6157 Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
6159 if (inh->inhparent == RelationGetRelid(parent_rel))
6161 (errcode(ERRCODE_DUPLICATE_TABLE),
6162 errmsg("inherited relation \"%s\" duplicated",
6163 RelationGetRelationName(parent_rel))));
6164 if (inh->inhseqno > inhseqno)
6165 inhseqno = inh->inhseqno;
6167 systable_endscan(scan);
6170 * Prevent circularity by seeing if proposed parent inherits from child.
6171 * (In particular, this disallows making a rel inherit from itself.)
6173 * This is not completely bulletproof because of race conditions: in
6174 * multi-level inheritance trees, someone else could concurrently
6175 * be making another inheritance link that closes the loop but does
6176 * not join either of the rels we have locked. Preventing that seems
6177 * to require exclusive locks on the entire inheritance tree, which is
6178 * a cure worse than the disease. find_all_inheritors() will cope with
6179 * circularity anyway, so don't sweat it too much.
6181 children = find_all_inheritors(RelationGetRelid(child_rel));
6183 if (list_member_oid(children, RelationGetRelid(parent_rel)))
6185 (errcode(ERRCODE_DUPLICATE_TABLE),
6186 errmsg("circular inheritance not allowed"),
6187 errdetail("\"%s\" is already a child of \"%s\".",
6189 RelationGetRelationName(child_rel))));
6191 /* If parent has OIDs then child must have OIDs */
6192 if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
6194 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6195 errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
6196 RelationGetRelationName(child_rel),
6197 RelationGetRelationName(parent_rel))));
6199 /* Match up the columns and bump attinhcount and attislocal */
6200 MergeAttributesIntoExisting(child_rel, parent_rel);
6202 /* Match up the constraints and make sure they're present in child */
6203 MergeConstraintsIntoExisting(child_rel, parent_rel);
6206 * OK, it looks valid. Make the catalog entries that show inheritance.
6208 StoreCatalogInheritance1(RelationGetRelid(child_rel),
6209 RelationGetRelid(parent_rel),
6213 /* Now we're done with pg_inherits */
6214 heap_close(catalogRelation, RowExclusiveLock);
6216 /* keep our lock on the parent relation until commit */
6217 heap_close(parent_rel, NoLock);
6221 * Obtain the source-text form of the constraint expression for a check
6222 * constraint, given its pg_constraint tuple
6225 decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
6227 Form_pg_constraint con;
6232 con = (Form_pg_constraint) GETSTRUCT(contup);
6233 attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
6235 elog(ERROR, "null conbin for constraint %u", HeapTupleGetOid(contup));
6237 expr = DirectFunctionCall2(pg_get_expr, attr,
6238 ObjectIdGetDatum(con->conrelid));
6239 return DatumGetCString(DirectFunctionCall1(textout, expr));
6243 * Check columns in child table match up with columns in parent, and increment
6244 * their attinhcount.
6246 * Called by ATExecAddInherit
6248 * Currently all parent columns must be found in child. Missing columns are an
6249 * error. One day we might consider creating new columns like CREATE TABLE
6250 * does. However, that is widely unpopular --- in the common use case of
6251 * partitioned tables it's a foot-gun.
6253 * The data type must match exactly. If the parent column is NOT NULL then
6254 * the child must be as well. Defaults are not compared, however.
6257 MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel)
6260 AttrNumber parent_attno;
6262 TupleDesc tupleDesc;
6263 TupleConstr *constr;
6266 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
6268 tupleDesc = RelationGetDescr(parent_rel);
6269 parent_natts = tupleDesc->natts;
6270 constr = tupleDesc->constr;
6272 for (parent_attno = 1; parent_attno <= parent_natts; parent_attno++)
6274 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
6275 char *attributeName = NameStr(attribute->attname);
6277 /* Ignore dropped columns in the parent. */
6278 if (attribute->attisdropped)
6281 /* Find same column in child (matching on column name). */
6282 tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel),
6284 if (HeapTupleIsValid(tuple))
6286 /* Check they are same type and typmod */
6287 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
6289 if (attribute->atttypid != childatt->atttypid ||
6290 attribute->atttypmod != childatt->atttypmod)
6292 (errcode(ERRCODE_DATATYPE_MISMATCH),
6293 errmsg("child table \"%s\" has different type for column \"%s\"",
6294 RelationGetRelationName(child_rel),
6297 if (attribute->attnotnull && !childatt->attnotnull)
6299 (errcode(ERRCODE_DATATYPE_MISMATCH),
6300 errmsg("column \"%s\" in child table must be marked NOT NULL",
6304 * OK, bump the child column's inheritance count. (If we fail
6305 * later on, this change will just roll back.)
6307 childatt->attinhcount++;
6308 simple_heap_update(attrrel, &tuple->t_self, tuple);
6309 CatalogUpdateIndexes(attrrel, tuple);
6310 heap_freetuple(tuple);
6315 (errcode(ERRCODE_DATATYPE_MISMATCH),
6316 errmsg("child table is missing column \"%s\"",
6321 heap_close(attrrel, RowExclusiveLock);
6325 * Check constraints in child table match up with constraints in parent
6327 * Called by ATExecAddInherit
6329 * Currently all constraints in parent must be present in the child. One day we
6330 * may consider adding new constraints like CREATE TABLE does. We may also want
6331 * to allow an optional flag on parent table constraints indicating they are
6332 * intended to ONLY apply to the master table, not to the children. That would
6333 * make it possible to ensure no records are mistakenly inserted into the
6334 * master in partitioned tables rather than the appropriate child.
6336 * XXX This is O(N^2) which may be an issue with tables with hundreds of
6337 * constraints. As long as tables have more like 10 constraints it shouldn't be
6338 * a problem though. Even 100 constraints ought not be the end of the world.
6341 MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
6343 Relation catalogRelation;
6344 TupleDesc tupleDesc;
6347 HeapTuple constraintTuple;
6351 /* First gather up the child's constraint definitions */
6352 catalogRelation = heap_open(ConstraintRelationId, AccessShareLock);
6353 tupleDesc = RelationGetDescr(catalogRelation);
6356 Anum_pg_constraint_conrelid,
6357 BTEqualStrategyNumber, F_OIDEQ,
6358 ObjectIdGetDatum(RelationGetRelid(child_rel)));
6359 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
6360 true, SnapshotNow, 1, &key);
6363 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
6365 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
6367 if (con->contype != CONSTRAINT_CHECK)
6370 constraints = lappend(constraints, heap_copytuple(constraintTuple));
6373 systable_endscan(scan);
6375 /* Then scan through the parent's constraints looking for matches */
6377 Anum_pg_constraint_conrelid,
6378 BTEqualStrategyNumber, F_OIDEQ,
6379 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
6380 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId, true,
6381 SnapshotNow, 1, &key);
6383 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
6385 Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
6387 Form_pg_constraint child_con = NULL;
6388 HeapTuple child_contuple = NULL;
6390 if (parent_con->contype != CONSTRAINT_CHECK)
6393 foreach(elem, constraints)
6395 child_contuple = (HeapTuple) lfirst(elem);
6396 child_con = (Form_pg_constraint) GETSTRUCT(child_contuple);
6397 if (strcmp(NameStr(parent_con->conname),
6398 NameStr(child_con->conname)) == 0)
6407 (errcode(ERRCODE_DATATYPE_MISMATCH),
6408 errmsg("child table is missing constraint \"%s\"",
6409 NameStr(parent_con->conname))));
6411 if (parent_con->condeferrable != child_con->condeferrable ||
6412 parent_con->condeferred != child_con->condeferred ||
6413 strcmp(decompile_conbin(constraintTuple, tupleDesc),
6414 decompile_conbin(child_contuple, tupleDesc)) != 0)
6416 (errcode(ERRCODE_DATATYPE_MISMATCH),
6417 errmsg("constraint definition for check constraint \"%s\" does not match",
6418 NameStr(parent_con->conname))));
6421 * TODO: add conislocal,coninhcount to constraints. This is where we
6422 * would have to bump them just like attributes
6426 systable_endscan(scan);
6427 heap_close(catalogRelation, AccessShareLock);
6431 * ALTER TABLE NO INHERIT
6433 * Drop a parent from the child's parents. This just adjusts the attinhcount
6434 * and attislocal of the columns and removes the pg_inherit and pg_depend
6437 * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
6438 * up attislocal stays true, which means if a child is ever removed from a
6439 * parent then its columns will never be automatically dropped which may
6440 * surprise. But at least we'll never surprise by dropping columns someone
6441 * isn't expecting to be dropped which would actually mean data loss.
6444 ATExecDropInherit(Relation rel, RangeVar *parent)
6446 Relation parent_rel;
6447 Relation catalogRelation;
6450 HeapTuple inheritsTuple,
6456 * AccessShareLock on the parent is probably enough, seeing that DROP TABLE
6457 * doesn't lock parent tables at all. We need some lock since we'll be
6458 * inspecting the parent's schema.
6460 parent_rel = heap_openrv(parent, AccessShareLock);
6463 * We don't bother to check ownership of the parent table --- ownership
6464 * of the child is presumed enough rights.
6468 * Find and destroy the pg_inherits entry linking the two, or error out
6471 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
6472 ScanKeyInit(&key[0],
6473 Anum_pg_inherits_inhrelid,
6474 BTEqualStrategyNumber, F_OIDEQ,
6475 ObjectIdGetDatum(RelationGetRelid(rel)));
6476 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
6477 true, SnapshotNow, 1, key);
6479 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
6483 inhparent = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
6484 if (inhparent == RelationGetRelid(parent_rel))
6486 simple_heap_delete(catalogRelation, &inheritsTuple->t_self);
6492 systable_endscan(scan);
6493 heap_close(catalogRelation, RowExclusiveLock);
6497 (errcode(ERRCODE_UNDEFINED_TABLE),
6498 errmsg("relation \"%s\" is not a parent of relation \"%s\"",
6499 RelationGetRelationName(parent_rel),
6500 RelationGetRelationName(rel))));
6503 * Search through child columns looking for ones matching parent rel
6505 catalogRelation = heap_open(AttributeRelationId, RowExclusiveLock);
6506 ScanKeyInit(&key[0],
6507 Anum_pg_attribute_attrelid,
6508 BTEqualStrategyNumber, F_OIDEQ,
6509 ObjectIdGetDatum(RelationGetRelid(rel)));
6510 scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
6511 true, SnapshotNow, 1, key);
6512 while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
6514 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
6516 /* Ignore if dropped or not inherited */
6517 if (att->attisdropped)
6519 if (att->attinhcount <= 0)
6522 if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
6523 NameStr(att->attname)))
6525 /* Decrement inhcount and possibly set islocal to true */
6526 HeapTuple copyTuple = heap_copytuple(attributeTuple);
6527 Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
6529 copy_att->attinhcount--;
6530 if (copy_att->attinhcount == 0)
6531 copy_att->attislocal = true;
6533 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
6534 CatalogUpdateIndexes(catalogRelation, copyTuple);
6535 heap_freetuple(copyTuple);
6538 systable_endscan(scan);
6539 heap_close(catalogRelation, RowExclusiveLock);
6542 * Drop the dependency
6544 * There's no convenient way to do this, so go trawling through pg_depend
6546 catalogRelation = heap_open(DependRelationId, RowExclusiveLock);
6548 ScanKeyInit(&key[0],
6549 Anum_pg_depend_classid,
6550 BTEqualStrategyNumber, F_OIDEQ,
6551 ObjectIdGetDatum(RelationRelationId));
6552 ScanKeyInit(&key[1],
6553 Anum_pg_depend_objid,
6554 BTEqualStrategyNumber, F_OIDEQ,
6555 ObjectIdGetDatum(RelationGetRelid(rel)));
6556 ScanKeyInit(&key[2],
6557 Anum_pg_depend_objsubid,
6558 BTEqualStrategyNumber, F_INT4EQ,
6561 scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
6562 SnapshotNow, 3, key);
6564 while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
6566 Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
6568 if (dep->refclassid == RelationRelationId &&
6569 dep->refobjid == RelationGetRelid(parent_rel) &&
6570 dep->refobjsubid == 0 &&
6571 dep->deptype == DEPENDENCY_NORMAL)
6572 simple_heap_delete(catalogRelation, &depTuple->t_self);
6575 systable_endscan(scan);
6576 heap_close(catalogRelation, RowExclusiveLock);
6578 /* keep our lock on the parent relation until commit */
6579 heap_close(parent_rel, NoLock);
6584 * Execute ALTER TABLE SET SCHEMA
6586 * Note: caller must have checked ownership of the relation already
6589 AlterTableNamespace(RangeVar *relation, const char *newschema)
6597 rel = heap_openrv(relation, AccessExclusiveLock);
6599 relid = RelationGetRelid(rel);
6600 oldNspOid = RelationGetNamespace(rel);
6602 /* heap_openrv allows TOAST, but we don't want to */
6603 if (rel->rd_rel->relkind == RELKIND_TOASTVALUE)
6605 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6606 errmsg("\"%s\" is a TOAST relation",
6607 RelationGetRelationName(rel))));
6609 /* if it's an owned sequence, disallow moving it by itself */
6610 if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
6615 if (sequenceIsOwned(relid, &tableId, &colId))
6617 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6618 errmsg("cannot move an owned sequence into another schema"),
6619 errdetail("Sequence \"%s\" is linked to table \"%s\".",
6620 RelationGetRelationName(rel),
6621 get_rel_name(tableId))));
6624 /* get schema OID and check its permissions */
6625 nspOid = LookupCreationNamespace(newschema);
6627 if (oldNspOid == nspOid)
6629 (errcode(ERRCODE_DUPLICATE_TABLE),
6630 errmsg("relation \"%s\" is already in schema \"%s\"",
6631 RelationGetRelationName(rel),
6634 /* disallow renaming into or out of temp schemas */
6635 if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
6637 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6638 errmsg("cannot move objects into or out of temporary schemas")));
6640 /* same for TOAST schema */
6641 if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
6643 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6644 errmsg("cannot move objects into or out of TOAST schema")));
6646 /* OK, modify the pg_class row and pg_depend entry */
6647 classRel = heap_open(RelationRelationId, RowExclusiveLock);
6649 AlterRelationNamespaceInternal(classRel, relid, oldNspOid, nspOid, true);
6651 /* Fix the table's rowtype too */
6652 AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid, false);
6654 /* Fix other dependent stuff */
6655 if (rel->rd_rel->relkind == RELKIND_RELATION)
6657 AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid);
6658 AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid, newschema);
6659 AlterConstraintNamespaces(relid, oldNspOid, nspOid, false);
6662 heap_close(classRel, RowExclusiveLock);
6664 /* close rel, but keep lock until commit */
6665 relation_close(rel, NoLock);
6669 * The guts of relocating a relation to another namespace: fix the pg_class
6670 * entry, and the pg_depend entry if any. Caller must already have
6671 * opened and write-locked pg_class.
6674 AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
6675 Oid oldNspOid, Oid newNspOid,
6676 bool hasDependEntry)
6679 Form_pg_class classForm;
6681 classTup = SearchSysCacheCopy(RELOID,
6682 ObjectIdGetDatum(relOid),
6684 if (!HeapTupleIsValid(classTup))
6685 elog(ERROR, "cache lookup failed for relation %u", relOid);
6686 classForm = (Form_pg_class) GETSTRUCT(classTup);
6688 Assert(classForm->relnamespace == oldNspOid);
6690 /* check for duplicate name (more friendly than unique-index failure) */
6691 if (get_relname_relid(NameStr(classForm->relname),
6692 newNspOid) != InvalidOid)
6694 (errcode(ERRCODE_DUPLICATE_TABLE),
6695 errmsg("relation \"%s\" already exists in schema \"%s\"",
6696 NameStr(classForm->relname),
6697 get_namespace_name(newNspOid))));
6699 /* classTup is a copy, so OK to scribble on */
6700 classForm->relnamespace = newNspOid;
6702 simple_heap_update(classRel, &classTup->t_self, classTup);
6703 CatalogUpdateIndexes(classRel, classTup);
6705 /* Update dependency on schema if caller said so */
6706 if (hasDependEntry &&
6707 changeDependencyFor(RelationRelationId, relOid,
6708 NamespaceRelationId, oldNspOid, newNspOid) != 1)
6709 elog(ERROR, "failed to change schema dependency for relation \"%s\"",
6710 NameStr(classForm->relname));
6712 heap_freetuple(classTup);
6716 * Move all indexes for the specified relation to another namespace.
6718 * Note: we assume adequate permission checking was done by the caller,
6719 * and that the caller has a suitable lock on the owning relation.
6722 AlterIndexNamespaces(Relation classRel, Relation rel,
6723 Oid oldNspOid, Oid newNspOid)
6728 indexList = RelationGetIndexList(rel);
6730 foreach(l, indexList)
6732 Oid indexOid = lfirst_oid(l);
6735 * Note: currently, the index will not have its own dependency on the
6736 * namespace, so we don't need to do changeDependencyFor(). There's no
6737 * rowtype in pg_type, either.
6739 AlterRelationNamespaceInternal(classRel, indexOid,
6740 oldNspOid, newNspOid,
6744 list_free(indexList);
6748 * Move all SERIAL-column sequences of the specified relation to another
6751 * Note: we assume adequate permission checking was done by the caller,
6752 * and that the caller has a suitable lock on the owning relation.
6755 AlterSeqNamespaces(Relation classRel, Relation rel,
6756 Oid oldNspOid, Oid newNspOid, const char *newNspName)
6764 * SERIAL sequences are those having an auto dependency on one of the
6765 * table's columns (we don't care *which* column, exactly).
6767 depRel = heap_open(DependRelationId, AccessShareLock);
6769 ScanKeyInit(&key[0],
6770 Anum_pg_depend_refclassid,
6771 BTEqualStrategyNumber, F_OIDEQ,
6772 ObjectIdGetDatum(RelationRelationId));
6773 ScanKeyInit(&key[1],
6774 Anum_pg_depend_refobjid,
6775 BTEqualStrategyNumber, F_OIDEQ,
6776 ObjectIdGetDatum(RelationGetRelid(rel)));
6777 /* we leave refobjsubid unspecified */
6779 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
6780 SnapshotNow, 2, key);
6782 while (HeapTupleIsValid(tup = systable_getnext(scan)))
6784 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
6787 /* skip dependencies other than auto dependencies on columns */
6788 if (depForm->refobjsubid == 0 ||
6789 depForm->classid != RelationRelationId ||
6790 depForm->objsubid != 0 ||
6791 depForm->deptype != DEPENDENCY_AUTO)
6794 /* Use relation_open just in case it's an index */
6795 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
6797 /* skip non-sequence relations */
6798 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
6800 /* No need to keep the lock */
6801 relation_close(seqRel, AccessExclusiveLock);
6805 /* Fix the pg_class and pg_depend entries */
6806 AlterRelationNamespaceInternal(classRel, depForm->objid,
6807 oldNspOid, newNspOid,
6811 * Sequences have entries in pg_type. We need to be careful to move
6812 * them to the new namespace, too.
6814 AlterTypeNamespaceInternal(RelationGetForm(seqRel)->reltype,
6817 /* Now we can close it. Keep the lock till end of transaction. */
6818 relation_close(seqRel, NoLock);
6821 systable_endscan(scan);
6823 relation_close(depRel, AccessShareLock);
6828 * This code supports
6829 * CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
6831 * Because we only support this for TEMP tables, it's sufficient to remember
6832 * the state in a backend-local data structure.
6836 * Register a newly-created relation's ON COMMIT action.
6839 register_on_commit_action(Oid relid, OnCommitAction action)
6842 MemoryContext oldcxt;
6845 * We needn't bother registering the relation unless there is an ON COMMIT
6846 * action we need to take.
6848 if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
6851 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
6853 oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
6855 oc->oncommit = action;
6856 oc->creating_subid = GetCurrentSubTransactionId();
6857 oc->deleting_subid = InvalidSubTransactionId;
6859 on_commits = lcons(oc, on_commits);
6861 MemoryContextSwitchTo(oldcxt);
6865 * Unregister any ON COMMIT action when a relation is deleted.
6867 * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
6870 remove_on_commit_action(Oid relid)
6874 foreach(l, on_commits)
6876 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
6878 if (oc->relid == relid)
6880 oc->deleting_subid = GetCurrentSubTransactionId();
6887 * Perform ON COMMIT actions.
6889 * This is invoked just before actually committing, since it's possible
6890 * to encounter errors.
6893 PreCommit_on_commit_actions(void)
6896 List *oids_to_truncate = NIL;
6898 foreach(l, on_commits)
6900 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
6902 /* Ignore entry if already dropped in this xact */
6903 if (oc->deleting_subid != InvalidSubTransactionId)
6906 switch (oc->oncommit)
6909 case ONCOMMIT_PRESERVE_ROWS:
6910 /* Do nothing (there shouldn't be such entries, actually) */
6912 case ONCOMMIT_DELETE_ROWS:
6913 oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
6917 ObjectAddress object;
6919 object.classId = RelationRelationId;
6920 object.objectId = oc->relid;
6921 object.objectSubId = 0;
6922 performDeletion(&object, DROP_CASCADE);
6925 * Note that table deletion will call
6926 * remove_on_commit_action, so the entry should get marked
6929 Assert(oc->deleting_subid != InvalidSubTransactionId);
6934 if (oids_to_truncate != NIL)
6936 heap_truncate(oids_to_truncate);
6937 CommandCounterIncrement(); /* XXX needed? */
6942 * Post-commit or post-abort cleanup for ON COMMIT management.
6944 * All we do here is remove no-longer-needed OnCommitItem entries.
6946 * During commit, remove entries that were deleted during this transaction;
6947 * during abort, remove those created during this transaction.
6950 AtEOXact_on_commit_actions(bool isCommit)
6953 ListCell *prev_item;
6956 cur_item = list_head(on_commits);
6958 while (cur_item != NULL)
6960 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
6962 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
6963 oc->creating_subid != InvalidSubTransactionId)
6965 /* cur_item must be removed */
6966 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
6969 cur_item = lnext(prev_item);
6971 cur_item = list_head(on_commits);
6975 /* cur_item must be preserved */
6976 oc->creating_subid = InvalidSubTransactionId;
6977 oc->deleting_subid = InvalidSubTransactionId;
6978 prev_item = cur_item;
6979 cur_item = lnext(prev_item);
6985 * Post-subcommit or post-subabort cleanup for ON COMMIT management.
6987 * During subabort, we can immediately remove entries created during this
6988 * subtransaction. During subcommit, just relabel entries marked during
6989 * this subtransaction as being the parent's responsibility.
6992 AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
6993 SubTransactionId parentSubid)
6996 ListCell *prev_item;
6999 cur_item = list_head(on_commits);
7001 while (cur_item != NULL)
7003 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
7005 if (!isCommit && oc->creating_subid == mySubid)
7007 /* cur_item must be removed */
7008 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
7011 cur_item = lnext(prev_item);
7013 cur_item = list_head(on_commits);
7017 /* cur_item must be preserved */
7018 if (oc->creating_subid == mySubid)
7019 oc->creating_subid = parentSubid;
7020 if (oc->deleting_subid == mySubid)
7021 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
7022 prev_item = cur_item;
7023 cur_item = lnext(prev_item);