1 /*-------------------------------------------------------------------------
4 * Commands for creating and altering table structures and settings
6 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/commands/tablecmds.c
13 *-------------------------------------------------------------------------
17 #include "access/genam.h"
18 #include "access/heapam.h"
19 #include "access/reloptions.h"
20 #include "access/relscan.h"
21 #include "access/sysattr.h"
22 #include "access/xact.h"
23 #include "catalog/catalog.h"
24 #include "catalog/dependency.h"
25 #include "catalog/heap.h"
26 #include "catalog/index.h"
27 #include "catalog/indexing.h"
28 #include "catalog/namespace.h"
29 #include "catalog/objectaccess.h"
30 #include "catalog/pg_constraint.h"
31 #include "catalog/pg_depend.h"
32 #include "catalog/pg_foreign_table.h"
33 #include "catalog/pg_inherits.h"
34 #include "catalog/pg_inherits_fn.h"
35 #include "catalog/pg_namespace.h"
36 #include "catalog/pg_opclass.h"
37 #include "catalog/pg_tablespace.h"
38 #include "catalog/pg_trigger.h"
39 #include "catalog/pg_type.h"
40 #include "catalog/pg_type_fn.h"
41 #include "catalog/storage.h"
42 #include "catalog/toasting.h"
43 #include "commands/cluster.h"
44 #include "commands/comment.h"
45 #include "commands/defrem.h"
46 #include "commands/sequence.h"
47 #include "commands/tablecmds.h"
48 #include "commands/tablespace.h"
49 #include "commands/trigger.h"
50 #include "commands/typecmds.h"
51 #include "executor/executor.h"
52 #include "foreign/foreign.h"
53 #include "miscadmin.h"
54 #include "nodes/makefuncs.h"
55 #include "nodes/nodeFuncs.h"
56 #include "nodes/parsenodes.h"
57 #include "optimizer/clauses.h"
58 #include "parser/parse_clause.h"
59 #include "parser/parse_coerce.h"
60 #include "parser/parse_expr.h"
61 #include "parser/parse_oper.h"
62 #include "parser/parse_relation.h"
63 #include "parser/parse_type.h"
64 #include "parser/parse_utilcmd.h"
65 #include "parser/parser.h"
66 #include "rewrite/rewriteDefine.h"
67 #include "rewrite/rewriteHandler.h"
68 #include "storage/bufmgr.h"
69 #include "storage/lmgr.h"
70 #include "storage/lock.h"
71 #include "storage/smgr.h"
72 #include "utils/acl.h"
73 #include "utils/builtins.h"
74 #include "utils/fmgroids.h"
75 #include "utils/inval.h"
76 #include "utils/lsyscache.h"
77 #include "utils/memutils.h"
78 #include "utils/relcache.h"
79 #include "utils/snapmgr.h"
80 #include "utils/syscache.h"
81 #include "utils/tqual.h"
85 * ON COMMIT action list
87 typedef struct OnCommitItem
89 Oid relid; /* relid of relation */
90 OnCommitAction oncommit; /* what to do at end of xact */
93 * If this entry was created during the current transaction,
94 * creating_subid is the ID of the creating subxact; if created in a prior
95 * transaction, creating_subid is zero. If deleted during the current
96 * transaction, deleting_subid is the ID of the deleting subxact; if no
97 * deletion request is pending, deleting_subid is zero.
99 SubTransactionId creating_subid;
100 SubTransactionId deleting_subid;
103 static List *on_commits = NIL;
107 * State information for ALTER TABLE
109 * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
110 * structs, one for each table modified by the operation (the named table
111 * plus any child tables that are affected). We save lists of subcommands
112 * to apply to this table (possibly modified by parse transformation steps);
113 * these lists will be executed in Phase 2. If a Phase 3 step is needed,
114 * necessary information is stored in the constraints and newvals lists.
116 * Phase 2 is divided into multiple passes; subcommands are executed in
117 * a pass determined by subcommand type.
120 #define AT_PASS_DROP 0 /* DROP (all flavors) */
121 #define AT_PASS_ALTER_TYPE 1 /* ALTER COLUMN TYPE */
122 #define AT_PASS_OLD_INDEX 2 /* re-add existing indexes */
123 #define AT_PASS_OLD_CONSTR 3 /* re-add existing constraints */
124 #define AT_PASS_COL_ATTRS 4 /* set other column attributes */
125 /* We could support a RENAME COLUMN pass here, but not currently used */
126 #define AT_PASS_ADD_COL 5 /* ADD COLUMN */
127 #define AT_PASS_ADD_INDEX 6 /* ADD indexes */
128 #define AT_PASS_ADD_CONSTR 7 /* ADD constraints, defaults */
129 #define AT_PASS_MISC 8 /* other stuff */
130 #define AT_NUM_PASSES 9
132 typedef struct AlteredTableInfo
134 /* Information saved before any work commences: */
135 Oid relid; /* Relation to work on */
136 char relkind; /* Its relkind */
137 TupleDesc oldDesc; /* Pre-modification tuple descriptor */
138 /* Information saved by Phase 1 for Phase 2: */
139 List *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
140 /* Information saved by Phases 1/2 for Phase 3: */
141 List *constraints; /* List of NewConstraint */
142 List *newvals; /* List of NewColumnValue */
143 bool new_notnull; /* T if we added new NOT NULL constraints */
144 bool new_changeoids; /* T if we added/dropped the OID column */
145 Oid newTableSpace; /* new tablespace; 0 means no change */
146 /* Objects to rebuild after completing ALTER TYPE operations */
147 List *changedConstraintOids; /* OIDs of constraints to rebuild */
148 List *changedConstraintDefs; /* string definitions of same */
149 List *changedIndexOids; /* OIDs of indexes to rebuild */
150 List *changedIndexDefs; /* string definitions of same */
153 /* Struct describing one new constraint to check in Phase 3 scan */
154 /* Note: new NOT NULL constraints are handled elsewhere */
155 typedef struct NewConstraint
157 char *name; /* Constraint name, or NULL if none */
158 ConstrType contype; /* CHECK or FOREIGN */
159 Oid refrelid; /* PK rel, if FOREIGN */
160 Oid refindid; /* OID of PK's index, if FOREIGN */
161 Oid conid; /* OID of pg_constraint entry, if FOREIGN */
162 Node *qual; /* Check expr or CONSTR_FOREIGN Constraint */
163 List *qualstate; /* Execution state for CHECK */
167 * Struct describing one new column value that needs to be computed during
168 * Phase 3 copy (this could be either a new column with a non-null default, or
169 * a column that we're changing the type of). Columns without such an entry
170 * are just copied from the old table during ATRewriteTable. Note that the
171 * expr is an expression over *old* table values.
173 typedef struct NewColumnValue
175 AttrNumber attnum; /* which column */
176 Expr *expr; /* expression to compute */
177 ExprState *exprstate; /* execution state */
181 * Error-reporting support for RemoveRelations
183 struct dropmsgstrings
186 int nonexistent_code;
187 const char *nonexistent_msg;
188 const char *skipping_msg;
189 const char *nota_msg;
190 const char *drophint_msg;
193 static const struct dropmsgstrings dropmsgstringarray[] = {
195 ERRCODE_UNDEFINED_TABLE,
196 gettext_noop("table \"%s\" does not exist"),
197 gettext_noop("table \"%s\" does not exist, skipping"),
198 gettext_noop("\"%s\" is not a table"),
199 gettext_noop("Use DROP TABLE to remove a table.")},
201 ERRCODE_UNDEFINED_TABLE,
202 gettext_noop("sequence \"%s\" does not exist"),
203 gettext_noop("sequence \"%s\" does not exist, skipping"),
204 gettext_noop("\"%s\" is not a sequence"),
205 gettext_noop("Use DROP SEQUENCE to remove a sequence.")},
207 ERRCODE_UNDEFINED_TABLE,
208 gettext_noop("view \"%s\" does not exist"),
209 gettext_noop("view \"%s\" does not exist, skipping"),
210 gettext_noop("\"%s\" is not a view"),
211 gettext_noop("Use DROP VIEW to remove a view.")},
213 ERRCODE_UNDEFINED_OBJECT,
214 gettext_noop("index \"%s\" does not exist"),
215 gettext_noop("index \"%s\" does not exist, skipping"),
216 gettext_noop("\"%s\" is not an index"),
217 gettext_noop("Use DROP INDEX to remove an index.")},
218 {RELKIND_COMPOSITE_TYPE,
219 ERRCODE_UNDEFINED_OBJECT,
220 gettext_noop("type \"%s\" does not exist"),
221 gettext_noop("type \"%s\" does not exist, skipping"),
222 gettext_noop("\"%s\" is not a type"),
223 gettext_noop("Use DROP TYPE to remove a type.")},
224 {RELKIND_FOREIGN_TABLE,
225 ERRCODE_UNDEFINED_OBJECT,
226 gettext_noop("foreign table \"%s\" does not exist"),
227 gettext_noop("foreign table \"%s\" does not exist, skipping"),
228 gettext_noop("\"%s\" is not a foreign table"),
229 gettext_noop("Use DROP FOREIGN TABLE to remove a foreign table.")},
230 {'\0', 0, NULL, NULL, NULL, NULL}
233 /* Alter table target-type flags for ATSimplePermissions */
234 #define ATT_TABLE 0x0001
235 #define ATT_VIEW 0x0002
236 #define ATT_INDEX 0x0004
237 #define ATT_COMPOSITE_TYPE 0x0008
238 #define ATT_FOREIGN_TABLE 0x0010
240 static void truncate_check_rel(Relation rel);
241 static List *MergeAttributes(List *schema, List *supers, char relpersistence,
242 List **supOids, List **supconstr, int *supOidCount);
243 static bool MergeCheckConstraint(List *constraints, char *name, Node *expr);
244 static bool change_varattnos_walker(Node *node, const AttrNumber *newattno);
245 static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel);
246 static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
247 static void StoreCatalogInheritance(Oid relationId, List *supers);
248 static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
249 int16 seqNumber, Relation inhRelation);
250 static int findAttrByName(const char *attributeName, List *schema);
251 static void setRelhassubclassInRelation(Oid relationId, bool relhassubclass);
252 static void AlterIndexNamespaces(Relation classRel, Relation rel,
253 Oid oldNspOid, Oid newNspOid);
254 static void AlterSeqNamespaces(Relation classRel, Relation rel,
255 Oid oldNspOid, Oid newNspOid,
256 const char *newNspName, LOCKMODE lockmode);
257 static void ATExecValidateConstraint(Relation rel, const char *constrName);
258 static int transformColumnNameList(Oid relId, List *colList,
259 int16 *attnums, Oid *atttypids);
260 static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
262 int16 *attnums, Oid *atttypids,
264 static Oid transformFkeyCheckAttrs(Relation pkrel,
265 int numattrs, int16 *attnums,
267 static void checkFkeyPermissions(Relation rel, int16 *attnums, int natts);
268 static void validateForeignKeyConstraint(char *conname,
269 Relation rel, Relation pkrel,
270 Oid pkindOid, Oid constraintOid);
271 static void createForeignKeyTriggers(Relation rel, Constraint *fkconstraint,
272 Oid constraintOid, Oid indexOid);
273 static void ATController(Relation rel, List *cmds, bool recurse, LOCKMODE lockmode);
274 static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
275 bool recurse, bool recursing, LOCKMODE lockmode);
276 static void ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode);
277 static void ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
278 AlterTableCmd *cmd, LOCKMODE lockmode);
279 static void ATRewriteTables(List **wqueue, LOCKMODE lockmode);
280 static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap, LOCKMODE lockmode);
281 static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
282 static void ATSimplePermissions(Relation rel, int allowed_targets);
283 static void ATWrongRelkindError(Relation rel, int allowed_targets);
284 static void ATSimpleRecursion(List **wqueue, Relation rel,
285 AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode);
286 static void ATOneLevelRecursion(List **wqueue, Relation rel,
287 AlterTableCmd *cmd, LOCKMODE lockmode);
288 static void ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
290 static List *find_typed_table_dependencies(Oid typeOid, const char *typeName,
291 DropBehavior behavior);
292 static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
293 AlterTableCmd *cmd, LOCKMODE lockmode);
294 static void ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
295 ColumnDef *colDef, bool isOid, LOCKMODE lockmode);
296 static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
297 static void ATPrepAddOids(List **wqueue, Relation rel, bool recurse,
298 AlterTableCmd *cmd, LOCKMODE lockmode);
299 static void ATExecDropNotNull(Relation rel, const char *colName, LOCKMODE lockmode);
300 static void ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
301 const char *colName, LOCKMODE lockmode);
302 static void ATExecColumnDefault(Relation rel, const char *colName,
303 Node *newDefault, LOCKMODE lockmode);
304 static void ATPrepSetStatistics(Relation rel, const char *colName,
305 Node *newValue, LOCKMODE lockmode);
306 static void ATExecSetStatistics(Relation rel, const char *colName,
307 Node *newValue, LOCKMODE lockmode);
308 static void ATExecSetOptions(Relation rel, const char *colName,
309 Node *options, bool isReset, LOCKMODE lockmode);
310 static void ATExecSetStorage(Relation rel, const char *colName,
311 Node *newValue, LOCKMODE lockmode);
312 static void ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
313 AlterTableCmd *cmd, LOCKMODE lockmode);
314 static void ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
315 DropBehavior behavior,
316 bool recurse, bool recursing,
317 bool missing_ok, LOCKMODE lockmode);
318 static void ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
319 IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode);
320 static void ATExecAddConstraint(List **wqueue,
321 AlteredTableInfo *tab, Relation rel,
322 Constraint *newConstraint, bool recurse, LOCKMODE lockmode);
323 static void ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
324 IndexStmt *stmt, LOCKMODE lockmode);
325 static void ATAddCheckConstraint(List **wqueue,
326 AlteredTableInfo *tab, Relation rel,
328 bool recurse, bool recursing, LOCKMODE lockmode);
329 static void ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
330 Constraint *fkconstraint, LOCKMODE lockmode);
331 static void ATExecDropConstraint(Relation rel, const char *constrName,
332 DropBehavior behavior,
333 bool recurse, bool recursing,
334 bool missing_ok, LOCKMODE lockmode);
335 static void ATPrepAlterColumnType(List **wqueue,
336 AlteredTableInfo *tab, Relation rel,
337 bool recurse, bool recursing,
338 AlterTableCmd *cmd, LOCKMODE lockmode);
339 static void ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
340 const char *colName, TypeName *typeName, LOCKMODE lockmode);
341 static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode);
342 static void ATPostAlterTypeParse(char *cmd, List **wqueue, LOCKMODE lockmode);
343 static void change_owner_recurse_to_sequences(Oid relationOid,
344 Oid newOwnerId, LOCKMODE lockmode);
345 static void ATExecClusterOn(Relation rel, const char *indexName, LOCKMODE lockmode);
346 static void ATExecDropCluster(Relation rel, LOCKMODE lockmode);
347 static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
348 char *tablespacename, LOCKMODE lockmode);
349 static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode);
350 static void ATExecSetRelOptions(Relation rel, List *defList, bool isReset, LOCKMODE lockmode);
351 static void ATExecEnableDisableTrigger(Relation rel, char *trigname,
352 char fires_when, bool skip_system, LOCKMODE lockmode);
353 static void ATExecEnableDisableRule(Relation rel, char *rulename,
354 char fires_when, LOCKMODE lockmode);
355 static void ATPrepAddInherit(Relation child_rel);
356 static void ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode);
357 static void ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode);
358 static void ATExecGenericOptions(Relation rel, List *options);
360 static void copy_relation_data(SMgrRelation rel, SMgrRelation dst,
361 ForkNumber forkNum, char relpersistence);
362 static const char *storage_name(char c);
365 /* ----------------------------------------------------------------
367 * Creates a new relation.
369 * stmt carries parsetree information from an ordinary CREATE TABLE statement.
370 * The other arguments are used to extend the behavior for other cases:
371 * relkind: relkind to assign to the new relation
372 * ownerId: if not InvalidOid, use this as the new relation's owner.
374 * Note that permissions checks are done against current user regardless of
375 * ownerId. A nonzero ownerId is used when someone is creating a relation
376 * "on behalf of" someone else, so we still want to see that the current user
377 * has permissions to do it.
379 * If successful, returns the OID of the new relation.
380 * ----------------------------------------------------------------
383 DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId)
385 char relname[NAMEDATALEN];
387 List *schema = stmt->tableElts;
391 TupleDesc descriptor;
393 List *old_constraints;
397 List *cookedDefaults;
401 static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
405 * Truncate relname to appropriate length (probably a waste of time, as
406 * parser should have done this already).
408 StrNCpy(relname, stmt->relation->relname, NAMEDATALEN);
411 * Check consistency of arguments
413 if (stmt->oncommit != ONCOMMIT_NOOP
414 && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
416 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
417 errmsg("ON COMMIT can only be used on temporary tables")));
418 if (stmt->constraints != NIL && relkind == RELKIND_FOREIGN_TABLE)
420 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
421 errmsg("constraints on foreign tables are not supported")));
424 * Security check: disallow creating temp tables from security-restricted
425 * code. This is needed because calling code might not expect untrusted
426 * tables to appear in pg_temp at the front of its search path.
428 if (stmt->relation->relpersistence == RELPERSISTENCE_TEMP
429 && InSecurityRestrictedOperation())
431 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
432 errmsg("cannot create temporary table within security-restricted operation")));
435 * Look up the namespace in which we are supposed to create the relation.
436 * Check we have permission to create there. Skip check if bootstrapping,
437 * since permissions machinery may not be working yet.
439 namespaceId = RangeVarGetCreationNamespace(stmt->relation);
441 if (!IsBootstrapProcessingMode())
445 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
447 if (aclresult != ACLCHECK_OK)
448 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
449 get_namespace_name(namespaceId));
453 * Select tablespace to use. If not specified, use default tablespace
454 * (which may in turn default to database's default).
456 if (stmt->tablespacename)
458 tablespaceId = get_tablespace_oid(stmt->tablespacename, false);
462 tablespaceId = GetDefaultTablespace(stmt->relation->relpersistence);
463 /* note InvalidOid is OK in this case */
466 /* Check permissions except when using database's default */
467 if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
471 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
473 if (aclresult != ACLCHECK_OK)
474 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
475 get_tablespace_name(tablespaceId));
478 /* In all cases disallow placing user relations in pg_global */
479 if (tablespaceId == GLOBALTABLESPACE_OID)
481 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
482 errmsg("only shared relations can be placed in pg_global tablespace")));
484 /* Identify user ID that will own the table */
485 if (!OidIsValid(ownerId))
486 ownerId = GetUserId();
489 * Parse and validate reloptions, if any.
491 reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, validnsps,
494 (void) heap_reloptions(relkind, reloptions, true);
496 if (stmt->ofTypename)
497 ofTypeId = typenameTypeId(NULL, stmt->ofTypename);
499 ofTypeId = InvalidOid;
502 * Look up inheritance ancestors and generate relation schema, including
503 * inherited attributes.
505 schema = MergeAttributes(schema, stmt->inhRelations,
506 stmt->relation->relpersistence,
507 &inheritOids, &old_constraints, &parentOidCount);
510 * Create a tuple descriptor from the relation schema. Note that this
511 * deals with column names, types, and NOT NULL constraints, but not
512 * default values or CHECK constraints; we handle those below.
514 descriptor = BuildDescForRelation(schema);
516 localHasOids = interpretOidsOption(stmt->options);
517 descriptor->tdhasoid = (localHasOids || parentOidCount > 0);
520 * Find columns with default values and prepare for insertion of the
521 * defaults. Pre-cooked (that is, inherited) defaults go into a list of
522 * CookedConstraint structs that we'll pass to heap_create_with_catalog,
523 * while raw defaults go into a list of RawColumnDefault structs that will
524 * be processed by AddRelationNewConstraints. (We can't deal with raw
525 * expressions until we can do transformExpr.)
527 * We can set the atthasdef flags now in the tuple descriptor; this just
528 * saves StoreAttrDefault from having to do an immediate update of the
532 cookedDefaults = NIL;
535 foreach(listptr, schema)
537 ColumnDef *colDef = lfirst(listptr);
541 if (colDef->raw_default != NULL)
543 RawColumnDefault *rawEnt;
545 if (relkind == RELKIND_FOREIGN_TABLE)
547 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
548 errmsg("default values on foreign tables are not supported")));
550 Assert(colDef->cooked_default == NULL);
552 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
553 rawEnt->attnum = attnum;
554 rawEnt->raw_default = colDef->raw_default;
555 rawDefaults = lappend(rawDefaults, rawEnt);
556 descriptor->attrs[attnum - 1]->atthasdef = true;
558 else if (colDef->cooked_default != NULL)
560 CookedConstraint *cooked;
562 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
563 cooked->contype = CONSTR_DEFAULT;
565 cooked->attnum = attnum;
566 cooked->expr = colDef->cooked_default;
567 cooked->is_local = true; /* not used for defaults */
568 cooked->inhcount = 0; /* ditto */
569 cookedDefaults = lappend(cookedDefaults, cooked);
570 descriptor->attrs[attnum - 1]->atthasdef = true;
575 * Create the relation. Inherited defaults and constraints are passed in
576 * for immediate handling --- since they don't need parsing, they can be
577 * stored immediately.
579 relationId = heap_create_with_catalog(relname,
587 list_concat(cookedDefaults,
590 stmt->relation->relpersistence,
598 allowSystemTableMods,
599 stmt->if_not_exists);
602 * If heap_create_with_catalog returns InvalidOid, it means that the user
603 * specified "IF NOT EXISTS" and the relation already exists. In that
604 * case we do nothing further.
606 if (relationId == InvalidOid)
609 /* Store inheritance information for new rel. */
610 StoreCatalogInheritance(relationId, inheritOids);
613 * We must bump the command counter to make the newly-created relation
614 * tuple visible for opening.
616 CommandCounterIncrement();
619 * Open the new relation and acquire exclusive lock on it. This isn't
620 * really necessary for locking out other backends (since they can't see
621 * the new rel anyway until we commit), but it keeps the lock manager from
622 * complaining about deadlock risks.
624 rel = relation_open(relationId, AccessExclusiveLock);
627 * Now add any newly specified column default values and CHECK constraints
628 * to the new relation. These are passed to us in the form of raw
629 * parsetrees; we need to transform them to executable expression trees
630 * before they can be added. The most convenient way to do that is to
631 * apply the parser's transformExpr routine, but transformExpr doesn't
632 * work unless we have a pre-existing relation. So, the transformation has
633 * to be postponed to this final step of CREATE TABLE.
635 if (rawDefaults || stmt->constraints)
636 AddRelationNewConstraints(rel, rawDefaults, stmt->constraints,
640 * Clean up. We keep lock on new relation (although it shouldn't be
641 * visible to anyone else anyway, until commit).
643 relation_close(rel, NoLock);
649 * Emit the right error or warning message for a "DROP" command issued on a
650 * non-existent relation
653 DropErrorMsgNonExistent(const char *relname, char rightkind, bool missing_ok)
655 const struct dropmsgstrings *rentry;
657 for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
659 if (rentry->kind == rightkind)
664 (errcode(rentry->nonexistent_code),
665 errmsg(rentry->nonexistent_msg, relname)));
669 ereport(NOTICE, (errmsg(rentry->skipping_msg, relname)));
675 Assert(rentry->kind != '\0'); /* Should be impossible */
679 * Emit the right error message for a "DROP" command issued on a
680 * relation of the wrong type
683 DropErrorMsgWrongType(const char *relname, char wrongkind, char rightkind)
685 const struct dropmsgstrings *rentry;
686 const struct dropmsgstrings *wentry;
688 for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
689 if (rentry->kind == rightkind)
691 Assert(rentry->kind != '\0');
693 for (wentry = dropmsgstringarray; wentry->kind != '\0'; wentry++)
694 if (wentry->kind == wrongkind)
696 /* wrongkind could be something we don't have in our table... */
699 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
700 errmsg(rentry->nota_msg, relname),
701 (wentry->kind != '\0') ? errhint("%s", _(wentry->drophint_msg)) : 0));
706 * Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW,
710 RemoveRelations(DropStmt *drop)
712 ObjectAddresses *objects;
717 * First we identify all the relations, then we delete them in a single
718 * performMultipleDeletions() call. This is to avoid unwanted DROP
719 * RESTRICT errors if one of the relations depends on another.
722 /* Determine required relkind */
723 switch (drop->removeType)
726 relkind = RELKIND_RELATION;
730 relkind = RELKIND_INDEX;
733 case OBJECT_SEQUENCE:
734 relkind = RELKIND_SEQUENCE;
738 relkind = RELKIND_VIEW;
741 case OBJECT_FOREIGN_TABLE:
742 relkind = RELKIND_FOREIGN_TABLE;
746 elog(ERROR, "unrecognized drop object type: %d",
747 (int) drop->removeType);
748 relkind = 0; /* keep compiler quiet */
752 /* Lock and validate each relation; build a list of object addresses */
753 objects = new_object_addresses();
755 foreach(cell, drop->objects)
757 RangeVar *rel = makeRangeVarFromNameList((List *) lfirst(cell));
760 Form_pg_class classform;
764 * These next few steps are a great deal like relation_openrv, but we
765 * don't bother building a relcache entry since we don't need it.
767 * Check for shared-cache-inval messages before trying to access the
768 * relation. This is needed to cover the case where the name
769 * identifies a rel that has been dropped and recreated since the
770 * start of our transaction: if we don't flush the old syscache entry,
771 * then we'll latch onto that entry and suffer an error later.
773 AcceptInvalidationMessages();
775 /* Look up the appropriate relation using namespace search */
776 relOid = RangeVarGetRelid(rel, true);
779 if (!OidIsValid(relOid))
781 DropErrorMsgNonExistent(rel->relname, relkind, drop->missing_ok);
786 * In DROP INDEX, attempt to acquire lock on the parent table before
787 * locking the index. index_drop() will need this anyway, and since
788 * regular queries lock tables before their indexes, we risk deadlock
789 * if we do it the other way around. No error if we don't find a
790 * pg_index entry, though --- that most likely means it isn't an
791 * index, and we'll fail below.
793 if (relkind == RELKIND_INDEX)
795 tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(relOid));
796 if (HeapTupleIsValid(tuple))
798 Form_pg_index index = (Form_pg_index) GETSTRUCT(tuple);
800 LockRelationOid(index->indrelid, AccessExclusiveLock);
801 ReleaseSysCache(tuple);
805 /* Get the lock before trying to fetch the syscache entry */
806 LockRelationOid(relOid, AccessExclusiveLock);
808 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
809 if (!HeapTupleIsValid(tuple))
810 elog(ERROR, "cache lookup failed for relation %u", relOid);
811 classform = (Form_pg_class) GETSTRUCT(tuple);
813 if (classform->relkind != relkind)
814 DropErrorMsgWrongType(rel->relname, classform->relkind, relkind);
816 /* Allow DROP to either table owner or schema owner */
817 if (!pg_class_ownercheck(relOid, GetUserId()) &&
818 !pg_namespace_ownercheck(classform->relnamespace, GetUserId()))
819 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
822 if (!allowSystemTableMods && IsSystemClass(classform))
824 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
825 errmsg("permission denied: \"%s\" is a system catalog",
828 /* OK, we're ready to delete this one */
829 obj.classId = RelationRelationId;
830 obj.objectId = relOid;
833 add_exact_object_address(&obj, objects);
835 ReleaseSysCache(tuple);
838 performMultipleDeletions(objects, drop->behavior);
840 free_object_addresses(objects);
845 * Executes a TRUNCATE command.
847 * This is a multi-relation truncate. We first open and grab exclusive
848 * lock on all relations involved, checking permissions and otherwise
849 * verifying that the relation is OK for truncation. In CASCADE mode,
850 * relations having FK references to the targeted relations are automatically
851 * added to the group; in RESTRICT mode, we check that all FK references are
852 * internal to the group that's being truncated. Finally all the relations
853 * are truncated and reindexed.
856 ExecuteTruncate(TruncateStmt *stmt)
860 List *seq_relids = NIL;
862 ResultRelInfo *resultRelInfos;
863 ResultRelInfo *resultRelInfo;
864 SubTransactionId mySubid;
868 * Open, exclusive-lock, and check all the explicitly-specified relations
870 foreach(cell, stmt->relations)
872 RangeVar *rv = lfirst(cell);
874 bool recurse = interpretInhOption(rv->inhOpt);
877 rel = heap_openrv(rv, AccessExclusiveLock);
878 myrelid = RelationGetRelid(rel);
879 /* don't throw error for "TRUNCATE foo, foo" */
880 if (list_member_oid(relids, myrelid))
882 heap_close(rel, AccessExclusiveLock);
885 truncate_check_rel(rel);
886 rels = lappend(rels, rel);
887 relids = lappend_oid(relids, myrelid);
894 children = find_all_inheritors(myrelid, AccessExclusiveLock, NULL);
896 foreach(child, children)
898 Oid childrelid = lfirst_oid(child);
900 if (list_member_oid(relids, childrelid))
903 /* find_all_inheritors already got lock */
904 rel = heap_open(childrelid, NoLock);
905 truncate_check_rel(rel);
906 rels = lappend(rels, rel);
907 relids = lappend_oid(relids, childrelid);
913 * In CASCADE mode, suck in all referencing relations as well. This
914 * requires multiple iterations to find indirectly-dependent relations. At
915 * each phase, we need to exclusive-lock new rels before looking for their
916 * dependencies, else we might miss something. Also, we check each rel as
917 * soon as we open it, to avoid a faux pas such as holding lock for a long
918 * time on a rel we have no permissions for.
920 if (stmt->behavior == DROP_CASCADE)
926 newrelids = heap_truncate_find_FKs(relids);
927 if (newrelids == NIL)
928 break; /* nothing else to add */
930 foreach(cell, newrelids)
932 Oid relid = lfirst_oid(cell);
935 rel = heap_open(relid, AccessExclusiveLock);
937 (errmsg("truncate cascades to table \"%s\"",
938 RelationGetRelationName(rel))));
939 truncate_check_rel(rel);
940 rels = lappend(rels, rel);
941 relids = lappend_oid(relids, relid);
947 * Check foreign key references. In CASCADE mode, this should be
948 * unnecessary since we just pulled in all the references; but as a
949 * cross-check, do it anyway if in an Assert-enabled build.
951 #ifdef USE_ASSERT_CHECKING
952 heap_truncate_check_FKs(rels, false);
954 if (stmt->behavior == DROP_RESTRICT)
955 heap_truncate_check_FKs(rels, false);
959 * If we are asked to restart sequences, find all the sequences, lock them
960 * (we need AccessExclusiveLock for ResetSequence), and check permissions.
961 * We want to do this early since it's pointless to do all the truncation
962 * work only to fail on sequence permissions.
964 if (stmt->restart_seqs)
968 Relation rel = (Relation) lfirst(cell);
969 List *seqlist = getOwnedSequences(RelationGetRelid(rel));
972 foreach(seqcell, seqlist)
974 Oid seq_relid = lfirst_oid(seqcell);
977 seq_rel = relation_open(seq_relid, AccessExclusiveLock);
979 /* This check must match AlterSequence! */
980 if (!pg_class_ownercheck(seq_relid, GetUserId()))
981 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
982 RelationGetRelationName(seq_rel));
984 seq_relids = lappend_oid(seq_relids, seq_relid);
986 relation_close(seq_rel, NoLock);
991 /* Prepare to catch AFTER triggers. */
992 AfterTriggerBeginQuery();
995 * To fire triggers, we'll need an EState as well as a ResultRelInfo for
998 estate = CreateExecutorState();
999 resultRelInfos = (ResultRelInfo *)
1000 palloc(list_length(rels) * sizeof(ResultRelInfo));
1001 resultRelInfo = resultRelInfos;
1004 Relation rel = (Relation) lfirst(cell);
1006 InitResultRelInfo(resultRelInfo,
1008 0, /* dummy rangetable index */
1009 CMD_DELETE, /* don't need any index info */
1013 estate->es_result_relations = resultRelInfos;
1014 estate->es_num_result_relations = list_length(rels);
1017 * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
1018 * truncating (this is because one of them might throw an error). Also, if
1019 * we were to allow them to prevent statement execution, that would need
1020 * to be handled here.
1022 resultRelInfo = resultRelInfos;
1025 estate->es_result_relation_info = resultRelInfo;
1026 ExecBSTruncateTriggers(estate, resultRelInfo);
1031 * OK, truncate each table.
1033 mySubid = GetCurrentSubTransactionId();
1037 Relation rel = (Relation) lfirst(cell);
1040 * Normally, we need a transaction-safe truncation here. However, if
1041 * the table was either created in the current (sub)transaction or has
1042 * a new relfilenode in the current (sub)transaction, then we can just
1043 * truncate it in-place, because a rollback would cause the whole
1044 * table or the current physical file to be thrown away anyway.
1046 if (rel->rd_createSubid == mySubid ||
1047 rel->rd_newRelfilenodeSubid == mySubid)
1049 /* Immediate, non-rollbackable truncation is OK */
1050 heap_truncate_one_rel(rel);
1058 * Need the full transaction-safe pushups.
1060 * Create a new empty storage file for the relation, and assign it
1061 * as the relfilenode value. The old storage file is scheduled for
1062 * deletion at commit.
1064 RelationSetNewRelfilenode(rel, RecentXmin);
1066 heap_relid = RelationGetRelid(rel);
1067 toast_relid = rel->rd_rel->reltoastrelid;
1070 * The same for the toast table, if any.
1072 if (OidIsValid(toast_relid))
1074 rel = relation_open(toast_relid, AccessExclusiveLock);
1075 RelationSetNewRelfilenode(rel, RecentXmin);
1076 heap_close(rel, NoLock);
1080 * Reconstruct the indexes to match, and we're done.
1082 reindex_relation(heap_relid, true, 0);
1087 * Restart owned sequences if we were asked to.
1089 foreach(cell, seq_relids)
1091 Oid seq_relid = lfirst_oid(cell);
1093 ResetSequence(seq_relid);
1097 * Process all AFTER STATEMENT TRUNCATE triggers.
1099 resultRelInfo = resultRelInfos;
1102 estate->es_result_relation_info = resultRelInfo;
1103 ExecASTruncateTriggers(estate, resultRelInfo);
1107 /* Handle queued AFTER triggers */
1108 AfterTriggerEndQuery(estate);
1110 /* We can clean up the EState now */
1111 FreeExecutorState(estate);
1113 /* And close the rels (can't do this while EState still holds refs) */
1116 Relation rel = (Relation) lfirst(cell);
1118 heap_close(rel, NoLock);
1123 * Check that a given rel is safe to truncate. Subroutine for ExecuteTruncate
1126 truncate_check_rel(Relation rel)
1128 AclResult aclresult;
1130 /* Only allow truncate on regular tables */
1131 if (rel->rd_rel->relkind != RELKIND_RELATION)
1133 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1134 errmsg("\"%s\" is not a table",
1135 RelationGetRelationName(rel))));
1137 /* Permissions checks */
1138 aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
1140 if (aclresult != ACLCHECK_OK)
1141 aclcheck_error(aclresult, ACL_KIND_CLASS,
1142 RelationGetRelationName(rel));
1144 if (!allowSystemTableMods && IsSystemRelation(rel))
1146 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1147 errmsg("permission denied: \"%s\" is a system catalog",
1148 RelationGetRelationName(rel))));
1151 * Don't allow truncate on temp tables of other backends ... their local
1152 * buffer manager is not going to cope.
1154 if (RELATION_IS_OTHER_TEMP(rel))
1156 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1157 errmsg("cannot truncate temporary tables of other sessions")));
1160 * Also check for active uses of the relation in the current transaction,
1161 * including open scans and pending AFTER trigger events.
1163 CheckTableNotInUse(rel, "TRUNCATE");
1168 * returns the name corresponding to a typstorage/attstorage enum value
1171 storage_name(char c)
1190 * Returns new schema given initial schema and superclasses.
1193 * 'schema' is the column/attribute definition for the table. (It's a list
1194 * of ColumnDef's.) It is destructively changed.
1195 * 'supers' is a list of names (as RangeVar nodes) of parent relations.
1196 * 'relpersistence' is a persistence type of the table.
1199 * 'supOids' receives a list of the OIDs of the parent relations.
1200 * 'supconstr' receives a list of constraints belonging to the parents,
1201 * updated as necessary to be valid for the child.
1202 * 'supOidCount' is set to the number of parents that have OID columns.
1205 * Completed schema list.
1208 * The order in which the attributes are inherited is very important.
1209 * Intuitively, the inherited attributes should come first. If a table
1210 * inherits from multiple parents, the order of those attributes are
1211 * according to the order of the parents specified in CREATE TABLE.
1213 * Here's an example:
1215 * create table person (name text, age int4, location point);
1216 * create table emp (salary int4, manager text) inherits(person);
1217 * create table student (gpa float8) inherits (person);
1218 * create table stud_emp (percent int4) inherits (emp, student);
1220 * The order of the attributes of stud_emp is:
1222 * person {1:name, 2:age, 3:location}
1224 * {6:gpa} student emp {4:salary, 5:manager}
1226 * stud_emp {7:percent}
1228 * If the same attribute name appears multiple times, then it appears
1229 * in the result table in the proper location for its first appearance.
1231 * Constraints (including NOT NULL constraints) for the child table
1232 * are the union of all relevant constraints, from both the child schema
1233 * and parent tables.
1235 * The default value for a child column is defined as:
1236 * (1) If the child schema specifies a default, that value is used.
1237 * (2) If neither the child nor any parent specifies a default, then
1238 * the column will not have a default.
1239 * (3) If conflicting defaults are inherited from different parents
1240 * (and not overridden by the child), an error is raised.
1241 * (4) Otherwise the inherited default is used.
1242 * Rule (3) is new in Postgres 7.1; in earlier releases you got a
1243 * rather arbitrary choice of which parent default to use.
1247 MergeAttributes(List *schema, List *supers, char relpersistence,
1248 List **supOids, List **supconstr, int *supOidCount)
1251 List *inhSchema = NIL;
1252 List *parentOids = NIL;
1253 List *constraints = NIL;
1254 int parentsWithOids = 0;
1255 bool have_bogus_defaults = false;
1257 static Node bogus_marker = {0}; /* marks conflicting defaults */
1260 * Check for and reject tables with too many columns. We perform this
1261 * check relatively early for two reasons: (a) we don't run the risk of
1262 * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
1263 * okay if we're processing <= 1600 columns, but could take minutes to
1264 * execute if the user attempts to create a table with hundreds of
1265 * thousands of columns.
1267 * Note that we also need to check that any we do not exceed this figure
1268 * after including columns from inherited relations.
1270 if (list_length(schema) > MaxHeapAttributeNumber)
1272 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1273 errmsg("tables can have at most %d columns",
1274 MaxHeapAttributeNumber)));
1277 * Check for duplicate names in the explicit list of attributes.
1279 * Although we might consider merging such entries in the same way that we
1280 * handle name conflicts for inherited attributes, it seems to make more
1281 * sense to assume such conflicts are errors.
1283 foreach(entry, schema)
1285 ColumnDef *coldef = lfirst(entry);
1286 ListCell *rest = lnext(entry);
1287 ListCell *prev = entry;
1289 if (coldef->typeName == NULL)
1292 * Typed table column option that does not belong to a column from
1293 * the type. This works because the columns from the type come
1294 * first in the list.
1297 (errcode(ERRCODE_UNDEFINED_COLUMN),
1298 errmsg("column \"%s\" does not exist",
1301 while (rest != NULL)
1303 ColumnDef *restdef = lfirst(rest);
1304 ListCell *next = lnext(rest); /* need to save it in case we
1307 if (strcmp(coldef->colname, restdef->colname) == 0)
1309 if (coldef->is_from_type)
1312 * merge the column options into the column from the type
1314 coldef->is_not_null = restdef->is_not_null;
1315 coldef->raw_default = restdef->raw_default;
1316 coldef->cooked_default = restdef->cooked_default;
1317 coldef->constraints = restdef->constraints;
1318 coldef->is_from_type = false;
1319 list_delete_cell(schema, rest, prev);
1323 (errcode(ERRCODE_DUPLICATE_COLUMN),
1324 errmsg("column \"%s\" specified more than once",
1333 * Scan the parents left-to-right, and merge their attributes to form a
1334 * list of inherited attributes (inhSchema). Also check to see if we need
1335 * to inherit an OID column.
1338 foreach(entry, supers)
1340 RangeVar *parent = (RangeVar *) lfirst(entry);
1342 TupleDesc tupleDesc;
1343 TupleConstr *constr;
1344 AttrNumber *newattno;
1345 AttrNumber parent_attno;
1347 relation = heap_openrv(parent, AccessShareLock);
1349 if (relation->rd_rel->relkind != RELKIND_RELATION)
1351 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1352 errmsg("inherited relation \"%s\" is not a table",
1354 /* Permanent rels cannot inherit from temporary ones */
1355 if (relpersistence != RELPERSISTENCE_TEMP
1356 && RelationUsesTempNamespace(relation))
1358 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1359 errmsg("cannot inherit from temporary relation \"%s\"",
1363 * We should have an UNDER permission flag for this, but for now,
1364 * demand that creator of a child table own the parent.
1366 if (!pg_class_ownercheck(RelationGetRelid(relation), GetUserId()))
1367 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1368 RelationGetRelationName(relation));
1371 * Reject duplications in the list of parents.
1373 if (list_member_oid(parentOids, RelationGetRelid(relation)))
1375 (errcode(ERRCODE_DUPLICATE_TABLE),
1376 errmsg("relation \"%s\" would be inherited from more than once",
1379 parentOids = lappend_oid(parentOids, RelationGetRelid(relation));
1381 if (relation->rd_rel->relhasoids)
1384 tupleDesc = RelationGetDescr(relation);
1385 constr = tupleDesc->constr;
1388 * newattno[] will contain the child-table attribute numbers for the
1389 * attributes of this parent table. (They are not the same for
1390 * parents after the first one, nor if we have dropped columns.)
1392 newattno = (AttrNumber *)
1393 palloc(tupleDesc->natts * sizeof(AttrNumber));
1395 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1398 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
1399 char *attributeName = NameStr(attribute->attname);
1404 * Ignore dropped columns in the parent.
1406 if (attribute->attisdropped)
1409 * change_varattnos_of_a_node asserts that this is greater
1410 * than zero, so if anything tries to use it, we should find
1413 newattno[parent_attno - 1] = 0;
1418 * Does it conflict with some previously inherited column?
1420 exist_attno = findAttrByName(attributeName, inhSchema);
1421 if (exist_attno > 0)
1428 * Yes, try to merge the two column definitions. They must
1429 * have the same type and typmod.
1432 (errmsg("merging multiple inherited definitions of column \"%s\"",
1434 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1435 typenameTypeIdModColl(NULL, def->typeName, &defTypeId, &deftypmod, &defCollId);
1436 if (defTypeId != attribute->atttypid ||
1437 deftypmod != attribute->atttypmod)
1439 (errcode(ERRCODE_DATATYPE_MISMATCH),
1440 errmsg("inherited column \"%s\" has a type conflict",
1442 errdetail("%s versus %s",
1443 TypeNameToString(def->typeName),
1444 format_type_be(attribute->atttypid))));
1445 if (defCollId != attribute->attcollation)
1447 (errcode(ERRCODE_COLLATION_MISMATCH),
1448 errmsg("inherited column \"%s\" has a collation conflict",
1450 errdetail("\"%s\" versus \"%s\"",
1451 get_collation_name(defCollId),
1452 get_collation_name(attribute->attcollation))));
1454 /* Copy storage parameter */
1455 if (def->storage == 0)
1456 def->storage = attribute->attstorage;
1457 else if (def->storage != attribute->attstorage)
1459 (errcode(ERRCODE_DATATYPE_MISMATCH),
1460 errmsg("inherited column \"%s\" has a storage parameter conflict",
1462 errdetail("%s versus %s",
1463 storage_name(def->storage),
1464 storage_name(attribute->attstorage))));
1467 /* Merge of NOT NULL constraints = OR 'em together */
1468 def->is_not_null |= attribute->attnotnull;
1469 /* Default and other constraints are handled below */
1470 newattno[parent_attno - 1] = exist_attno;
1475 * No, create a new inherited column
1477 def = makeNode(ColumnDef);
1478 def->colname = pstrdup(attributeName);
1479 def->typeName = makeTypeNameFromOid(attribute->atttypid,
1480 attribute->atttypmod,
1481 attribute->attcollation);
1483 def->is_local = false;
1484 def->is_not_null = attribute->attnotnull;
1485 def->storage = attribute->attstorage;
1486 def->raw_default = NULL;
1487 def->cooked_default = NULL;
1488 def->constraints = NIL;
1489 inhSchema = lappend(inhSchema, def);
1490 newattno[parent_attno - 1] = ++child_attno;
1494 * Copy default if any
1496 if (attribute->atthasdef)
1498 Node *this_default = NULL;
1499 AttrDefault *attrdef;
1502 /* Find default in constraint structure */
1503 Assert(constr != NULL);
1504 attrdef = constr->defval;
1505 for (i = 0; i < constr->num_defval; i++)
1507 if (attrdef[i].adnum == parent_attno)
1509 this_default = stringToNode(attrdef[i].adbin);
1513 Assert(this_default != NULL);
1516 * If default expr could contain any vars, we'd need to fix
1517 * 'em, but it can't; so default is ready to apply to child.
1519 * If we already had a default from some prior parent, check
1520 * to see if they are the same. If so, no problem; if not,
1521 * mark the column as having a bogus default. Below, we will
1522 * complain if the bogus default isn't overridden by the child
1525 Assert(def->raw_default == NULL);
1526 if (def->cooked_default == NULL)
1527 def->cooked_default = this_default;
1528 else if (!equal(def->cooked_default, this_default))
1530 def->cooked_default = &bogus_marker;
1531 have_bogus_defaults = true;
1537 * Now copy the CHECK constraints of this parent, adjusting attnos
1538 * using the completed newattno[] map. Identically named constraints
1539 * are merged if possible, else we throw error.
1541 if (constr && constr->num_check > 0)
1543 ConstrCheck *check = constr->check;
1546 for (i = 0; i < constr->num_check; i++)
1548 char *name = check[i].ccname;
1551 /* adjust varattnos of ccbin here */
1552 expr = stringToNode(check[i].ccbin);
1553 change_varattnos_of_a_node(expr, newattno);
1555 /* check for duplicate */
1556 if (!MergeCheckConstraint(constraints, name, expr))
1558 /* nope, this is a new one */
1559 CookedConstraint *cooked;
1561 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1562 cooked->contype = CONSTR_CHECK;
1563 cooked->name = pstrdup(name);
1564 cooked->attnum = 0; /* not used for constraints */
1565 cooked->expr = expr;
1566 cooked->is_local = false;
1567 cooked->inhcount = 1;
1568 constraints = lappend(constraints, cooked);
1576 * Close the parent rel, but keep our AccessShareLock on it until xact
1577 * commit. That will prevent someone else from deleting or ALTERing
1578 * the parent before the child is committed.
1580 heap_close(relation, NoLock);
1584 * If we had no inherited attributes, the result schema is just the
1585 * explicitly declared columns. Otherwise, we need to merge the declared
1586 * columns into the inherited schema list.
1588 if (inhSchema != NIL)
1590 foreach(entry, schema)
1592 ColumnDef *newdef = lfirst(entry);
1593 char *attributeName = newdef->colname;
1597 * Does it conflict with some previously inherited column?
1599 exist_attno = findAttrByName(attributeName, inhSchema);
1600 if (exist_attno > 0)
1611 * Yes, try to merge the two column definitions. They must
1612 * have the same type and typmod.
1615 (errmsg("merging column \"%s\" with inherited definition",
1617 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1618 typenameTypeIdModColl(NULL, def->typeName, &defTypeId, &deftypmod, &defcollid);
1619 typenameTypeIdModColl(NULL, newdef->typeName, &newTypeId, &newtypmod, &newcollid);
1620 if (defTypeId != newTypeId || deftypmod != newtypmod)
1622 (errcode(ERRCODE_DATATYPE_MISMATCH),
1623 errmsg("column \"%s\" has a type conflict",
1625 errdetail("%s versus %s",
1626 TypeNameToString(def->typeName),
1627 TypeNameToString(newdef->typeName))));
1628 if (defcollid != newcollid)
1630 (errcode(ERRCODE_COLLATION_MISMATCH),
1631 errmsg("column \"%s\" has a collation conflict",
1633 errdetail("\"%s\" versus \"%s\"",
1634 get_collation_name(defcollid),
1635 get_collation_name(newcollid))));
1637 /* Copy storage parameter */
1638 if (def->storage == 0)
1639 def->storage = newdef->storage;
1640 else if (newdef->storage != 0 && def->storage != newdef->storage)
1642 (errcode(ERRCODE_DATATYPE_MISMATCH),
1643 errmsg("column \"%s\" has a storage parameter conflict",
1645 errdetail("%s versus %s",
1646 storage_name(def->storage),
1647 storage_name(newdef->storage))));
1649 /* Mark the column as locally defined */
1650 def->is_local = true;
1651 /* Merge of NOT NULL constraints = OR 'em together */
1652 def->is_not_null |= newdef->is_not_null;
1653 /* If new def has a default, override previous default */
1654 if (newdef->raw_default != NULL)
1656 def->raw_default = newdef->raw_default;
1657 def->cooked_default = newdef->cooked_default;
1663 * No, attach new column to result schema
1665 inhSchema = lappend(inhSchema, newdef);
1672 * Check that we haven't exceeded the legal # of columns after merging
1673 * in inherited columns.
1675 if (list_length(schema) > MaxHeapAttributeNumber)
1677 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1678 errmsg("tables can have at most %d columns",
1679 MaxHeapAttributeNumber)));
1683 * If we found any conflicting parent default values, check to make sure
1684 * they were overridden by the child.
1686 if (have_bogus_defaults)
1688 foreach(entry, schema)
1690 ColumnDef *def = lfirst(entry);
1692 if (def->cooked_default == &bogus_marker)
1694 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
1695 errmsg("column \"%s\" inherits conflicting default values",
1697 errhint("To resolve the conflict, specify a default explicitly.")));
1701 *supOids = parentOids;
1702 *supconstr = constraints;
1703 *supOidCount = parentsWithOids;
1709 * MergeCheckConstraint
1710 * Try to merge an inherited CHECK constraint with previous ones
1712 * If we inherit identically-named constraints from multiple parents, we must
1713 * merge them, or throw an error if they don't have identical definitions.
1715 * constraints is a list of CookedConstraint structs for previous constraints.
1717 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
1718 * got a so-far-unique name, or throws error if conflict.
1721 MergeCheckConstraint(List *constraints, char *name, Node *expr)
1725 foreach(lc, constraints)
1727 CookedConstraint *ccon = (CookedConstraint *) lfirst(lc);
1729 Assert(ccon->contype == CONSTR_CHECK);
1731 /* Non-matching names never conflict */
1732 if (strcmp(ccon->name, name) != 0)
1735 if (equal(expr, ccon->expr))
1743 (errcode(ERRCODE_DUPLICATE_OBJECT),
1744 errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
1753 * Replace varattno values in an expression tree according to the given
1754 * map array, that is, varattno N is replaced by newattno[N-1]. It is
1755 * caller's responsibility to ensure that the array is long enough to
1756 * define values for all user varattnos present in the tree. System column
1757 * attnos remain unchanged.
1759 * Note that the passed node tree is modified in-place!
1762 change_varattnos_of_a_node(Node *node, const AttrNumber *newattno)
1764 /* no setup needed, so away we go */
1765 (void) change_varattnos_walker(node, newattno);
1769 change_varattnos_walker(Node *node, const AttrNumber *newattno)
1775 Var *var = (Var *) node;
1777 if (var->varlevelsup == 0 && var->varno == 1 &&
1781 * ??? the following may be a problem when the node is multiply
1782 * referenced though stringToNode() doesn't create such a node
1785 Assert(newattno[var->varattno - 1] > 0);
1786 var->varattno = var->varoattno = newattno[var->varattno - 1];
1790 return expression_tree_walker(node, change_varattnos_walker,
1795 * Generate a map for change_varattnos_of_a_node from old and new TupleDesc's,
1796 * matching according to column name.
1799 varattnos_map(TupleDesc olddesc, TupleDesc newdesc)
1805 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * olddesc->natts);
1806 for (i = 1; i <= olddesc->natts; i++)
1808 if (olddesc->attrs[i - 1]->attisdropped)
1809 continue; /* leave the entry as zero */
1811 for (j = 1; j <= newdesc->natts; j++)
1813 if (strcmp(NameStr(olddesc->attrs[i - 1]->attname),
1814 NameStr(newdesc->attrs[j - 1]->attname)) == 0)
1825 * Generate a map for change_varattnos_of_a_node from a TupleDesc and a list
1829 varattnos_map_schema(TupleDesc old, List *schema)
1834 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * old->natts);
1835 for (i = 1; i <= old->natts; i++)
1837 if (old->attrs[i - 1]->attisdropped)
1838 continue; /* leave the entry as zero */
1840 attmap[i - 1] = findAttrByName(NameStr(old->attrs[i - 1]->attname),
1848 * StoreCatalogInheritance
1849 * Updates the system catalogs with proper inheritance information.
1851 * supers is a list of the OIDs of the new relation's direct ancestors.
1854 StoreCatalogInheritance(Oid relationId, List *supers)
1863 AssertArg(OidIsValid(relationId));
1869 * Store INHERITS information in pg_inherits using direct ancestors only.
1870 * Also enter dependencies on the direct ancestors, and make sure they are
1871 * marked with relhassubclass = true.
1873 * (Once upon a time, both direct and indirect ancestors were found here
1874 * and then entered into pg_ipl. Since that catalog doesn't exist
1875 * anymore, there's no need to look for indirect ancestors.)
1877 relation = heap_open(InheritsRelationId, RowExclusiveLock);
1880 foreach(entry, supers)
1882 Oid parentOid = lfirst_oid(entry);
1884 StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation);
1888 heap_close(relation, RowExclusiveLock);
1892 * Make catalog entries showing relationId as being an inheritance child
1893 * of parentOid. inhRelation is the already-opened pg_inherits catalog.
1896 StoreCatalogInheritance1(Oid relationId, Oid parentOid,
1897 int16 seqNumber, Relation inhRelation)
1899 TupleDesc desc = RelationGetDescr(inhRelation);
1900 Datum values[Natts_pg_inherits];
1901 bool nulls[Natts_pg_inherits];
1902 ObjectAddress childobject,
1907 * Make the pg_inherits entry
1909 values[Anum_pg_inherits_inhrelid - 1] = ObjectIdGetDatum(relationId);
1910 values[Anum_pg_inherits_inhparent - 1] = ObjectIdGetDatum(parentOid);
1911 values[Anum_pg_inherits_inhseqno - 1] = Int16GetDatum(seqNumber);
1913 memset(nulls, 0, sizeof(nulls));
1915 tuple = heap_form_tuple(desc, values, nulls);
1917 simple_heap_insert(inhRelation, tuple);
1919 CatalogUpdateIndexes(inhRelation, tuple);
1921 heap_freetuple(tuple);
1924 * Store a dependency too
1926 parentobject.classId = RelationRelationId;
1927 parentobject.objectId = parentOid;
1928 parentobject.objectSubId = 0;
1929 childobject.classId = RelationRelationId;
1930 childobject.objectId = relationId;
1931 childobject.objectSubId = 0;
1933 recordDependencyOn(&childobject, &parentobject, DEPENDENCY_NORMAL);
1936 * Mark the parent as having subclasses.
1938 setRelhassubclassInRelation(parentOid, true);
1942 * Look for an existing schema entry with the given name.
1944 * Returns the index (starting with 1) if attribute already exists in schema,
1948 findAttrByName(const char *attributeName, List *schema)
1955 ColumnDef *def = lfirst(s);
1957 if (strcmp(attributeName, def->colname) == 0)
1966 * Update a relation's pg_class.relhassubclass entry to the given value
1969 setRelhassubclassInRelation(Oid relationId, bool relhassubclass)
1971 Relation relationRelation;
1973 Form_pg_class classtuple;
1976 * Fetch a modifiable copy of the tuple, modify it, update pg_class.
1978 * If the tuple already has the right relhassubclass setting, we don't
1979 * need to update it, but we still need to issue an SI inval message.
1981 relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
1982 tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
1983 if (!HeapTupleIsValid(tuple))
1984 elog(ERROR, "cache lookup failed for relation %u", relationId);
1985 classtuple = (Form_pg_class) GETSTRUCT(tuple);
1987 if (classtuple->relhassubclass != relhassubclass)
1989 classtuple->relhassubclass = relhassubclass;
1990 simple_heap_update(relationRelation, &tuple->t_self, tuple);
1992 /* keep the catalog indexes up to date */
1993 CatalogUpdateIndexes(relationRelation, tuple);
1997 /* no need to change tuple, but force relcache rebuild anyway */
1998 CacheInvalidateRelcacheByTuple(tuple);
2001 heap_freetuple(tuple);
2002 heap_close(relationRelation, RowExclusiveLock);
2007 * renameatt_internal - workhorse for renameatt
2010 renameatt_internal(Oid myrelid,
2011 const char *oldattname,
2012 const char *newattname,
2015 int expected_parents,
2016 DropBehavior behavior)
2018 Relation targetrelation;
2019 Relation attrelation;
2021 Form_pg_attribute attform;
2026 * Grab an exclusive lock on the target table, which we will NOT release
2027 * until end of transaction.
2029 targetrelation = relation_open(myrelid, AccessExclusiveLock);
2031 if (targetrelation->rd_rel->reloftype && !recursing)
2033 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2034 errmsg("cannot rename column of typed table")));
2037 * Renaming the columns of sequences or toast tables doesn't actually
2038 * break anything from the system's point of view, since internal
2039 * references are by attnum. But it doesn't seem right to allow users to
2040 * change names that are hardcoded into the system, hence the following
2043 relkind = RelationGetForm(targetrelation)->relkind;
2044 if (relkind != RELKIND_RELATION &&
2045 relkind != RELKIND_VIEW &&
2046 relkind != RELKIND_COMPOSITE_TYPE &&
2047 relkind != RELKIND_INDEX &&
2048 relkind != RELKIND_FOREIGN_TABLE)
2050 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2051 errmsg("\"%s\" is not a table, view, composite type, index or foreign table",
2052 RelationGetRelationName(targetrelation))));
2055 * permissions checking. only the owner of a class can change its schema.
2057 if (!pg_class_ownercheck(myrelid, GetUserId()))
2058 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
2059 RelationGetRelationName(targetrelation));
2060 if (!allowSystemTableMods && IsSystemRelation(targetrelation))
2062 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2063 errmsg("permission denied: \"%s\" is a system catalog",
2064 RelationGetRelationName(targetrelation))));
2067 * if the 'recurse' flag is set then we are supposed to rename this
2068 * attribute in all classes that inherit from 'relname' (as well as in
2071 * any permissions or problems with duplicate attributes will cause the
2072 * whole transaction to abort, which is what we want -- all or nothing.
2082 * we need the number of parents for each child so that the recursive
2083 * calls to renameatt() can determine whether there are any parents
2084 * outside the inheritance hierarchy being processed.
2086 child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
2090 * find_all_inheritors does the recursive search of the inheritance
2091 * hierarchy, so all we have to do is process all of the relids in the
2092 * list that it returns.
2094 forboth(lo, child_oids, li, child_numparents)
2096 Oid childrelid = lfirst_oid(lo);
2097 int numparents = lfirst_int(li);
2099 if (childrelid == myrelid)
2101 /* note we need not recurse again */
2102 renameatt_internal(childrelid, oldattname, newattname, false, true, numparents, behavior);
2108 * If we are told not to recurse, there had better not be any child
2109 * tables; else the rename would put them out of step.
2111 * expected_parents will only be 0 if we are not already recursing.
2113 if (expected_parents == 0 &&
2114 find_inheritance_children(myrelid, NoLock) != NIL)
2116 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2117 errmsg("inherited column \"%s\" must be renamed in child tables too",
2121 /* rename attributes in typed tables of composite type */
2122 if (targetrelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
2127 child_oids = find_typed_table_dependencies(targetrelation->rd_rel->reltype,
2128 RelationGetRelationName(targetrelation),
2131 foreach(lo, child_oids)
2132 renameatt_internal(lfirst_oid(lo), oldattname, newattname, true, true, 0, behavior);
2135 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
2137 atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
2138 if (!HeapTupleIsValid(atttup))
2140 (errcode(ERRCODE_UNDEFINED_COLUMN),
2141 errmsg("column \"%s\" does not exist",
2143 attform = (Form_pg_attribute) GETSTRUCT(atttup);
2145 attnum = attform->attnum;
2148 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2149 errmsg("cannot rename system column \"%s\"",
2153 * if the attribute is inherited, forbid the renaming. if this is a
2154 * top-level call to renameatt(), then expected_parents will be 0, so the
2155 * effect of this code will be to prohibit the renaming if the attribute
2156 * is inherited at all. if this is a recursive call to renameatt(),
2157 * expected_parents will be the number of parents the current relation has
2158 * within the inheritance hierarchy being processed, so we'll prohibit the
2159 * renaming only if there are additional parents from elsewhere.
2161 if (attform->attinhcount > expected_parents)
2163 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2164 errmsg("cannot rename inherited column \"%s\"",
2167 /* new name should not already exist */
2169 /* this test is deliberately not attisdropped-aware */
2170 if (SearchSysCacheExists2(ATTNAME,
2171 ObjectIdGetDatum(myrelid),
2172 PointerGetDatum(newattname)))
2174 (errcode(ERRCODE_DUPLICATE_COLUMN),
2175 errmsg("column \"%s\" of relation \"%s\" already exists",
2176 newattname, RelationGetRelationName(targetrelation))));
2178 /* apply the update */
2179 namestrcpy(&(attform->attname), newattname);
2181 simple_heap_update(attrelation, &atttup->t_self, atttup);
2183 /* keep system catalog indexes current */
2184 CatalogUpdateIndexes(attrelation, atttup);
2186 heap_freetuple(atttup);
2188 heap_close(attrelation, RowExclusiveLock);
2190 relation_close(targetrelation, NoLock); /* close rel but keep lock */
2195 * renameatt - changes the name of a attribute in a relation
2198 renameatt(Oid myrelid, RenameStmt *stmt)
2200 renameatt_internal(myrelid,
2201 stmt->subname, /* old att name */
2202 stmt->newname, /* new att name */
2203 interpretInhOption(stmt->relation->inhOpt), /* recursive? */
2204 false, /* recursing? */
2205 0, /* expected inhcount */
2211 * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW/FOREIGN TABLE RENAME
2213 * Caller has already done permissions checks.
2216 RenameRelation(Oid myrelid, const char *newrelname, ObjectType reltype)
2218 Relation targetrelation;
2223 * Grab an exclusive lock on the target table, index, sequence or view,
2224 * which we will NOT release until end of transaction.
2226 targetrelation = relation_open(myrelid, AccessExclusiveLock);
2228 namespaceId = RelationGetNamespace(targetrelation);
2229 relkind = targetrelation->rd_rel->relkind;
2232 * For compatibility with prior releases, we don't complain if ALTER TABLE
2233 * or ALTER INDEX is used to rename some other type of relation. But
2234 * ALTER SEQUENCE/VIEW/FOREIGN TABLE are only to be used with relations of
2237 if (reltype == OBJECT_SEQUENCE && relkind != RELKIND_SEQUENCE)
2239 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2240 errmsg("\"%s\" is not a sequence",
2241 RelationGetRelationName(targetrelation))));
2243 if (reltype == OBJECT_VIEW && relkind != RELKIND_VIEW)
2245 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2246 errmsg("\"%s\" is not a view",
2247 RelationGetRelationName(targetrelation))));
2249 if (reltype == OBJECT_FOREIGN_TABLE && relkind != RELKIND_FOREIGN_TABLE)
2251 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2252 errmsg("\"%s\" is not a foreign table",
2253 RelationGetRelationName(targetrelation)),
2254 errhint("Use ALTER FOREIGN TABLE instead.")));
2257 * Don't allow ALTER TABLE on composite types. We want people to use ALTER
2260 if (relkind == RELKIND_COMPOSITE_TYPE)
2262 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2263 errmsg("\"%s\" is a composite type",
2264 RelationGetRelationName(targetrelation)),
2265 errhint("Use ALTER TYPE instead.")));
2268 RenameRelationInternal(myrelid, newrelname, namespaceId);
2271 * Close rel, but keep exclusive lock!
2273 relation_close(targetrelation, NoLock);
2277 * RenameRelationInternal - change the name of a relation
2279 * XXX - When renaming sequences, we don't bother to modify the
2280 * sequence name that is stored within the sequence itself
2281 * (this would cause problems with MVCC). In the future,
2282 * the sequence name should probably be removed from the
2283 * sequence, AFAIK there's no need for it to be there.
2286 RenameRelationInternal(Oid myrelid, const char *newrelname, Oid namespaceId)
2288 Relation targetrelation;
2289 Relation relrelation; /* for RELATION relation */
2291 Form_pg_class relform;
2294 * Grab an exclusive lock on the target table, index, sequence or view,
2295 * which we will NOT release until end of transaction.
2297 targetrelation = relation_open(myrelid, AccessExclusiveLock);
2300 * Find relation's pg_class tuple, and make sure newrelname isn't in use.
2302 relrelation = heap_open(RelationRelationId, RowExclusiveLock);
2304 reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
2305 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
2306 elog(ERROR, "cache lookup failed for relation %u", myrelid);
2307 relform = (Form_pg_class) GETSTRUCT(reltup);
2309 if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
2311 (errcode(ERRCODE_DUPLICATE_TABLE),
2312 errmsg("relation \"%s\" already exists",
2316 * Update pg_class tuple with new relname. (Scribbling on reltup is OK
2317 * because it's a copy...)
2319 namestrcpy(&(relform->relname), newrelname);
2321 simple_heap_update(relrelation, &reltup->t_self, reltup);
2323 /* keep the system catalog indexes current */
2324 CatalogUpdateIndexes(relrelation, reltup);
2326 heap_freetuple(reltup);
2327 heap_close(relrelation, RowExclusiveLock);
2330 * Also rename the associated type, if any.
2332 if (OidIsValid(targetrelation->rd_rel->reltype))
2333 RenameTypeInternal(targetrelation->rd_rel->reltype,
2334 newrelname, namespaceId);
2337 * Also rename the associated constraint, if any.
2339 if (targetrelation->rd_rel->relkind == RELKIND_INDEX)
2341 Oid constraintId = get_index_constraint(myrelid);
2343 if (OidIsValid(constraintId))
2344 RenameConstraintById(constraintId, newrelname);
2348 * Close rel, but keep exclusive lock!
2350 relation_close(targetrelation, NoLock);
2354 * Disallow ALTER TABLE (and similar commands) when the current backend has
2355 * any open reference to the target table besides the one just acquired by
2356 * the calling command; this implies there's an open cursor or active plan.
2357 * We need this check because our lock doesn't protect us against stomping
2358 * on our own foot, only other people's feet!
2360 * For ALTER TABLE, the only case known to cause serious trouble is ALTER
2361 * COLUMN TYPE, and some changes are obviously pretty benign, so this could
2362 * possibly be relaxed to only error out for certain types of alterations.
2363 * But the use-case for allowing any of these things is not obvious, so we
2364 * won't work hard at it for now.
2366 * We also reject these commands if there are any pending AFTER trigger events
2367 * for the rel. This is certainly necessary for the rewriting variants of
2368 * ALTER TABLE, because they don't preserve tuple TIDs and so the pending
2369 * events would try to fetch the wrong tuples. It might be overly cautious
2370 * in other cases, but again it seems better to err on the side of paranoia.
2372 * REINDEX calls this with "rel" referencing the index to be rebuilt; here
2373 * we are worried about active indexscans on the index. The trigger-event
2374 * check can be skipped, since we are doing no damage to the parent table.
2376 * The statement name (eg, "ALTER TABLE") is passed for use in error messages.
2379 CheckTableNotInUse(Relation rel, const char *stmt)
2381 int expected_refcnt;
2383 expected_refcnt = rel->rd_isnailed ? 2 : 1;
2384 if (rel->rd_refcnt != expected_refcnt)
2386 (errcode(ERRCODE_OBJECT_IN_USE),
2387 /* translator: first %s is a SQL command, eg ALTER TABLE */
2388 errmsg("cannot %s \"%s\" because "
2389 "it is being used by active queries in this session",
2390 stmt, RelationGetRelationName(rel))));
2392 if (rel->rd_rel->relkind != RELKIND_INDEX &&
2393 AfterTriggerPendingOnRel(RelationGetRelid(rel)))
2395 (errcode(ERRCODE_OBJECT_IN_USE),
2396 /* translator: first %s is a SQL command, eg ALTER TABLE */
2397 errmsg("cannot %s \"%s\" because "
2398 "it has pending trigger events",
2399 stmt, RelationGetRelationName(rel))));
2404 * Execute ALTER TABLE, which can be a list of subcommands
2406 * ALTER TABLE is performed in three phases:
2407 * 1. Examine subcommands and perform pre-transformation checking.
2408 * 2. Update system catalogs.
2409 * 3. Scan table(s) to check new constraints, and optionally recopy
2410 * the data into new table(s).
2411 * Phase 3 is not performed unless one or more of the subcommands requires
2412 * it. The intention of this design is to allow multiple independent
2413 * updates of the table schema to be performed with only one pass over the
2416 * ATPrepCmd performs phase 1. A "work queue" entry is created for
2417 * each table to be affected (there may be multiple affected tables if the
2418 * commands traverse a table inheritance hierarchy). Also we do preliminary
2419 * validation of the subcommands, including parse transformation of those
2420 * expressions that need to be evaluated with respect to the old table
2423 * ATRewriteCatalogs performs phase 2 for each affected table. (Note that
2424 * phases 2 and 3 normally do no explicit recursion, since phase 1 already
2425 * did it --- although some subcommands have to recurse in phase 2 instead.)
2426 * Certain subcommands need to be performed before others to avoid
2427 * unnecessary conflicts; for example, DROP COLUMN should come before
2428 * ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
2429 * lists, one for each logical "pass" of phase 2.
2431 * ATRewriteTables performs phase 3 for those tables that need it.
2433 * Thanks to the magic of MVCC, an error anywhere along the way rolls back
2434 * the whole operation; we don't have to do anything special to clean up.
2436 * We lock the table as the first action, with an appropriate lock level
2437 * for the subcommands requested. Any subcommand that needs to rewrite
2438 * tuples in the table forces the whole command to be executed with
2439 * AccessExclusiveLock. If all subcommands do not require rewrite table
2440 * then we may be able to use lower lock levels. We pass the lock level down
2441 * so that we can apply it recursively to inherited tables. Note that the
2442 * lock level we want as we recurse may well be higher than required for
2443 * that specific subcommand. So we pass down the overall lock requirement,
2444 * rather than reassess it at lower levels.
2447 AlterTable(AlterTableStmt *stmt)
2450 LOCKMODE lockmode = AlterTableGetLockLevel(stmt->cmds);
2453 * Acquire same level of lock as already acquired during parsing.
2455 rel = relation_openrv(stmt->relation, lockmode);
2457 CheckTableNotInUse(rel, "ALTER TABLE");
2459 /* Check relation type against type specified in the ALTER command */
2460 switch (stmt->relkind)
2465 * For mostly-historical reasons, we allow ALTER TABLE to apply to
2466 * almost all relation types.
2468 if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE
2469 || rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2471 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2472 errmsg("\"%s\" is not a table",
2473 RelationGetRelationName(rel))));
2477 if (rel->rd_rel->relkind != RELKIND_INDEX)
2479 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2480 errmsg("\"%s\" is not an index",
2481 RelationGetRelationName(rel))));
2484 case OBJECT_SEQUENCE:
2485 if (rel->rd_rel->relkind != RELKIND_SEQUENCE)
2487 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2488 errmsg("\"%s\" is not a sequence",
2489 RelationGetRelationName(rel))));
2493 if (rel->rd_rel->relkind != RELKIND_COMPOSITE_TYPE)
2495 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2496 errmsg("\"%s\" is not a composite type",
2497 RelationGetRelationName(rel))));
2501 if (rel->rd_rel->relkind != RELKIND_VIEW)
2503 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2504 errmsg("\"%s\" is not a view",
2505 RelationGetRelationName(rel))));
2508 case OBJECT_FOREIGN_TABLE:
2509 if (rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
2511 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2512 errmsg("\"%s\" is not a foreign table",
2513 RelationGetRelationName(rel))));
2517 elog(ERROR, "unrecognized object type: %d", (int) stmt->relkind);
2520 ATController(rel, stmt->cmds, interpretInhOption(stmt->relation->inhOpt),
2525 * AlterTableInternal
2527 * ALTER TABLE with target specified by OID
2529 * We do not reject if the relation is already open, because it's quite
2530 * likely that one or more layers of caller have it open. That means it
2531 * is unsafe to use this entry point for alterations that could break
2532 * existing query plans. On the assumption it's not used for such, we
2533 * don't have to reject pending AFTER triggers, either.
2536 AlterTableInternal(Oid relid, List *cmds, bool recurse)
2539 LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
2541 rel = relation_open(relid, lockmode);
2543 ATController(rel, cmds, recurse, lockmode);
2547 * AlterTableGetLockLevel
2549 * Sets the overall lock level required for the supplied list of subcommands.
2550 * Policy for doing this set according to needs of AlterTable(), see
2551 * comments there for overall explanation.
2553 * Function is called before and after parsing, so it must give same
2554 * answer each time it is called. Some subcommands are transformed
2555 * into other subcommand types, so the transform must never be made to a
2556 * lower lock level than previously assigned. All transforms are noted below.
2558 * Since this is called before we lock the table we cannot use table metadata
2559 * to influence the type of lock we acquire.
2561 * There should be no lockmodes hardcoded into the subcommand functions. All
2562 * lockmode decisions for ALTER TABLE are made here only. The one exception is
2563 * ALTER TABLE RENAME which is treated as a different statement type T_RenameStmt
2564 * and does not travel through this section of code and cannot be combined with
2565 * any of the subcommands given here.
2568 AlterTableGetLockLevel(List *cmds)
2571 LOCKMODE lockmode = ShareUpdateExclusiveLock;
2575 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2576 LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
2578 switch (cmd->subtype)
2581 * Need AccessExclusiveLock for these subcommands because they
2582 * affect or potentially affect both read and write operations.
2584 * New subcommand types should be added here by default.
2586 case AT_AddColumn: /* may rewrite heap, in some cases and visible to SELECT */
2587 case AT_DropColumn: /* change visible to SELECT */
2588 case AT_AddColumnToView: /* CREATE VIEW */
2589 case AT_AlterColumnType: /* must rewrite heap */
2590 case AT_DropConstraint: /* as DROP INDEX */
2591 case AT_AddOids: /* must rewrite heap */
2592 case AT_DropOids: /* calls AT_DropColumn */
2593 case AT_EnableAlwaysRule: /* may change SELECT rules */
2594 case AT_EnableReplicaRule: /* may change SELECT rules */
2595 case AT_EnableRule: /* may change SELECT rules */
2596 case AT_DisableRule: /* may change SELECT rules */
2597 case AT_ChangeOwner: /* change visible to SELECT */
2598 case AT_SetTableSpace: /* must rewrite heap */
2599 case AT_DropNotNull: /* may change some SQL plans */
2601 case AT_GenericOptions:
2602 cmd_lockmode = AccessExclusiveLock;
2606 * These subcommands affect write operations only.
2608 case AT_ColumnDefault:
2609 case AT_ProcessedConstraint: /* becomes AT_AddConstraint */
2610 case AT_AddConstraintRecurse: /* becomes AT_AddConstraint */
2612 case AT_EnableAlwaysTrig:
2613 case AT_EnableReplicaTrig:
2614 case AT_EnableTrigAll:
2615 case AT_EnableTrigUser:
2616 case AT_DisableTrig:
2617 case AT_DisableTrigAll:
2618 case AT_DisableTrigUser:
2619 case AT_AddIndex: /* from ADD CONSTRAINT */
2620 case AT_AddIndexConstraint:
2621 cmd_lockmode = ShareRowExclusiveLock;
2624 case AT_AddConstraint:
2625 if (IsA(cmd->def, Constraint))
2627 Constraint *con = (Constraint *) cmd->def;
2629 switch (con->contype)
2631 case CONSTR_EXCLUSION:
2632 case CONSTR_PRIMARY:
2635 * Cases essentially the same as CREATE INDEX. We
2636 * could reduce the lock strength to ShareLock if we
2637 * can work out how to allow concurrent catalog updates.
2639 cmd_lockmode = ShareRowExclusiveLock;
2641 case CONSTR_FOREIGN:
2643 * We add triggers to both tables when we add a
2644 * Foreign Key, so the lock level must be at least
2645 * as strong as CREATE TRIGGER.
2647 cmd_lockmode = ShareRowExclusiveLock;
2651 cmd_lockmode = ShareRowExclusiveLock;
2657 * These subcommands affect inheritance behaviour. Queries started before us
2658 * will continue to see the old inheritance behaviour, while queries started
2659 * after we commit will see new behaviour. No need to prevent reads or writes
2660 * to the subtable while we hook it up though. In both cases the parent table
2661 * is locked with AccessShareLock.
2664 case AT_DropInherit:
2665 cmd_lockmode = ShareUpdateExclusiveLock;
2669 * These subcommands affect general strategies for performance and maintenance,
2670 * though don't change the semantic results from normal data reads and writes.
2671 * Delaying an ALTER TABLE behind currently active writes only delays the point
2672 * where the new strategy begins to take effect, so there is no benefit in waiting.
2673 * In this case the minimum restriction applies: we don't currently allow
2674 * concurrent catalog updates.
2676 case AT_SetStatistics:
2678 case AT_DropCluster:
2679 case AT_SetRelOptions:
2680 case AT_ResetRelOptions:
2682 case AT_ResetOptions:
2684 case AT_ValidateConstraint:
2685 cmd_lockmode = ShareUpdateExclusiveLock;
2689 elog(ERROR, "unrecognized alter table type: %d",
2690 (int) cmd->subtype);
2695 * Take the greatest lockmode from any subcommand
2697 if (cmd_lockmode > lockmode)
2698 lockmode = cmd_lockmode;
2705 ATController(Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
2710 /* Phase 1: preliminary examination of commands, create work queue */
2713 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2715 ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode);
2718 /* Close the relation, but keep lock until commit */
2719 relation_close(rel, NoLock);
2721 /* Phase 2: update system catalogs */
2722 ATRewriteCatalogs(&wqueue, lockmode);
2724 /* Phase 3: scan/rewrite tables as needed */
2725 ATRewriteTables(&wqueue, lockmode);
2731 * Traffic cop for ALTER TABLE Phase 1 operations, including simple
2732 * recursion and permission checks.
2734 * Caller must have acquired appropriate lock type on relation already.
2735 * This lock should be held until commit.
2738 ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
2739 bool recurse, bool recursing, LOCKMODE lockmode)
2741 AlteredTableInfo *tab;
2744 /* Find or create work queue entry for this table */
2745 tab = ATGetQueueEntry(wqueue, rel);
2748 * Copy the original subcommand for each table. This avoids conflicts
2749 * when different child tables need to make different parse
2750 * transformations (for example, the same column may have different column
2751 * numbers in different children).
2753 cmd = copyObject(cmd);
2756 * Do permissions checking, recursion to child tables if needed, and any
2757 * additional phase-1 processing needed.
2759 switch (cmd->subtype)
2761 case AT_AddColumn: /* ADD COLUMN */
2762 ATSimplePermissions(rel,
2763 ATT_TABLE|ATT_COMPOSITE_TYPE|ATT_FOREIGN_TABLE);
2764 /* Performs own recursion */
2765 ATPrepAddColumn(wqueue, rel, recurse, recursing, cmd, lockmode);
2766 pass = AT_PASS_ADD_COL;
2768 case AT_AddColumnToView: /* add column via CREATE OR REPLACE
2770 ATSimplePermissions(rel, ATT_VIEW);
2771 /* Performs own recursion */
2772 ATPrepAddColumn(wqueue, rel, recurse, recursing, cmd, lockmode);
2773 pass = AT_PASS_ADD_COL;
2775 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
2778 * We allow defaults on views so that INSERT into a view can have
2779 * default-ish behavior. This works because the rewriter
2780 * substitutes default values into INSERTs before it expands
2783 ATSimplePermissions(rel, ATT_TABLE|ATT_VIEW);
2784 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
2785 /* No command-specific prep needed */
2786 pass = cmd->def ? AT_PASS_ADD_CONSTR : AT_PASS_DROP;
2788 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
2789 ATSimplePermissions(rel, ATT_TABLE|ATT_FOREIGN_TABLE);
2790 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
2791 /* No command-specific prep needed */
2792 pass = AT_PASS_DROP;
2794 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
2795 ATSimplePermissions(rel, ATT_TABLE|ATT_FOREIGN_TABLE);
2796 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
2797 /* No command-specific prep needed */
2798 pass = AT_PASS_ADD_CONSTR;
2800 case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
2801 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
2802 /* Performs own permission checks */
2803 ATPrepSetStatistics(rel, cmd->name, cmd->def, lockmode);
2804 pass = AT_PASS_MISC;
2806 case AT_SetOptions: /* ALTER COLUMN SET ( options ) */
2807 case AT_ResetOptions: /* ALTER COLUMN RESET ( options ) */
2808 ATSimplePermissions(rel, ATT_TABLE|ATT_INDEX);
2809 /* This command never recurses */
2810 pass = AT_PASS_MISC;
2812 case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
2813 ATSimplePermissions(rel, ATT_TABLE);
2814 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
2815 /* No command-specific prep needed */
2816 pass = AT_PASS_MISC;
2818 case AT_DropColumn: /* DROP COLUMN */
2819 ATSimplePermissions(rel,
2820 ATT_TABLE|ATT_COMPOSITE_TYPE|ATT_FOREIGN_TABLE);
2821 ATPrepDropColumn(wqueue, rel, recurse, recursing, cmd, lockmode);
2822 /* Recursion occurs during execution phase */
2823 pass = AT_PASS_DROP;
2825 case AT_AddIndex: /* ADD INDEX */
2826 ATSimplePermissions(rel, ATT_TABLE);
2827 /* This command never recurses */
2828 /* No command-specific prep needed */
2829 pass = AT_PASS_ADD_INDEX;
2831 case AT_AddConstraint: /* ADD CONSTRAINT */
2832 ATSimplePermissions(rel, ATT_TABLE);
2833 /* Recursion occurs during execution phase */
2834 /* No command-specific prep needed except saving recurse flag */
2836 cmd->subtype = AT_AddConstraintRecurse;
2837 pass = AT_PASS_ADD_CONSTR;
2839 case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
2840 ATSimplePermissions(rel, ATT_TABLE);
2841 /* This command never recurses */
2842 /* No command-specific prep needed */
2843 pass = AT_PASS_ADD_CONSTR;
2845 case AT_DropConstraint: /* DROP CONSTRAINT */
2846 ATSimplePermissions(rel, ATT_TABLE);
2847 /* Recursion occurs during execution phase */
2848 /* No command-specific prep needed except saving recurse flag */
2850 cmd->subtype = AT_DropConstraintRecurse;
2851 pass = AT_PASS_DROP;
2853 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
2854 ATSimplePermissions(rel,
2855 ATT_TABLE|ATT_COMPOSITE_TYPE|ATT_FOREIGN_TABLE);
2856 /* Performs own recursion */
2857 ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd, lockmode);
2858 pass = AT_PASS_ALTER_TYPE;
2860 case AT_ChangeOwner: /* ALTER OWNER */
2861 /* This command never recurses */
2862 /* No command-specific prep needed */
2863 pass = AT_PASS_MISC;
2865 case AT_ClusterOn: /* CLUSTER ON */
2866 case AT_DropCluster: /* SET WITHOUT CLUSTER */
2867 ATSimplePermissions(rel, ATT_TABLE);
2868 /* These commands never recurse */
2869 /* No command-specific prep needed */
2870 pass = AT_PASS_MISC;
2872 case AT_AddOids: /* SET WITH OIDS */
2873 ATSimplePermissions(rel, ATT_TABLE);
2874 /* Performs own recursion */
2875 if (!rel->rd_rel->relhasoids || recursing)
2876 ATPrepAddOids(wqueue, rel, recurse, cmd, lockmode);
2877 pass = AT_PASS_ADD_COL;
2879 case AT_DropOids: /* SET WITHOUT OIDS */
2880 ATSimplePermissions(rel, ATT_TABLE);
2881 /* Performs own recursion */
2882 if (rel->rd_rel->relhasoids)
2884 AlterTableCmd *dropCmd = makeNode(AlterTableCmd);
2886 dropCmd->subtype = AT_DropColumn;
2887 dropCmd->name = pstrdup("oid");
2888 dropCmd->behavior = cmd->behavior;
2889 ATPrepCmd(wqueue, rel, dropCmd, recurse, false, lockmode);
2891 pass = AT_PASS_DROP;
2893 case AT_SetTableSpace: /* SET TABLESPACE */
2894 ATSimplePermissions(rel, ATT_TABLE|ATT_INDEX);
2895 /* This command never recurses */
2896 ATPrepSetTableSpace(tab, rel, cmd->name, lockmode);
2897 pass = AT_PASS_MISC; /* doesn't actually matter */
2899 case AT_SetRelOptions: /* SET (...) */
2900 case AT_ResetRelOptions: /* RESET (...) */
2901 ATSimplePermissions(rel, ATT_TABLE|ATT_INDEX);
2902 /* This command never recurses */
2903 /* No command-specific prep needed */
2904 pass = AT_PASS_MISC;
2906 case AT_AddInherit: /* INHERIT */
2907 ATSimplePermissions(rel, ATT_TABLE);
2908 /* This command never recurses */
2909 ATPrepAddInherit(rel);
2910 pass = AT_PASS_MISC;
2912 case AT_ValidateConstraint:
2913 case AT_EnableTrig: /* ENABLE TRIGGER variants */
2914 case AT_EnableAlwaysTrig:
2915 case AT_EnableReplicaTrig:
2916 case AT_EnableTrigAll:
2917 case AT_EnableTrigUser:
2918 case AT_DisableTrig: /* DISABLE TRIGGER variants */
2919 case AT_DisableTrigAll:
2920 case AT_DisableTrigUser:
2921 case AT_EnableRule: /* ENABLE/DISABLE RULE variants */
2922 case AT_EnableAlwaysRule:
2923 case AT_EnableReplicaRule:
2924 case AT_DisableRule:
2925 ATSimplePermissions(rel, ATT_TABLE);
2926 /* These commands never recurse */
2927 /* No command-specific prep needed */
2928 pass = AT_PASS_MISC;
2930 case AT_DropInherit: /* NO INHERIT */
2931 ATSimplePermissions(rel, ATT_TABLE);
2932 /* No command-specific prep needed */
2933 pass = AT_PASS_MISC;
2935 case AT_GenericOptions:
2936 ATSimplePermissions(rel, ATT_FOREIGN_TABLE);
2937 /* No command-specific prep needed */
2938 pass = AT_PASS_MISC;
2941 elog(ERROR, "unrecognized alter table type: %d",
2942 (int) cmd->subtype);
2943 pass = 0; /* keep compiler quiet */
2947 /* Add the subcommand to the appropriate list for phase 2 */
2948 tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
2954 * Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
2955 * dispatched in a "safe" execution order (designed to avoid unnecessary
2959 ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode)
2965 * We process all the tables "in parallel", one pass at a time. This is
2966 * needed because we may have to propagate work from one table to another
2967 * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
2968 * re-adding of the foreign key constraint to the other table). Work can
2969 * only be propagated into later passes, however.
2971 for (pass = 0; pass < AT_NUM_PASSES; pass++)
2973 /* Go through each table that needs to be processed */
2974 foreach(ltab, *wqueue)
2976 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2977 List *subcmds = tab->subcmds[pass];
2985 * Appropriate lock was obtained by phase 1, needn't get it again
2987 rel = relation_open(tab->relid, NoLock);
2989 foreach(lcmd, subcmds)
2990 ATExecCmd(wqueue, tab, rel, (AlterTableCmd *) lfirst(lcmd), lockmode);
2993 * After the ALTER TYPE pass, do cleanup work (this is not done in
2994 * ATExecAlterColumnType since it should be done only once if
2995 * multiple columns of a table are altered).
2997 if (pass == AT_PASS_ALTER_TYPE)
2998 ATPostAlterTypeCleanup(wqueue, tab, lockmode);
3000 relation_close(rel, NoLock);
3005 * Check to see if a toast table must be added, if we executed any
3006 * subcommands that might have added a column or changed column storage.
3008 foreach(ltab, *wqueue)
3010 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
3012 if (tab->relkind == RELKIND_RELATION &&
3013 (tab->subcmds[AT_PASS_ADD_COL] ||
3014 tab->subcmds[AT_PASS_ALTER_TYPE] ||
3015 tab->subcmds[AT_PASS_COL_ATTRS]))
3016 AlterTableCreateToastTable(tab->relid, (Datum) 0);
3021 * ATExecCmd: dispatch a subcommand to appropriate execution routine
3024 ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
3025 AlterTableCmd *cmd, LOCKMODE lockmode)
3027 switch (cmd->subtype)
3029 case AT_AddColumn: /* ADD COLUMN */
3030 case AT_AddColumnToView: /* add column via CREATE OR REPLACE
3032 ATExecAddColumn(tab, rel, (ColumnDef *) cmd->def, false, lockmode);
3034 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
3035 ATExecColumnDefault(rel, cmd->name, cmd->def, lockmode);
3037 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
3038 ATExecDropNotNull(rel, cmd->name, lockmode);
3040 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
3041 ATExecSetNotNull(tab, rel, cmd->name, lockmode);
3043 case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
3044 ATExecSetStatistics(rel, cmd->name, cmd->def, lockmode);
3046 case AT_SetOptions: /* ALTER COLUMN SET ( options ) */
3047 ATExecSetOptions(rel, cmd->name, cmd->def, false, lockmode);
3049 case AT_ResetOptions: /* ALTER COLUMN RESET ( options ) */
3050 ATExecSetOptions(rel, cmd->name, cmd->def, true, lockmode);
3052 case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
3053 ATExecSetStorage(rel, cmd->name, cmd->def, lockmode);
3055 case AT_DropColumn: /* DROP COLUMN */
3056 ATExecDropColumn(wqueue, rel, cmd->name,
3057 cmd->behavior, false, false, cmd->missing_ok, lockmode);
3059 case AT_DropColumnRecurse: /* DROP COLUMN with recursion */
3060 ATExecDropColumn(wqueue, rel, cmd->name,
3061 cmd->behavior, true, false, cmd->missing_ok, lockmode);
3063 case AT_AddIndex: /* ADD INDEX */
3064 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false, lockmode);
3066 case AT_ReAddIndex: /* ADD INDEX */
3067 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true, lockmode);
3069 case AT_AddConstraint: /* ADD CONSTRAINT */
3070 ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
3073 case AT_AddConstraintRecurse: /* ADD CONSTRAINT with recursion */
3074 ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
3077 case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
3078 ATExecAddIndexConstraint(tab, rel, (IndexStmt *) cmd->def, lockmode);
3080 case AT_ValidateConstraint:
3081 ATExecValidateConstraint(rel, cmd->name);
3083 case AT_DropConstraint: /* DROP CONSTRAINT */
3084 ATExecDropConstraint(rel, cmd->name, cmd->behavior,
3086 cmd->missing_ok, lockmode);
3088 case AT_DropConstraintRecurse: /* DROP CONSTRAINT with recursion */
3089 ATExecDropConstraint(rel, cmd->name, cmd->behavior,
3091 cmd->missing_ok, lockmode);
3093 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
3094 ATExecAlterColumnType(tab, rel, cmd->name, (TypeName *) cmd->def, lockmode);
3096 case AT_ChangeOwner: /* ALTER OWNER */
3097 ATExecChangeOwner(RelationGetRelid(rel),
3098 get_role_oid(cmd->name, false),
3101 case AT_ClusterOn: /* CLUSTER ON */
3102 ATExecClusterOn(rel, cmd->name, lockmode);
3104 case AT_DropCluster: /* SET WITHOUT CLUSTER */
3105 ATExecDropCluster(rel, lockmode);
3107 case AT_AddOids: /* SET WITH OIDS */
3108 /* Use the ADD COLUMN code, unless prep decided to do nothing */
3109 if (cmd->def != NULL)
3110 ATExecAddColumn(tab, rel, (ColumnDef *) cmd->def, true, lockmode);
3112 case AT_DropOids: /* SET WITHOUT OIDS */
3115 * Nothing to do here; we'll have generated a DropColumn
3116 * subcommand to do the real work
3119 case AT_SetTableSpace: /* SET TABLESPACE */
3122 * Nothing to do here; Phase 3 does the work
3125 case AT_SetRelOptions: /* SET (...) */
3126 ATExecSetRelOptions(rel, (List *) cmd->def, false, lockmode);
3128 case AT_ResetRelOptions: /* RESET (...) */
3129 ATExecSetRelOptions(rel, (List *) cmd->def, true, lockmode);
3132 case AT_EnableTrig: /* ENABLE TRIGGER name */
3133 ATExecEnableDisableTrigger(rel, cmd->name,
3134 TRIGGER_FIRES_ON_ORIGIN, false, lockmode);
3136 case AT_EnableAlwaysTrig: /* ENABLE ALWAYS TRIGGER name */
3137 ATExecEnableDisableTrigger(rel, cmd->name,
3138 TRIGGER_FIRES_ALWAYS, false, lockmode);
3140 case AT_EnableReplicaTrig: /* ENABLE REPLICA TRIGGER name */
3141 ATExecEnableDisableTrigger(rel, cmd->name,
3142 TRIGGER_FIRES_ON_REPLICA, false, lockmode);
3144 case AT_DisableTrig: /* DISABLE TRIGGER name */
3145 ATExecEnableDisableTrigger(rel, cmd->name,
3146 TRIGGER_DISABLED, false, lockmode);
3148 case AT_EnableTrigAll: /* ENABLE TRIGGER ALL */
3149 ATExecEnableDisableTrigger(rel, NULL,
3150 TRIGGER_FIRES_ON_ORIGIN, false, lockmode);
3152 case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
3153 ATExecEnableDisableTrigger(rel, NULL,
3154 TRIGGER_DISABLED, false, lockmode);
3156 case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
3157 ATExecEnableDisableTrigger(rel, NULL,
3158 TRIGGER_FIRES_ON_ORIGIN, true, lockmode);
3160 case AT_DisableTrigUser: /* DISABLE TRIGGER USER */
3161 ATExecEnableDisableTrigger(rel, NULL,
3162 TRIGGER_DISABLED, true, lockmode);
3165 case AT_EnableRule: /* ENABLE RULE name */
3166 ATExecEnableDisableRule(rel, cmd->name,
3167 RULE_FIRES_ON_ORIGIN, lockmode);
3169 case AT_EnableAlwaysRule: /* ENABLE ALWAYS RULE name */
3170 ATExecEnableDisableRule(rel, cmd->name,
3171 RULE_FIRES_ALWAYS, lockmode);
3173 case AT_EnableReplicaRule: /* ENABLE REPLICA RULE name */
3174 ATExecEnableDisableRule(rel, cmd->name,
3175 RULE_FIRES_ON_REPLICA, lockmode);
3177 case AT_DisableRule: /* DISABLE RULE name */
3178 ATExecEnableDisableRule(rel, cmd->name,
3179 RULE_DISABLED, lockmode);
3183 ATExecAddInherit(rel, (RangeVar *) cmd->def, lockmode);
3185 case AT_DropInherit:
3186 ATExecDropInherit(rel, (RangeVar *) cmd->def, lockmode);
3188 case AT_GenericOptions:
3189 ATExecGenericOptions(rel, (List *) cmd->def);
3192 elog(ERROR, "unrecognized alter table type: %d",
3193 (int) cmd->subtype);
3198 * Bump the command counter to ensure the next subcommand in the sequence
3199 * can see the changes so far
3201 CommandCounterIncrement();
3205 * ATRewriteTables: ALTER TABLE phase 3
3208 ATRewriteTables(List **wqueue, LOCKMODE lockmode)
3212 /* Go through each table that needs to be checked or rewritten */
3213 foreach(ltab, *wqueue)
3215 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
3217 /* Foreign tables have no storage. */
3218 if (tab->relkind == RELKIND_FOREIGN_TABLE)
3222 * We only need to rewrite the table if at least one column needs to
3223 * be recomputed, or we are adding/removing the OID column.
3225 if (tab->newvals != NIL || tab->new_changeoids)
3227 /* Build a temporary relation and copy data */
3232 OldHeap = heap_open(tab->relid, NoLock);
3235 * We don't support rewriting of system catalogs; there are too
3236 * many corner cases and too little benefit. In particular this
3237 * is certainly not going to work for mapped catalogs.
3239 if (IsSystemRelation(OldHeap))
3241 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3242 errmsg("cannot rewrite system relation \"%s\"",
3243 RelationGetRelationName(OldHeap))));
3246 * Don't allow rewrite on temp tables of other backends ... their
3247 * local buffer manager is not going to cope.
3249 if (RELATION_IS_OTHER_TEMP(OldHeap))
3251 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3252 errmsg("cannot rewrite temporary tables of other sessions")));
3255 * Select destination tablespace (same as original unless user
3256 * requested a change)
3258 if (tab->newTableSpace)
3259 NewTableSpace = tab->newTableSpace;
3261 NewTableSpace = OldHeap->rd_rel->reltablespace;
3263 heap_close(OldHeap, NoLock);
3265 /* Create transient table that will receive the modified data */
3266 OIDNewHeap = make_new_heap(tab->relid, NewTableSpace);
3269 * Copy the heap data into the new table with the desired
3270 * modifications, and test the current data within the table
3271 * against new constraints generated by ALTER TABLE commands.
3273 ATRewriteTable(tab, OIDNewHeap, lockmode);
3276 * Swap the physical files of the old and new heaps, then rebuild
3277 * indexes and discard the old heap. We can use RecentXmin for
3278 * the table's new relfrozenxid because we rewrote all the tuples
3279 * in ATRewriteTable, so no older Xid remains in the table. Also,
3280 * we never try to swap toast tables by content, since we have no
3281 * interest in letting this code work on system catalogs.
3283 finish_heap_swap(tab->relid, OIDNewHeap,
3284 false, false, true, RecentXmin);
3289 * Test the current data within the table against new constraints
3290 * generated by ALTER TABLE commands, but don't rebuild data.
3292 if (tab->constraints != NIL || tab->new_notnull)
3293 ATRewriteTable(tab, InvalidOid, lockmode);
3296 * If we had SET TABLESPACE but no reason to reconstruct tuples,
3297 * just do a block-by-block copy.
3299 if (tab->newTableSpace)
3300 ATExecSetTableSpace(tab->relid, tab->newTableSpace, lockmode);
3305 * Foreign key constraints are checked in a final pass, since (a) it's
3306 * generally best to examine each one separately, and (b) it's at least
3307 * theoretically possible that we have changed both relations of the
3308 * foreign key, and we'd better have finished both rewrites before we try
3309 * to read the tables.
3311 foreach(ltab, *wqueue)
3313 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
3314 Relation rel = NULL;
3317 foreach(lcon, tab->constraints)
3319 NewConstraint *con = lfirst(lcon);
3321 if (con->contype == CONSTR_FOREIGN)
3323 Constraint *fkconstraint = (Constraint *) con->qual;
3327 /* Long since locked, no need for another */
3328 rel = heap_open(tab->relid, NoLock);
3331 * We're adding a trigger to both tables, so the lock level
3332 * here should sensibly reflect that.
3334 refrel = heap_open(con->refrelid, ShareRowExclusiveLock);
3336 validateForeignKeyConstraint(fkconstraint->conname, rel, refrel,
3341 * No need to mark the constraint row as validated,
3342 * we did that when we inserted the row earlier.
3345 heap_close(refrel, NoLock);
3350 heap_close(rel, NoLock);
3355 * ATRewriteTable: scan or rewrite one table
3357 * OIDNewHeap is InvalidOid if we don't need to rewrite
3360 ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap, LOCKMODE lockmode)
3364 TupleDesc oldTupDesc;
3365 TupleDesc newTupDesc;
3366 bool needscan = false;
3367 List *notnull_attrs;
3372 BulkInsertState bistate;
3376 * Open the relation(s). We have surely already locked the existing
3379 oldrel = heap_open(tab->relid, NoLock);
3380 oldTupDesc = tab->oldDesc;
3381 newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
3383 if (OidIsValid(OIDNewHeap))
3384 newrel = heap_open(OIDNewHeap, lockmode);
3389 * Prepare a BulkInsertState and options for heap_insert. Because we're
3390 * building a new heap, we can skip WAL-logging and fsync it to disk at
3391 * the end instead (unless WAL-logging is required for archiving or
3392 * streaming replication). The FSM is empty too, so don't bother using it.
3396 mycid = GetCurrentCommandId(true);
3397 bistate = GetBulkInsertState();
3399 hi_options = HEAP_INSERT_SKIP_FSM;
3400 if (!XLogIsNeeded())
3401 hi_options |= HEAP_INSERT_SKIP_WAL;
3405 /* keep compiler quiet about using these uninitialized */
3412 * If we change column data types or add/remove OIDs, the operation has to
3413 * be propagated to tables that use this table's rowtype as a column type.
3414 * newrel will also be non-NULL in the case where we're adding a column
3415 * with a default. We choose to forbid that case as well, since composite
3416 * types might eventually support defaults.
3418 * (Eventually we'll probably need to check for composite type
3419 * dependencies even when we're just scanning the table without a rewrite,
3420 * but at the moment a composite type does not enforce any constraints,
3421 * so it's not necessary/appropriate to enforce them just during ALTER.)
3424 find_composite_type_dependencies(oldrel->rd_rel->reltype,
3425 oldrel->rd_rel->relkind,
3426 RelationGetRelationName(oldrel));
3429 * Generate the constraint and default execution states
3432 estate = CreateExecutorState();
3434 /* Build the needed expression execution states */
3435 foreach(l, tab->constraints)
3437 NewConstraint *con = lfirst(l);
3439 switch (con->contype)
3443 con->qualstate = (List *)
3444 ExecPrepareExpr((Expr *) con->qual, estate);
3446 case CONSTR_FOREIGN:
3447 /* Nothing to do here */
3450 elog(ERROR, "unrecognized constraint type: %d",
3451 (int) con->contype);
3455 foreach(l, tab->newvals)
3457 NewColumnValue *ex = lfirst(l);
3459 ex->exprstate = ExecPrepareExpr((Expr *) ex->expr, estate);
3462 notnull_attrs = NIL;
3463 if (newrel || tab->new_notnull)
3466 * If we are rebuilding the tuples OR if we added any new NOT NULL
3467 * constraints, check all not-null constraints. This is a bit of
3468 * overkill but it minimizes risk of bugs, and heap_attisnull is a
3469 * pretty cheap test anyway.
3471 for (i = 0; i < newTupDesc->natts; i++)
3473 if (newTupDesc->attrs[i]->attnotnull &&
3474 !newTupDesc->attrs[i]->attisdropped)
3475 notnull_attrs = lappend_int(notnull_attrs, i);
3481 if (newrel || needscan)
3483 ExprContext *econtext;
3486 TupleTableSlot *oldslot;
3487 TupleTableSlot *newslot;
3490 MemoryContext oldCxt;
3491 List *dropped_attrs = NIL;
3494 econtext = GetPerTupleExprContext(estate);
3497 * Make tuple slots for old and new tuples. Note that even when the
3498 * tuples are the same, the tupDescs might not be (consider ADD COLUMN
3499 * without a default).
3501 oldslot = MakeSingleTupleTableSlot(oldTupDesc);
3502 newslot = MakeSingleTupleTableSlot(newTupDesc);
3504 /* Preallocate values/isnull arrays */
3505 i = Max(newTupDesc->natts, oldTupDesc->natts);
3506 values = (Datum *) palloc(i * sizeof(Datum));
3507 isnull = (bool *) palloc(i * sizeof(bool));
3508 memset(values, 0, i * sizeof(Datum));
3509 memset(isnull, true, i * sizeof(bool));
3512 * Any attributes that are dropped according to the new tuple
3513 * descriptor can be set to NULL. We precompute the list of dropped
3514 * attributes to avoid needing to do so in the per-tuple loop.
3516 for (i = 0; i < newTupDesc->natts; i++)
3518 if (newTupDesc->attrs[i]->attisdropped)
3519 dropped_attrs = lappend_int(dropped_attrs, i);
3523 * Scan through the rows, generating a new row if needed and then
3524 * checking all the constraints.
3526 scan = heap_beginscan(oldrel, SnapshotNow, 0, NULL);
3529 * Switch to per-tuple memory context and reset it for each tuple
3530 * produced, so we don't leak memory.
3532 oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
3534 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
3538 Oid tupOid = InvalidOid;
3540 /* Extract data from old tuple */
3541 heap_deform_tuple(tuple, oldTupDesc, values, isnull);
3542 if (oldTupDesc->tdhasoid)
3543 tupOid = HeapTupleGetOid(tuple);
3545 /* Set dropped attributes to null in new tuple */
3546 foreach(lc, dropped_attrs)
3547 isnull[lfirst_int(lc)] = true;
3550 * Process supplied expressions to replace selected columns.
3551 * Expression inputs come from the old tuple.
3553 ExecStoreTuple(tuple, oldslot, InvalidBuffer, false);
3554 econtext->ecxt_scantuple = oldslot;
3556 foreach(l, tab->newvals)
3558 NewColumnValue *ex = lfirst(l);
3560 values[ex->attnum - 1] = ExecEvalExpr(ex->exprstate,
3562 &isnull[ex->attnum - 1],
3567 * Form the new tuple. Note that we don't explicitly pfree it,
3568 * since the per-tuple memory context will be reset shortly.
3570 tuple = heap_form_tuple(newTupDesc, values, isnull);
3572 /* Preserve OID, if any */
3573 if (newTupDesc->tdhasoid)
3574 HeapTupleSetOid(tuple, tupOid);
3577 /* Now check any constraints on the possibly-changed tuple */
3578 ExecStoreTuple(tuple, newslot, InvalidBuffer, false);
3579 econtext->ecxt_scantuple = newslot;
3581 foreach(l, notnull_attrs)
3583 int attn = lfirst_int(l);
3585 if (heap_attisnull(tuple, attn + 1))
3587 (errcode(ERRCODE_NOT_NULL_VIOLATION),
3588 errmsg("column \"%s\" contains null values",
3589 NameStr(newTupDesc->attrs[attn]->attname))));
3592 foreach(l, tab->constraints)
3594 NewConstraint *con = lfirst(l);
3596 switch (con->contype)
3599 if (!ExecQual(con->qualstate, econtext, true))
3601 (errcode(ERRCODE_CHECK_VIOLATION),
3602 errmsg("check constraint \"%s\" is violated by some row",
3605 case CONSTR_FOREIGN:
3606 /* Nothing to do here */
3609 elog(ERROR, "unrecognized constraint type: %d",
3610 (int) con->contype);
3614 /* Write the tuple out to the new relation */
3616 heap_insert(newrel, tuple, mycid, hi_options, bistate);
3618 ResetExprContext(econtext);
3620 CHECK_FOR_INTERRUPTS();
3623 MemoryContextSwitchTo(oldCxt);
3626 ExecDropSingleTupleTableSlot(oldslot);
3627 ExecDropSingleTupleTableSlot(newslot);
3630 FreeExecutorState(estate);
3632 heap_close(oldrel, NoLock);
3635 FreeBulkInsertState(bistate);
3637 /* If we skipped writing WAL, then we need to sync the heap. */
3638 if (hi_options & HEAP_INSERT_SKIP_WAL)
3641 heap_close(newrel, NoLock);
3646 * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
3648 static AlteredTableInfo *
3649 ATGetQueueEntry(List **wqueue, Relation rel)
3651 Oid relid = RelationGetRelid(rel);
3652 AlteredTableInfo *tab;
3655 foreach(ltab, *wqueue)
3657 tab = (AlteredTableInfo *) lfirst(ltab);
3658 if (tab->relid == relid)
3663 * Not there, so add it. Note that we make a copy of the relation's
3664 * existing descriptor before anything interesting can happen to it.
3666 tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
3668 tab->relkind = rel->rd_rel->relkind;
3669 tab->oldDesc = CreateTupleDescCopy(RelationGetDescr(rel));
3671 *wqueue = lappend(*wqueue, tab);
3677 * ATSimplePermissions
3679 * - Ensure that it is a relation (or possibly a view)
3680 * - Ensure this user is the owner
3681 * - Ensure that it is not a system table
3684 ATSimplePermissions(Relation rel, int allowed_targets)
3688 switch (rel->rd_rel->relkind)
3690 case RELKIND_RELATION:
3691 actual_target = ATT_TABLE;
3694 actual_target = ATT_VIEW;
3697 actual_target = ATT_INDEX;
3699 case RELKIND_COMPOSITE_TYPE:
3700 actual_target = ATT_COMPOSITE_TYPE;
3702 case RELKIND_FOREIGN_TABLE:
3703 actual_target = ATT_FOREIGN_TABLE;
3710 /* Wrong target type? */
3711 if ((actual_target & allowed_targets) == 0)
3712 ATWrongRelkindError(rel, allowed_targets);
3714 /* Permissions checks */
3715 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3716 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3717 RelationGetRelationName(rel));
3719 if (!allowSystemTableMods && IsSystemRelation(rel))
3721 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3722 errmsg("permission denied: \"%s\" is a system catalog",
3723 RelationGetRelationName(rel))));
3727 * ATWrongRelkindError
3729 * Throw an error when a relation has been determined to be of the wrong
3733 ATWrongRelkindError(Relation rel, int allowed_targets)
3737 switch (allowed_targets)
3740 msg = _("\"%s\" is not a table");
3742 case ATT_TABLE|ATT_INDEX:
3743 msg = _("\"%s\" is not a table or index");
3745 case ATT_TABLE|ATT_VIEW:
3746 msg = _("\"%s\" is not a table or view");
3748 case ATT_TABLE|ATT_FOREIGN_TABLE:
3749 msg = _("\"%s\" is not a table or foreign table");
3751 case ATT_TABLE|ATT_COMPOSITE_TYPE|ATT_FOREIGN_TABLE:
3752 msg = _("\"%s\" is not a table, composite type, or foreign table");
3755 msg = _("\"%s\" is not a view");
3757 case ATT_FOREIGN_TABLE:
3758 msg = _("\"%s\" is not a foreign table");
3761 /* shouldn't get here, add all necessary cases above */
3762 msg = _("\"%s\" is of the wrong type");
3767 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3768 errmsg(msg, RelationGetRelationName(rel))));
3774 * Simple table recursion sufficient for most ALTER TABLE operations.
3775 * All direct and indirect children are processed in an unspecified order.
3776 * Note that if a child inherits from the original table via multiple
3777 * inheritance paths, it will be visited just once.
3780 ATSimpleRecursion(List **wqueue, Relation rel,
3781 AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode)
3784 * Propagate to children if desired. Non-table relations never have
3785 * children, so no need to search in that case.
3787 if (recurse && rel->rd_rel->relkind == RELKIND_RELATION)
3789 Oid relid = RelationGetRelid(rel);
3793 children = find_all_inheritors(relid, lockmode, NULL);
3796 * find_all_inheritors does the recursive search of the inheritance
3797 * hierarchy, so all we have to do is process all of the relids in the
3798 * list that it returns.
3800 foreach(child, children)
3802 Oid childrelid = lfirst_oid(child);
3805 if (childrelid == relid)
3807 /* find_all_inheritors already got lock */
3808 childrel = relation_open(childrelid, NoLock);
3809 CheckTableNotInUse(childrel, "ALTER TABLE");
3810 ATPrepCmd(wqueue, childrel, cmd, false, true, lockmode);
3811 relation_close(childrel, NoLock);
3817 * ATOneLevelRecursion
3819 * Here, we visit only direct inheritance children. It is expected that
3820 * the command's prep routine will recurse again to find indirect children.
3821 * When using this technique, a multiply-inheriting child will be visited
3825 ATOneLevelRecursion(List **wqueue, Relation rel,
3826 AlterTableCmd *cmd, LOCKMODE lockmode)
3828 Oid relid = RelationGetRelid(rel);
3832 children = find_inheritance_children(relid, lockmode);
3834 foreach(child, children)
3836 Oid childrelid = lfirst_oid(child);
3839 /* find_inheritance_children already got lock */
3840 childrel = relation_open(childrelid, NoLock);
3841 CheckTableNotInUse(childrel, "ALTER TABLE");
3842 ATPrepCmd(wqueue, childrel, cmd, true, true, lockmode);
3843 relation_close(childrel, NoLock);
3848 * ATTypedTableRecursion
3850 * Propagate ALTER TYPE operations to the typed tables of that type.
3851 * Also check the RESTRICT/CASCADE behavior.
3854 ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
3860 Assert(rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
3862 children = find_typed_table_dependencies(rel->rd_rel->reltype,
3863 RelationGetRelationName(rel),
3866 foreach(child, children)
3868 Oid childrelid = lfirst_oid(child);
3871 childrel = relation_open(childrelid, lockmode);
3872 CheckTableNotInUse(childrel, "ALTER TABLE");
3873 ATPrepCmd(wqueue, childrel, cmd, false, true, lockmode);
3874 relation_close(childrel, NoLock);
3880 * find_composite_type_dependencies
3882 * Check to see if a composite type is being used as a column in some
3883 * other table (possibly nested several levels deep in composite types!).
3884 * Eventually, we'd like to propagate the check or rewrite operation
3885 * into other such tables, but for now, just error out if we find any.
3887 * Caller should provide either a table name or a type name (not both) to
3888 * report in the error message, if any.
3890 * We assume that functions and views depending on the type are not reasons
3891 * to reject the ALTER. (How safe is this really?)
3894 find_composite_type_dependencies(Oid typeOid, char origRelkind,
3895 const char *origRelname)
3899 SysScanDesc depScan;
3904 * We scan pg_depend to find those things that depend on the rowtype. (We
3905 * assume we can ignore refobjsubid for a rowtype.)
3907 depRel = heap_open(DependRelationId, AccessShareLock);
3909 ScanKeyInit(&key[0],
3910 Anum_pg_depend_refclassid,
3911 BTEqualStrategyNumber, F_OIDEQ,
3912 ObjectIdGetDatum(TypeRelationId));
3913 ScanKeyInit(&key[1],
3914 Anum_pg_depend_refobjid,
3915 BTEqualStrategyNumber, F_OIDEQ,
3916 ObjectIdGetDatum(typeOid));
3918 depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
3919 SnapshotNow, 2, key);
3921 while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
3923 Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
3925 Form_pg_attribute att;
3927 /* Ignore dependees that aren't user columns of relations */
3928 /* (we assume system columns are never of rowtypes) */
3929 if (pg_depend->classid != RelationRelationId ||
3930 pg_depend->objsubid <= 0)
3933 rel = relation_open(pg_depend->objid, AccessShareLock);
3934 att = rel->rd_att->attrs[pg_depend->objsubid - 1];
3936 if (rel->rd_rel->relkind == RELKIND_RELATION)
3939 if (origRelkind == RELKIND_COMPOSITE_TYPE)
3940 msg = gettext_noop("cannot alter type \"%s\" because column \"%s\".\"%s\" uses it");
3941 else if (origRelkind == RELKIND_FOREIGN_TABLE)
3942 msg = gettext_noop("cannot alter foreign table \"%s\" because column \"%s\".\"%s\" uses its rowtype");
3944 msg = gettext_noop("cannot alter table \"%s\" because column \"%s\".\"%s\" uses its rowtype");
3946 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3949 RelationGetRelationName(rel),
3950 NameStr(att->attname))));
3952 else if (OidIsValid(rel->rd_rel->reltype))
3955 * A view or composite type itself isn't a problem, but we must
3956 * recursively check for indirect dependencies via its rowtype.
3958 find_composite_type_dependencies(rel->rd_rel->reltype,
3959 origRelkind, origRelname);
3962 relation_close(rel, AccessShareLock);
3965 systable_endscan(depScan);
3967 relation_close(depRel, AccessShareLock);
3970 * If there's an array type for the rowtype, must check for uses of it,
3973 arrayOid = get_array_type(typeOid);
3974 if (OidIsValid(arrayOid))
3975 find_composite_type_dependencies(arrayOid, origRelkind, origRelname);
3980 * find_typed_table_dependencies
3982 * Check to see if a composite type is being used as the type of a
3983 * typed table. Abort if any are found and behavior is RESTRICT.
3984 * Else return the list of tables.
3987 find_typed_table_dependencies(Oid typeOid, const char *typeName, DropBehavior behavior)
3995 classRel = heap_open(RelationRelationId, AccessShareLock);
3997 ScanKeyInit(&key[0],
3998 Anum_pg_class_reloftype,
3999 BTEqualStrategyNumber, F_OIDEQ,
4000 ObjectIdGetDatum(typeOid));
4002 scan = heap_beginscan(classRel, SnapshotNow, 1, key);
4004 if (HeapTupleIsValid(tuple = heap_getnext(scan, ForwardScanDirection)))
4006 if (behavior == DROP_RESTRICT)
4008 (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
4009 errmsg("cannot alter type \"%s\" because it is the type of a typed table",
4011 errhint("Use ALTER ... CASCADE to alter the typed tables too.")));
4013 result = lappend_oid(result, HeapTupleGetOid(tuple));
4017 heap_close(classRel, AccessShareLock);
4024 * ALTER TABLE ADD COLUMN
4026 * Adds an additional attribute to a relation making the assumption that
4027 * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
4028 * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
4032 ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
4033 AlterTableCmd *cmd, LOCKMODE lockmode)
4035 if (rel->rd_rel->reloftype && !recursing)
4037 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4038 errmsg("cannot add column to typed table")));
4041 * Recurse to add the column to child classes, if requested.
4043 * We must recurse one level at a time, so that multiply-inheriting
4044 * children are visited the right number of times and end up with the
4045 * right attinhcount.
4049 AlterTableCmd *childCmd = copyObject(cmd);
4050 ColumnDef *colDefChild = (ColumnDef *) childCmd->def;
4052 /* Child should see column as singly inherited */
4053 colDefChild->inhcount = 1;
4054 colDefChild->is_local = false;
4056 ATOneLevelRecursion(wqueue, rel, childCmd, lockmode);
4061 * If we are told not to recurse, there had better not be any child
4062 * tables; else the addition would put them out of step.
4064 if (find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL)
4066 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4067 errmsg("column must be added to child tables too")));
4070 if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
4071 ATTypedTableRecursion(wqueue, rel, cmd, lockmode);
4075 ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
4076 ColumnDef *colDef, bool isOid, LOCKMODE lockmode)
4078 Oid myrelid = RelationGetRelid(rel);
4082 FormData_pg_attribute attribute;
4085 HeapTuple typeTuple;
4092 attrdesc = heap_open(AttributeRelationId, RowExclusiveLock);
4095 * Are we adding the column to a recursion child? If so, check whether to
4096 * merge with an existing definition for the column.
4098 if (colDef->inhcount > 0)
4102 /* Does child already have a column by this name? */
4103 tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
4104 if (HeapTupleIsValid(tuple))
4106 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
4111 /* Child column must match by type */
4112 typenameTypeIdModColl(NULL, colDef->typeName, &ctypeId, &ctypmod, &ccollid);
4113 if (ctypeId != childatt->atttypid ||
4114 ctypmod != childatt->atttypmod)
4116 (errcode(ERRCODE_DATATYPE_MISMATCH),
4117 errmsg("child table \"%s\" has different type for column \"%s\"",
4118 RelationGetRelationName(rel), colDef->colname)));
4119 if (ccollid != childatt->attcollation)
4121 (errcode(ERRCODE_COLLATION_MISMATCH),
4122 errmsg("child table \"%s\" has different collation for column \"%s\"",
4123 RelationGetRelationName(rel), colDef->colname),
4124 errdetail("\"%s\" versus \"%s\"",
4125 get_collation_name(ccollid),
4126 get_collation_name(childatt->attcollation))));
4128 /* If it's OID, child column must actually be OID */
4129 if (isOid && childatt->attnum != ObjectIdAttributeNumber)
4131 (errcode(ERRCODE_DATATYPE_MISMATCH),
4132 errmsg("child table \"%s\" has a conflicting \"%s\" column",
4133 RelationGetRelationName(rel), colDef->colname)));
4135 /* Bump the existing child att's inhcount */
4136 childatt->attinhcount++;
4137 simple_heap_update(attrdesc, &tuple->t_self, tuple);
4138 CatalogUpdateIndexes(attrdesc, tuple);
4140 heap_freetuple(tuple);
4142 /* Inform the user about the merge */
4144 (errmsg("merging definition of column \"%s\" for child \"%s\"",
4145 colDef->colname, RelationGetRelationName(rel))));
4147 heap_close(attrdesc, RowExclusiveLock);
4152 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
4154 reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
4155 if (!HeapTupleIsValid(reltup))
4156 elog(ERROR, "cache lookup failed for relation %u", myrelid);
4157 relkind = ((Form_pg_class) GETSTRUCT(reltup))->relkind;
4160 * this test is deliberately not attisdropped-aware, since if one tries to
4161 * add a column matching a dropped column name, it's gonna fail anyway.
4163 if (SearchSysCacheExists2(ATTNAME,
4164 ObjectIdGetDatum(myrelid),
4165 PointerGetDatum(colDef->colname)))
4167 (errcode(ERRCODE_DUPLICATE_COLUMN),
4168 errmsg("column \"%s\" of relation \"%s\" already exists",
4169 colDef->colname, RelationGetRelationName(rel))));
4171 /* Determine the new attribute's number */
4173 newattnum = ObjectIdAttributeNumber;
4176 newattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts + 1;
4177 if (newattnum > MaxHeapAttributeNumber)
4179 (errcode(ERRCODE_TOO_MANY_COLUMNS),
4180 errmsg("tables can have at most %d columns",
4181 MaxHeapAttributeNumber)));
4184 typeTuple = typenameType(NULL, colDef->typeName, &typmod, &collOid);
4185 tform = (Form_pg_type) GETSTRUCT(typeTuple);
4186 typeOid = HeapTupleGetOid(typeTuple);
4188 /* make sure datatype is legal for a column */
4189 CheckAttributeType(colDef->colname, typeOid, false);
4191 /* construct new attribute's pg_attribute entry */
4192 attribute.attrelid = myrelid;
4193 namestrcpy(&(attribute.attname), colDef->colname);
4194 attribute.atttypid = typeOid;
4195 attribute.attstattarget = (newattnum > 0) ? -1 : 0;
4196 attribute.attlen = tform->typlen;
4197 attribute.attcacheoff = -1;
4198 attribute.atttypmod = typmod;
4199 attribute.attnum = newattnum;
4200 attribute.attbyval = tform->typbyval;
4201 attribute.attndims = list_length(colDef->typeName->arrayBounds);
4202 attribute.attstorage = tform->typstorage;
4203 attribute.attalign = tform->typalign;
4204 attribute.attnotnull = colDef->is_not_null;
4205 attribute.atthasdef = false;
4206 attribute.attisdropped = false;
4207 attribute.attislocal = colDef->is_local;
4208 attribute.attinhcount = colDef->inhcount;
4209 attribute.attcollation = collOid;
4210 /* attribute.attacl is handled by InsertPgAttributeTuple */
4212 ReleaseSysCache(typeTuple);
4214 InsertPgAttributeTuple(attrdesc, &attribute, NULL);
4216 heap_close(attrdesc, RowExclusiveLock);
4219 * Update pg_class tuple as appropriate
4222 ((Form_pg_class) GETSTRUCT(reltup))->relhasoids = true;
4224 ((Form_pg_class) GETSTRUCT(reltup))->relnatts = newattnum;
4226 simple_heap_update(pgclass, &reltup->t_self, reltup);
4228 /* keep catalog indexes current */
4229 CatalogUpdateIndexes(pgclass, reltup);
4231 heap_freetuple(reltup);
4233 /* Post creation hook for new attribute */
4234 InvokeObjectAccessHook(OAT_POST_CREATE,
4235 RelationRelationId, myrelid, newattnum);
4237 heap_close(pgclass, RowExclusiveLock);
4239 /* Make the attribute's catalog entry visible */
4240 CommandCounterIncrement();
4243 * Store the DEFAULT, if any, in the catalogs
4245 if (colDef->raw_default)
4247 RawColumnDefault *rawEnt;
4249 if (relkind == RELKIND_FOREIGN_TABLE)
4251 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4252 errmsg("default values on foreign tables are not supported")));
4254 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
4255 rawEnt->attnum = attribute.attnum;
4256 rawEnt->raw_default = copyObject(colDef->raw_default);
4259 * This function is intended for CREATE TABLE, so it processes a
4260 * _list_ of defaults, but we just do one.
4262 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL, false, true);
4264 /* Make the additional catalog changes visible */
4265 CommandCounterIncrement();
4269 * Tell Phase 3 to fill in the default expression, if there is one.
4271 * If there is no default, Phase 3 doesn't have to do anything, because
4272 * that effectively means that the default is NULL. The heap tuple access
4273 * routines always check for attnum > # of attributes in tuple, and return
4274 * NULL if so, so without any modification of the tuple data we will get
4275 * the effect of NULL values in the new column.
4277 * An exception occurs when the new column is of a domain type: the domain
4278 * might have a NOT NULL constraint, or a check constraint that indirectly
4279 * rejects nulls. If there are any domain constraints then we construct
4280 * an explicit NULL default value that will be passed through
4281 * CoerceToDomain processing. (This is a tad inefficient, since it causes
4282 * rewriting the table which we really don't have to do, but the present
4283 * design of domain processing doesn't offer any simple way of checking
4284 * the constraints more directly.)
4286 * Note: we use build_column_default, and not just the cooked default
4287 * returned by AddRelationNewConstraints, so that the right thing happens
4288 * when a datatype's default applies.
4290 * We skip this step completely for views and foreign tables. For a view,
4291 * we can only get here from CREATE OR REPLACE VIEW, which historically
4292 * doesn't set up defaults, not even for domain-typed columns. And in any
4293 * case we mustn't invoke Phase 3 on a view or foreign table, since they
4296 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE
4297 && relkind != RELKIND_FOREIGN_TABLE && attribute.attnum > 0)
4299 defval = (Expr *) build_column_default(rel, attribute.attnum);
4301 if (!defval && GetDomainConstraints(typeOid) != NIL)
4306 baseTypeMod = typmod;
4307 baseTypeId = getBaseTypeAndTypmod(typeOid, &baseTypeMod);
4308 defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod);
4309 defval = (Expr *) coerce_to_target_type(NULL,
4314 COERCION_ASSIGNMENT,
4315 COERCE_IMPLICIT_CAST,
4317 if (defval == NULL) /* should not happen */
4318 elog(ERROR, "failed to coerce base type to domain");
4323 NewColumnValue *newval;
4325 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
4326 newval->attnum = attribute.attnum;
4327 newval->expr = defval;
4329 tab->newvals = lappend(tab->newvals, newval);
4333 * If the new column is NOT NULL, tell Phase 3 it needs to test that.
4334 * (Note we don't do this for an OID column. OID will be marked not
4335 * null, but since it's filled specially, there's no need to test
4338 tab->new_notnull |= colDef->is_not_null;
4342 * If we are adding an OID column, we have to tell Phase 3 to rewrite the
4343 * table to fix that.
4346 tab->new_changeoids = true;
4349 * Add needed dependency entries for the new column.
4351 add_column_datatype_dependency(myrelid, newattnum, attribute.atttypid);
4355 * Install a column's dependency on its datatype.
4358 add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
4360 ObjectAddress myself,
4363 myself.classId = RelationRelationId;
4364 myself.objectId = relid;
4365 myself.objectSubId = attnum;
4366 referenced.classId = TypeRelationId;
4367 referenced.objectId = typid;
4368 referenced.objectSubId = 0;
4369 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
4373 * ALTER TABLE SET WITH OIDS
4375 * Basically this is an ADD COLUMN for the special OID column. We have
4376 * to cons up a ColumnDef node because the ADD COLUMN code needs one.
4379 ATPrepAddOids(List **wqueue, Relation rel, bool recurse, AlterTableCmd *cmd, LOCKMODE lockmode)
4381 /* If we're recursing to a child table, the ColumnDef is already set up */
4382 if (cmd->def == NULL)
4384 ColumnDef *cdef = makeNode(ColumnDef);
4386 cdef->colname = pstrdup("oid");
4387 cdef->typeName = makeTypeNameFromOid(OIDOID, -1, InvalidOid);
4389 cdef->is_local = true;
4390 cdef->is_not_null = true;
4392 cmd->def = (Node *) cdef;
4394 ATPrepAddColumn(wqueue, rel, recurse, false, cmd, lockmode);
4398 * ALTER TABLE ALTER COLUMN DROP NOT NULL
4401 ATExecDropNotNull(Relation rel, const char *colName, LOCKMODE lockmode)
4407 ListCell *indexoidscan;
4410 * lookup the attribute
4412 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
4414 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4416 if (!HeapTupleIsValid(tuple))
4418 (errcode(ERRCODE_UNDEFINED_COLUMN),
4419 errmsg("column \"%s\" of relation \"%s\" does not exist",
4420 colName, RelationGetRelationName(rel))));
4422 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
4424 /* Prevent them from altering a system attribute */
4427 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4428 errmsg("cannot alter system column \"%s\"",
4432 * Check that the attribute is not in a primary key
4435 /* Loop over all indexes on the relation */
4436 indexoidlist = RelationGetIndexList(rel);
4438 foreach(indexoidscan, indexoidlist)
4440 Oid indexoid = lfirst_oid(indexoidscan);
4441 HeapTuple indexTuple;
4442 Form_pg_index indexStruct;
4445 indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
4446 if (!HeapTupleIsValid(indexTuple))
4447 elog(ERROR, "cache lookup failed for index %u", indexoid);
4448 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4450 /* If the index is not a primary key, skip the check */
4451 if (indexStruct->indisprimary)
4454 * Loop over each attribute in the primary key and see if it
4455 * matches the to-be-altered attribute
4457 for (i = 0; i < indexStruct->indnatts; i++)
4459 if (indexStruct->indkey.values[i] == attnum)
4461 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4462 errmsg("column \"%s\" is in a primary key",
4467 ReleaseSysCache(indexTuple);
4470 list_free(indexoidlist);
4473 * Okay, actually perform the catalog change ... if needed
4475 if (((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
4477 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = FALSE;
4479 simple_heap_update(attr_rel, &tuple->t_self, tuple);
4481 /* keep the system catalog indexes current */
4482 CatalogUpdateIndexes(attr_rel, tuple);
4485 heap_close(attr_rel, RowExclusiveLock);
4489 * ALTER TABLE ALTER COLUMN SET NOT NULL
4492 ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
4493 const char *colName, LOCKMODE lockmode)
4500 * lookup the attribute
4502 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
4504 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4506 if (!HeapTupleIsValid(tuple))
4508 (errcode(ERRCODE_UNDEFINED_COLUMN),
4509 errmsg("column \"%s\" of relation \"%s\" does not exist",
4510 colName, RelationGetRelationName(rel))));
4512 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
4514 /* Prevent them from altering a system attribute */
4517 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4518 errmsg("cannot alter system column \"%s\"",
4522 * Okay, actually perform the catalog change ... if needed
4524 if (!((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
4526 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = TRUE;
4528 simple_heap_update(attr_rel, &tuple->t_self, tuple);
4530 /* keep the system catalog indexes current */
4531 CatalogUpdateIndexes(attr_rel, tuple);
4533 /* Tell Phase 3 it needs to test the constraint */
4534 tab->new_notnull = true;
4537 heap_close(attr_rel, RowExclusiveLock);
4541 * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
4544 ATExecColumnDefault(Relation rel, const char *colName,
4545 Node *newDefault, LOCKMODE lockmode)
4550 * get the number of the attribute
4552 attnum = get_attnum(RelationGetRelid(rel), colName);
4553 if (attnum == InvalidAttrNumber)
4555 (errcode(ERRCODE_UNDEFINED_COLUMN),
4556 errmsg("column \"%s\" of relation \"%s\" does not exist",
4557 colName, RelationGetRelationName(rel))));
4559 /* Prevent them from altering a system attribute */
4562 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4563 errmsg("cannot alter system column \"%s\"",
4567 * Remove any old default for the column. We use RESTRICT here for
4568 * safety, but at present we do not expect anything to depend on the
4571 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false);
4576 RawColumnDefault *rawEnt;
4578 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
4579 rawEnt->attnum = attnum;
4580 rawEnt->raw_default = newDefault;
4583 * This function is intended for CREATE TABLE, so it processes a
4584 * _list_ of defaults, but we just do one.
4586 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL, false, true);
4591 * ALTER TABLE ALTER COLUMN SET STATISTICS
4594 ATPrepSetStatistics(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
4597 * We do our own permission checking because (a) we want to allow SET
4598 * STATISTICS on indexes (for expressional index columns), and (b) we want
4599 * to allow SET STATISTICS on system catalogs without requiring
4600 * allowSystemTableMods to be turned on.
4602 if (rel->rd_rel->relkind != RELKIND_RELATION &&
4603 rel->rd_rel->relkind != RELKIND_INDEX)
4605 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4606 errmsg("\"%s\" is not a table or index",
4607 RelationGetRelationName(rel))));
4609 /* Permissions checks */
4610 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
4611 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
4612 RelationGetRelationName(rel));
4616 ATExecSetStatistics(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
4619 Relation attrelation;
4621 Form_pg_attribute attrtuple;
4623 Assert(IsA(newValue, Integer));
4624 newtarget = intVal(newValue);
4627 * Limit target to a sane range
4632 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4633 errmsg("statistics target %d is too low",
4636 else if (newtarget > 10000)
4640 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4641 errmsg("lowering statistics target to %d",
4645 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
4647 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4649 if (!HeapTupleIsValid(tuple))
4651 (errcode(ERRCODE_UNDEFINED_COLUMN),
4652 errmsg("column \"%s\" of relation \"%s\" does not exist",
4653 colName, RelationGetRelationName(rel))));
4654 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
4656 if (attrtuple->attnum <= 0)
4658 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4659 errmsg("cannot alter system column \"%s\"",
4662 attrtuple->attstattarget = newtarget;
4664 simple_heap_update(attrelation, &tuple->t_self, tuple);
4666 /* keep system catalog indexes current */
4667 CatalogUpdateIndexes(attrelation, tuple);
4669 heap_freetuple(tuple);
4671 heap_close(attrelation, RowExclusiveLock);
4675 ATExecSetOptions(Relation rel, const char *colName, Node *options,
4676 bool isReset, LOCKMODE lockmode)
4678 Relation attrelation;
4681 Form_pg_attribute attrtuple;
4685 Datum repl_val[Natts_pg_attribute];
4686 bool repl_null[Natts_pg_attribute];
4687 bool repl_repl[Natts_pg_attribute];
4689 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
4691 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
4693 if (!HeapTupleIsValid(tuple))
4695 (errcode(ERRCODE_UNDEFINED_COLUMN),
4696 errmsg("column \"%s\" of relation \"%s\" does not exist",
4697 colName, RelationGetRelationName(rel))));
4698 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
4700 if (attrtuple->attnum <= 0)
4702 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4703 errmsg("cannot alter system column \"%s\"",
4706 /* Generate new proposed attoptions (text array) */
4707 Assert(IsA(options, List));
4708 datum = SysCacheGetAttr(ATTNAME, tuple, Anum_pg_attribute_attoptions,
4710 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
4711 (List *) options, NULL, NULL, false,
4713 /* Validate new options */
4714 (void) attribute_reloptions(newOptions, true);
4716 /* Build new tuple. */
4717 memset(repl_null, false, sizeof(repl_null));
4718 memset(repl_repl, false, sizeof(repl_repl));
4719 if (newOptions != (Datum) 0)
4720 repl_val[Anum_pg_attribute_attoptions - 1] = newOptions;
4722 repl_null[Anum_pg_attribute_attoptions - 1] = true;
4723 repl_repl[Anum_pg_attribute_attoptions - 1] = true;
4724 newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrelation),
4725 repl_val, repl_null, repl_repl);
4726 ReleaseSysCache(tuple);
4728 /* Update system catalog. */
4729 simple_heap_update(attrelation, &newtuple->t_self, newtuple);
4730 CatalogUpdateIndexes(attrelation, newtuple);
4731 heap_freetuple(newtuple);
4733 heap_close(attrelation, RowExclusiveLock);
4737 * ALTER TABLE ALTER COLUMN SET STORAGE
4740 ATExecSetStorage(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
4744 Relation attrelation;
4746 Form_pg_attribute attrtuple;
4748 Assert(IsA(newValue, String));
4749 storagemode = strVal(newValue);
4751 if (pg_strcasecmp(storagemode, "plain") == 0)
4753 else if (pg_strcasecmp(storagemode, "external") == 0)
4755 else if (pg_strcasecmp(storagemode, "extended") == 0)
4757 else if (pg_strcasecmp(storagemode, "main") == 0)
4762 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4763 errmsg("invalid storage type \"%s\"",
4765 newstorage = 0; /* keep compiler quiet */
4768 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
4770 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4772 if (!HeapTupleIsValid(tuple))
4774 (errcode(ERRCODE_UNDEFINED_COLUMN),
4775 errmsg("column \"%s\" of relation \"%s\" does not exist",
4776 colName, RelationGetRelationName(rel))));
4777 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
4779 if (attrtuple->attnum <= 0)
4781 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4782 errmsg("cannot alter system column \"%s\"",
4786 * safety check: do not allow toasted storage modes unless column datatype
4789 if (newstorage == 'p' || TypeIsToastable(attrtuple->atttypid))
4790 attrtuple->attstorage = newstorage;
4793 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4794 errmsg("column data type %s can only have storage PLAIN",
4795 format_type_be(attrtuple->atttypid))));
4797 simple_heap_update(attrelation, &tuple->t_self, tuple);
4799 /* keep system catalog indexes current */
4800 CatalogUpdateIndexes(attrelation, tuple);
4802 heap_freetuple(tuple);
4804 heap_close(attrelation, RowExclusiveLock);
4809 * ALTER TABLE DROP COLUMN
4811 * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
4812 * because we have to decide at runtime whether to recurse or not depending
4813 * on whether attinhcount goes to zero or not. (We can't check this in a
4814 * static pre-pass because it won't handle multiple inheritance situations
4818 ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
4819 AlterTableCmd *cmd, LOCKMODE lockmode)
4821 if (rel->rd_rel->reloftype && !recursing)
4823 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4824 errmsg("cannot drop column from typed table")));
4826 if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
4827 ATTypedTableRecursion(wqueue, rel, cmd, lockmode);
4830 cmd->subtype = AT_DropColumnRecurse;
4834 ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
4835 DropBehavior behavior,
4836 bool recurse, bool recursing,
4837 bool missing_ok, LOCKMODE lockmode)
4840 Form_pg_attribute targetatt;
4843 ObjectAddress object;
4845 /* At top level, permission check was done in ATPrepCmd, else do it */
4847 ATSimplePermissions(rel, ATT_TABLE);
4850 * get the number of the attribute
4852 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
4853 if (!HeapTupleIsValid(tuple))
4858 (errcode(ERRCODE_UNDEFINED_COLUMN),
4859 errmsg("column \"%s\" of relation \"%s\" does not exist",
4860 colName, RelationGetRelationName(rel))));
4865 (errmsg("column \"%s\" of relation \"%s\" does not exist, skipping",
4866 colName, RelationGetRelationName(rel))));
4870 targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
4872 attnum = targetatt->attnum;
4874 /* Can't drop a system attribute, except OID */
4875 if (attnum <= 0 && attnum != ObjectIdAttributeNumber)
4877 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4878 errmsg("cannot drop system column \"%s\"",
4881 /* Don't drop inherited columns */
4882 if (targetatt->attinhcount > 0 && !recursing)
4884 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4885 errmsg("cannot drop inherited column \"%s\"",
4888 ReleaseSysCache(tuple);
4891 * Propagate to children as appropriate. Unlike most other ALTER
4892 * routines, we have to do this one level of recursion at a time; we can't
4893 * use find_all_inheritors to do it in one pass.
4895 children = find_inheritance_children(RelationGetRelid(rel), lockmode);
4902 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
4903 foreach(child, children)
4905 Oid childrelid = lfirst_oid(child);
4907 Form_pg_attribute childatt;
4909 /* find_inheritance_children already got lock */
4910 childrel = heap_open(childrelid, NoLock);
4911 CheckTableNotInUse(childrel, "ALTER TABLE");
4913 tuple = SearchSysCacheCopyAttName(childrelid, colName);
4914 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
4915 elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
4916 colName, childrelid);
4917 childatt = (Form_pg_attribute) GETSTRUCT(tuple);
4919 if (childatt->attinhcount <= 0) /* shouldn't happen */
4920 elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
4921 childrelid, colName);
4926 * If the child column has other definition sources, just
4927 * decrement its inheritance count; if not, recurse to delete
4930 if (childatt->attinhcount == 1 && !childatt->attislocal)
4932 /* Time to delete this child column, too */
4933 ATExecDropColumn(wqueue, childrel, colName,
4934 behavior, true, true,
4939 /* Child column must survive my deletion */
4940 childatt->attinhcount--;
4942 simple_heap_update(attr_rel, &tuple->t_self, tuple);
4944 /* keep the system catalog indexes current */
4945 CatalogUpdateIndexes(attr_rel, tuple);
4947 /* Make update visible */
4948 CommandCounterIncrement();
4954 * If we were told to drop ONLY in this table (no recursion),
4955 * we need to mark the inheritors' attributes as locally
4956 * defined rather than inherited.
4958 childatt->attinhcount--;
4959 childatt->attislocal = true;
4961 simple_heap_update(attr_rel, &tuple->t_self, tuple);
4963 /* keep the system catalog indexes current */
4964 CatalogUpdateIndexes(attr_rel, tuple);
4966 /* Make update visible */
4967 CommandCounterIncrement();
4970 heap_freetuple(tuple);
4972 heap_close(childrel, NoLock);
4974 heap_close(attr_rel, RowExclusiveLock);
4978 * Perform the actual column deletion
4980 object.classId = RelationRelationId;
4981 object.objectId = RelationGetRelid(rel);
4982 object.objectSubId = attnum;
4984 performDeletion(&object, behavior);
4987 * If we dropped the OID column, must adjust pg_class.relhasoids and tell
4988 * Phase 3 to physically get rid of the column. We formerly left the
4989 * column in place physically, but this caused subtle problems. See
4990 * http://archives.postgresql.org/pgsql-hackers/2009-02/msg00363.php
4992 if (attnum == ObjectIdAttributeNumber)
4995 Form_pg_class tuple_class;
4996 AlteredTableInfo *tab;
4998 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
5000 tuple = SearchSysCacheCopy1(RELOID,
5001 ObjectIdGetDatum(RelationGetRelid(rel)));
5002 if (!HeapTupleIsValid(tuple))
5003 elog(ERROR, "cache lookup failed for relation %u",
5004 RelationGetRelid(rel));
5005 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
5007 tuple_class->relhasoids = false;
5008 simple_heap_update(class_rel, &tuple->t_self, tuple);
5010 /* Keep the catalog indexes up to date */
5011 CatalogUpdateIndexes(class_rel, tuple);
5013 heap_close(class_rel, RowExclusiveLock);
5015 /* Find or create work queue entry for this table */
5016 tab = ATGetQueueEntry(wqueue, rel);
5018 /* Tell Phase 3 to physically remove the OID column */
5019 tab->new_changeoids = true;
5024 * ALTER TABLE ADD INDEX
5026 * There is no such command in the grammar, but parse_utilcmd.c converts
5027 * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands. This lets
5028 * us schedule creation of the index at the appropriate time during ALTER.
5031 ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
5032 IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
5038 Assert(IsA(stmt, IndexStmt));
5040 /* suppress schema rights check when rebuilding existing index */
5041 check_rights = !is_rebuild;
5042 /* skip index build if phase 3 will have to rewrite table anyway */
5043 skip_build = (tab->newvals != NIL);
5044 /* suppress notices when rebuilding existing index */
5047 /* The IndexStmt has already been through transformIndexStmt */
5049 DefineIndex(stmt->relation, /* relation */
5050 stmt->idxname, /* index name */
5051 InvalidOid, /* no predefined OID */
5052 stmt->accessMethod, /* am name */
5054 stmt->indexParams, /* parameters */
5055 (Expr *) stmt->whereClause,
5057 stmt->excludeOpNames,
5063 true, /* is_alter_table */
5071 * ALTER TABLE ADD CONSTRAINT USING INDEX
5074 ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
5075 IndexStmt *stmt, LOCKMODE lockmode)
5077 Oid index_oid = stmt->indexOid;
5080 IndexInfo *indexInfo;
5081 char *constraintName;
5082 char constraintType;
5084 Assert(IsA(stmt, IndexStmt));
5085 Assert(OidIsValid(index_oid));
5086 Assert(stmt->isconstraint);
5088 indexRel = index_open(index_oid, AccessShareLock);
5090 indexName = pstrdup(RelationGetRelationName(indexRel));
5092 indexInfo = BuildIndexInfo(indexRel);
5094 /* this should have been checked at parse time */
5095 if (!indexInfo->ii_Unique)
5096 elog(ERROR, "index \"%s\" is not unique", indexName);
5099 * Determine name to assign to constraint. We require a constraint to
5100 * have the same name as the underlying index; therefore, use the index's
5101 * existing name as the default constraint name, and if the user explicitly
5102 * gives some other name for the constraint, rename the index to match.
5104 constraintName = stmt->idxname;
5105 if (constraintName == NULL)
5106 constraintName = indexName;
5107 else if (strcmp(constraintName, indexName) != 0)
5110 (errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index \"%s\" to \"%s\"",
5111 indexName, constraintName)));
5112 RenameRelation(index_oid, constraintName, OBJECT_INDEX);
5115 /* Extra checks needed if making primary key */
5117 index_check_primary_key(rel, indexInfo, true);
5119 /* Note we currently don't support EXCLUSION constraints here */
5121 constraintType = CONSTRAINT_PRIMARY;
5123 constraintType = CONSTRAINT_UNIQUE;
5125 /* Create the catalog entries for the constraint */
5126 index_constraint_create(rel,
5135 allowSystemTableMods);
5137 index_close(indexRel, NoLock);
5141 * ALTER TABLE ADD CONSTRAINT
5144 ATExecAddConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
5145 Constraint *newConstraint, bool recurse, LOCKMODE lockmode)
5147 Assert(IsA(newConstraint, Constraint));
5150 * Currently, we only expect to see CONSTR_CHECK and CONSTR_FOREIGN nodes
5151 * arriving here (see the preprocessing done in parse_utilcmd.c). Use a
5152 * switch anyway to make it easier to add more code later.
5154 switch (newConstraint->contype)
5157 ATAddCheckConstraint(wqueue, tab, rel,
5158 newConstraint, recurse, false, lockmode);
5161 case CONSTR_FOREIGN:
5164 * Note that we currently never recurse for FK constraints, so the
5165 * "recurse" flag is silently ignored.
5167 * Assign or validate constraint name
5169 if (newConstraint->conname)
5171 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
5172 RelationGetRelid(rel),
5173 RelationGetNamespace(rel),
5174 newConstraint->conname))
5176 (errcode(ERRCODE_DUPLICATE_OBJECT),
5177 errmsg("constraint \"%s\" for relation \"%s\" already exists",
5178 newConstraint->conname,
5179 RelationGetRelationName(rel))));
5182 newConstraint->conname =
5183 ChooseConstraintName(RelationGetRelationName(rel),
5184 strVal(linitial(newConstraint->fk_attrs)),
5186 RelationGetNamespace(rel),
5189 ATAddForeignKeyConstraint(tab, rel, newConstraint, lockmode);
5193 elog(ERROR, "unrecognized constraint type: %d",
5194 (int) newConstraint->contype);
5199 * Add a check constraint to a single table and its children
5201 * Subroutine for ATExecAddConstraint.
5203 * We must recurse to child tables during execution, rather than using
5204 * ALTER TABLE's normal prep-time recursion. The reason is that all the
5205 * constraints *must* be given the same name, else they won't be seen as
5206 * related later. If the user didn't explicitly specify a name, then
5207 * AddRelationNewConstraints would normally assign different names to the
5208 * child constraints. To fix that, we must capture the name assigned at
5209 * the parent table and pass that down.
5212 ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
5213 Constraint *constr, bool recurse, bool recursing,
5221 /* At top level, permission check was done in ATPrepCmd, else do it */
5223 ATSimplePermissions(rel, ATT_TABLE);
5226 * Call AddRelationNewConstraints to do the work, making sure it works on
5227 * a copy of the Constraint so transformExpr can't modify the original. It
5228 * returns a list of cooked constraints.
5230 * If the constraint ends up getting merged with a pre-existing one, it's
5231 * omitted from the returned list, which is what we want: we do not need
5232 * to do any validation work. That can only happen at child tables,
5233 * though, since we disallow merging at the top level.
5235 newcons = AddRelationNewConstraints(rel, NIL,
5236 list_make1(copyObject(constr)),
5237 recursing, !recursing);
5239 /* Add each constraint to Phase 3's queue */
5240 foreach(lcon, newcons)
5242 CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
5243 NewConstraint *newcon;
5245 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
5246 newcon->name = ccon->name;
5247 newcon->contype = ccon->contype;
5248 /* ExecQual wants implicit-AND format */
5249 newcon->qual = (Node *) make_ands_implicit((Expr *) ccon->expr);
5251 tab->constraints = lappend(tab->constraints, newcon);
5253 /* Save the actually assigned name if it was defaulted */
5254 if (constr->conname == NULL)
5255 constr->conname = ccon->name;
5258 /* At this point we must have a locked-down name to use */
5259 Assert(constr->conname != NULL);
5261 /* Advance command counter in case same table is visited multiple times */
5262 CommandCounterIncrement();
5265 * If the constraint got merged with an existing constraint, we're done.
5266 * We mustn't recurse to child tables in this case, because they've already
5267 * got the constraint, and visiting them again would lead to an incorrect
5268 * value for coninhcount.
5274 * Propagate to children as appropriate. Unlike most other ALTER
5275 * routines, we have to do this one level of recursion at a time; we can't
5276 * use find_all_inheritors to do it in one pass.
5278 children = find_inheritance_children(RelationGetRelid(rel), lockmode);
5281 * If we are told not to recurse, there had better not be any child
5282 * tables; else the addition would put them out of step.
5284 if (children && !recurse)
5286 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5287 errmsg("constraint must be added to child tables too")));
5289 foreach(child, children)
5291 Oid childrelid = lfirst_oid(child);
5293 AlteredTableInfo *childtab;
5295 /* find_inheritance_children already got lock */
5296 childrel = heap_open(childrelid, NoLock);
5297 CheckTableNotInUse(childrel, "ALTER TABLE");
5299 /* Find or create work queue entry for this table */
5300 childtab = ATGetQueueEntry(wqueue, childrel);
5302 /* Recurse to child */
5303 ATAddCheckConstraint(wqueue, childtab, childrel,
5304 constr, recurse, true, lockmode);
5306 heap_close(childrel, NoLock);
5311 * Add a foreign-key constraint to a single table
5313 * Subroutine for ATExecAddConstraint. Must already hold exclusive
5314 * lock on the rel, and have done appropriate validity checks for it.
5315 * We do permissions checks here, however.
5318 ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
5319 Constraint *fkconstraint, LOCKMODE lockmode)
5322 int16 pkattnum[INDEX_MAX_KEYS];
5323 int16 fkattnum[INDEX_MAX_KEYS];
5324 Oid pktypoid[INDEX_MAX_KEYS];
5325 Oid fktypoid[INDEX_MAX_KEYS];
5326 Oid opclasses[INDEX_MAX_KEYS];
5327 Oid pfeqoperators[INDEX_MAX_KEYS];
5328 Oid ppeqoperators[INDEX_MAX_KEYS];
5329 Oid ffeqoperators[INDEX_MAX_KEYS];
5336 pkrel = heap_openrv(fkconstraint->pktable, lockmode);
5339 * Validity checks (permission checks wait till we have the column
5342 if (pkrel->rd_rel->relkind != RELKIND_RELATION)
5344 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5345 errmsg("referenced relation \"%s\" is not a table",
5346 RelationGetRelationName(pkrel))));
5348 if (!allowSystemTableMods && IsSystemRelation(pkrel))
5350 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5351 errmsg("permission denied: \"%s\" is a system catalog",
5352 RelationGetRelationName(pkrel))));
5355 * References from permanent or unlogged tables to temp tables, and from
5356 * permanent tables to unlogged tables, are disallowed because the
5357 * referenced data can vanish out from under us. References from temp
5358 * tables to any other table type are also disallowed, because other
5359 * backends might need to run the RI triggers on the perm table, but they
5360 * can't reliably see tuples in the local buffers of other backends.
5362 switch (rel->rd_rel->relpersistence)
5364 case RELPERSISTENCE_PERMANENT:
5365 if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT)
5367 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5368 errmsg("constraints on permanent tables may reference only permanent tables")));
5370 case RELPERSISTENCE_UNLOGGED:
5371 if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT
5372 && pkrel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED)
5374 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5375 errmsg("constraints on unlogged tables may reference only permanent or unlogged tables")));
5377 case RELPERSISTENCE_TEMP:
5378 if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
5380 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5381 errmsg("constraints on temporary tables may reference only temporary tables")));
5386 * Look up the referencing attributes to make sure they exist, and record
5387 * their attnums and type OIDs.
5389 MemSet(pkattnum, 0, sizeof(pkattnum));
5390 MemSet(fkattnum, 0, sizeof(fkattnum));
5391 MemSet(pktypoid, 0, sizeof(pktypoid));
5392 MemSet(fktypoid, 0, sizeof(fktypoid));
5393 MemSet(opclasses, 0, sizeof(opclasses));
5394 MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
5395 MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
5396 MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
5398 numfks = transformColumnNameList(RelationGetRelid(rel),
5399 fkconstraint->fk_attrs,
5400 fkattnum, fktypoid);
5403 * If the attribute list for the referenced table was omitted, lookup the
5404 * definition of the primary key and use it. Otherwise, validate the
5405 * supplied attribute list. In either case, discover the index OID and
5406 * index opclasses, and the attnums and type OIDs of the attributes.
5408 if (fkconstraint->pk_attrs == NIL)
5410 numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
5411 &fkconstraint->pk_attrs,
5417 numpks = transformColumnNameList(RelationGetRelid(pkrel),
5418 fkconstraint->pk_attrs,
5419 pkattnum, pktypoid);
5420 /* Look for an index matching the column list */
5421 indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
5426 * Now we can check permissions.
5428 checkFkeyPermissions(pkrel, pkattnum, numpks);
5429 checkFkeyPermissions(rel, fkattnum, numfks);
5432 * Look up the equality operators to use in the constraint.
5434 * Note that we have to be careful about the difference between the actual
5435 * PK column type and the opclass' declared input type, which might be
5436 * only binary-compatible with it. The declared opcintype is the right
5437 * thing to probe pg_amop with.
5439 if (numfks != numpks)
5441 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
5442 errmsg("number of referencing and referenced columns for foreign key disagree")));
5444 for (i = 0; i < numpks; i++)
5446 Oid pktype = pktypoid[i];
5447 Oid fktype = fktypoid[i];
5450 Form_pg_opclass cla_tup;
5459 /* We need several fields out of the pg_opclass entry */
5460 cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclasses[i]));
5461 if (!HeapTupleIsValid(cla_ht))
5462 elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
5463 cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
5464 amid = cla_tup->opcmethod;
5465 opfamily = cla_tup->opcfamily;
5466 opcintype = cla_tup->opcintype;
5467 ReleaseSysCache(cla_ht);
5470 * Check it's a btree; currently this can never fail since no other
5471 * index AMs support unique indexes. If we ever did have other types
5472 * of unique indexes, we'd need a way to determine which operator
5473 * strategy number is equality. (Is it reasonable to insist that
5474 * every such index AM use btree's number for equality?)
5476 if (amid != BTREE_AM_OID)
5477 elog(ERROR, "only b-tree indexes are supported for foreign keys");
5478 eqstrategy = BTEqualStrategyNumber;
5481 * There had better be a primary equality operator for the index.
5482 * We'll use it for PK = PK comparisons.
5484 ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
5487 if (!OidIsValid(ppeqop))
5488 elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
5489 eqstrategy, opcintype, opcintype, opfamily);
5492 * Are there equality operators that take exactly the FK type? Assume
5493 * we should look through any domain here.
5495 fktyped = getBaseType(fktype);
5497 pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
5499 if (OidIsValid(pfeqop))
5500 ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
5503 ffeqop = InvalidOid; /* keep compiler quiet */
5505 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
5508 * Otherwise, look for an implicit cast from the FK type to the
5509 * opcintype, and if found, use the primary equality operator.
5510 * This is a bit tricky because opcintype might be a polymorphic
5511 * type such as ANYARRAY or ANYENUM; so what we have to test is
5512 * whether the two actual column types can be concurrently cast to
5513 * that type. (Otherwise, we'd fail to reject combinations such
5514 * as int[] and point[].)
5516 Oid input_typeids[2];
5517 Oid target_typeids[2];
5519 input_typeids[0] = pktype;
5520 input_typeids[1] = fktype;
5521 target_typeids[0] = opcintype;
5522 target_typeids[1] = opcintype;
5523 if (can_coerce_type(2, input_typeids, target_typeids,
5525 pfeqop = ffeqop = ppeqop;
5528 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
5530 (errcode(ERRCODE_DATATYPE_MISMATCH),
5531 errmsg("foreign key constraint \"%s\" "
5532 "cannot be implemented",
5533 fkconstraint->conname),
5534 errdetail("Key columns \"%s\" and \"%s\" "
5535 "are of incompatible types: %s and %s.",
5536 strVal(list_nth(fkconstraint->fk_attrs, i)),
5537 strVal(list_nth(fkconstraint->pk_attrs, i)),
5538 format_type_be(fktype),
5539 format_type_be(pktype))));
5541 pfeqoperators[i] = pfeqop;
5542 ppeqoperators[i] = ppeqop;
5543 ffeqoperators[i] = ffeqop;
5547 * Record the FK constraint in pg_constraint.
5549 constrOid = CreateConstraintEntry(fkconstraint->conname,
5550 RelationGetNamespace(rel),
5552 fkconstraint->deferrable,
5553 fkconstraint->initdeferred,
5554 !fkconstraint->skip_validation,
5555 RelationGetRelid(rel),
5558 InvalidOid, /* not a domain
5561 RelationGetRelid(pkrel),
5567 fkconstraint->fk_upd_action,
5568 fkconstraint->fk_del_action,
5569 fkconstraint->fk_matchtype,
5570 NULL, /* no exclusion constraint */
5571 NULL, /* no check constraint */
5578 * Create the triggers that will enforce the constraint.
5580 createForeignKeyTriggers(rel, fkconstraint, constrOid, indexOid);
5583 * Tell Phase 3 to check that the constraint is satisfied by existing rows
5584 * We can skip this during table creation or if requested explicitly
5585 * by specifying NOT VALID on an alter table statement.
5587 if (!fkconstraint->skip_validation)
5589 NewConstraint *newcon;
5591 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
5592 newcon->name = fkconstraint->conname;
5593 newcon->contype = CONSTR_FOREIGN;
5594 newcon->refrelid = RelationGetRelid(pkrel);
5595 newcon->refindid = indexOid;
5596 newcon->conid = constrOid;
5597 newcon->qual = (Node *) fkconstraint;
5599 tab->constraints = lappend(tab->constraints, newcon);
5603 * Close pk table, but keep lock until we've committed.
5605 heap_close(pkrel, NoLock);
5609 * ALTER TABLE VALIDATE CONSTRAINT
5612 ATExecValidateConstraint(Relation rel, const char *constrName)
5618 Form_pg_constraint con = NULL;
5621 conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
5624 * Find and check the target constraint
5627 Anum_pg_constraint_conrelid,
5628 BTEqualStrategyNumber, F_OIDEQ,
5629 ObjectIdGetDatum(RelationGetRelid(rel)));
5630 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
5631 true, SnapshotNow, 1, &key);
5633 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
5635 con = (Form_pg_constraint) GETSTRUCT(tuple);
5636 if (con->contype == CONSTRAINT_FOREIGN &&
5637 strcmp(NameStr(con->conname), constrName) == 0)
5646 (errcode(ERRCODE_UNDEFINED_OBJECT),
5647 errmsg("foreign key constraint \"%s\" of relation \"%s\" does not exist",
5648 constrName, RelationGetRelationName(rel))));
5650 if (!con->convalidated)
5652 Oid conid = HeapTupleGetOid(tuple);
5653 HeapTuple copyTuple = heap_copytuple(tuple);
5654 Form_pg_constraint copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
5658 * Triggers are already in place on both tables, so a
5659 * concurrent write that alters the result here is not
5660 * possible. Normally we can run a query here to do the
5661 * validation, which would only require AccessShareLock.
5662 * In some cases, it is possible that we might need to
5663 * fire triggers to perform the check, so we take a lock
5664 * at RowShareLock level just in case.
5666 refrel = heap_open(con->confrelid, RowShareLock);
5668 validateForeignKeyConstraint((char *)constrName, rel, refrel,
5673 * Now update the catalog, while we have the door open.
5675 copy_con->convalidated = true;
5676 simple_heap_update(conrel, ©Tuple->t_self, copyTuple);
5677 CatalogUpdateIndexes(conrel, copyTuple);
5678 heap_freetuple(copyTuple);
5680 heap_close(refrel, NoLock);
5683 systable_endscan(scan);
5685 heap_close(conrel, RowExclusiveLock);
5689 * transformColumnNameList - transform list of column names
5691 * Lookup each name and return its attnum and type OID
5694 transformColumnNameList(Oid relId, List *colList,
5695 int16 *attnums, Oid *atttypids)
5703 char *attname = strVal(lfirst(l));
5706 atttuple = SearchSysCacheAttName(relId, attname);
5707 if (!HeapTupleIsValid(atttuple))
5709 (errcode(ERRCODE_UNDEFINED_COLUMN),
5710 errmsg("column \"%s\" referenced in foreign key constraint does not exist",
5712 if (attnum >= INDEX_MAX_KEYS)
5714 (errcode(ERRCODE_TOO_MANY_COLUMNS),
5715 errmsg("cannot have more than %d keys in a foreign key",
5717 attnums[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->attnum;
5718 atttypids[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->atttypid;
5719 ReleaseSysCache(atttuple);
5727 * transformFkeyGetPrimaryKey -
5729 * Look up the names, attnums, and types of the primary key attributes
5730 * for the pkrel. Also return the index OID and index opclasses of the
5731 * index supporting the primary key.
5733 * All parameters except pkrel are output parameters. Also, the function
5734 * return value is the number of attributes in the primary key.
5736 * Used when the column list in the REFERENCES specification is omitted.
5739 transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
5741 int16 *attnums, Oid *atttypids,
5745 ListCell *indexoidscan;
5746 HeapTuple indexTuple = NULL;
5747 Form_pg_index indexStruct = NULL;
5748 Datum indclassDatum;
5750 oidvector *indclass;
5754 * Get the list of index OIDs for the table from the relcache, and look up
5755 * each one in the pg_index syscache until we find one marked primary key
5756 * (hopefully there isn't more than one such).
5758 *indexOid = InvalidOid;
5760 indexoidlist = RelationGetIndexList(pkrel);
5762 foreach(indexoidscan, indexoidlist)
5764 Oid indexoid = lfirst_oid(indexoidscan);
5766 indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
5767 if (!HeapTupleIsValid(indexTuple))
5768 elog(ERROR, "cache lookup failed for index %u", indexoid);
5769 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
5770 if (indexStruct->indisprimary)
5773 * Refuse to use a deferrable primary key. This is per SQL spec,
5774 * and there would be a lot of interesting semantic problems if we
5775 * tried to allow it.
5777 if (!indexStruct->indimmediate)
5779 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5780 errmsg("cannot use a deferrable primary key for referenced table \"%s\"",
5781 RelationGetRelationName(pkrel))));
5783 *indexOid = indexoid;
5786 ReleaseSysCache(indexTuple);
5789 list_free(indexoidlist);
5792 * Check that we found it
5794 if (!OidIsValid(*indexOid))
5796 (errcode(ERRCODE_UNDEFINED_OBJECT),
5797 errmsg("there is no primary key for referenced table \"%s\"",
5798 RelationGetRelationName(pkrel))));
5800 /* Must get indclass the hard way */
5801 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
5802 Anum_pg_index_indclass, &isnull);
5804 indclass = (oidvector *) DatumGetPointer(indclassDatum);
5807 * Now build the list of PK attributes from the indkey definition (we
5808 * assume a primary key cannot have expressional elements)
5811 for (i = 0; i < indexStruct->indnatts; i++)
5813 int pkattno = indexStruct->indkey.values[i];
5815 attnums[i] = pkattno;
5816 atttypids[i] = attnumTypeId(pkrel, pkattno);
5817 opclasses[i] = indclass->values[i];
5818 *attnamelist = lappend(*attnamelist,
5819 makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
5822 ReleaseSysCache(indexTuple);
5828 * transformFkeyCheckAttrs -
5830 * Make sure that the attributes of a referenced table belong to a unique
5831 * (or primary key) constraint. Return the OID of the index supporting
5832 * the constraint, as well as the opclasses associated with the index
5836 transformFkeyCheckAttrs(Relation pkrel,
5837 int numattrs, int16 *attnums,
5838 Oid *opclasses) /* output parameter */
5840 Oid indexoid = InvalidOid;
5842 bool found_deferrable = false;
5844 ListCell *indexoidscan;
5847 * Get the list of index OIDs for the table from the relcache, and look up
5848 * each one in the pg_index syscache, and match unique indexes to the list
5849 * of attnums we are given.
5851 indexoidlist = RelationGetIndexList(pkrel);
5853 foreach(indexoidscan, indexoidlist)
5855 HeapTuple indexTuple;
5856 Form_pg_index indexStruct;
5860 indexoid = lfirst_oid(indexoidscan);
5861 indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
5862 if (!HeapTupleIsValid(indexTuple))
5863 elog(ERROR, "cache lookup failed for index %u", indexoid);
5864 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
5867 * Must have the right number of columns; must be unique and not a
5868 * partial index; forget it if there are any expressions, too
5870 if (indexStruct->indnatts == numattrs &&
5871 indexStruct->indisunique &&
5872 heap_attisnull(indexTuple, Anum_pg_index_indpred) &&
5873 heap_attisnull(indexTuple, Anum_pg_index_indexprs))
5875 /* Must get indclass the hard way */
5876 Datum indclassDatum;
5878 oidvector *indclass;
5880 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
5881 Anum_pg_index_indclass, &isnull);
5883 indclass = (oidvector *) DatumGetPointer(indclassDatum);
5886 * The given attnum list may match the index columns in any order.
5887 * Check that each list is a subset of the other.
5889 for (i = 0; i < numattrs; i++)
5892 for (j = 0; j < numattrs; j++)
5894 if (attnums[i] == indexStruct->indkey.values[j])
5905 for (i = 0; i < numattrs; i++)
5908 for (j = 0; j < numattrs; j++)
5910 if (attnums[j] == indexStruct->indkey.values[i])
5912 opclasses[j] = indclass->values[i];
5923 * Refuse to use a deferrable unique/primary key. This is per SQL
5924 * spec, and there would be a lot of interesting semantic problems
5925 * if we tried to allow it.
5927 if (found && !indexStruct->indimmediate)
5930 * Remember that we found an otherwise matching index, so that
5931 * we can generate a more appropriate error message.
5933 found_deferrable = true;
5937 ReleaseSysCache(indexTuple);
5944 if (found_deferrable)
5946 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5947 errmsg("cannot use a deferrable unique constraint for referenced table \"%s\"",
5948 RelationGetRelationName(pkrel))));
5951 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
5952 errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
5953 RelationGetRelationName(pkrel))));
5956 list_free(indexoidlist);
5961 /* Permissions checks for ADD FOREIGN KEY */
5963 checkFkeyPermissions(Relation rel, int16 *attnums, int natts)
5965 Oid roleid = GetUserId();
5966 AclResult aclresult;
5969 /* Okay if we have relation-level REFERENCES permission */
5970 aclresult = pg_class_aclcheck(RelationGetRelid(rel), roleid,
5972 if (aclresult == ACLCHECK_OK)
5974 /* Else we must have REFERENCES on each column */
5975 for (i = 0; i < natts; i++)
5977 aclresult = pg_attribute_aclcheck(RelationGetRelid(rel), attnums[i],
5978 roleid, ACL_REFERENCES);
5979 if (aclresult != ACLCHECK_OK)
5980 aclcheck_error(aclresult, ACL_KIND_CLASS,
5981 RelationGetRelationName(rel));
5986 * Scan the existing rows in a table to verify they meet a proposed FK
5989 * Caller must have opened and locked both relations appropriately.
5992 validateForeignKeyConstraint(char *conname,
6003 * Build a trigger call structure; we'll need it either way.
6005 MemSet(&trig, 0, sizeof(trig));
6006 trig.tgoid = InvalidOid;
6007 trig.tgname = conname;
6008 trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
6009 trig.tgisinternal = TRUE;
6010 trig.tgconstrrelid = RelationGetRelid(pkrel);
6011 trig.tgconstrindid = pkindOid;
6012 trig.tgconstraint = constraintOid;
6013 trig.tgdeferrable = FALSE;
6014 trig.tginitdeferred = FALSE;
6015 /* we needn't fill in tgargs or tgqual */
6018 * See if we can do it with a single LEFT JOIN query. A FALSE result
6019 * indicates we must proceed with the fire-the-trigger method.
6021 if (RI_Initial_Check(&trig, rel, pkrel))
6025 * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
6026 * if that tuple had just been inserted. If any of those fail, it should
6027 * ereport(ERROR) and that's that.
6029 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
6031 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
6033 FunctionCallInfoData fcinfo;
6034 TriggerData trigdata;
6037 * Make a call to the trigger function
6039 * No parameters are passed, but we do set a context
6041 MemSet(&fcinfo, 0, sizeof(fcinfo));
6044 * We assume RI_FKey_check_ins won't look at flinfo...
6046 trigdata.type = T_TriggerData;
6047 trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
6048 trigdata.tg_relation = rel;
6049 trigdata.tg_trigtuple = tuple;
6050 trigdata.tg_newtuple = NULL;
6051 trigdata.tg_trigger = &trig;
6052 trigdata.tg_trigtuplebuf = scan->rs_cbuf;
6053 trigdata.tg_newtuplebuf = InvalidBuffer;
6055 fcinfo.context = (Node *) &trigdata;
6057 RI_FKey_check_ins(&fcinfo);
6064 CreateFKCheckTrigger(RangeVar *myRel, Constraint *fkconstraint,
6065 Oid constraintOid, Oid indexOid, bool on_insert)
6067 CreateTrigStmt *fk_trigger;
6069 fk_trigger = makeNode(CreateTrigStmt);
6070 fk_trigger->trigname = "RI_ConstraintTrigger";
6071 fk_trigger->relation = myRel;
6072 fk_trigger->row = true;
6073 fk_trigger->timing = TRIGGER_TYPE_AFTER;
6075 /* Either ON INSERT or ON UPDATE */
6078 fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
6079 fk_trigger->events = TRIGGER_TYPE_INSERT;
6083 fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
6084 fk_trigger->events = TRIGGER_TYPE_UPDATE;
6087 fk_trigger->columns = NIL;
6088 fk_trigger->whenClause = NULL;
6089 fk_trigger->isconstraint = true;
6090 fk_trigger->deferrable = fkconstraint->deferrable;
6091 fk_trigger->initdeferred = fkconstraint->initdeferred;
6092 fk_trigger->constrrel = fkconstraint->pktable;
6093 fk_trigger->args = NIL;
6095 (void) CreateTrigger(fk_trigger, NULL, constraintOid, indexOid, true);
6097 /* Make changes-so-far visible */
6098 CommandCounterIncrement();
6102 * Create the triggers that implement an FK constraint.
6105 createForeignKeyTriggers(Relation rel, Constraint *fkconstraint,
6106 Oid constraintOid, Oid indexOid)
6109 CreateTrigStmt *fk_trigger;
6112 * Reconstruct a RangeVar for my relation (not passed in, unfortunately).
6114 myRel = makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
6115 pstrdup(RelationGetRelationName(rel)),
6118 /* Make changes-so-far visible */
6119 CommandCounterIncrement();
6122 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the CHECK
6123 * action for both INSERTs and UPDATEs on the referencing table.
6125 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, indexOid, true);
6126 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, indexOid, false);
6129 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
6130 * DELETE action on the referenced table.
6132 fk_trigger = makeNode(CreateTrigStmt);
6133 fk_trigger->trigname = "RI_ConstraintTrigger";
6134 fk_trigger->relation = fkconstraint->pktable;
6135 fk_trigger->row = true;
6136 fk_trigger->timing = TRIGGER_TYPE_AFTER;
6137 fk_trigger->events = TRIGGER_TYPE_DELETE;
6138 fk_trigger->columns = NIL;
6139 fk_trigger->whenClause = NULL;
6140 fk_trigger->isconstraint = true;
6141 fk_trigger->constrrel = myRel;
6142 switch (fkconstraint->fk_del_action)
6144 case FKCONSTR_ACTION_NOACTION:
6145 fk_trigger->deferrable = fkconstraint->deferrable;
6146 fk_trigger->initdeferred = fkconstraint->initdeferred;
6147 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
6149 case FKCONSTR_ACTION_RESTRICT:
6150 fk_trigger->deferrable = false;
6151 fk_trigger->initdeferred = false;
6152 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
6154 case FKCONSTR_ACTION_CASCADE:
6155 fk_trigger->deferrable = false;
6156 fk_trigger->initdeferred = false;
6157 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
6159 case FKCONSTR_ACTION_SETNULL:
6160 fk_trigger->deferrable = false;
6161 fk_trigger->initdeferred = false;
6162 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
6164 case FKCONSTR_ACTION_SETDEFAULT:
6165 fk_trigger->deferrable = false;
6166 fk_trigger->initdeferred = false;
6167 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
6170 elog(ERROR, "unrecognized FK action type: %d",
6171 (int) fkconstraint->fk_del_action);
6174 fk_trigger->args = NIL;
6176 (void) CreateTrigger(fk_trigger, NULL, constraintOid, indexOid, true);
6178 /* Make changes-so-far visible */
6179 CommandCounterIncrement();
6182 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
6183 * UPDATE action on the referenced table.
6185 fk_trigger = makeNode(CreateTrigStmt);
6186 fk_trigger->trigname = "RI_ConstraintTrigger";
6187 fk_trigger->relation = fkconstraint->pktable;
6188 fk_trigger->row = true;
6189 fk_trigger->timing = TRIGGER_TYPE_AFTER;
6190 fk_trigger->events = TRIGGER_TYPE_UPDATE;
6191 fk_trigger->columns = NIL;
6192 fk_trigger->whenClause = NULL;
6193 fk_trigger->isconstraint = true;
6194 fk_trigger->constrrel = myRel;
6195 switch (fkconstraint->fk_upd_action)
6197 case FKCONSTR_ACTION_NOACTION:
6198 fk_trigger->deferrable = fkconstraint->deferrable;
6199 fk_trigger->initdeferred = fkconstraint->initdeferred;
6200 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
6202 case FKCONSTR_ACTION_RESTRICT:
6203 fk_trigger->deferrable = false;
6204 fk_trigger->initdeferred = false;
6205 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
6207 case FKCONSTR_ACTION_CASCADE:
6208 fk_trigger->deferrable = false;
6209 fk_trigger->initdeferred = false;
6210 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
6212 case FKCONSTR_ACTION_SETNULL:
6213 fk_trigger->deferrable = false;
6214 fk_trigger->initdeferred = false;
6215 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
6217 case FKCONSTR_ACTION_SETDEFAULT:
6218 fk_trigger->deferrable = false;
6219 fk_trigger->initdeferred = false;
6220 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
6223 elog(ERROR, "unrecognized FK action type: %d",
6224 (int) fkconstraint->fk_upd_action);
6227 fk_trigger->args = NIL;
6229 (void) CreateTrigger(fk_trigger, NULL, constraintOid, indexOid, true);
6233 * ALTER TABLE DROP CONSTRAINT
6235 * Like DROP COLUMN, we can't use the normal ALTER TABLE recursion mechanism.
6238 ATExecDropConstraint(Relation rel, const char *constrName,
6239 DropBehavior behavior,
6240 bool recurse, bool recursing,
6241 bool missing_ok, LOCKMODE lockmode)
6246 Form_pg_constraint con;
6251 bool is_check_constraint = false;
6253 /* At top level, permission check was done in ATPrepCmd, else do it */
6255 ATSimplePermissions(rel, ATT_TABLE);
6257 conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
6260 * Find and drop the target constraint
6263 Anum_pg_constraint_conrelid,
6264 BTEqualStrategyNumber, F_OIDEQ,
6265 ObjectIdGetDatum(RelationGetRelid(rel)));
6266 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
6267 true, SnapshotNow, 1, &key);
6269 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
6271 ObjectAddress conobj;
6273 con = (Form_pg_constraint) GETSTRUCT(tuple);
6275 if (strcmp(NameStr(con->conname), constrName) != 0)
6278 /* Don't drop inherited constraints */
6279 if (con->coninhcount > 0 && !recursing)
6281 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6282 errmsg("cannot drop inherited constraint \"%s\" of relation \"%s\"",
6283 constrName, RelationGetRelationName(rel))));
6285 /* Right now only CHECK constraints can be inherited */
6286 if (con->contype == CONSTRAINT_CHECK)
6287 is_check_constraint = true;
6290 * Perform the actual constraint deletion
6292 conobj.classId = ConstraintRelationId;
6293 conobj.objectId = HeapTupleGetOid(tuple);
6294 conobj.objectSubId = 0;
6296 performDeletion(&conobj, behavior);
6301 systable_endscan(scan);
6308 (errcode(ERRCODE_UNDEFINED_OBJECT),
6309 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
6310 constrName, RelationGetRelationName(rel))));
6315 (errmsg("constraint \"%s\" of relation \"%s\" does not exist, skipping",
6316 constrName, RelationGetRelationName(rel))));
6317 heap_close(conrel, RowExclusiveLock);
6323 * Propagate to children as appropriate. Unlike most other ALTER
6324 * routines, we have to do this one level of recursion at a time; we can't
6325 * use find_all_inheritors to do it in one pass.
6327 if (is_check_constraint)
6328 children = find_inheritance_children(RelationGetRelid(rel), lockmode);
6332 foreach(child, children)
6334 Oid childrelid = lfirst_oid(child);
6337 /* find_inheritance_children already got lock */
6338 childrel = heap_open(childrelid, NoLock);
6339 CheckTableNotInUse(childrel, "ALTER TABLE");
6342 Anum_pg_constraint_conrelid,
6343 BTEqualStrategyNumber, F_OIDEQ,
6344 ObjectIdGetDatum(childrelid));
6345 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
6346 true, SnapshotNow, 1, &key);
6350 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
6352 HeapTuple copy_tuple;
6354 con = (Form_pg_constraint) GETSTRUCT(tuple);
6356 /* Right now only CHECK constraints can be inherited */
6357 if (con->contype != CONSTRAINT_CHECK)
6360 if (strcmp(NameStr(con->conname), constrName) != 0)
6365 if (con->coninhcount <= 0) /* shouldn't happen */
6366 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
6367 childrelid, constrName);
6369 copy_tuple = heap_copytuple(tuple);
6370 con = (Form_pg_constraint) GETSTRUCT(copy_tuple);
6375 * If the child constraint has other definition sources, just
6376 * decrement its inheritance count; if not, recurse to delete
6379 if (con->coninhcount == 1 && !con->conislocal)
6381 /* Time to delete this child constraint, too */
6382 ATExecDropConstraint(childrel, constrName, behavior,
6388 /* Child constraint must survive my deletion */
6390 simple_heap_update(conrel, ©_tuple->t_self, copy_tuple);
6391 CatalogUpdateIndexes(conrel, copy_tuple);
6393 /* Make update visible */
6394 CommandCounterIncrement();
6400 * If we were told to drop ONLY in this table (no recursion),
6401 * we need to mark the inheritors' constraints as locally
6402 * defined rather than inherited.
6405 con->conislocal = true;
6407 simple_heap_update(conrel, ©_tuple->t_self, copy_tuple);
6408 CatalogUpdateIndexes(conrel, copy_tuple);
6410 /* Make update visible */
6411 CommandCounterIncrement();
6414 heap_freetuple(copy_tuple);
6417 systable_endscan(scan);
6421 (errcode(ERRCODE_UNDEFINED_OBJECT),
6422 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
6424 RelationGetRelationName(childrel))));
6426 heap_close(childrel, NoLock);
6429 heap_close(conrel, RowExclusiveLock);
6436 ATPrepAlterColumnType(List **wqueue,
6437 AlteredTableInfo *tab, Relation rel,
6438 bool recurse, bool recursing,
6439 AlterTableCmd *cmd, LOCKMODE lockmode)
6441 char *colName = cmd->name;
6442 TypeName *typeName = (TypeName *) cmd->def;
6444 Form_pg_attribute attTup;
6450 NewColumnValue *newval;
6451 ParseState *pstate = make_parsestate(NULL);
6453 if (rel->rd_rel->reloftype && !recursing)
6455 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6456 errmsg("cannot alter column type of typed table")));
6458 /* lookup the attribute so we can check inheritance status */
6459 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
6460 if (!HeapTupleIsValid(tuple))
6462 (errcode(ERRCODE_UNDEFINED_COLUMN),
6463 errmsg("column \"%s\" of relation \"%s\" does not exist",
6464 colName, RelationGetRelationName(rel))));
6465 attTup = (Form_pg_attribute) GETSTRUCT(tuple);
6466 attnum = attTup->attnum;
6468 /* Can't alter a system attribute */
6471 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6472 errmsg("cannot alter system column \"%s\"",
6475 /* Don't alter inherited columns */
6476 if (attTup->attinhcount > 0 && !recursing)
6478 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6479 errmsg("cannot alter inherited column \"%s\"",
6482 /* Look up the target type */
6483 typenameTypeIdModColl(NULL, typeName, &targettype, &targettypmod, &targetcollid);
6485 /* make sure datatype is legal for a column */
6486 CheckAttributeType(colName, targettype, false);
6488 if (tab->relkind == RELKIND_RELATION)
6491 * Set up an expression to transform the old data value to the new type.
6492 * If a USING option was given, transform and use that expression, else
6493 * just take the old value and try to coerce it. We do this first so that
6494 * type incompatibility can be detected before we waste effort, and
6495 * because we need the expression to be parsed against the original table
6502 /* Expression must be able to access vars of old table */
6503 rte = addRangeTableEntryForRelation(pstate,
6508 addRTEtoQuery(pstate, rte, false, true, true);
6510 transform = transformExpr(pstate, cmd->transform);
6512 /* It can't return a set */
6513 if (expression_returns_set(transform))
6515 (errcode(ERRCODE_DATATYPE_MISMATCH),
6516 errmsg("transform expression must not return a set")));
6518 /* No subplans or aggregates, either... */
6519 if (pstate->p_hasSubLinks)
6521 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6522 errmsg("cannot use subquery in transform expression")));
6523 if (pstate->p_hasAggs)
6525 (errcode(ERRCODE_GROUPING_ERROR),
6526 errmsg("cannot use aggregate function in transform expression")));
6527 if (pstate->p_hasWindowFuncs)
6529 (errcode(ERRCODE_WINDOWING_ERROR),
6530 errmsg("cannot use window function in transform expression")));
6534 transform = (Node *) makeVar(1, attnum,
6535 attTup->atttypid, attTup->atttypmod, attTup->attcollation,
6539 transform = coerce_to_target_type(pstate,
6540 transform, exprType(transform),
6541 targettype, targettypmod,
6542 COERCION_ASSIGNMENT,
6543 COERCE_IMPLICIT_CAST,
6545 if (transform == NULL)
6547 (errcode(ERRCODE_DATATYPE_MISMATCH),
6548 errmsg("column \"%s\" cannot be cast to type %s",
6549 colName, format_type_be(targettype))));
6552 * Add a work queue item to make ATRewriteTable update the column
6555 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
6556 newval->attnum = attnum;
6557 newval->expr = (Expr *) transform;
6559 tab->newvals = lappend(tab->newvals, newval);
6561 else if (tab->relkind == RELKIND_FOREIGN_TABLE)
6565 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6566 errmsg("ALTER TYPE USING is not supported on foreign tables")));
6569 if (tab->relkind == RELKIND_COMPOSITE_TYPE
6570 || tab->relkind == RELKIND_FOREIGN_TABLE)
6573 * For composite types, do this check now. Tables will check
6574 * it later when the table is being rewritten.
6576 find_composite_type_dependencies(rel->rd_rel->reltype,
6577 rel->rd_rel->relkind,
6578 RelationGetRelationName(rel));
6581 ReleaseSysCache(tuple);
6584 * The recursion case is handled by ATSimpleRecursion. However, if we are
6585 * told not to recurse, there had better not be any child tables; else the
6586 * alter would put them out of step.
6589 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
6590 else if (!recursing &&
6591 find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL)
6593 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6594 errmsg("type of inherited column \"%s\" must be changed in child tables too",
6597 if (tab->relkind == RELKIND_COMPOSITE_TYPE)
6598 ATTypedTableRecursion(wqueue, rel, cmd, lockmode);
6602 ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
6603 const char *colName, TypeName *typeName, LOCKMODE lockmode)
6606 Form_pg_attribute attTup;
6608 HeapTuple typeTuple;
6614 Relation attrelation;
6620 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
6622 /* Look up the target column */
6623 heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
6624 if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
6626 (errcode(ERRCODE_UNDEFINED_COLUMN),
6627 errmsg("column \"%s\" of relation \"%s\" does not exist",
6628 colName, RelationGetRelationName(rel))));
6629 attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
6630 attnum = attTup->attnum;
6632 /* Check for multiple ALTER TYPE on same column --- can't cope */
6633 if (attTup->atttypid != tab->oldDesc->attrs[attnum - 1]->atttypid ||
6634 attTup->atttypmod != tab->oldDesc->attrs[attnum - 1]->atttypmod)
6636 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6637 errmsg("cannot alter type of column \"%s\" twice",
6640 /* Look up the target type (should not fail, since prep found it) */
6641 typeTuple = typenameType(NULL, typeName, &targettypmod, &targetcollid);
6642 tform = (Form_pg_type) GETSTRUCT(typeTuple);
6643 targettype = HeapTupleGetOid(typeTuple);
6646 * If there is a default expression for the column, get it and ensure we
6647 * can coerce it to the new datatype. (We must do this before changing
6648 * the column type, because build_column_default itself will try to
6649 * coerce, and will not issue the error message we want if it fails.)
6651 * We remove any implicit coercion steps at the top level of the old
6652 * default expression; this has been agreed to satisfy the principle of
6653 * least surprise. (The conversion to the new column type should act like
6654 * it started from what the user sees as the stored expression, and the
6655 * implicit coercions aren't going to be shown.)
6657 if (attTup->atthasdef)
6659 defaultexpr = build_column_default(rel, attnum);
6660 Assert(defaultexpr);
6661 defaultexpr = strip_implicit_coercions(defaultexpr);
6662 defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
6663 defaultexpr, exprType(defaultexpr),
6664 targettype, targettypmod,
6665 COERCION_ASSIGNMENT,
6666 COERCE_IMPLICIT_CAST,
6668 if (defaultexpr == NULL)
6670 (errcode(ERRCODE_DATATYPE_MISMATCH),
6671 errmsg("default for column \"%s\" cannot be cast to type %s",
6672 colName, format_type_be(targettype))));
6678 * Find everything that depends on the column (constraints, indexes, etc),
6679 * and record enough information to let us recreate the objects.
6681 * The actual recreation does not happen here, but only after we have
6682 * performed all the individual ALTER TYPE operations. We have to save
6683 * the info before executing ALTER TYPE, though, else the deparser will
6686 * There could be multiple entries for the same object, so we must check
6687 * to ensure we process each one only once. Note: we assume that an index
6688 * that implements a constraint will not show a direct dependency on the
6691 depRel = heap_open(DependRelationId, RowExclusiveLock);
6693 ScanKeyInit(&key[0],
6694 Anum_pg_depend_refclassid,
6695 BTEqualStrategyNumber, F_OIDEQ,
6696 ObjectIdGetDatum(RelationRelationId));
6697 ScanKeyInit(&key[1],
6698 Anum_pg_depend_refobjid,
6699 BTEqualStrategyNumber, F_OIDEQ,
6700 ObjectIdGetDatum(RelationGetRelid(rel)));
6701 ScanKeyInit(&key[2],
6702 Anum_pg_depend_refobjsubid,
6703 BTEqualStrategyNumber, F_INT4EQ,
6704 Int32GetDatum((int32) attnum));
6706 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
6707 SnapshotNow, 3, key);
6709 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
6711 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
6712 ObjectAddress foundObject;
6714 /* We don't expect any PIN dependencies on columns */
6715 if (foundDep->deptype == DEPENDENCY_PIN)
6716 elog(ERROR, "cannot alter type of a pinned column");
6718 foundObject.classId = foundDep->classid;
6719 foundObject.objectId = foundDep->objid;
6720 foundObject.objectSubId = foundDep->objsubid;
6722 switch (getObjectClass(&foundObject))
6726 char relKind = get_rel_relkind(foundObject.objectId);
6728 if (relKind == RELKIND_INDEX)
6730 Assert(foundObject.objectSubId == 0);
6731 if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
6733 tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
6734 foundObject.objectId);
6735 tab->changedIndexDefs = lappend(tab->changedIndexDefs,
6736 pg_get_indexdef_string(foundObject.objectId));
6739 else if (relKind == RELKIND_SEQUENCE)
6742 * This must be a SERIAL column's sequence. We need
6743 * not do anything to it.
6745 Assert(foundObject.objectSubId == 0);
6749 /* Not expecting any other direct dependencies... */
6750 elog(ERROR, "unexpected object depending on column: %s",
6751 getObjectDescription(&foundObject));
6756 case OCLASS_CONSTRAINT:
6757 Assert(foundObject.objectSubId == 0);
6758 if (!list_member_oid(tab->changedConstraintOids,
6759 foundObject.objectId))
6761 char *defstring = pg_get_constraintdef_string(foundObject.objectId);
6764 * Put NORMAL dependencies at the front of the list and
6765 * AUTO dependencies at the back. This makes sure that
6766 * foreign-key constraints depending on this column will
6767 * be dropped before unique or primary-key constraints of
6768 * the column; which we must have because the FK
6769 * constraints depend on the indexes belonging to the
6770 * unique constraints.
6772 if (foundDep->deptype == DEPENDENCY_NORMAL)
6774 tab->changedConstraintOids =
6775 lcons_oid(foundObject.objectId,
6776 tab->changedConstraintOids);
6777 tab->changedConstraintDefs =
6779 tab->changedConstraintDefs);
6783 tab->changedConstraintOids =
6784 lappend_oid(tab->changedConstraintOids,
6785 foundObject.objectId);
6786 tab->changedConstraintDefs =
6787 lappend(tab->changedConstraintDefs,
6793 case OCLASS_REWRITE:
6794 /* XXX someday see if we can cope with revising views */
6796 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6797 errmsg("cannot alter type of a column used by a view or rule"),
6798 errdetail("%s depends on column \"%s\"",
6799 getObjectDescription(&foundObject),
6803 case OCLASS_TRIGGER:
6805 * A trigger can depend on a column because the column is
6806 * specified as an update target, or because the column is
6807 * used in the trigger's WHEN condition. The first case would
6808 * not require any extra work, but the second case would
6809 * require updating the WHEN expression, which will take a
6810 * significant amount of new code. Since we can't easily tell
6811 * which case applies, we punt for both. FIXME someday.
6814 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6815 errmsg("cannot alter type of a column used in a trigger definition"),
6816 errdetail("%s depends on column \"%s\"",
6817 getObjectDescription(&foundObject),
6821 case OCLASS_DEFAULT:
6824 * Ignore the column's default expression, since we will fix
6827 Assert(defaultexpr);
6833 case OCLASS_CONVERSION:
6834 case OCLASS_LANGUAGE:
6835 case OCLASS_LARGEOBJECT:
6836 case OCLASS_OPERATOR:
6837 case OCLASS_OPCLASS:
6838 case OCLASS_OPFAMILY:
6842 case OCLASS_TSPARSER:
6844 case OCLASS_TSTEMPLATE:
6845 case OCLASS_TSCONFIG:
6847 case OCLASS_DATABASE:
6848 case OCLASS_TBLSPACE:
6850 case OCLASS_FOREIGN_SERVER:
6851 case OCLASS_USER_MAPPING:
6853 case OCLASS_EXTENSION:
6856 * We don't expect any of these sorts of objects to depend on
6859 elog(ERROR, "unexpected object depending on column: %s",
6860 getObjectDescription(&foundObject));
6864 elog(ERROR, "unrecognized object class: %u",
6865 foundObject.classId);
6869 systable_endscan(scan);
6872 * Now scan for dependencies of this column on other things. The only
6873 * thing we should find is the dependency on the column datatype, which we
6876 ScanKeyInit(&key[0],
6877 Anum_pg_depend_classid,
6878 BTEqualStrategyNumber, F_OIDEQ,
6879 ObjectIdGetDatum(RelationRelationId));
6880 ScanKeyInit(&key[1],
6881 Anum_pg_depend_objid,
6882 BTEqualStrategyNumber, F_OIDEQ,
6883 ObjectIdGetDatum(RelationGetRelid(rel)));
6884 ScanKeyInit(&key[2],
6885 Anum_pg_depend_objsubid,
6886 BTEqualStrategyNumber, F_INT4EQ,
6887 Int32GetDatum((int32) attnum));
6889 scan = systable_beginscan(depRel, DependDependerIndexId, true,
6890 SnapshotNow, 3, key);
6892 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
6894 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
6896 if (foundDep->deptype != DEPENDENCY_NORMAL)
6897 elog(ERROR, "found unexpected dependency type '%c'",
6899 if (foundDep->refclassid != TypeRelationId ||
6900 foundDep->refobjid != attTup->atttypid)
6901 elog(ERROR, "found unexpected dependency for column");
6903 simple_heap_delete(depRel, &depTup->t_self);
6906 systable_endscan(scan);
6908 heap_close(depRel, RowExclusiveLock);
6911 * Here we go --- change the recorded column type. (Note heapTup is a
6912 * copy of the syscache entry, so okay to scribble on.)
6914 attTup->atttypid = targettype;
6915 attTup->atttypmod = targettypmod;
6916 attTup->attcollation = targetcollid;
6917 attTup->attndims = list_length(typeName->arrayBounds);
6918 attTup->attlen = tform->typlen;
6919 attTup->attbyval = tform->typbyval;
6920 attTup->attalign = tform->typalign;
6921 attTup->attstorage = tform->typstorage;
6923 ReleaseSysCache(typeTuple);
6925 simple_heap_update(attrelation, &heapTup->t_self, heapTup);
6927 /* keep system catalog indexes current */
6928 CatalogUpdateIndexes(attrelation, heapTup);
6930 heap_close(attrelation, RowExclusiveLock);
6932 /* Install dependency on new datatype */
6933 add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
6936 * Drop any pg_statistic entry for the column, since it's now wrong type
6938 RemoveStatistics(RelationGetRelid(rel), attnum);
6941 * Update the default, if present, by brute force --- remove and re-add
6942 * the default. Probably unsafe to take shortcuts, since the new version
6943 * may well have additional dependencies. (It's okay to do this now,
6944 * rather than after other ALTER TYPE commands, since the default won't
6945 * depend on other column types.)
6949 /* Must make new row visible since it will be updated again */
6950 CommandCounterIncrement();
6953 * We use RESTRICT here for safety, but at present we do not expect
6954 * anything to depend on the default.
6956 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true);
6958 StoreAttrDefault(rel, attnum, defaultexpr);
6962 heap_freetuple(heapTup);
6966 * Cleanup after we've finished all the ALTER TYPE operations for a
6967 * particular relation. We have to drop and recreate all the indexes
6968 * and constraints that depend on the altered columns.
6971 ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)
6977 * Re-parse the index and constraint definitions, and attach them to the
6978 * appropriate work queue entries. We do this before dropping because in
6979 * the case of a FOREIGN KEY constraint, we might not yet have exclusive
6980 * lock on the table the constraint is attached to, and we need to get
6981 * that before dropping. It's safe because the parser won't actually look
6982 * at the catalogs to detect the existing entry.
6984 foreach(l, tab->changedIndexDefs)
6985 ATPostAlterTypeParse((char *) lfirst(l), wqueue, lockmode);
6986 foreach(l, tab->changedConstraintDefs)
6987 ATPostAlterTypeParse((char *) lfirst(l), wqueue, lockmode);
6990 * Now we can drop the existing constraints and indexes --- constraints
6991 * first, since some of them might depend on the indexes. In fact, we
6992 * have to delete FOREIGN KEY constraints before UNIQUE constraints, but
6993 * we already ordered the constraint list to ensure that would happen. It
6994 * should be okay to use DROP_RESTRICT here, since nothing else should be
6995 * depending on these objects.
6997 foreach(l, tab->changedConstraintOids)
6999 obj.classId = ConstraintRelationId;
7000 obj.objectId = lfirst_oid(l);
7001 obj.objectSubId = 0;
7002 performDeletion(&obj, DROP_RESTRICT);
7005 foreach(l, tab->changedIndexOids)
7007 obj.classId = RelationRelationId;
7008 obj.objectId = lfirst_oid(l);
7009 obj.objectSubId = 0;
7010 performDeletion(&obj, DROP_RESTRICT);
7014 * The objects will get recreated during subsequent passes over the work
7020 ATPostAlterTypeParse(char *cmd, List **wqueue, LOCKMODE lockmode)
7022 List *raw_parsetree_list;
7023 List *querytree_list;
7024 ListCell *list_item;
7027 * We expect that we will get only ALTER TABLE and CREATE INDEX
7028 * statements. Hence, there is no need to pass them through
7029 * parse_analyze() or the rewriter, but instead we need to pass them
7030 * through parse_utilcmd.c to make them ready for execution.
7032 raw_parsetree_list = raw_parser(cmd);
7033 querytree_list = NIL;
7034 foreach(list_item, raw_parsetree_list)
7036 Node *stmt = (Node *) lfirst(list_item);
7038 if (IsA(stmt, IndexStmt))
7039 querytree_list = lappend(querytree_list,
7040 transformIndexStmt((IndexStmt *) stmt,
7042 else if (IsA(stmt, AlterTableStmt))
7043 querytree_list = list_concat(querytree_list,
7044 transformAlterTableStmt((AlterTableStmt *) stmt,
7047 querytree_list = lappend(querytree_list, stmt);
7051 * Attach each generated command to the proper place in the work queue.
7052 * Note this could result in creation of entirely new work-queue entries.
7054 foreach(list_item, querytree_list)
7056 Node *stm = (Node *) lfirst(list_item);
7058 AlteredTableInfo *tab;
7060 switch (nodeTag(stm))
7064 IndexStmt *stmt = (IndexStmt *) stm;
7065 AlterTableCmd *newcmd;
7067 rel = relation_openrv(stmt->relation, lockmode);
7068 tab = ATGetQueueEntry(wqueue, rel);
7069 newcmd = makeNode(AlterTableCmd);
7070 newcmd->subtype = AT_ReAddIndex;
7071 newcmd->def = (Node *) stmt;
7072 tab->subcmds[AT_PASS_OLD_INDEX] =
7073 lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
7074 relation_close(rel, NoLock);
7077 case T_AlterTableStmt:
7079 AlterTableStmt *stmt = (AlterTableStmt *) stm;
7082 rel = relation_openrv(stmt->relation, lockmode);
7083 tab = ATGetQueueEntry(wqueue, rel);
7084 foreach(lcmd, stmt->cmds)
7086 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
7088 switch (cmd->subtype)
7091 cmd->subtype = AT_ReAddIndex;
7092 tab->subcmds[AT_PASS_OLD_INDEX] =
7093 lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
7095 case AT_AddConstraint:
7096 tab->subcmds[AT_PASS_OLD_CONSTR] =
7097 lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
7100 elog(ERROR, "unexpected statement type: %d",
7101 (int) cmd->subtype);
7104 relation_close(rel, NoLock);
7108 elog(ERROR, "unexpected statement type: %d",
7109 (int) nodeTag(stm));
7118 * recursing is true if we are recursing from a table to its indexes,
7119 * sequences, or toast table. We don't allow the ownership of those things to
7120 * be changed separately from the parent table. Also, we can skip permission
7121 * checks (this is necessary not just an optimization, else we'd fail to
7122 * handle toast tables properly).
7124 * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
7125 * free-standing composite type.
7128 ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
7130 Relation target_rel;
7133 Form_pg_class tuple_class;
7136 * Get exclusive lock till end of transaction on the target table. Use
7137 * relation_open so that we can work on indexes and sequences.
7139 target_rel = relation_open(relationOid, lockmode);
7141 /* Get its pg_class tuple, too */
7142 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
7144 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
7145 if (!HeapTupleIsValid(tuple))
7146 elog(ERROR, "cache lookup failed for relation %u", relationOid);
7147 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
7149 /* Can we change the ownership of this tuple? */
7150 switch (tuple_class->relkind)
7152 case RELKIND_RELATION:
7154 case RELKIND_FOREIGN_TABLE:
7155 /* ok to change owner */
7161 * Because ALTER INDEX OWNER used to be allowed, and in fact
7162 * is generated by old versions of pg_dump, we give a warning
7163 * and do nothing rather than erroring out. Also, to avoid
7164 * unnecessary chatter while restoring those old dumps, say
7165 * nothing at all if the command would be a no-op anyway.
7167 if (tuple_class->relowner != newOwnerId)
7169 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7170 errmsg("cannot change owner of index \"%s\"",
7171 NameStr(tuple_class->relname)),
7172 errhint("Change the ownership of the index's table, instead.")));
7173 /* quick hack to exit via the no-op path */
7174 newOwnerId = tuple_class->relowner;
7177 case RELKIND_SEQUENCE:
7179 tuple_class->relowner != newOwnerId)
7181 /* if it's an owned sequence, disallow changing it by itself */
7185 if (sequenceIsOwned(relationOid, &tableId, &colId))
7187 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7188 errmsg("cannot change owner of sequence \"%s\"",
7189 NameStr(tuple_class->relname)),
7190 errdetail("Sequence \"%s\" is linked to table \"%s\".",
7191 NameStr(tuple_class->relname),
7192 get_rel_name(tableId))));
7195 case RELKIND_COMPOSITE_TYPE:
7199 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7200 errmsg("\"%s\" is a composite type",
7201 NameStr(tuple_class->relname)),
7202 errhint("Use ALTER TYPE instead.")));
7204 case RELKIND_TOASTVALUE:
7210 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7211 errmsg("\"%s\" is not a table, view, sequence, or foreign tabl, or foreign tablee",
7212 NameStr(tuple_class->relname))));
7216 * If the new owner is the same as the existing owner, consider the
7217 * command to have succeeded. This is for dump restoration purposes.
7219 if (tuple_class->relowner != newOwnerId)
7221 Datum repl_val[Natts_pg_class];
7222 bool repl_null[Natts_pg_class];
7223 bool repl_repl[Natts_pg_class];
7229 /* skip permission checks when recursing to index or toast table */
7232 /* Superusers can always do it */
7235 Oid namespaceOid = tuple_class->relnamespace;
7236 AclResult aclresult;
7238 /* Otherwise, must be owner of the existing object */
7239 if (!pg_class_ownercheck(relationOid, GetUserId()))
7240 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
7241 RelationGetRelationName(target_rel));
7243 /* Must be able to become new owner */
7244 check_is_member_of_role(GetUserId(), newOwnerId);
7246 /* New owner must have CREATE privilege on namespace */
7247 aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
7249 if (aclresult != ACLCHECK_OK)
7250 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
7251 get_namespace_name(namespaceOid));
7255 memset(repl_null, false, sizeof(repl_null));
7256 memset(repl_repl, false, sizeof(repl_repl));
7258 repl_repl[Anum_pg_class_relowner - 1] = true;
7259 repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
7262 * Determine the modified ACL for the new owner. This is only
7263 * necessary when the ACL is non-null.
7265 aclDatum = SysCacheGetAttr(RELOID, tuple,
7266 Anum_pg_class_relacl,
7270 newAcl = aclnewowner(DatumGetAclP(aclDatum),
7271 tuple_class->relowner, newOwnerId);
7272 repl_repl[Anum_pg_class_relacl - 1] = true;
7273 repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
7276 newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
7278 simple_heap_update(class_rel, &newtuple->t_self, newtuple);
7279 CatalogUpdateIndexes(class_rel, newtuple);
7281 heap_freetuple(newtuple);
7284 * Update owner dependency reference, if any. A composite type has
7285 * none, because it's tracked for the pg_type entry instead of here;
7286 * indexes and TOAST tables don't have their own entries either.
7288 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
7289 tuple_class->relkind != RELKIND_INDEX &&
7290 tuple_class->relkind != RELKIND_TOASTVALUE)
7291 changeDependencyOnOwner(RelationRelationId, relationOid,
7295 * Also change the ownership of the table's rowtype, if it has one
7297 if (tuple_class->relkind != RELKIND_INDEX)
7298 AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId,
7299 tuple_class->relkind == RELKIND_COMPOSITE_TYPE);
7302 * If we are operating on a table, also change the ownership of any
7303 * indexes and sequences that belong to the table, as well as the
7304 * table's toast table (if it has one)
7306 if (tuple_class->relkind == RELKIND_RELATION ||
7307 tuple_class->relkind == RELKIND_TOASTVALUE)
7309 List *index_oid_list;
7312 /* Find all the indexes belonging to this relation */
7313 index_oid_list = RelationGetIndexList(target_rel);
7315 /* For each index, recursively change its ownership */
7316 foreach(i, index_oid_list)
7317 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
7319 list_free(index_oid_list);
7322 if (tuple_class->relkind == RELKIND_RELATION)
7324 /* If it has a toast table, recurse to change its ownership */
7325 if (tuple_class->reltoastrelid != InvalidOid)
7326 ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
7329 /* If it has dependent sequences, recurse to change them too */
7330 change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
7334 ReleaseSysCache(tuple);
7335 heap_close(class_rel, RowExclusiveLock);
7336 relation_close(target_rel, NoLock);
7340 * change_owner_recurse_to_sequences
7342 * Helper function for ATExecChangeOwner. Examines pg_depend searching
7343 * for sequences that are dependent on serial columns, and changes their
7347 change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
7355 * SERIAL sequences are those having an auto dependency on one of the
7356 * table's columns (we don't care *which* column, exactly).
7358 depRel = heap_open(DependRelationId, AccessShareLock);
7360 ScanKeyInit(&key[0],
7361 Anum_pg_depend_refclassid,
7362 BTEqualStrategyNumber, F_OIDEQ,
7363 ObjectIdGetDatum(RelationRelationId));
7364 ScanKeyInit(&key[1],
7365 Anum_pg_depend_refobjid,
7366 BTEqualStrategyNumber, F_OIDEQ,
7367 ObjectIdGetDatum(relationOid));
7368 /* we leave refobjsubid unspecified */
7370 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
7371 SnapshotNow, 2, key);
7373 while (HeapTupleIsValid(tup = systable_getnext(scan)))
7375 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
7378 /* skip dependencies other than auto dependencies on columns */
7379 if (depForm->refobjsubid == 0 ||
7380 depForm->classid != RelationRelationId ||
7381 depForm->objsubid != 0 ||
7382 depForm->deptype != DEPENDENCY_AUTO)
7385 /* Use relation_open just in case it's an index */
7386 seqRel = relation_open(depForm->objid, lockmode);
7388 /* skip non-sequence relations */
7389 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
7391 /* No need to keep the lock */
7392 relation_close(seqRel, lockmode);
7396 /* We don't need to close the sequence while we alter it. */
7397 ATExecChangeOwner(depForm->objid, newOwnerId, true, lockmode);
7399 /* Now we can close it. Keep the lock till end of transaction. */
7400 relation_close(seqRel, NoLock);
7403 systable_endscan(scan);
7405 relation_close(depRel, AccessShareLock);
7409 * ALTER TABLE CLUSTER ON
7411 * The only thing we have to do is to change the indisclustered bits.
7414 ATExecClusterOn(Relation rel, const char *indexName, LOCKMODE lockmode)
7418 indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
7420 if (!OidIsValid(indexOid))
7422 (errcode(ERRCODE_UNDEFINED_OBJECT),
7423 errmsg("index \"%s\" for table \"%s\" does not exist",
7424 indexName, RelationGetRelationName(rel))));
7426 /* Check index is valid to cluster on */
7427 check_index_is_clusterable(rel, indexOid, false, lockmode);
7429 /* And do the work */
7430 mark_index_clustered(rel, indexOid);
7434 * ALTER TABLE SET WITHOUT CLUSTER
7436 * We have to find any indexes on the table that have indisclustered bit
7437 * set and turn it off.
7440 ATExecDropCluster(Relation rel, LOCKMODE lockmode)
7442 mark_index_clustered(rel, InvalidOid);
7446 * ALTER TABLE SET TABLESPACE
7449 ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, char *tablespacename, LOCKMODE lockmode)
7452 AclResult aclresult;
7454 /* Check that the tablespace exists */
7455 tablespaceId = get_tablespace_oid(tablespacename, false);
7457 /* Check its permissions */
7458 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(), ACL_CREATE);
7459 if (aclresult != ACLCHECK_OK)
7460 aclcheck_error(aclresult, ACL_KIND_TABLESPACE, tablespacename);
7462 /* Save info for Phase 3 to do the real work */
7463 if (OidIsValid(tab->newTableSpace))
7465 (errcode(ERRCODE_SYNTAX_ERROR),
7466 errmsg("cannot have multiple SET TABLESPACE subcommands")));
7467 tab->newTableSpace = tablespaceId;
7471 * ALTER TABLE/INDEX SET (...) or RESET (...)
7474 ATExecSetRelOptions(Relation rel, List *defList, bool isReset, LOCKMODE lockmode)
7483 Datum repl_val[Natts_pg_class];
7484 bool repl_null[Natts_pg_class];
7485 bool repl_repl[Natts_pg_class];
7486 static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
7489 return; /* nothing to do */
7491 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
7493 /* Get the old reloptions */
7494 relid = RelationGetRelid(rel);
7495 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
7496 if (!HeapTupleIsValid(tuple))
7497 elog(ERROR, "cache lookup failed for relation %u", relid);
7499 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions, &isnull);
7501 /* Generate new proposed reloptions (text array) */
7502 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
7503 defList, NULL, validnsps, false, isReset);
7506 switch (rel->rd_rel->relkind)
7508 case RELKIND_RELATION:
7509 case RELKIND_TOASTVALUE:
7510 (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
7513 (void) index_reloptions(rel->rd_am->amoptions, newOptions, true);
7517 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7518 errmsg("\"%s\" is not a table, index, or TOAST table",
7519 RelationGetRelationName(rel))));
7524 * All we need do here is update the pg_class row; the new options will be
7525 * propagated into relcaches during post-commit cache inval.
7527 memset(repl_val, 0, sizeof(repl_val));
7528 memset(repl_null, false, sizeof(repl_null));
7529 memset(repl_repl, false, sizeof(repl_repl));
7531 if (newOptions != (Datum) 0)
7532 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
7534 repl_null[Anum_pg_class_reloptions - 1] = true;
7536 repl_repl[Anum_pg_class_reloptions - 1] = true;
7538 newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
7539 repl_val, repl_null, repl_repl);
7541 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
7543 CatalogUpdateIndexes(pgclass, newtuple);
7545 heap_freetuple(newtuple);
7547 ReleaseSysCache(tuple);
7549 /* repeat the whole exercise for the toast table, if there's one */
7550 if (OidIsValid(rel->rd_rel->reltoastrelid))
7553 Oid toastid = rel->rd_rel->reltoastrelid;
7555 toastrel = heap_open(toastid, lockmode);
7557 /* Get the old reloptions */
7558 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(toastid));
7559 if (!HeapTupleIsValid(tuple))
7560 elog(ERROR, "cache lookup failed for relation %u", toastid);
7562 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions, &isnull);
7564 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
7565 defList, "toast", validnsps, false, isReset);
7567 (void) heap_reloptions(RELKIND_TOASTVALUE, newOptions, true);
7569 memset(repl_val, 0, sizeof(repl_val));
7570 memset(repl_null, false, sizeof(repl_null));
7571 memset(repl_repl, false, sizeof(repl_repl));
7573 if (newOptions != (Datum) 0)
7574 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
7576 repl_null[Anum_pg_class_reloptions - 1] = true;
7578 repl_repl[Anum_pg_class_reloptions - 1] = true;
7580 newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
7581 repl_val, repl_null, repl_repl);
7583 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
7585 CatalogUpdateIndexes(pgclass, newtuple);
7587 heap_freetuple(newtuple);
7589 ReleaseSysCache(tuple);
7591 heap_close(toastrel, NoLock);
7594 heap_close(pgclass, RowExclusiveLock);
7598 * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
7599 * rewriting to be done, so we just want to copy the data as fast as possible.
7602 ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode)
7609 RelFileNode newrnode;
7610 SMgrRelation dstrel;
7613 Form_pg_class rd_rel;
7617 * Need lock here in case we are recursing to toast table or index
7619 rel = relation_open(tableOid, lockmode);
7622 * No work if no change in tablespace.
7624 oldTableSpace = rel->rd_rel->reltablespace;
7625 if (newTableSpace == oldTableSpace ||
7626 (newTableSpace == MyDatabaseTableSpace && oldTableSpace == 0))
7628 relation_close(rel, NoLock);
7633 * We cannot support moving mapped relations into different tablespaces.
7634 * (In particular this eliminates all shared catalogs.)
7636 if (RelationIsMapped(rel))
7638 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7639 errmsg("cannot move system relation \"%s\"",
7640 RelationGetRelationName(rel))));
7642 /* Can't move a non-shared relation into pg_global */
7643 if (newTableSpace == GLOBALTABLESPACE_OID)
7645 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
7646 errmsg("only shared relations can be placed in pg_global tablespace")));
7649 * Don't allow moving temp tables of other backends ... their local buffer
7650 * manager is not going to cope.
7652 if (RELATION_IS_OTHER_TEMP(rel))
7654 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7655 errmsg("cannot move temporary tables of other sessions")));
7657 reltoastrelid = rel->rd_rel->reltoastrelid;
7658 reltoastidxid = rel->rd_rel->reltoastidxid;
7660 /* Get a modifiable copy of the relation's pg_class row */
7661 pg_class = heap_open(RelationRelationId, RowExclusiveLock);
7663 tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(tableOid));
7664 if (!HeapTupleIsValid(tuple))
7665 elog(ERROR, "cache lookup failed for relation %u", tableOid);
7666 rd_rel = (Form_pg_class) GETSTRUCT(tuple);
7669 * Since we copy the file directly without looking at the shared buffers,
7670 * we'd better first flush out any pages of the source relation that are
7671 * in shared buffers. We assume no new changes will be made while we are
7672 * holding exclusive lock on the rel.
7674 FlushRelationBuffers(rel);
7677 * Relfilenodes are not unique across tablespaces, so we need to allocate
7678 * a new one in the new tablespace.
7680 newrelfilenode = GetNewRelFileNode(newTableSpace, NULL,
7681 rel->rd_rel->relpersistence);
7683 /* Open old and new relation */
7684 newrnode = rel->rd_node;
7685 newrnode.relNode = newrelfilenode;
7686 newrnode.spcNode = newTableSpace;
7687 dstrel = smgropen(newrnode, rel->rd_backend);
7689 RelationOpenSmgr(rel);
7692 * Create and copy all forks of the relation, and schedule unlinking of
7693 * old physical files.
7695 * NOTE: any conflict in relfilenode value will be caught in
7696 * RelationCreateStorage().
7698 RelationCreateStorage(newrnode, rel->rd_rel->relpersistence);
7700 /* copy main fork */
7701 copy_relation_data(rel->rd_smgr, dstrel, MAIN_FORKNUM,
7702 rel->rd_rel->relpersistence);
7704 /* copy those extra forks that exist */
7705 for (forkNum = MAIN_FORKNUM + 1; forkNum <= MAX_FORKNUM; forkNum++)
7707 if (smgrexists(rel->rd_smgr, forkNum))
7709 smgrcreate(dstrel, forkNum, false);
7710 copy_relation_data(rel->rd_smgr, dstrel, forkNum,
7711 rel->rd_rel->relpersistence);
7715 /* drop old relation, and close new one */
7716 RelationDropStorage(rel);
7719 /* update the pg_class row */
7720 rd_rel->reltablespace = (newTableSpace == MyDatabaseTableSpace) ? InvalidOid : newTableSpace;
7721 rd_rel->relfilenode = newrelfilenode;
7722 simple_heap_update(pg_class, &tuple->t_self, tuple);
7723 CatalogUpdateIndexes(pg_class, tuple);
7725 heap_freetuple(tuple);
7727 heap_close(pg_class, RowExclusiveLock);
7729 relation_close(rel, NoLock);
7731 /* Make sure the reltablespace change is visible */
7732 CommandCounterIncrement();
7734 /* Move associated toast relation and/or index, too */
7735 if (OidIsValid(reltoastrelid))
7736 ATExecSetTableSpace(reltoastrelid, newTableSpace, lockmode);
7737 if (OidIsValid(reltoastidxid))
7738 ATExecSetTableSpace(reltoastidxid, newTableSpace, lockmode);
7742 * Copy data, block by block
7745 copy_relation_data(SMgrRelation src, SMgrRelation dst,
7746 ForkNumber forkNum, char relpersistence)
7751 BlockNumber nblocks;
7755 * palloc the buffer so that it's MAXALIGN'd. If it were just a local
7756 * char[] array, the compiler might align it on any byte boundary, which
7757 * can seriously hurt transfer speed to and from the kernel; not to
7758 * mention possibly making log_newpage's accesses to the page header fail.
7760 buf = (char *) palloc(BLCKSZ);
7764 * We need to log the copied data in WAL iff WAL archiving/streaming is
7765 * enabled AND it's a permanent relation.
7767 use_wal = XLogIsNeeded() && relpersistence == RELPERSISTENCE_PERMANENT;
7769 nblocks = smgrnblocks(src, forkNum);
7771 for (blkno = 0; blkno < nblocks; blkno++)
7773 /* If we got a cancel signal during the copy of the data, quit */
7774 CHECK_FOR_INTERRUPTS();
7776 smgrread(src, forkNum, blkno, buf);
7780 log_newpage(&dst->smgr_rnode.node, forkNum, blkno, page);
7783 * Now write the page. We say isTemp = true even if it's not a temp
7784 * rel, because there's no need for smgr to schedule an fsync for this
7785 * write; we'll do it ourselves below.
7787 smgrextend(dst, forkNum, blkno, buf, true);
7793 * If the rel isn't temp, we must fsync it down to disk before it's safe
7794 * to commit the transaction. (For a temp rel we don't care since the rel
7795 * will be uninteresting after a crash anyway.)
7797 * It's obvious that we must do this when not WAL-logging the copy. It's
7798 * less obvious that we have to do it even if we did WAL-log the copied
7799 * pages. The reason is that since we're copying outside shared buffers, a
7800 * CHECKPOINT occurring during the copy has no way to flush the previously
7801 * written data to disk (indeed it won't know the new rel even exists). A
7802 * crash later on would replay WAL from the checkpoint, therefore it
7803 * wouldn't replay our earlier WAL entries. If we do not fsync those pages
7804 * here, they might still not be on disk when the crash occurs.
7806 if (relpersistence == RELPERSISTENCE_PERMANENT)
7807 smgrimmedsync(dst, forkNum);
7811 * ALTER TABLE ENABLE/DISABLE TRIGGER
7813 * We just pass this off to trigger.c.
7816 ATExecEnableDisableTrigger(Relation rel, char *trigname,
7817 char fires_when, bool skip_system, LOCKMODE lockmode)
7819 EnableDisableTrigger(rel, trigname, fires_when, skip_system);
7823 * ALTER TABLE ENABLE/DISABLE RULE
7825 * We just pass this off to rewriteDefine.c.
7828 ATExecEnableDisableRule(Relation rel, char *trigname,
7829 char fires_when, LOCKMODE lockmode)
7831 EnableDisableRule(rel, trigname, fires_when);
7835 * ALTER TABLE INHERIT
7837 * Add a parent to the child's parents. This verifies that all the columns and
7838 * check constraints of the parent appear in the child and that they have the
7839 * same data types and expressions.
7842 ATPrepAddInherit(Relation child_rel)
7844 if (child_rel->rd_rel->reloftype)
7846 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7847 errmsg("cannot change inheritance of typed table")));
7851 ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode)
7853 Relation parent_rel,
7857 HeapTuple inheritsTuple;
7862 * AccessShareLock on the parent is what's obtained during normal CREATE
7863 * TABLE ... INHERITS ..., so should be enough here.
7865 parent_rel = heap_openrv(parent, AccessShareLock);
7868 * Must be owner of both parent and child -- child was checked by
7869 * ATSimplePermissions call in ATPrepCmd
7871 ATSimplePermissions(parent_rel, ATT_TABLE);
7873 /* Permanent rels cannot inherit from temporary ones */
7874 if (RelationUsesTempNamespace(parent_rel)
7875 && !RelationUsesTempNamespace(child_rel))
7877 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7878 errmsg("cannot inherit from temporary relation \"%s\"",
7879 RelationGetRelationName(parent_rel))));
7882 * Check for duplicates in the list of parents, and determine the highest
7883 * inhseqno already present; we'll use the next one for the new parent.
7884 * (Note: get RowExclusiveLock because we will write pg_inherits below.)
7886 * Note: we do not reject the case where the child already inherits from
7887 * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
7889 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
7891 Anum_pg_inherits_inhrelid,
7892 BTEqualStrategyNumber, F_OIDEQ,
7893 ObjectIdGetDatum(RelationGetRelid(child_rel)));
7894 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
7895 true, SnapshotNow, 1, &key);
7897 /* inhseqno sequences start at 1 */
7899 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
7901 Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
7903 if (inh->inhparent == RelationGetRelid(parent_rel))
7905 (errcode(ERRCODE_DUPLICATE_TABLE),
7906 errmsg("relation \"%s\" would be inherited from more than once",
7907 RelationGetRelationName(parent_rel))));
7908 if (inh->inhseqno > inhseqno)
7909 inhseqno = inh->inhseqno;
7911 systable_endscan(scan);
7914 * Prevent circularity by seeing if proposed parent inherits from child.
7915 * (In particular, this disallows making a rel inherit from itself.)
7917 * This is not completely bulletproof because of race conditions: in
7918 * multi-level inheritance trees, someone else could concurrently be
7919 * making another inheritance link that closes the loop but does not join
7920 * either of the rels we have locked. Preventing that seems to require
7921 * exclusive locks on the entire inheritance tree, which is a cure worse
7922 * than the disease. find_all_inheritors() will cope with circularity
7923 * anyway, so don't sweat it too much.
7925 * We use weakest lock we can on child's children, namely AccessShareLock.
7927 children = find_all_inheritors(RelationGetRelid(child_rel),
7928 AccessShareLock, NULL);
7930 if (list_member_oid(children, RelationGetRelid(parent_rel)))
7932 (errcode(ERRCODE_DUPLICATE_TABLE),
7933 errmsg("circular inheritance not allowed"),
7934 errdetail("\"%s\" is already a child of \"%s\".",
7936 RelationGetRelationName(child_rel))));
7938 /* If parent has OIDs then child must have OIDs */
7939 if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
7941 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7942 errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
7943 RelationGetRelationName(child_rel),
7944 RelationGetRelationName(parent_rel))));
7946 /* Match up the columns and bump attinhcount as needed */
7947 MergeAttributesIntoExisting(child_rel, parent_rel);
7949 /* Match up the constraints and bump coninhcount as needed */
7950 MergeConstraintsIntoExisting(child_rel, parent_rel);
7953 * OK, it looks valid. Make the catalog entries that show inheritance.
7955 StoreCatalogInheritance1(RelationGetRelid(child_rel),
7956 RelationGetRelid(parent_rel),
7960 /* Now we're done with pg_inherits */
7961 heap_close(catalogRelation, RowExclusiveLock);
7963 /* keep our lock on the parent relation until commit */
7964 heap_close(parent_rel, NoLock);
7968 * Obtain the source-text form of the constraint expression for a check
7969 * constraint, given its pg_constraint tuple
7972 decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
7974 Form_pg_constraint con;
7979 con = (Form_pg_constraint) GETSTRUCT(contup);
7980 attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
7982 elog(ERROR, "null conbin for constraint %u", HeapTupleGetOid(contup));
7984 expr = DirectFunctionCall2(pg_get_expr, attr,
7985 ObjectIdGetDatum(con->conrelid));
7986 return TextDatumGetCString(expr);
7990 * Determine whether two check constraints are functionally equivalent
7992 * The test we apply is to see whether they reverse-compile to the same
7993 * source string. This insulates us from issues like whether attributes
7994 * have the same physical column numbers in parent and child relations.
7997 constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
7999 Form_pg_constraint acon = (Form_pg_constraint) GETSTRUCT(a);
8000 Form_pg_constraint bcon = (Form_pg_constraint) GETSTRUCT(b);
8002 if (acon->condeferrable != bcon->condeferrable ||
8003 acon->condeferred != bcon->condeferred ||
8004 strcmp(decompile_conbin(a, tupleDesc),
8005 decompile_conbin(b, tupleDesc)) != 0)
8012 * Check columns in child table match up with columns in parent, and increment
8013 * their attinhcount.
8015 * Called by ATExecAddInherit
8017 * Currently all parent columns must be found in child. Missing columns are an
8018 * error. One day we might consider creating new columns like CREATE TABLE
8019 * does. However, that is widely unpopular --- in the common use case of
8020 * partitioned tables it's a foot-gun.
8022 * The data type must match exactly. If the parent column is NOT NULL then
8023 * the child must be as well. Defaults are not compared, however.
8026 MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel)
8029 AttrNumber parent_attno;
8031 TupleDesc tupleDesc;
8032 TupleConstr *constr;
8035 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
8037 tupleDesc = RelationGetDescr(parent_rel);
8038 parent_natts = tupleDesc->natts;
8039 constr = tupleDesc->constr;
8041 for (parent_attno = 1; parent_attno <= parent_natts; parent_attno++)
8043 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
8044 char *attributeName = NameStr(attribute->attname);
8046 /* Ignore dropped columns in the parent. */
8047 if (attribute->attisdropped)
8050 /* Find same column in child (matching on column name). */
8051 tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel),
8053 if (HeapTupleIsValid(tuple))
8055 /* Check they are same type and typmod */
8056 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
8058 if (attribute->atttypid != childatt->atttypid ||
8059 attribute->atttypmod != childatt->atttypmod)
8061 (errcode(ERRCODE_DATATYPE_MISMATCH),
8062 errmsg("child table \"%s\" has different type for column \"%s\"",
8063 RelationGetRelationName(child_rel),
8066 if (attribute->attnotnull && !childatt->attnotnull)
8068 (errcode(ERRCODE_DATATYPE_MISMATCH),
8069 errmsg("column \"%s\" in child table must be marked NOT NULL",
8073 * OK, bump the child column's inheritance count. (If we fail
8074 * later on, this change will just roll back.)
8076 childatt->attinhcount++;
8077 simple_heap_update(attrrel, &tuple->t_self, tuple);
8078 CatalogUpdateIndexes(attrrel, tuple);
8079 heap_freetuple(tuple);
8084 (errcode(ERRCODE_DATATYPE_MISMATCH),
8085 errmsg("child table is missing column \"%s\"",
8090 heap_close(attrrel, RowExclusiveLock);
8094 * Check constraints in child table match up with constraints in parent,
8095 * and increment their coninhcount.
8097 * Called by ATExecAddInherit
8099 * Currently all constraints in parent must be present in the child. One day we
8100 * may consider adding new constraints like CREATE TABLE does. We may also want
8101 * to allow an optional flag on parent table constraints indicating they are
8102 * intended to ONLY apply to the master table, not to the children. That would
8103 * make it possible to ensure no records are mistakenly inserted into the
8104 * master in partitioned tables rather than the appropriate child.
8106 * XXX This is O(N^2) which may be an issue with tables with hundreds of
8107 * constraints. As long as tables have more like 10 constraints it shouldn't be
8108 * a problem though. Even 100 constraints ought not be the end of the world.
8111 MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
8113 Relation catalog_relation;
8114 TupleDesc tuple_desc;
8115 SysScanDesc parent_scan;
8116 ScanKeyData parent_key;
8117 HeapTuple parent_tuple;
8119 catalog_relation = heap_open(ConstraintRelationId, RowExclusiveLock);
8120 tuple_desc = RelationGetDescr(catalog_relation);
8122 /* Outer loop scans through the parent's constraint definitions */
8123 ScanKeyInit(&parent_key,
8124 Anum_pg_constraint_conrelid,
8125 BTEqualStrategyNumber, F_OIDEQ,
8126 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
8127 parent_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
8128 true, SnapshotNow, 1, &parent_key);
8130 while (HeapTupleIsValid(parent_tuple = systable_getnext(parent_scan)))
8132 Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(parent_tuple);
8133 SysScanDesc child_scan;
8134 ScanKeyData child_key;
8135 HeapTuple child_tuple;
8138 if (parent_con->contype != CONSTRAINT_CHECK)
8141 /* Search for a child constraint matching this one */
8142 ScanKeyInit(&child_key,
8143 Anum_pg_constraint_conrelid,
8144 BTEqualStrategyNumber, F_OIDEQ,
8145 ObjectIdGetDatum(RelationGetRelid(child_rel)));
8146 child_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
8147 true, SnapshotNow, 1, &child_key);
8149 while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
8151 Form_pg_constraint child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
8152 HeapTuple child_copy;
8154 if (child_con->contype != CONSTRAINT_CHECK)
8157 if (strcmp(NameStr(parent_con->conname),
8158 NameStr(child_con->conname)) != 0)
8161 if (!constraints_equivalent(parent_tuple, child_tuple, tuple_desc))
8163 (errcode(ERRCODE_DATATYPE_MISMATCH),
8164 errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
8165 RelationGetRelationName(child_rel),
8166 NameStr(parent_con->conname))));
8169 * OK, bump the child constraint's inheritance count. (If we fail
8170 * later on, this change will just roll back.)
8172 child_copy = heap_copytuple(child_tuple);
8173 child_con = (Form_pg_constraint) GETSTRUCT(child_copy);
8174 child_con->coninhcount++;
8175 simple_heap_update(catalog_relation, &child_copy->t_self, child_copy);
8176 CatalogUpdateIndexes(catalog_relation, child_copy);
8177 heap_freetuple(child_copy);
8183 systable_endscan(child_scan);
8187 (errcode(ERRCODE_DATATYPE_MISMATCH),
8188 errmsg("child table is missing constraint \"%s\"",
8189 NameStr(parent_con->conname))));
8192 systable_endscan(parent_scan);
8193 heap_close(catalog_relation, RowExclusiveLock);
8197 * ALTER TABLE NO INHERIT
8199 * Drop a parent from the child's parents. This just adjusts the attinhcount
8200 * and attislocal of the columns and removes the pg_inherit and pg_depend
8203 * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
8204 * up attislocal stays true, which means if a child is ever removed from a
8205 * parent then its columns will never be automatically dropped which may
8206 * surprise. But at least we'll never surprise by dropping columns someone
8207 * isn't expecting to be dropped which would actually mean data loss.
8209 * coninhcount and conislocal for inherited constraints are adjusted in
8210 * exactly the same way.
8213 ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode)
8215 Relation parent_rel;
8216 Relation catalogRelation;
8219 HeapTuple inheritsTuple,
8227 * AccessShareLock on the parent is probably enough, seeing that DROP
8228 * TABLE doesn't lock parent tables at all. We need some lock since we'll
8229 * be inspecting the parent's schema.
8231 parent_rel = heap_openrv(parent, AccessShareLock);
8234 * We don't bother to check ownership of the parent table --- ownership of
8235 * the child is presumed enough rights.
8239 * Find and destroy the pg_inherits entry linking the two, or error out if
8242 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
8243 ScanKeyInit(&key[0],
8244 Anum_pg_inherits_inhrelid,
8245 BTEqualStrategyNumber, F_OIDEQ,
8246 ObjectIdGetDatum(RelationGetRelid(rel)));
8247 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
8248 true, SnapshotNow, 1, key);
8250 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
8254 inhparent = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
8255 if (inhparent == RelationGetRelid(parent_rel))
8257 simple_heap_delete(catalogRelation, &inheritsTuple->t_self);
8263 systable_endscan(scan);
8264 heap_close(catalogRelation, RowExclusiveLock);
8268 (errcode(ERRCODE_UNDEFINED_TABLE),
8269 errmsg("relation \"%s\" is not a parent of relation \"%s\"",
8270 RelationGetRelationName(parent_rel),
8271 RelationGetRelationName(rel))));
8274 * Search through child columns looking for ones matching parent rel
8276 catalogRelation = heap_open(AttributeRelationId, RowExclusiveLock);
8277 ScanKeyInit(&key[0],
8278 Anum_pg_attribute_attrelid,
8279 BTEqualStrategyNumber, F_OIDEQ,
8280 ObjectIdGetDatum(RelationGetRelid(rel)));
8281 scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
8282 true, SnapshotNow, 1, key);
8283 while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
8285 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
8287 /* Ignore if dropped or not inherited */
8288 if (att->attisdropped)
8290 if (att->attinhcount <= 0)
8293 if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
8294 NameStr(att->attname)))
8296 /* Decrement inhcount and possibly set islocal to true */
8297 HeapTuple copyTuple = heap_copytuple(attributeTuple);
8298 Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
8300 copy_att->attinhcount--;
8301 if (copy_att->attinhcount == 0)
8302 copy_att->attislocal = true;
8304 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
8305 CatalogUpdateIndexes(catalogRelation, copyTuple);
8306 heap_freetuple(copyTuple);
8309 systable_endscan(scan);
8310 heap_close(catalogRelation, RowExclusiveLock);
8313 * Likewise, find inherited check constraints and disinherit them. To do
8314 * this, we first need a list of the names of the parent's check
8315 * constraints. (We cheat a bit by only checking for name matches,
8316 * assuming that the expressions will match.)
8318 catalogRelation = heap_open(ConstraintRelationId, RowExclusiveLock);
8319 ScanKeyInit(&key[0],
8320 Anum_pg_constraint_conrelid,
8321 BTEqualStrategyNumber, F_OIDEQ,
8322 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
8323 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
8324 true, SnapshotNow, 1, key);
8328 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
8330 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
8332 if (con->contype == CONSTRAINT_CHECK)
8333 connames = lappend(connames, pstrdup(NameStr(con->conname)));
8336 systable_endscan(scan);
8338 /* Now scan the child's constraints */
8339 ScanKeyInit(&key[0],
8340 Anum_pg_constraint_conrelid,
8341 BTEqualStrategyNumber, F_OIDEQ,
8342 ObjectIdGetDatum(RelationGetRelid(rel)));
8343 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
8344 true, SnapshotNow, 1, key);
8346 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
8348 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
8352 if (con->contype != CONSTRAINT_CHECK)
8356 foreach(lc, connames)
8358 if (strcmp(NameStr(con->conname), (char *) lfirst(lc)) == 0)
8367 /* Decrement inhcount and possibly set islocal to true */
8368 HeapTuple copyTuple = heap_copytuple(constraintTuple);
8369 Form_pg_constraint copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
8371 if (copy_con->coninhcount <= 0) /* shouldn't happen */
8372 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
8373 RelationGetRelid(rel), NameStr(copy_con->conname));
8375 copy_con->coninhcount--;
8376 if (copy_con->coninhcount == 0)
8377 copy_con->conislocal = true;
8379 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
8380 CatalogUpdateIndexes(catalogRelation, copyTuple);
8381 heap_freetuple(copyTuple);
8385 systable_endscan(scan);
8386 heap_close(catalogRelation, RowExclusiveLock);
8389 * Drop the dependency
8391 * There's no convenient way to do this, so go trawling through pg_depend
8393 catalogRelation = heap_open(DependRelationId, RowExclusiveLock);
8395 ScanKeyInit(&key[0],
8396 Anum_pg_depend_classid,
8397 BTEqualStrategyNumber, F_OIDEQ,
8398 ObjectIdGetDatum(RelationRelationId));
8399 ScanKeyInit(&key[1],
8400 Anum_pg_depend_objid,
8401 BTEqualStrategyNumber, F_OIDEQ,
8402 ObjectIdGetDatum(RelationGetRelid(rel)));
8403 ScanKeyInit(&key[2],
8404 Anum_pg_depend_objsubid,
8405 BTEqualStrategyNumber, F_INT4EQ,
8408 scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
8409 SnapshotNow, 3, key);
8411 while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
8413 Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
8415 if (dep->refclassid == RelationRelationId &&
8416 dep->refobjid == RelationGetRelid(parent_rel) &&
8417 dep->refobjsubid == 0 &&
8418 dep->deptype == DEPENDENCY_NORMAL)
8419 simple_heap_delete(catalogRelation, &depTuple->t_self);
8422 systable_endscan(scan);
8423 heap_close(catalogRelation, RowExclusiveLock);
8425 /* keep our lock on the parent relation until commit */
8426 heap_close(parent_rel, NoLock);
8430 * ALTER FOREIGN TABLE <name> OPTIONS (...)
8433 ATExecGenericOptions(Relation rel, List *options)
8436 ForeignServer *server;
8437 ForeignDataWrapper *fdw;
8440 Datum repl_val[Natts_pg_foreign_table];
8441 bool repl_null[Natts_pg_foreign_table];
8442 bool repl_repl[Natts_pg_foreign_table];
8444 Form_pg_foreign_table tableform;
8449 ftrel = heap_open(ForeignTableRelationId, RowExclusiveLock);
8451 tuple = SearchSysCacheCopy1(FOREIGNTABLEREL, rel->rd_id);
8452 if (!HeapTupleIsValid(tuple))
8454 (errcode(ERRCODE_UNDEFINED_OBJECT),
8455 errmsg("foreign table \"%s\" does not exist",
8456 RelationGetRelationName(rel))));
8457 tableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
8458 server = GetForeignServer(tableform->ftserver);
8459 fdw = GetForeignDataWrapper(server->fdwid);
8461 memset(repl_val, 0, sizeof(repl_val));
8462 memset(repl_null, false, sizeof(repl_null));
8463 memset(repl_repl, false, sizeof(repl_repl));
8465 /* Extract the current options */
8466 datum = SysCacheGetAttr(FOREIGNTABLEREL,
8468 Anum_pg_foreign_table_ftoptions,
8471 datum = PointerGetDatum(NULL);
8473 /* Transform the options */
8474 datum = transformGenericOptions(ForeignTableRelationId,
8479 if (PointerIsValid(DatumGetPointer(datum)))
8480 repl_val[Anum_pg_foreign_table_ftoptions - 1] = datum;
8482 repl_null[Anum_pg_foreign_table_ftoptions - 1] = true;
8484 repl_repl[Anum_pg_foreign_table_ftoptions - 1] = true;
8486 /* Everything looks good - update the tuple */
8488 tuple = heap_modify_tuple(tuple, RelationGetDescr(ftrel),
8489 repl_val, repl_null, repl_repl);
8491 simple_heap_update(ftrel, &tuple->t_self, tuple);
8492 CatalogUpdateIndexes(ftrel, tuple);
8494 heap_close(ftrel, RowExclusiveLock);
8496 heap_freetuple(tuple);
8501 * Execute ALTER TABLE SET SCHEMA
8503 * Note: caller must have checked ownership of the relation already
8506 AlterTableNamespace(RangeVar *relation, const char *newschema,
8507 ObjectType stmttype, LOCKMODE lockmode)
8515 rel = relation_openrv(relation, lockmode);
8517 relid = RelationGetRelid(rel);
8518 oldNspOid = RelationGetNamespace(rel);
8520 /* Check relation type against type specified in the ALTER command */
8526 * For mostly-historical reasons, we allow ALTER TABLE to apply to
8527 * all relation types.
8531 case OBJECT_SEQUENCE:
8532 if (rel->rd_rel->relkind != RELKIND_SEQUENCE)
8534 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8535 errmsg("\"%s\" is not a sequence",
8536 RelationGetRelationName(rel))));
8540 if (rel->rd_rel->relkind != RELKIND_VIEW)
8542 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8543 errmsg("\"%s\" is not a view",
8544 RelationGetRelationName(rel))));
8547 case OBJECT_FOREIGN_TABLE:
8548 if (rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
8550 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8551 errmsg("\"%s\" is not a foreign table",
8552 RelationGetRelationName(rel))));
8556 elog(ERROR, "unrecognized object type: %d", (int) stmttype);
8559 /* Can we change the schema of this tuple? */
8560 switch (rel->rd_rel->relkind)
8562 case RELKIND_RELATION:
8564 case RELKIND_FOREIGN_TABLE:
8565 /* ok to change schema */
8567 case RELKIND_SEQUENCE:
8569 /* if it's an owned sequence, disallow moving it by itself */
8573 if (sequenceIsOwned(relid, &tableId, &colId))
8575 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8576 errmsg("cannot move an owned sequence into another schema"),
8577 errdetail("Sequence \"%s\" is linked to table \"%s\".",
8578 RelationGetRelationName(rel),
8579 get_rel_name(tableId))));
8582 case RELKIND_COMPOSITE_TYPE:
8584 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8585 errmsg("\"%s\" is a composite type",
8586 RelationGetRelationName(rel)),
8587 errhint("Use ALTER TYPE instead.")));
8590 case RELKIND_TOASTVALUE:
8594 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8595 errmsg("\"%s\" is not a table, view, sequence, or foreign table",
8596 RelationGetRelationName(rel))));
8599 /* get schema OID and check its permissions */
8600 nspOid = LookupCreationNamespace(newschema);
8602 /* common checks on switching namespaces */
8603 CheckSetNamespace(oldNspOid, nspOid, RelationRelationId, relid);
8605 /* OK, modify the pg_class row and pg_depend entry */
8606 classRel = heap_open(RelationRelationId, RowExclusiveLock);
8608 AlterRelationNamespaceInternal(classRel, relid, oldNspOid, nspOid, true);
8610 /* Fix the table's rowtype too */
8611 AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid, false, false);
8613 /* Fix other dependent stuff */
8614 if (rel->rd_rel->relkind == RELKIND_RELATION)
8616 AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid);
8617 AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid, newschema, lockmode);
8618 AlterConstraintNamespaces(relid, oldNspOid, nspOid, false);
8621 heap_close(classRel, RowExclusiveLock);
8623 /* close rel, but keep lock until commit */
8624 relation_close(rel, NoLock);
8628 * The guts of relocating a relation to another namespace: fix the pg_class
8629 * entry, and the pg_depend entry if any. Caller must already have
8630 * opened and write-locked pg_class.
8633 AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
8634 Oid oldNspOid, Oid newNspOid,
8635 bool hasDependEntry)
8638 Form_pg_class classForm;
8640 classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
8641 if (!HeapTupleIsValid(classTup))
8642 elog(ERROR, "cache lookup failed for relation %u", relOid);
8643 classForm = (Form_pg_class) GETSTRUCT(classTup);
8645 Assert(classForm->relnamespace == oldNspOid);
8647 /* check for duplicate name (more friendly than unique-index failure) */
8648 if (get_relname_relid(NameStr(classForm->relname),
8649 newNspOid) != InvalidOid)
8651 (errcode(ERRCODE_DUPLICATE_TABLE),
8652 errmsg("relation \"%s\" already exists in schema \"%s\"",
8653 NameStr(classForm->relname),
8654 get_namespace_name(newNspOid))));
8656 /* classTup is a copy, so OK to scribble on */
8657 classForm->relnamespace = newNspOid;
8659 simple_heap_update(classRel, &classTup->t_self, classTup);
8660 CatalogUpdateIndexes(classRel, classTup);
8662 /* Update dependency on schema if caller said so */
8663 if (hasDependEntry &&
8664 changeDependencyFor(RelationRelationId, relOid,
8665 NamespaceRelationId, oldNspOid, newNspOid) != 1)
8666 elog(ERROR, "failed to change schema dependency for relation \"%s\"",
8667 NameStr(classForm->relname));
8669 heap_freetuple(classTup);
8673 * Move all indexes for the specified relation to another namespace.
8675 * Note: we assume adequate permission checking was done by the caller,
8676 * and that the caller has a suitable lock on the owning relation.
8679 AlterIndexNamespaces(Relation classRel, Relation rel,
8680 Oid oldNspOid, Oid newNspOid)
8685 indexList = RelationGetIndexList(rel);
8687 foreach(l, indexList)
8689 Oid indexOid = lfirst_oid(l);
8692 * Note: currently, the index will not have its own dependency on the
8693 * namespace, so we don't need to do changeDependencyFor(). There's no
8694 * rowtype in pg_type, either.
8696 AlterRelationNamespaceInternal(classRel, indexOid,
8697 oldNspOid, newNspOid,
8701 list_free(indexList);
8705 * Move all SERIAL-column sequences of the specified relation to another
8708 * Note: we assume adequate permission checking was done by the caller,
8709 * and that the caller has a suitable lock on the owning relation.
8712 AlterSeqNamespaces(Relation classRel, Relation rel,
8713 Oid oldNspOid, Oid newNspOid, const char *newNspName, LOCKMODE lockmode)
8721 * SERIAL sequences are those having an auto dependency on one of the
8722 * table's columns (we don't care *which* column, exactly).
8724 depRel = heap_open(DependRelationId, AccessShareLock);
8726 ScanKeyInit(&key[0],
8727 Anum_pg_depend_refclassid,
8728 BTEqualStrategyNumber, F_OIDEQ,
8729 ObjectIdGetDatum(RelationRelationId));
8730 ScanKeyInit(&key[1],
8731 Anum_pg_depend_refobjid,
8732 BTEqualStrategyNumber, F_OIDEQ,
8733 ObjectIdGetDatum(RelationGetRelid(rel)));
8734 /* we leave refobjsubid unspecified */
8736 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
8737 SnapshotNow, 2, key);
8739 while (HeapTupleIsValid(tup = systable_getnext(scan)))
8741 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
8744 /* skip dependencies other than auto dependencies on columns */
8745 if (depForm->refobjsubid == 0 ||
8746 depForm->classid != RelationRelationId ||
8747 depForm->objsubid != 0 ||
8748 depForm->deptype != DEPENDENCY_AUTO)
8751 /* Use relation_open just in case it's an index */
8752 seqRel = relation_open(depForm->objid, lockmode);
8754 /* skip non-sequence relations */
8755 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
8757 /* No need to keep the lock */
8758 relation_close(seqRel, lockmode);
8762 /* Fix the pg_class and pg_depend entries */
8763 AlterRelationNamespaceInternal(classRel, depForm->objid,
8764 oldNspOid, newNspOid,
8768 * Sequences have entries in pg_type. We need to be careful to move
8769 * them to the new namespace, too.
8771 AlterTypeNamespaceInternal(RelationGetForm(seqRel)->reltype,
8772 newNspOid, false, false);
8774 /* Now we can close it. Keep the lock till end of transaction. */
8775 relation_close(seqRel, NoLock);
8778 systable_endscan(scan);
8780 relation_close(depRel, AccessShareLock);
8785 * This code supports
8786 * CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
8788 * Because we only support this for TEMP tables, it's sufficient to remember
8789 * the state in a backend-local data structure.
8793 * Register a newly-created relation's ON COMMIT action.
8796 register_on_commit_action(Oid relid, OnCommitAction action)
8799 MemoryContext oldcxt;
8802 * We needn't bother registering the relation unless there is an ON COMMIT
8803 * action we need to take.
8805 if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
8808 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
8810 oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
8812 oc->oncommit = action;
8813 oc->creating_subid = GetCurrentSubTransactionId();
8814 oc->deleting_subid = InvalidSubTransactionId;
8816 on_commits = lcons(oc, on_commits);
8818 MemoryContextSwitchTo(oldcxt);
8822 * Unregister any ON COMMIT action when a relation is deleted.
8824 * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
8827 remove_on_commit_action(Oid relid)
8831 foreach(l, on_commits)
8833 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
8835 if (oc->relid == relid)
8837 oc->deleting_subid = GetCurrentSubTransactionId();
8844 * Perform ON COMMIT actions.
8846 * This is invoked just before actually committing, since it's possible
8847 * to encounter errors.
8850 PreCommit_on_commit_actions(void)
8853 List *oids_to_truncate = NIL;
8855 foreach(l, on_commits)
8857 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
8859 /* Ignore entry if already dropped in this xact */
8860 if (oc->deleting_subid != InvalidSubTransactionId)
8863 switch (oc->oncommit)
8866 case ONCOMMIT_PRESERVE_ROWS:
8867 /* Do nothing (there shouldn't be such entries, actually) */
8869 case ONCOMMIT_DELETE_ROWS:
8870 oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
8874 ObjectAddress object;
8876 object.classId = RelationRelationId;
8877 object.objectId = oc->relid;
8878 object.objectSubId = 0;
8879 performDeletion(&object, DROP_CASCADE);
8882 * Note that table deletion will call
8883 * remove_on_commit_action, so the entry should get marked
8886 Assert(oc->deleting_subid != InvalidSubTransactionId);
8891 if (oids_to_truncate != NIL)
8893 heap_truncate(oids_to_truncate);
8894 CommandCounterIncrement(); /* XXX needed? */
8899 * Post-commit or post-abort cleanup for ON COMMIT management.
8901 * All we do here is remove no-longer-needed OnCommitItem entries.
8903 * During commit, remove entries that were deleted during this transaction;
8904 * during abort, remove those created during this transaction.
8907 AtEOXact_on_commit_actions(bool isCommit)
8910 ListCell *prev_item;
8913 cur_item = list_head(on_commits);
8915 while (cur_item != NULL)
8917 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
8919 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
8920 oc->creating_subid != InvalidSubTransactionId)
8922 /* cur_item must be removed */
8923 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
8926 cur_item = lnext(prev_item);
8928 cur_item = list_head(on_commits);
8932 /* cur_item must be preserved */
8933 oc->creating_subid = InvalidSubTransactionId;
8934 oc->deleting_subid = InvalidSubTransactionId;
8935 prev_item = cur_item;
8936 cur_item = lnext(prev_item);
8942 * Post-subcommit or post-subabort cleanup for ON COMMIT management.
8944 * During subabort, we can immediately remove entries created during this
8945 * subtransaction. During subcommit, just relabel entries marked during
8946 * this subtransaction as being the parent's responsibility.
8949 AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
8950 SubTransactionId parentSubid)
8953 ListCell *prev_item;
8956 cur_item = list_head(on_commits);
8958 while (cur_item != NULL)
8960 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
8962 if (!isCommit && oc->creating_subid == mySubid)
8964 /* cur_item must be removed */
8965 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
8968 cur_item = lnext(prev_item);
8970 cur_item = list_head(on_commits);
8974 /* cur_item must be preserved */
8975 if (oc->creating_subid == mySubid)
8976 oc->creating_subid = parentSubid;
8977 if (oc->deleting_subid == mySubid)
8978 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
8979 prev_item = cur_item;
8980 cur_item = lnext(prev_item);