1 /*-------------------------------------------------------------------------
4 * Commands for creating and altering table structures and settings
6 * Portions Copyright (c) 1996-2015, 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/multixact.h"
20 #include "access/reloptions.h"
21 #include "access/relscan.h"
22 #include "access/sysattr.h"
23 #include "access/xact.h"
24 #include "access/xlog.h"
25 #include "catalog/catalog.h"
26 #include "catalog/dependency.h"
27 #include "catalog/heap.h"
28 #include "catalog/index.h"
29 #include "catalog/indexing.h"
30 #include "catalog/namespace.h"
31 #include "catalog/objectaccess.h"
32 #include "catalog/pg_collation.h"
33 #include "catalog/pg_constraint.h"
34 #include "catalog/pg_depend.h"
35 #include "catalog/pg_foreign_table.h"
36 #include "catalog/pg_inherits.h"
37 #include "catalog/pg_inherits_fn.h"
38 #include "catalog/pg_namespace.h"
39 #include "catalog/pg_opclass.h"
40 #include "catalog/pg_tablespace.h"
41 #include "catalog/pg_trigger.h"
42 #include "catalog/pg_type.h"
43 #include "catalog/pg_type_fn.h"
44 #include "catalog/storage.h"
45 #include "catalog/toasting.h"
46 #include "commands/cluster.h"
47 #include "commands/comment.h"
48 #include "commands/defrem.h"
49 #include "commands/event_trigger.h"
50 #include "commands/policy.h"
51 #include "commands/sequence.h"
52 #include "commands/tablecmds.h"
53 #include "commands/tablespace.h"
54 #include "commands/trigger.h"
55 #include "commands/typecmds.h"
56 #include "commands/user.h"
57 #include "executor/executor.h"
58 #include "foreign/foreign.h"
59 #include "miscadmin.h"
60 #include "nodes/makefuncs.h"
61 #include "nodes/nodeFuncs.h"
62 #include "nodes/parsenodes.h"
63 #include "optimizer/clauses.h"
64 #include "optimizer/planner.h"
65 #include "parser/parse_clause.h"
66 #include "parser/parse_coerce.h"
67 #include "parser/parse_collate.h"
68 #include "parser/parse_expr.h"
69 #include "parser/parse_oper.h"
70 #include "parser/parse_relation.h"
71 #include "parser/parse_type.h"
72 #include "parser/parse_utilcmd.h"
73 #include "parser/parser.h"
75 #include "rewrite/rewriteDefine.h"
76 #include "rewrite/rewriteHandler.h"
77 #include "rewrite/rewriteManip.h"
78 #include "storage/bufmgr.h"
79 #include "storage/lmgr.h"
80 #include "storage/lock.h"
81 #include "storage/predicate.h"
82 #include "storage/smgr.h"
83 #include "utils/acl.h"
84 #include "utils/builtins.h"
85 #include "utils/fmgroids.h"
86 #include "utils/inval.h"
87 #include "utils/lsyscache.h"
88 #include "utils/memutils.h"
89 #include "utils/relcache.h"
90 #include "utils/ruleutils.h"
91 #include "utils/snapmgr.h"
92 #include "utils/syscache.h"
93 #include "utils/tqual.h"
94 #include "utils/typcache.h"
98 * ON COMMIT action list
100 typedef struct OnCommitItem
102 Oid relid; /* relid of relation */
103 OnCommitAction oncommit; /* what to do at end of xact */
106 * If this entry was created during the current transaction,
107 * creating_subid is the ID of the creating subxact; if created in a prior
108 * transaction, creating_subid is zero. If deleted during the current
109 * transaction, deleting_subid is the ID of the deleting subxact; if no
110 * deletion request is pending, deleting_subid is zero.
112 SubTransactionId creating_subid;
113 SubTransactionId deleting_subid;
116 static List *on_commits = NIL;
120 * State information for ALTER TABLE
122 * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
123 * structs, one for each table modified by the operation (the named table
124 * plus any child tables that are affected). We save lists of subcommands
125 * to apply to this table (possibly modified by parse transformation steps);
126 * these lists will be executed in Phase 2. If a Phase 3 step is needed,
127 * necessary information is stored in the constraints and newvals lists.
129 * Phase 2 is divided into multiple passes; subcommands are executed in
130 * a pass determined by subcommand type.
133 #define AT_PASS_UNSET -1 /* UNSET will cause ERROR */
134 #define AT_PASS_DROP 0 /* DROP (all flavors) */
135 #define AT_PASS_ALTER_TYPE 1 /* ALTER COLUMN TYPE */
136 #define AT_PASS_OLD_INDEX 2 /* re-add existing indexes */
137 #define AT_PASS_OLD_CONSTR 3 /* re-add existing constraints */
138 #define AT_PASS_COL_ATTRS 4 /* set other column attributes */
139 /* We could support a RENAME COLUMN pass here, but not currently used */
140 #define AT_PASS_ADD_COL 5 /* ADD COLUMN */
141 #define AT_PASS_ADD_INDEX 6 /* ADD indexes */
142 #define AT_PASS_ADD_CONSTR 7 /* ADD constraints, defaults */
143 #define AT_PASS_MISC 8 /* other stuff */
144 #define AT_NUM_PASSES 9
146 typedef struct AlteredTableInfo
148 /* Information saved before any work commences: */
149 Oid relid; /* Relation to work on */
150 char relkind; /* Its relkind */
151 TupleDesc oldDesc; /* Pre-modification tuple descriptor */
152 /* Information saved by Phase 1 for Phase 2: */
153 List *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
154 /* Information saved by Phases 1/2 for Phase 3: */
155 List *constraints; /* List of NewConstraint */
156 List *newvals; /* List of NewColumnValue */
157 bool new_notnull; /* T if we added new NOT NULL constraints */
158 int rewrite; /* Reason for forced rewrite, if any */
159 Oid newTableSpace; /* new tablespace; 0 means no change */
160 bool chgPersistence; /* T if SET LOGGED/UNLOGGED is used */
161 char newrelpersistence; /* if above is true */
162 /* Objects to rebuild after completing ALTER TYPE operations */
163 List *changedConstraintOids; /* OIDs of constraints to rebuild */
164 List *changedConstraintDefs; /* string definitions of same */
165 List *changedIndexOids; /* OIDs of indexes to rebuild */
166 List *changedIndexDefs; /* string definitions of same */
169 /* Struct describing one new constraint to check in Phase 3 scan */
170 /* Note: new NOT NULL constraints are handled elsewhere */
171 typedef struct NewConstraint
173 char *name; /* Constraint name, or NULL if none */
174 ConstrType contype; /* CHECK or FOREIGN */
175 Oid refrelid; /* PK rel, if FOREIGN */
176 Oid refindid; /* OID of PK's index, if FOREIGN */
177 Oid conid; /* OID of pg_constraint entry, if FOREIGN */
178 Node *qual; /* Check expr or CONSTR_FOREIGN Constraint */
179 List *qualstate; /* Execution state for CHECK */
183 * Struct describing one new column value that needs to be computed during
184 * Phase 3 copy (this could be either a new column with a non-null default, or
185 * a column that we're changing the type of). Columns without such an entry
186 * are just copied from the old table during ATRewriteTable. Note that the
187 * expr is an expression over *old* table values.
189 typedef struct NewColumnValue
191 AttrNumber attnum; /* which column */
192 Expr *expr; /* expression to compute */
193 ExprState *exprstate; /* execution state */
197 * Error-reporting support for RemoveRelations
199 struct dropmsgstrings
202 int nonexistent_code;
203 const char *nonexistent_msg;
204 const char *skipping_msg;
205 const char *nota_msg;
206 const char *drophint_msg;
209 static const struct dropmsgstrings dropmsgstringarray[] = {
211 ERRCODE_UNDEFINED_TABLE,
212 gettext_noop("table \"%s\" does not exist"),
213 gettext_noop("table \"%s\" does not exist, skipping"),
214 gettext_noop("\"%s\" is not a table"),
215 gettext_noop("Use DROP TABLE to remove a table.")},
217 ERRCODE_UNDEFINED_TABLE,
218 gettext_noop("sequence \"%s\" does not exist"),
219 gettext_noop("sequence \"%s\" does not exist, skipping"),
220 gettext_noop("\"%s\" is not a sequence"),
221 gettext_noop("Use DROP SEQUENCE to remove a sequence.")},
223 ERRCODE_UNDEFINED_TABLE,
224 gettext_noop("view \"%s\" does not exist"),
225 gettext_noop("view \"%s\" does not exist, skipping"),
226 gettext_noop("\"%s\" is not a view"),
227 gettext_noop("Use DROP VIEW to remove a view.")},
229 ERRCODE_UNDEFINED_TABLE,
230 gettext_noop("materialized view \"%s\" does not exist"),
231 gettext_noop("materialized view \"%s\" does not exist, skipping"),
232 gettext_noop("\"%s\" is not a materialized view"),
233 gettext_noop("Use DROP MATERIALIZED VIEW to remove a materialized view.")},
235 ERRCODE_UNDEFINED_OBJECT,
236 gettext_noop("index \"%s\" does not exist"),
237 gettext_noop("index \"%s\" does not exist, skipping"),
238 gettext_noop("\"%s\" is not an index"),
239 gettext_noop("Use DROP INDEX to remove an index.")},
240 {RELKIND_COMPOSITE_TYPE,
241 ERRCODE_UNDEFINED_OBJECT,
242 gettext_noop("type \"%s\" does not exist"),
243 gettext_noop("type \"%s\" does not exist, skipping"),
244 gettext_noop("\"%s\" is not a type"),
245 gettext_noop("Use DROP TYPE to remove a type.")},
246 {RELKIND_FOREIGN_TABLE,
247 ERRCODE_UNDEFINED_OBJECT,
248 gettext_noop("foreign table \"%s\" does not exist"),
249 gettext_noop("foreign table \"%s\" does not exist, skipping"),
250 gettext_noop("\"%s\" is not a foreign table"),
251 gettext_noop("Use DROP FOREIGN TABLE to remove a foreign table.")},
252 {'\0', 0, NULL, NULL, NULL, NULL}
255 struct DropRelationCallbackState
262 /* Alter table target-type flags for ATSimplePermissions */
263 #define ATT_TABLE 0x0001
264 #define ATT_VIEW 0x0002
265 #define ATT_MATVIEW 0x0004
266 #define ATT_INDEX 0x0008
267 #define ATT_COMPOSITE_TYPE 0x0010
268 #define ATT_FOREIGN_TABLE 0x0020
270 static void truncate_check_rel(Relation rel);
271 static List *MergeAttributes(List *schema, List *supers, char relpersistence,
272 List **supOids, List **supconstr, int *supOidCount);
273 static bool MergeCheckConstraint(List *constraints, char *name, Node *expr);
274 static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel);
275 static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
276 static void StoreCatalogInheritance(Oid relationId, List *supers);
277 static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
278 int16 seqNumber, Relation inhRelation);
279 static int findAttrByName(const char *attributeName, List *schema);
280 static void AlterIndexNamespaces(Relation classRel, Relation rel,
281 Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved);
282 static void AlterSeqNamespaces(Relation classRel, Relation rel,
283 Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved,
285 static void ATExecAlterConstraint(Relation rel, AlterTableCmd *cmd,
286 bool recurse, bool recursing, LOCKMODE lockmode);
287 static void ATExecValidateConstraint(Relation rel, char *constrName,
288 bool recurse, bool recursing, LOCKMODE lockmode);
289 static int transformColumnNameList(Oid relId, List *colList,
290 int16 *attnums, Oid *atttypids);
291 static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
293 int16 *attnums, Oid *atttypids,
295 static Oid transformFkeyCheckAttrs(Relation pkrel,
296 int numattrs, int16 *attnums,
298 static void checkFkeyPermissions(Relation rel, int16 *attnums, int natts);
299 static CoercionPathType findFkeyCast(Oid targetTypeId, Oid sourceTypeId,
301 static void validateCheckConstraint(Relation rel, HeapTuple constrtup);
302 static void validateForeignKeyConstraint(char *conname,
303 Relation rel, Relation pkrel,
304 Oid pkindOid, Oid constraintOid);
305 static void createForeignKeyTriggers(Relation rel, Oid refRelOid,
306 Constraint *fkconstraint,
307 Oid constraintOid, Oid indexOid);
308 static void ATController(AlterTableStmt *parsetree,
309 Relation rel, List *cmds, bool recurse, LOCKMODE lockmode);
310 static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
311 bool recurse, bool recursing, LOCKMODE lockmode);
312 static void ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode);
313 static void ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
314 AlterTableCmd *cmd, LOCKMODE lockmode);
315 static void ATRewriteTables(AlterTableStmt *parsetree,
316 List **wqueue, LOCKMODE lockmode);
317 static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap, LOCKMODE lockmode);
318 static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
319 static void ATSimplePermissions(Relation rel, int allowed_targets);
320 static void ATWrongRelkindError(Relation rel, int allowed_targets);
321 static void ATSimpleRecursion(List **wqueue, Relation rel,
322 AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode);
323 static void ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
325 static List *find_typed_table_dependencies(Oid typeOid, const char *typeName,
326 DropBehavior behavior);
327 static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
328 AlterTableCmd *cmd, LOCKMODE lockmode);
329 static void ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel,
330 ColumnDef *colDef, bool isOid,
331 bool recurse, bool recursing, LOCKMODE lockmode);
332 static void check_for_column_name_collision(Relation rel, const char *colname);
333 static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
334 static void add_column_collation_dependency(Oid relid, int32 attnum, Oid collid);
335 static void ATPrepAddOids(List **wqueue, Relation rel, bool recurse,
336 AlterTableCmd *cmd, LOCKMODE lockmode);
337 static void ATExecDropNotNull(Relation rel, const char *colName, LOCKMODE lockmode);
338 static void ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
339 const char *colName, LOCKMODE lockmode);
340 static void ATExecColumnDefault(Relation rel, const char *colName,
341 Node *newDefault, LOCKMODE lockmode);
342 static void ATPrepSetStatistics(Relation rel, const char *colName,
343 Node *newValue, LOCKMODE lockmode);
344 static void ATExecSetStatistics(Relation rel, const char *colName,
345 Node *newValue, LOCKMODE lockmode);
346 static void ATExecSetOptions(Relation rel, const char *colName,
347 Node *options, bool isReset, LOCKMODE lockmode);
348 static void ATExecSetStorage(Relation rel, const char *colName,
349 Node *newValue, LOCKMODE lockmode);
350 static void ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
351 AlterTableCmd *cmd, LOCKMODE lockmode);
352 static void ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
353 DropBehavior behavior,
354 bool recurse, bool recursing,
355 bool missing_ok, LOCKMODE lockmode);
356 static void ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
357 IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode);
358 static void ATExecAddConstraint(List **wqueue,
359 AlteredTableInfo *tab, Relation rel,
360 Constraint *newConstraint, bool recurse, bool is_readd,
362 static void ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
363 IndexStmt *stmt, LOCKMODE lockmode);
364 static void ATAddCheckConstraint(List **wqueue,
365 AlteredTableInfo *tab, Relation rel,
367 bool recurse, bool recursing, bool is_readd,
369 static void ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
370 Constraint *fkconstraint, LOCKMODE lockmode);
371 static void ATExecDropConstraint(Relation rel, const char *constrName,
372 DropBehavior behavior,
373 bool recurse, bool recursing,
374 bool missing_ok, LOCKMODE lockmode);
375 static void ATPrepAlterColumnType(List **wqueue,
376 AlteredTableInfo *tab, Relation rel,
377 bool recurse, bool recursing,
378 AlterTableCmd *cmd, LOCKMODE lockmode);
379 static bool ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno);
380 static void ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
381 AlterTableCmd *cmd, LOCKMODE lockmode);
382 static void ATExecAlterColumnGenericOptions(Relation rel, const char *colName,
383 List *options, LOCKMODE lockmode);
384 static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab,
386 static void ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId,
387 char *cmd, List **wqueue, LOCKMODE lockmode,
389 static void TryReuseIndex(Oid oldId, IndexStmt *stmt);
390 static void TryReuseForeignKey(Oid oldId, Constraint *con);
391 static void change_owner_fix_column_acls(Oid relationOid,
392 Oid oldOwnerId, Oid newOwnerId);
393 static void change_owner_recurse_to_sequences(Oid relationOid,
394 Oid newOwnerId, LOCKMODE lockmode);
395 static void ATExecClusterOn(Relation rel, const char *indexName,
397 static void ATExecDropCluster(Relation rel, LOCKMODE lockmode);
398 static bool ATPrepChangePersistence(Relation rel, bool toLogged);
399 static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
400 char *tablespacename, LOCKMODE lockmode);
401 static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode);
402 static void ATExecSetRelOptions(Relation rel, List *defList,
403 AlterTableType operation,
405 static void ATExecEnableDisableTrigger(Relation rel, char *trigname,
406 char fires_when, bool skip_system, LOCKMODE lockmode);
407 static void ATExecEnableDisableRule(Relation rel, char *rulename,
408 char fires_when, LOCKMODE lockmode);
409 static void ATPrepAddInherit(Relation child_rel);
410 static void ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode);
411 static void ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode);
412 static void drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid);
413 static void ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode);
414 static void ATExecDropOf(Relation rel, LOCKMODE lockmode);
415 static void ATExecReplicaIdentity(Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode);
416 static void ATExecGenericOptions(Relation rel, List *options);
417 static void ATExecEnableRowSecurity(Relation rel);
418 static void ATExecDisableRowSecurity(Relation rel);
420 static void copy_relation_data(SMgrRelation rel, SMgrRelation dst,
421 ForkNumber forkNum, char relpersistence);
422 static const char *storage_name(char c);
424 static void RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid,
425 Oid oldRelOid, void *arg);
426 static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid,
427 Oid oldrelid, void *arg);
430 /* ----------------------------------------------------------------
432 * Creates a new relation.
434 * stmt carries parsetree information from an ordinary CREATE TABLE statement.
435 * The other arguments are used to extend the behavior for other cases:
436 * relkind: relkind to assign to the new relation
437 * ownerId: if not InvalidOid, use this as the new relation's owner.
439 * Note that permissions checks are done against current user regardless of
440 * ownerId. A nonzero ownerId is used when someone is creating a relation
441 * "on behalf of" someone else, so we still want to see that the current user
442 * has permissions to do it.
444 * If successful, returns the OID of the new relation.
445 * ----------------------------------------------------------------
448 DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId)
450 char relname[NAMEDATALEN];
452 List *schema = stmt->tableElts;
456 TupleDesc descriptor;
458 List *old_constraints;
462 List *cookedDefaults;
466 static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
470 * Truncate relname to appropriate length (probably a waste of time, as
471 * parser should have done this already).
473 StrNCpy(relname, stmt->relation->relname, NAMEDATALEN);
476 * Check consistency of arguments
478 if (stmt->oncommit != ONCOMMIT_NOOP
479 && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
481 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
482 errmsg("ON COMMIT can only be used on temporary tables")));
485 * Look up the namespace in which we are supposed to create the relation,
486 * check we have permission to create there, lock it against concurrent
487 * drop, and mark stmt->relation as RELPERSISTENCE_TEMP if a temporary
488 * namespace is selected.
491 RangeVarGetAndCheckCreationNamespace(stmt->relation, NoLock, NULL);
494 * Security check: disallow creating temp tables from security-restricted
495 * code. This is needed because calling code might not expect untrusted
496 * tables to appear in pg_temp at the front of its search path.
498 if (stmt->relation->relpersistence == RELPERSISTENCE_TEMP
499 && InSecurityRestrictedOperation())
501 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
502 errmsg("cannot create temporary table within security-restricted operation")));
505 * Select tablespace to use. If not specified, use default tablespace
506 * (which may in turn default to database's default).
508 if (stmt->tablespacename)
510 tablespaceId = get_tablespace_oid(stmt->tablespacename, false);
514 tablespaceId = GetDefaultTablespace(stmt->relation->relpersistence);
515 /* note InvalidOid is OK in this case */
518 /* Check permissions except when using database's default */
519 if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
523 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
525 if (aclresult != ACLCHECK_OK)
526 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
527 get_tablespace_name(tablespaceId));
530 /* In all cases disallow placing user relations in pg_global */
531 if (tablespaceId == GLOBALTABLESPACE_OID)
533 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
534 errmsg("only shared relations can be placed in pg_global tablespace")));
536 /* Identify user ID that will own the table */
537 if (!OidIsValid(ownerId))
538 ownerId = GetUserId();
541 * Parse and validate reloptions, if any.
543 reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, validnsps,
546 if (relkind == RELKIND_VIEW)
547 (void) view_reloptions(reloptions, true);
549 (void) heap_reloptions(relkind, reloptions, true);
551 if (stmt->ofTypename)
555 ofTypeId = typenameTypeId(NULL, stmt->ofTypename);
557 aclresult = pg_type_aclcheck(ofTypeId, GetUserId(), ACL_USAGE);
558 if (aclresult != ACLCHECK_OK)
559 aclcheck_error_type(aclresult, ofTypeId);
562 ofTypeId = InvalidOid;
565 * Look up inheritance ancestors and generate relation schema, including
566 * inherited attributes.
568 schema = MergeAttributes(schema, stmt->inhRelations,
569 stmt->relation->relpersistence,
570 &inheritOids, &old_constraints, &parentOidCount);
573 * Create a tuple descriptor from the relation schema. Note that this
574 * deals with column names, types, and NOT NULL constraints, but not
575 * default values or CHECK constraints; we handle those below.
577 descriptor = BuildDescForRelation(schema);
579 localHasOids = interpretOidsOption(stmt->options,
580 (relkind == RELKIND_RELATION));
581 descriptor->tdhasoid = (localHasOids || parentOidCount > 0);
584 * Find columns with default values and prepare for insertion of the
585 * defaults. Pre-cooked (that is, inherited) defaults go into a list of
586 * CookedConstraint structs that we'll pass to heap_create_with_catalog,
587 * while raw defaults go into a list of RawColumnDefault structs that will
588 * be processed by AddRelationNewConstraints. (We can't deal with raw
589 * expressions until we can do transformExpr.)
591 * We can set the atthasdef flags now in the tuple descriptor; this just
592 * saves StoreAttrDefault from having to do an immediate update of the
596 cookedDefaults = NIL;
599 foreach(listptr, schema)
601 ColumnDef *colDef = lfirst(listptr);
605 if (colDef->raw_default != NULL)
607 RawColumnDefault *rawEnt;
609 Assert(colDef->cooked_default == NULL);
611 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
612 rawEnt->attnum = attnum;
613 rawEnt->raw_default = colDef->raw_default;
614 rawDefaults = lappend(rawDefaults, rawEnt);
615 descriptor->attrs[attnum - 1]->atthasdef = true;
617 else if (colDef->cooked_default != NULL)
619 CookedConstraint *cooked;
621 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
622 cooked->contype = CONSTR_DEFAULT;
624 cooked->attnum = attnum;
625 cooked->expr = colDef->cooked_default;
626 cooked->skip_validation = false;
627 cooked->is_local = true; /* not used for defaults */
628 cooked->inhcount = 0; /* ditto */
629 cooked->is_no_inherit = false;
630 cookedDefaults = lappend(cookedDefaults, cooked);
631 descriptor->attrs[attnum - 1]->atthasdef = true;
636 * Create the relation. Inherited defaults and constraints are passed in
637 * for immediate handling --- since they don't need parsing, they can be
638 * stored immediately.
640 relationId = heap_create_with_catalog(relname,
648 list_concat(cookedDefaults,
651 stmt->relation->relpersistence,
659 allowSystemTableMods,
662 /* Store inheritance information for new rel. */
663 StoreCatalogInheritance(relationId, inheritOids);
666 * We must bump the command counter to make the newly-created relation
667 * tuple visible for opening.
669 CommandCounterIncrement();
672 * Open the new relation and acquire exclusive lock on it. This isn't
673 * really necessary for locking out other backends (since they can't see
674 * the new rel anyway until we commit), but it keeps the lock manager from
675 * complaining about deadlock risks.
677 rel = relation_open(relationId, AccessExclusiveLock);
680 * Now add any newly specified column default values and CHECK constraints
681 * to the new relation. These are passed to us in the form of raw
682 * parsetrees; we need to transform them to executable expression trees
683 * before they can be added. The most convenient way to do that is to
684 * apply the parser's transformExpr routine, but transformExpr doesn't
685 * work unless we have a pre-existing relation. So, the transformation has
686 * to be postponed to this final step of CREATE TABLE.
688 if (rawDefaults || stmt->constraints)
689 AddRelationNewConstraints(rel, rawDefaults, stmt->constraints,
693 * Clean up. We keep lock on new relation (although it shouldn't be
694 * visible to anyone else anyway, until commit).
696 relation_close(rel, NoLock);
702 * Emit the right error or warning message for a "DROP" command issued on a
703 * non-existent relation
706 DropErrorMsgNonExistent(RangeVar *rel, char rightkind, bool missing_ok)
708 const struct dropmsgstrings *rentry;
710 if (rel->schemaname != NULL &&
711 !OidIsValid(LookupNamespaceNoError(rel->schemaname)))
716 (errcode(ERRCODE_UNDEFINED_SCHEMA),
717 errmsg("schema \"%s\" does not exist", rel->schemaname)));
722 (errmsg("schema \"%s\" does not exist, skipping",
728 for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
730 if (rentry->kind == rightkind)
735 (errcode(rentry->nonexistent_code),
736 errmsg(rentry->nonexistent_msg, rel->relname)));
740 ereport(NOTICE, (errmsg(rentry->skipping_msg, rel->relname)));
746 Assert(rentry->kind != '\0'); /* Should be impossible */
750 * Emit the right error message for a "DROP" command issued on a
751 * relation of the wrong type
754 DropErrorMsgWrongType(const char *relname, char wrongkind, char rightkind)
756 const struct dropmsgstrings *rentry;
757 const struct dropmsgstrings *wentry;
759 for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
760 if (rentry->kind == rightkind)
762 Assert(rentry->kind != '\0');
764 for (wentry = dropmsgstringarray; wentry->kind != '\0'; wentry++)
765 if (wentry->kind == wrongkind)
767 /* wrongkind could be something we don't have in our table... */
770 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
771 errmsg(rentry->nota_msg, relname),
772 (wentry->kind != '\0') ? errhint("%s", _(wentry->drophint_msg)) : 0));
777 * Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW,
778 * DROP MATERIALIZED VIEW, DROP FOREIGN TABLE
781 RemoveRelations(DropStmt *drop)
783 ObjectAddresses *objects;
787 LOCKMODE lockmode = AccessExclusiveLock;
789 /* DROP CONCURRENTLY uses a weaker lock, and has some restrictions */
790 if (drop->concurrent)
792 flags |= PERFORM_DELETION_CONCURRENTLY;
793 lockmode = ShareUpdateExclusiveLock;
794 Assert(drop->removeType == OBJECT_INDEX);
795 if (list_length(drop->objects) != 1)
797 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
798 errmsg("DROP INDEX CONCURRENTLY does not support dropping multiple objects")));
799 if (drop->behavior == DROP_CASCADE)
801 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
802 errmsg("DROP INDEX CONCURRENTLY does not support CASCADE")));
806 * First we identify all the relations, then we delete them in a single
807 * performMultipleDeletions() call. This is to avoid unwanted DROP
808 * RESTRICT errors if one of the relations depends on another.
811 /* Determine required relkind */
812 switch (drop->removeType)
815 relkind = RELKIND_RELATION;
819 relkind = RELKIND_INDEX;
822 case OBJECT_SEQUENCE:
823 relkind = RELKIND_SEQUENCE;
827 relkind = RELKIND_VIEW;
831 relkind = RELKIND_MATVIEW;
834 case OBJECT_FOREIGN_TABLE:
835 relkind = RELKIND_FOREIGN_TABLE;
839 elog(ERROR, "unrecognized drop object type: %d",
840 (int) drop->removeType);
841 relkind = 0; /* keep compiler quiet */
845 /* Lock and validate each relation; build a list of object addresses */
846 objects = new_object_addresses();
848 foreach(cell, drop->objects)
850 RangeVar *rel = makeRangeVarFromNameList((List *) lfirst(cell));
853 struct DropRelationCallbackState state;
856 * These next few steps are a great deal like relation_openrv, but we
857 * don't bother building a relcache entry since we don't need it.
859 * Check for shared-cache-inval messages before trying to access the
860 * relation. This is needed to cover the case where the name
861 * identifies a rel that has been dropped and recreated since the
862 * start of our transaction: if we don't flush the old syscache entry,
863 * then we'll latch onto that entry and suffer an error later.
865 AcceptInvalidationMessages();
867 /* Look up the appropriate relation using namespace search. */
868 state.relkind = relkind;
869 state.heapOid = InvalidOid;
870 state.concurrent = drop->concurrent;
871 relOid = RangeVarGetRelidExtended(rel, lockmode, true,
873 RangeVarCallbackForDropRelation,
877 if (!OidIsValid(relOid))
879 DropErrorMsgNonExistent(rel, relkind, drop->missing_ok);
883 /* OK, we're ready to delete this one */
884 obj.classId = RelationRelationId;
885 obj.objectId = relOid;
888 add_exact_object_address(&obj, objects);
891 performMultipleDeletions(objects, drop->behavior, flags);
893 free_object_addresses(objects);
897 * Before acquiring a table lock, check whether we have sufficient rights.
898 * In the case of DROP INDEX, also try to lock the table before the index.
901 RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid, Oid oldRelOid,
905 struct DropRelationCallbackState *state;
907 Form_pg_class classform;
908 LOCKMODE heap_lockmode;
910 state = (struct DropRelationCallbackState *) arg;
911 relkind = state->relkind;
912 heap_lockmode = state->concurrent ?
913 ShareUpdateExclusiveLock : AccessExclusiveLock;
916 * If we previously locked some other index's heap, and the name we're
917 * looking up no longer refers to that relation, release the now-useless
920 if (relOid != oldRelOid && OidIsValid(state->heapOid))
922 UnlockRelationOid(state->heapOid, heap_lockmode);
923 state->heapOid = InvalidOid;
926 /* Didn't find a relation, so no need for locking or permission checks. */
927 if (!OidIsValid(relOid))
930 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
931 if (!HeapTupleIsValid(tuple))
932 return; /* concurrently dropped, so nothing to do */
933 classform = (Form_pg_class) GETSTRUCT(tuple);
935 if (classform->relkind != relkind)
936 DropErrorMsgWrongType(rel->relname, classform->relkind, relkind);
938 /* Allow DROP to either table owner or schema owner */
939 if (!pg_class_ownercheck(relOid, GetUserId()) &&
940 !pg_namespace_ownercheck(classform->relnamespace, GetUserId()))
941 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
944 if (!allowSystemTableMods && IsSystemClass(relOid, classform))
946 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
947 errmsg("permission denied: \"%s\" is a system catalog",
950 ReleaseSysCache(tuple);
953 * In DROP INDEX, attempt to acquire lock on the parent table before
954 * locking the index. index_drop() will need this anyway, and since
955 * regular queries lock tables before their indexes, we risk deadlock if
956 * we do it the other way around. No error if we don't find a pg_index
957 * entry, though --- the relation may have been dropped.
959 if (relkind == RELKIND_INDEX && relOid != oldRelOid)
961 state->heapOid = IndexGetRelation(relOid, true);
962 if (OidIsValid(state->heapOid))
963 LockRelationOid(state->heapOid, heap_lockmode);
969 * Executes a TRUNCATE command.
971 * This is a multi-relation truncate. We first open and grab exclusive
972 * lock on all relations involved, checking permissions and otherwise
973 * verifying that the relation is OK for truncation. In CASCADE mode,
974 * relations having FK references to the targeted relations are automatically
975 * added to the group; in RESTRICT mode, we check that all FK references are
976 * internal to the group that's being truncated. Finally all the relations
977 * are truncated and reindexed.
980 ExecuteTruncate(TruncateStmt *stmt)
984 List *seq_relids = NIL;
986 ResultRelInfo *resultRelInfos;
987 ResultRelInfo *resultRelInfo;
988 SubTransactionId mySubid;
992 * Open, exclusive-lock, and check all the explicitly-specified relations
994 foreach(cell, stmt->relations)
996 RangeVar *rv = lfirst(cell);
998 bool recurse = interpretInhOption(rv->inhOpt);
1001 rel = heap_openrv(rv, AccessExclusiveLock);
1002 myrelid = RelationGetRelid(rel);
1003 /* don't throw error for "TRUNCATE foo, foo" */
1004 if (list_member_oid(relids, myrelid))
1006 heap_close(rel, AccessExclusiveLock);
1009 truncate_check_rel(rel);
1010 rels = lappend(rels, rel);
1011 relids = lappend_oid(relids, myrelid);
1018 children = find_all_inheritors(myrelid, AccessExclusiveLock, NULL);
1020 foreach(child, children)
1022 Oid childrelid = lfirst_oid(child);
1024 if (list_member_oid(relids, childrelid))
1027 /* find_all_inheritors already got lock */
1028 rel = heap_open(childrelid, NoLock);
1029 truncate_check_rel(rel);
1030 rels = lappend(rels, rel);
1031 relids = lappend_oid(relids, childrelid);
1037 * In CASCADE mode, suck in all referencing relations as well. This
1038 * requires multiple iterations to find indirectly-dependent relations. At
1039 * each phase, we need to exclusive-lock new rels before looking for their
1040 * dependencies, else we might miss something. Also, we check each rel as
1041 * soon as we open it, to avoid a faux pas such as holding lock for a long
1042 * time on a rel we have no permissions for.
1044 if (stmt->behavior == DROP_CASCADE)
1050 newrelids = heap_truncate_find_FKs(relids);
1051 if (newrelids == NIL)
1052 break; /* nothing else to add */
1054 foreach(cell, newrelids)
1056 Oid relid = lfirst_oid(cell);
1059 rel = heap_open(relid, AccessExclusiveLock);
1061 (errmsg("truncate cascades to table \"%s\"",
1062 RelationGetRelationName(rel))));
1063 truncate_check_rel(rel);
1064 rels = lappend(rels, rel);
1065 relids = lappend_oid(relids, relid);
1071 * Check foreign key references. In CASCADE mode, this should be
1072 * unnecessary since we just pulled in all the references; but as a
1073 * cross-check, do it anyway if in an Assert-enabled build.
1075 #ifdef USE_ASSERT_CHECKING
1076 heap_truncate_check_FKs(rels, false);
1078 if (stmt->behavior == DROP_RESTRICT)
1079 heap_truncate_check_FKs(rels, false);
1083 * If we are asked to restart sequences, find all the sequences, lock them
1084 * (we need AccessExclusiveLock for ResetSequence), and check permissions.
1085 * We want to do this early since it's pointless to do all the truncation
1086 * work only to fail on sequence permissions.
1088 if (stmt->restart_seqs)
1092 Relation rel = (Relation) lfirst(cell);
1093 List *seqlist = getOwnedSequences(RelationGetRelid(rel));
1096 foreach(seqcell, seqlist)
1098 Oid seq_relid = lfirst_oid(seqcell);
1101 seq_rel = relation_open(seq_relid, AccessExclusiveLock);
1103 /* This check must match AlterSequence! */
1104 if (!pg_class_ownercheck(seq_relid, GetUserId()))
1105 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1106 RelationGetRelationName(seq_rel));
1108 seq_relids = lappend_oid(seq_relids, seq_relid);
1110 relation_close(seq_rel, NoLock);
1115 /* Prepare to catch AFTER triggers. */
1116 AfterTriggerBeginQuery();
1119 * To fire triggers, we'll need an EState as well as a ResultRelInfo for
1120 * each relation. We don't need to call ExecOpenIndices, though.
1122 estate = CreateExecutorState();
1123 resultRelInfos = (ResultRelInfo *)
1124 palloc(list_length(rels) * sizeof(ResultRelInfo));
1125 resultRelInfo = resultRelInfos;
1128 Relation rel = (Relation) lfirst(cell);
1130 InitResultRelInfo(resultRelInfo,
1132 0, /* dummy rangetable index */
1136 estate->es_result_relations = resultRelInfos;
1137 estate->es_num_result_relations = list_length(rels);
1140 * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
1141 * truncating (this is because one of them might throw an error). Also, if
1142 * we were to allow them to prevent statement execution, that would need
1143 * to be handled here.
1145 resultRelInfo = resultRelInfos;
1148 estate->es_result_relation_info = resultRelInfo;
1149 ExecBSTruncateTriggers(estate, resultRelInfo);
1154 * OK, truncate each table.
1156 mySubid = GetCurrentSubTransactionId();
1160 Relation rel = (Relation) lfirst(cell);
1163 * Normally, we need a transaction-safe truncation here. However, if
1164 * the table was either created in the current (sub)transaction or has
1165 * a new relfilenode in the current (sub)transaction, then we can just
1166 * truncate it in-place, because a rollback would cause the whole
1167 * table or the current physical file to be thrown away anyway.
1169 if (rel->rd_createSubid == mySubid ||
1170 rel->rd_newRelfilenodeSubid == mySubid)
1172 /* Immediate, non-rollbackable truncation is OK */
1173 heap_truncate_one_rel(rel);
1179 MultiXactId minmulti;
1182 * This effectively deletes all rows in the table, and may be done
1183 * in a serializable transaction. In that case we must record a
1184 * rw-conflict in to this transaction from each transaction
1185 * holding a predicate lock on the table.
1187 CheckTableForSerializableConflictIn(rel);
1189 minmulti = GetOldestMultiXactId();
1192 * Need the full transaction-safe pushups.
1194 * Create a new empty storage file for the relation, and assign it
1195 * as the relfilenode value. The old storage file is scheduled for
1196 * deletion at commit.
1198 RelationSetNewRelfilenode(rel, rel->rd_rel->relpersistence,
1199 RecentXmin, minmulti);
1200 if (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED)
1201 heap_create_init_fork(rel);
1203 heap_relid = RelationGetRelid(rel);
1204 toast_relid = rel->rd_rel->reltoastrelid;
1207 * The same for the toast table, if any.
1209 if (OidIsValid(toast_relid))
1211 rel = relation_open(toast_relid, AccessExclusiveLock);
1212 RelationSetNewRelfilenode(rel, rel->rd_rel->relpersistence,
1213 RecentXmin, minmulti);
1214 if (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED)
1215 heap_create_init_fork(rel);
1216 heap_close(rel, NoLock);
1220 * Reconstruct the indexes to match, and we're done.
1222 reindex_relation(heap_relid, REINDEX_REL_PROCESS_TOAST);
1225 pgstat_count_truncate(rel);
1229 * Restart owned sequences if we were asked to.
1231 foreach(cell, seq_relids)
1233 Oid seq_relid = lfirst_oid(cell);
1235 ResetSequence(seq_relid);
1239 * Process all AFTER STATEMENT TRUNCATE triggers.
1241 resultRelInfo = resultRelInfos;
1244 estate->es_result_relation_info = resultRelInfo;
1245 ExecASTruncateTriggers(estate, resultRelInfo);
1249 /* Handle queued AFTER triggers */
1250 AfterTriggerEndQuery(estate);
1252 /* We can clean up the EState now */
1253 FreeExecutorState(estate);
1255 /* And close the rels (can't do this while EState still holds refs) */
1258 Relation rel = (Relation) lfirst(cell);
1260 heap_close(rel, NoLock);
1265 * Check that a given rel is safe to truncate. Subroutine for ExecuteTruncate
1268 truncate_check_rel(Relation rel)
1270 AclResult aclresult;
1272 /* Only allow truncate on regular tables */
1273 if (rel->rd_rel->relkind != RELKIND_RELATION)
1275 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1276 errmsg("\"%s\" is not a table",
1277 RelationGetRelationName(rel))));
1279 /* Permissions checks */
1280 aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
1282 if (aclresult != ACLCHECK_OK)
1283 aclcheck_error(aclresult, ACL_KIND_CLASS,
1284 RelationGetRelationName(rel));
1286 if (!allowSystemTableMods && IsSystemRelation(rel))
1288 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1289 errmsg("permission denied: \"%s\" is a system catalog",
1290 RelationGetRelationName(rel))));
1293 * Don't allow truncate on temp tables of other backends ... their local
1294 * buffer manager is not going to cope.
1296 if (RELATION_IS_OTHER_TEMP(rel))
1298 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1299 errmsg("cannot truncate temporary tables of other sessions")));
1302 * Also check for active uses of the relation in the current transaction,
1303 * including open scans and pending AFTER trigger events.
1305 CheckTableNotInUse(rel, "TRUNCATE");
1310 * returns the name corresponding to a typstorage/attstorage enum value
1313 storage_name(char c)
1332 * Returns new schema given initial schema and superclasses.
1335 * 'schema' is the column/attribute definition for the table. (It's a list
1336 * of ColumnDef's.) It is destructively changed.
1337 * 'supers' is a list of names (as RangeVar nodes) of parent relations.
1338 * 'relpersistence' is a persistence type of the table.
1341 * 'supOids' receives a list of the OIDs of the parent relations.
1342 * 'supconstr' receives a list of constraints belonging to the parents,
1343 * updated as necessary to be valid for the child.
1344 * 'supOidCount' is set to the number of parents that have OID columns.
1347 * Completed schema list.
1350 * The order in which the attributes are inherited is very important.
1351 * Intuitively, the inherited attributes should come first. If a table
1352 * inherits from multiple parents, the order of those attributes are
1353 * according to the order of the parents specified in CREATE TABLE.
1355 * Here's an example:
1357 * create table person (name text, age int4, location point);
1358 * create table emp (salary int4, manager text) inherits(person);
1359 * create table student (gpa float8) inherits (person);
1360 * create table stud_emp (percent int4) inherits (emp, student);
1362 * The order of the attributes of stud_emp is:
1364 * person {1:name, 2:age, 3:location}
1366 * {6:gpa} student emp {4:salary, 5:manager}
1368 * stud_emp {7:percent}
1370 * If the same attribute name appears multiple times, then it appears
1371 * in the result table in the proper location for its first appearance.
1373 * Constraints (including NOT NULL constraints) for the child table
1374 * are the union of all relevant constraints, from both the child schema
1375 * and parent tables.
1377 * The default value for a child column is defined as:
1378 * (1) If the child schema specifies a default, that value is used.
1379 * (2) If neither the child nor any parent specifies a default, then
1380 * the column will not have a default.
1381 * (3) If conflicting defaults are inherited from different parents
1382 * (and not overridden by the child), an error is raised.
1383 * (4) Otherwise the inherited default is used.
1384 * Rule (3) is new in Postgres 7.1; in earlier releases you got a
1385 * rather arbitrary choice of which parent default to use.
1389 MergeAttributes(List *schema, List *supers, char relpersistence,
1390 List **supOids, List **supconstr, int *supOidCount)
1393 List *inhSchema = NIL;
1394 List *parentOids = NIL;
1395 List *constraints = NIL;
1396 int parentsWithOids = 0;
1397 bool have_bogus_defaults = false;
1399 static Node bogus_marker = {0}; /* marks conflicting defaults */
1402 * Check for and reject tables with too many columns. We perform this
1403 * check relatively early for two reasons: (a) we don't run the risk of
1404 * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
1405 * okay if we're processing <= 1600 columns, but could take minutes to
1406 * execute if the user attempts to create a table with hundreds of
1407 * thousands of columns.
1409 * Note that we also need to check that any we do not exceed this figure
1410 * after including columns from inherited relations.
1412 if (list_length(schema) > MaxHeapAttributeNumber)
1414 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1415 errmsg("tables can have at most %d columns",
1416 MaxHeapAttributeNumber)));
1419 * Check for duplicate names in the explicit list of attributes.
1421 * Although we might consider merging such entries in the same way that we
1422 * handle name conflicts for inherited attributes, it seems to make more
1423 * sense to assume such conflicts are errors.
1425 foreach(entry, schema)
1427 ColumnDef *coldef = lfirst(entry);
1428 ListCell *rest = lnext(entry);
1429 ListCell *prev = entry;
1431 if (coldef->typeName == NULL)
1434 * Typed table column option that does not belong to a column from
1435 * the type. This works because the columns from the type come
1436 * first in the list.
1439 (errcode(ERRCODE_UNDEFINED_COLUMN),
1440 errmsg("column \"%s\" does not exist",
1443 while (rest != NULL)
1445 ColumnDef *restdef = lfirst(rest);
1446 ListCell *next = lnext(rest); /* need to save it in case we
1449 if (strcmp(coldef->colname, restdef->colname) == 0)
1451 if (coldef->is_from_type)
1454 * merge the column options into the column from the type
1456 coldef->is_not_null = restdef->is_not_null;
1457 coldef->raw_default = restdef->raw_default;
1458 coldef->cooked_default = restdef->cooked_default;
1459 coldef->constraints = restdef->constraints;
1460 coldef->is_from_type = false;
1461 list_delete_cell(schema, rest, prev);
1465 (errcode(ERRCODE_DUPLICATE_COLUMN),
1466 errmsg("column \"%s\" specified more than once",
1475 * Scan the parents left-to-right, and merge their attributes to form a
1476 * list of inherited attributes (inhSchema). Also check to see if we need
1477 * to inherit an OID column.
1480 foreach(entry, supers)
1482 RangeVar *parent = (RangeVar *) lfirst(entry);
1484 TupleDesc tupleDesc;
1485 TupleConstr *constr;
1486 AttrNumber *newattno;
1487 AttrNumber parent_attno;
1490 * A self-exclusive lock is needed here. If two backends attempt to
1491 * add children to the same parent simultaneously, and that parent has
1492 * no pre-existing children, then both will attempt to update the
1493 * parent's relhassubclass field, leading to a "tuple concurrently
1494 * updated" error. Also, this interlocks against a concurrent ANALYZE
1495 * on the parent table, which might otherwise be attempting to clear
1496 * the parent's relhassubclass field, if its previous children were
1499 relation = heap_openrv(parent, ShareUpdateExclusiveLock);
1501 if (relation->rd_rel->relkind != RELKIND_RELATION)
1503 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1504 errmsg("inherited relation \"%s\" is not a table",
1506 /* Permanent rels cannot inherit from temporary ones */
1507 if (relpersistence != RELPERSISTENCE_TEMP &&
1508 relation->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
1510 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1511 errmsg("cannot inherit from temporary relation \"%s\"",
1514 /* If existing rel is temp, it must belong to this session */
1515 if (relation->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
1516 !relation->rd_islocaltemp)
1518 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1519 errmsg("cannot inherit from temporary relation of another session")));
1522 * We should have an UNDER permission flag for this, but for now,
1523 * demand that creator of a child table own the parent.
1525 if (!pg_class_ownercheck(RelationGetRelid(relation), GetUserId()))
1526 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1527 RelationGetRelationName(relation));
1530 * Reject duplications in the list of parents.
1532 if (list_member_oid(parentOids, RelationGetRelid(relation)))
1534 (errcode(ERRCODE_DUPLICATE_TABLE),
1535 errmsg("relation \"%s\" would be inherited from more than once",
1538 parentOids = lappend_oid(parentOids, RelationGetRelid(relation));
1540 if (relation->rd_rel->relhasoids)
1543 tupleDesc = RelationGetDescr(relation);
1544 constr = tupleDesc->constr;
1547 * newattno[] will contain the child-table attribute numbers for the
1548 * attributes of this parent table. (They are not the same for
1549 * parents after the first one, nor if we have dropped columns.)
1551 newattno = (AttrNumber *)
1552 palloc0(tupleDesc->natts * sizeof(AttrNumber));
1554 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1557 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
1558 char *attributeName = NameStr(attribute->attname);
1563 * Ignore dropped columns in the parent.
1565 if (attribute->attisdropped)
1566 continue; /* leave newattno entry as zero */
1569 * Does it conflict with some previously inherited column?
1571 exist_attno = findAttrByName(attributeName, inhSchema);
1572 if (exist_attno > 0)
1579 * Yes, try to merge the two column definitions. They must
1580 * have the same type, typmod, and collation.
1583 (errmsg("merging multiple inherited definitions of column \"%s\"",
1585 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1586 typenameTypeIdAndMod(NULL, def->typeName, &defTypeId, &deftypmod);
1587 if (defTypeId != attribute->atttypid ||
1588 deftypmod != attribute->atttypmod)
1590 (errcode(ERRCODE_DATATYPE_MISMATCH),
1591 errmsg("inherited column \"%s\" has a type conflict",
1593 errdetail("%s versus %s",
1594 TypeNameToString(def->typeName),
1595 format_type_be(attribute->atttypid))));
1596 defCollId = GetColumnDefCollation(NULL, def, defTypeId);
1597 if (defCollId != attribute->attcollation)
1599 (errcode(ERRCODE_COLLATION_MISMATCH),
1600 errmsg("inherited column \"%s\" has a collation conflict",
1602 errdetail("\"%s\" versus \"%s\"",
1603 get_collation_name(defCollId),
1604 get_collation_name(attribute->attcollation))));
1606 /* Copy storage parameter */
1607 if (def->storage == 0)
1608 def->storage = attribute->attstorage;
1609 else if (def->storage != attribute->attstorage)
1611 (errcode(ERRCODE_DATATYPE_MISMATCH),
1612 errmsg("inherited column \"%s\" has a storage parameter conflict",
1614 errdetail("%s versus %s",
1615 storage_name(def->storage),
1616 storage_name(attribute->attstorage))));
1619 /* Merge of NOT NULL constraints = OR 'em together */
1620 def->is_not_null |= attribute->attnotnull;
1621 /* Default and other constraints are handled below */
1622 newattno[parent_attno - 1] = exist_attno;
1627 * No, create a new inherited column
1629 def = makeNode(ColumnDef);
1630 def->colname = pstrdup(attributeName);
1631 def->typeName = makeTypeNameFromOid(attribute->atttypid,
1632 attribute->atttypmod);
1634 def->is_local = false;
1635 def->is_not_null = attribute->attnotnull;
1636 def->is_from_type = false;
1637 def->storage = attribute->attstorage;
1638 def->raw_default = NULL;
1639 def->cooked_default = NULL;
1640 def->collClause = NULL;
1641 def->collOid = attribute->attcollation;
1642 def->constraints = NIL;
1644 inhSchema = lappend(inhSchema, def);
1645 newattno[parent_attno - 1] = ++child_attno;
1649 * Copy default if any
1651 if (attribute->atthasdef)
1653 Node *this_default = NULL;
1654 AttrDefault *attrdef;
1657 /* Find default in constraint structure */
1658 Assert(constr != NULL);
1659 attrdef = constr->defval;
1660 for (i = 0; i < constr->num_defval; i++)
1662 if (attrdef[i].adnum == parent_attno)
1664 this_default = stringToNode(attrdef[i].adbin);
1668 Assert(this_default != NULL);
1671 * If default expr could contain any vars, we'd need to fix
1672 * 'em, but it can't; so default is ready to apply to child.
1674 * If we already had a default from some prior parent, check
1675 * to see if they are the same. If so, no problem; if not,
1676 * mark the column as having a bogus default. Below, we will
1677 * complain if the bogus default isn't overridden by the child
1680 Assert(def->raw_default == NULL);
1681 if (def->cooked_default == NULL)
1682 def->cooked_default = this_default;
1683 else if (!equal(def->cooked_default, this_default))
1685 def->cooked_default = &bogus_marker;
1686 have_bogus_defaults = true;
1692 * Now copy the CHECK constraints of this parent, adjusting attnos
1693 * using the completed newattno[] map. Identically named constraints
1694 * are merged if possible, else we throw error.
1696 if (constr && constr->num_check > 0)
1698 ConstrCheck *check = constr->check;
1701 for (i = 0; i < constr->num_check; i++)
1703 char *name = check[i].ccname;
1705 bool found_whole_row;
1707 /* ignore if the constraint is non-inheritable */
1708 if (check[i].ccnoinherit)
1711 /* Adjust Vars to match new table's column numbering */
1712 expr = map_variable_attnos(stringToNode(check[i].ccbin),
1714 newattno, tupleDesc->natts,
1718 * For the moment we have to reject whole-row variables. We
1719 * could convert them, if we knew the new table's rowtype OID,
1720 * but that hasn't been assigned yet.
1722 if (found_whole_row)
1724 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1725 errmsg("cannot convert whole-row table reference"),
1726 errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
1728 RelationGetRelationName(relation))));
1730 /* check for duplicate */
1731 if (!MergeCheckConstraint(constraints, name, expr))
1733 /* nope, this is a new one */
1734 CookedConstraint *cooked;
1736 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1737 cooked->contype = CONSTR_CHECK;
1738 cooked->name = pstrdup(name);
1739 cooked->attnum = 0; /* not used for constraints */
1740 cooked->expr = expr;
1741 cooked->skip_validation = false;
1742 cooked->is_local = false;
1743 cooked->inhcount = 1;
1744 cooked->is_no_inherit = false;
1745 constraints = lappend(constraints, cooked);
1753 * Close the parent rel, but keep our AccessShareLock on it until xact
1754 * commit. That will prevent someone else from deleting or ALTERing
1755 * the parent before the child is committed.
1757 heap_close(relation, NoLock);
1761 * If we had no inherited attributes, the result schema is just the
1762 * explicitly declared columns. Otherwise, we need to merge the declared
1763 * columns into the inherited schema list.
1765 if (inhSchema != NIL)
1767 int schema_attno = 0;
1769 foreach(entry, schema)
1771 ColumnDef *newdef = lfirst(entry);
1772 char *attributeName = newdef->colname;
1778 * Does it conflict with some previously inherited column?
1780 exist_attno = findAttrByName(attributeName, inhSchema);
1781 if (exist_attno > 0)
1792 * Yes, try to merge the two column definitions. They must
1793 * have the same type, typmod, and collation.
1795 if (exist_attno == schema_attno)
1797 (errmsg("merging column \"%s\" with inherited definition",
1801 (errmsg("moving and merging column \"%s\" with inherited definition", attributeName),
1802 errdetail("User-specified column moved to the position of the inherited column.")));
1803 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1804 typenameTypeIdAndMod(NULL, def->typeName, &defTypeId, &deftypmod);
1805 typenameTypeIdAndMod(NULL, newdef->typeName, &newTypeId, &newtypmod);
1806 if (defTypeId != newTypeId || deftypmod != newtypmod)
1808 (errcode(ERRCODE_DATATYPE_MISMATCH),
1809 errmsg("column \"%s\" has a type conflict",
1811 errdetail("%s versus %s",
1812 TypeNameToString(def->typeName),
1813 TypeNameToString(newdef->typeName))));
1814 defcollid = GetColumnDefCollation(NULL, def, defTypeId);
1815 newcollid = GetColumnDefCollation(NULL, newdef, newTypeId);
1816 if (defcollid != newcollid)
1818 (errcode(ERRCODE_COLLATION_MISMATCH),
1819 errmsg("column \"%s\" has a collation conflict",
1821 errdetail("\"%s\" versus \"%s\"",
1822 get_collation_name(defcollid),
1823 get_collation_name(newcollid))));
1825 /* Copy storage parameter */
1826 if (def->storage == 0)
1827 def->storage = newdef->storage;
1828 else if (newdef->storage != 0 && def->storage != newdef->storage)
1830 (errcode(ERRCODE_DATATYPE_MISMATCH),
1831 errmsg("column \"%s\" has a storage parameter conflict",
1833 errdetail("%s versus %s",
1834 storage_name(def->storage),
1835 storage_name(newdef->storage))));
1837 /* Mark the column as locally defined */
1838 def->is_local = true;
1839 /* Merge of NOT NULL constraints = OR 'em together */
1840 def->is_not_null |= newdef->is_not_null;
1841 /* If new def has a default, override previous default */
1842 if (newdef->raw_default != NULL)
1844 def->raw_default = newdef->raw_default;
1845 def->cooked_default = newdef->cooked_default;
1851 * No, attach new column to result schema
1853 inhSchema = lappend(inhSchema, newdef);
1860 * Check that we haven't exceeded the legal # of columns after merging
1861 * in inherited columns.
1863 if (list_length(schema) > MaxHeapAttributeNumber)
1865 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1866 errmsg("tables can have at most %d columns",
1867 MaxHeapAttributeNumber)));
1871 * If we found any conflicting parent default values, check to make sure
1872 * they were overridden by the child.
1874 if (have_bogus_defaults)
1876 foreach(entry, schema)
1878 ColumnDef *def = lfirst(entry);
1880 if (def->cooked_default == &bogus_marker)
1882 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
1883 errmsg("column \"%s\" inherits conflicting default values",
1885 errhint("To resolve the conflict, specify a default explicitly.")));
1889 *supOids = parentOids;
1890 *supconstr = constraints;
1891 *supOidCount = parentsWithOids;
1897 * MergeCheckConstraint
1898 * Try to merge an inherited CHECK constraint with previous ones
1900 * If we inherit identically-named constraints from multiple parents, we must
1901 * merge them, or throw an error if they don't have identical definitions.
1903 * constraints is a list of CookedConstraint structs for previous constraints.
1905 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
1906 * got a so-far-unique name, or throws error if conflict.
1909 MergeCheckConstraint(List *constraints, char *name, Node *expr)
1913 foreach(lc, constraints)
1915 CookedConstraint *ccon = (CookedConstraint *) lfirst(lc);
1917 Assert(ccon->contype == CONSTR_CHECK);
1919 /* Non-matching names never conflict */
1920 if (strcmp(ccon->name, name) != 0)
1923 if (equal(expr, ccon->expr))
1931 (errcode(ERRCODE_DUPLICATE_OBJECT),
1932 errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
1941 * StoreCatalogInheritance
1942 * Updates the system catalogs with proper inheritance information.
1944 * supers is a list of the OIDs of the new relation's direct ancestors.
1947 StoreCatalogInheritance(Oid relationId, List *supers)
1956 AssertArg(OidIsValid(relationId));
1962 * Store INHERITS information in pg_inherits using direct ancestors only.
1963 * Also enter dependencies on the direct ancestors, and make sure they are
1964 * marked with relhassubclass = true.
1966 * (Once upon a time, both direct and indirect ancestors were found here
1967 * and then entered into pg_ipl. Since that catalog doesn't exist
1968 * anymore, there's no need to look for indirect ancestors.)
1970 relation = heap_open(InheritsRelationId, RowExclusiveLock);
1973 foreach(entry, supers)
1975 Oid parentOid = lfirst_oid(entry);
1977 StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation);
1981 heap_close(relation, RowExclusiveLock);
1985 * Make catalog entries showing relationId as being an inheritance child
1986 * of parentOid. inhRelation is the already-opened pg_inherits catalog.
1989 StoreCatalogInheritance1(Oid relationId, Oid parentOid,
1990 int16 seqNumber, Relation inhRelation)
1992 TupleDesc desc = RelationGetDescr(inhRelation);
1993 Datum values[Natts_pg_inherits];
1994 bool nulls[Natts_pg_inherits];
1995 ObjectAddress childobject,
2000 * Make the pg_inherits entry
2002 values[Anum_pg_inherits_inhrelid - 1] = ObjectIdGetDatum(relationId);
2003 values[Anum_pg_inherits_inhparent - 1] = ObjectIdGetDatum(parentOid);
2004 values[Anum_pg_inherits_inhseqno - 1] = Int16GetDatum(seqNumber);
2006 memset(nulls, 0, sizeof(nulls));
2008 tuple = heap_form_tuple(desc, values, nulls);
2010 simple_heap_insert(inhRelation, tuple);
2012 CatalogUpdateIndexes(inhRelation, tuple);
2014 heap_freetuple(tuple);
2017 * Store a dependency too
2019 parentobject.classId = RelationRelationId;
2020 parentobject.objectId = parentOid;
2021 parentobject.objectSubId = 0;
2022 childobject.classId = RelationRelationId;
2023 childobject.objectId = relationId;
2024 childobject.objectSubId = 0;
2026 recordDependencyOn(&childobject, &parentobject, DEPENDENCY_NORMAL);
2029 * Post creation hook of this inheritance. Since object_access_hook
2030 * doesn't take multiple object identifiers, we relay oid of parent
2031 * relation using auxiliary_id argument.
2033 InvokeObjectPostAlterHookArg(InheritsRelationId,
2038 * Mark the parent as having subclasses.
2040 SetRelationHasSubclass(parentOid, true);
2044 * Look for an existing schema entry with the given name.
2046 * Returns the index (starting with 1) if attribute already exists in schema,
2050 findAttrByName(const char *attributeName, List *schema)
2057 ColumnDef *def = lfirst(s);
2059 if (strcmp(attributeName, def->colname) == 0)
2069 * SetRelationHasSubclass
2070 * Set the value of the relation's relhassubclass field in pg_class.
2072 * NOTE: caller must be holding an appropriate lock on the relation.
2073 * ShareUpdateExclusiveLock is sufficient.
2075 * NOTE: an important side-effect of this operation is that an SI invalidation
2076 * message is sent out to all backends --- including me --- causing plans
2077 * referencing the relation to be rebuilt with the new list of children.
2078 * This must happen even if we find that no change is needed in the pg_class
2082 SetRelationHasSubclass(Oid relationId, bool relhassubclass)
2084 Relation relationRelation;
2086 Form_pg_class classtuple;
2089 * Fetch a modifiable copy of the tuple, modify it, update pg_class.
2091 relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
2092 tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
2093 if (!HeapTupleIsValid(tuple))
2094 elog(ERROR, "cache lookup failed for relation %u", relationId);
2095 classtuple = (Form_pg_class) GETSTRUCT(tuple);
2097 if (classtuple->relhassubclass != relhassubclass)
2099 classtuple->relhassubclass = relhassubclass;
2100 simple_heap_update(relationRelation, &tuple->t_self, tuple);
2102 /* keep the catalog indexes up to date */
2103 CatalogUpdateIndexes(relationRelation, tuple);
2107 /* no need to change tuple, but force relcache rebuild anyway */
2108 CacheInvalidateRelcacheByTuple(tuple);
2111 heap_freetuple(tuple);
2112 heap_close(relationRelation, RowExclusiveLock);
2116 * renameatt_check - basic sanity checks before attribute rename
2119 renameatt_check(Oid myrelid, Form_pg_class classform, bool recursing)
2121 char relkind = classform->relkind;
2123 if (classform->reloftype && !recursing)
2125 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2126 errmsg("cannot rename column of typed table")));
2129 * Renaming the columns of sequences or toast tables doesn't actually
2130 * break anything from the system's point of view, since internal
2131 * references are by attnum. But it doesn't seem right to allow users to
2132 * change names that are hardcoded into the system, hence the following
2135 if (relkind != RELKIND_RELATION &&
2136 relkind != RELKIND_VIEW &&
2137 relkind != RELKIND_MATVIEW &&
2138 relkind != RELKIND_COMPOSITE_TYPE &&
2139 relkind != RELKIND_INDEX &&
2140 relkind != RELKIND_FOREIGN_TABLE)
2142 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2143 errmsg("\"%s\" is not a table, view, materialized view, composite type, index, or foreign table",
2144 NameStr(classform->relname))));
2147 * permissions checking. only the owner of a class can change its schema.
2149 if (!pg_class_ownercheck(myrelid, GetUserId()))
2150 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
2151 NameStr(classform->relname));
2152 if (!allowSystemTableMods && IsSystemClass(myrelid, classform))
2154 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2155 errmsg("permission denied: \"%s\" is a system catalog",
2156 NameStr(classform->relname))));
2160 * renameatt_internal - workhorse for renameatt
2163 renameatt_internal(Oid myrelid,
2164 const char *oldattname,
2165 const char *newattname,
2168 int expected_parents,
2169 DropBehavior behavior)
2171 Relation targetrelation;
2172 Relation attrelation;
2174 Form_pg_attribute attform;
2178 * Grab an exclusive lock on the target table, which we will NOT release
2179 * until end of transaction.
2181 targetrelation = relation_open(myrelid, AccessExclusiveLock);
2182 renameatt_check(myrelid, RelationGetForm(targetrelation), recursing);
2185 * if the 'recurse' flag is set then we are supposed to rename this
2186 * attribute in all classes that inherit from 'relname' (as well as in
2189 * any permissions or problems with duplicate attributes will cause the
2190 * whole transaction to abort, which is what we want -- all or nothing.
2200 * we need the number of parents for each child so that the recursive
2201 * calls to renameatt() can determine whether there are any parents
2202 * outside the inheritance hierarchy being processed.
2204 child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
2208 * find_all_inheritors does the recursive search of the inheritance
2209 * hierarchy, so all we have to do is process all of the relids in the
2210 * list that it returns.
2212 forboth(lo, child_oids, li, child_numparents)
2214 Oid childrelid = lfirst_oid(lo);
2215 int numparents = lfirst_int(li);
2217 if (childrelid == myrelid)
2219 /* note we need not recurse again */
2220 renameatt_internal(childrelid, oldattname, newattname, false, true, numparents, behavior);
2226 * If we are told not to recurse, there had better not be any child
2227 * tables; else the rename would put them out of step.
2229 * expected_parents will only be 0 if we are not already recursing.
2231 if (expected_parents == 0 &&
2232 find_inheritance_children(myrelid, NoLock) != NIL)
2234 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2235 errmsg("inherited column \"%s\" must be renamed in child tables too",
2239 /* rename attributes in typed tables of composite type */
2240 if (targetrelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
2245 child_oids = find_typed_table_dependencies(targetrelation->rd_rel->reltype,
2246 RelationGetRelationName(targetrelation),
2249 foreach(lo, child_oids)
2250 renameatt_internal(lfirst_oid(lo), oldattname, newattname, true, true, 0, behavior);
2253 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
2255 atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
2256 if (!HeapTupleIsValid(atttup))
2258 (errcode(ERRCODE_UNDEFINED_COLUMN),
2259 errmsg("column \"%s\" does not exist",
2261 attform = (Form_pg_attribute) GETSTRUCT(atttup);
2263 attnum = attform->attnum;
2266 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2267 errmsg("cannot rename system column \"%s\"",
2271 * if the attribute is inherited, forbid the renaming. if this is a
2272 * top-level call to renameatt(), then expected_parents will be 0, so the
2273 * effect of this code will be to prohibit the renaming if the attribute
2274 * is inherited at all. if this is a recursive call to renameatt(),
2275 * expected_parents will be the number of parents the current relation has
2276 * within the inheritance hierarchy being processed, so we'll prohibit the
2277 * renaming only if there are additional parents from elsewhere.
2279 if (attform->attinhcount > expected_parents)
2281 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2282 errmsg("cannot rename inherited column \"%s\"",
2285 /* new name should not already exist */
2286 check_for_column_name_collision(targetrelation, newattname);
2288 /* apply the update */
2289 namestrcpy(&(attform->attname), newattname);
2291 simple_heap_update(attrelation, &atttup->t_self, atttup);
2293 /* keep system catalog indexes current */
2294 CatalogUpdateIndexes(attrelation, atttup);
2296 InvokeObjectPostAlterHook(RelationRelationId, myrelid, attnum);
2298 heap_freetuple(atttup);
2300 heap_close(attrelation, RowExclusiveLock);
2302 relation_close(targetrelation, NoLock); /* close rel but keep lock */
2306 * Perform permissions and integrity checks before acquiring a relation lock.
2309 RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid,
2315 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
2316 if (!HeapTupleIsValid(tuple))
2317 return; /* concurrently dropped */
2318 form = (Form_pg_class) GETSTRUCT(tuple);
2319 renameatt_check(relid, form, false);
2320 ReleaseSysCache(tuple);
2324 * renameatt - changes the name of a attribute in a relation
2327 renameatt(RenameStmt *stmt)
2331 /* lock level taken here should match renameatt_internal */
2332 relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
2333 stmt->missing_ok, false,
2334 RangeVarCallbackForRenameAttribute,
2337 if (!OidIsValid(relid))
2340 (errmsg("relation \"%s\" does not exist, skipping",
2341 stmt->relation->relname)));
2345 renameatt_internal(relid,
2346 stmt->subname, /* old att name */
2347 stmt->newname, /* new att name */
2348 interpretInhOption(stmt->relation->inhOpt), /* recursive? */
2349 false, /* recursing? */
2350 0, /* expected inhcount */
2353 /* This is an ALTER TABLE command so it's about the relid */
2359 * same logic as renameatt_internal
2362 rename_constraint_internal(Oid myrelid,
2364 const char *oldconname,
2365 const char *newconname,
2368 int expected_parents)
2370 Relation targetrelation = NULL;
2373 Form_pg_constraint con;
2375 AssertArg(!myrelid || !mytypid);
2379 constraintOid = get_domain_constraint_oid(mytypid, oldconname, false);
2383 targetrelation = relation_open(myrelid, AccessExclusiveLock);
2386 * don't tell it whether we're recursing; we allow changing typed
2389 renameatt_check(myrelid, RelationGetForm(targetrelation), false);
2391 constraintOid = get_relation_constraint_oid(myrelid, oldconname, false);
2394 tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
2395 if (!HeapTupleIsValid(tuple))
2396 elog(ERROR, "cache lookup failed for constraint %u",
2398 con = (Form_pg_constraint) GETSTRUCT(tuple);
2400 if (myrelid && con->contype == CONSTRAINT_CHECK && !con->connoinherit)
2409 child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
2412 forboth(lo, child_oids, li, child_numparents)
2414 Oid childrelid = lfirst_oid(lo);
2415 int numparents = lfirst_int(li);
2417 if (childrelid == myrelid)
2420 rename_constraint_internal(childrelid, InvalidOid, oldconname, newconname, false, true, numparents);
2425 if (expected_parents == 0 &&
2426 find_inheritance_children(myrelid, NoLock) != NIL)
2428 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2429 errmsg("inherited constraint \"%s\" must be renamed in child tables too",
2433 if (con->coninhcount > expected_parents)
2435 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2436 errmsg("cannot rename inherited constraint \"%s\"",
2441 && (con->contype == CONSTRAINT_PRIMARY
2442 || con->contype == CONSTRAINT_UNIQUE
2443 || con->contype == CONSTRAINT_EXCLUSION))
2444 /* rename the index; this renames the constraint as well */
2445 RenameRelationInternal(con->conindid, newconname, false);
2447 RenameConstraintById(constraintOid, newconname);
2449 ReleaseSysCache(tuple);
2452 relation_close(targetrelation, NoLock); /* close rel but keep lock */
2454 return constraintOid;
2458 RenameConstraint(RenameStmt *stmt)
2460 Oid relid = InvalidOid;
2461 Oid typid = InvalidOid;
2463 if (stmt->renameType == OBJECT_DOMCONSTRAINT)
2468 typid = typenameTypeId(NULL, makeTypeNameFromNameList(stmt->object));
2469 rel = heap_open(TypeRelationId, RowExclusiveLock);
2470 tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2471 if (!HeapTupleIsValid(tup))
2472 elog(ERROR, "cache lookup failed for type %u", typid);
2473 checkDomainOwner(tup);
2474 ReleaseSysCache(tup);
2475 heap_close(rel, NoLock);
2479 /* lock level taken here should match rename_constraint_internal */
2480 relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
2482 RangeVarCallbackForRenameAttribute,
2487 rename_constraint_internal(relid, typid,
2490 stmt->relation ? interpretInhOption(stmt->relation->inhOpt) : false, /* recursive? */
2491 false, /* recursing? */
2492 0 /* expected inhcount */ );
2497 * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW/MATERIALIZED VIEW/FOREIGN TABLE
2501 RenameRelation(RenameStmt *stmt)
2506 * Grab an exclusive lock on the target table, index, sequence, view,
2507 * materialized view, or foreign table, which we will NOT release until
2508 * end of transaction.
2510 * Lock level used here should match RenameRelationInternal, to avoid lock
2513 relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
2514 stmt->missing_ok, false,
2515 RangeVarCallbackForAlterRelation,
2518 if (!OidIsValid(relid))
2521 (errmsg("relation \"%s\" does not exist, skipping",
2522 stmt->relation->relname)));
2527 RenameRelationInternal(relid, stmt->newname, false);
2533 * RenameRelationInternal - change the name of a relation
2535 * XXX - When renaming sequences, we don't bother to modify the
2536 * sequence name that is stored within the sequence itself
2537 * (this would cause problems with MVCC). In the future,
2538 * the sequence name should probably be removed from the
2539 * sequence, AFAIK there's no need for it to be there.
2542 RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal)
2544 Relation targetrelation;
2545 Relation relrelation; /* for RELATION relation */
2547 Form_pg_class relform;
2551 * Grab an exclusive lock on the target table, index, sequence, view,
2552 * materialized view, or foreign table, which we will NOT release until
2553 * end of transaction.
2555 targetrelation = relation_open(myrelid, AccessExclusiveLock);
2556 namespaceId = RelationGetNamespace(targetrelation);
2559 * Find relation's pg_class tuple, and make sure newrelname isn't in use.
2561 relrelation = heap_open(RelationRelationId, RowExclusiveLock);
2563 reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
2564 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
2565 elog(ERROR, "cache lookup failed for relation %u", myrelid);
2566 relform = (Form_pg_class) GETSTRUCT(reltup);
2568 if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
2570 (errcode(ERRCODE_DUPLICATE_TABLE),
2571 errmsg("relation \"%s\" already exists",
2575 * Update pg_class tuple with new relname. (Scribbling on reltup is OK
2576 * because it's a copy...)
2578 namestrcpy(&(relform->relname), newrelname);
2580 simple_heap_update(relrelation, &reltup->t_self, reltup);
2582 /* keep the system catalog indexes current */
2583 CatalogUpdateIndexes(relrelation, reltup);
2585 InvokeObjectPostAlterHookArg(RelationRelationId, myrelid, 0,
2586 InvalidOid, is_internal);
2588 heap_freetuple(reltup);
2589 heap_close(relrelation, RowExclusiveLock);
2592 * Also rename the associated type, if any.
2594 if (OidIsValid(targetrelation->rd_rel->reltype))
2595 RenameTypeInternal(targetrelation->rd_rel->reltype,
2596 newrelname, namespaceId);
2599 * Also rename the associated constraint, if any.
2601 if (targetrelation->rd_rel->relkind == RELKIND_INDEX)
2603 Oid constraintId = get_index_constraint(myrelid);
2605 if (OidIsValid(constraintId))
2606 RenameConstraintById(constraintId, newrelname);
2610 * Close rel, but keep exclusive lock!
2612 relation_close(targetrelation, NoLock);
2616 * Disallow ALTER TABLE (and similar commands) when the current backend has
2617 * any open reference to the target table besides the one just acquired by
2618 * the calling command; this implies there's an open cursor or active plan.
2619 * We need this check because our lock doesn't protect us against stomping
2620 * on our own foot, only other people's feet!
2622 * For ALTER TABLE, the only case known to cause serious trouble is ALTER
2623 * COLUMN TYPE, and some changes are obviously pretty benign, so this could
2624 * possibly be relaxed to only error out for certain types of alterations.
2625 * But the use-case for allowing any of these things is not obvious, so we
2626 * won't work hard at it for now.
2628 * We also reject these commands if there are any pending AFTER trigger events
2629 * for the rel. This is certainly necessary for the rewriting variants of
2630 * ALTER TABLE, because they don't preserve tuple TIDs and so the pending
2631 * events would try to fetch the wrong tuples. It might be overly cautious
2632 * in other cases, but again it seems better to err on the side of paranoia.
2634 * REINDEX calls this with "rel" referencing the index to be rebuilt; here
2635 * we are worried about active indexscans on the index. The trigger-event
2636 * check can be skipped, since we are doing no damage to the parent table.
2638 * The statement name (eg, "ALTER TABLE") is passed for use in error messages.
2641 CheckTableNotInUse(Relation rel, const char *stmt)
2643 int expected_refcnt;
2645 expected_refcnt = rel->rd_isnailed ? 2 : 1;
2646 if (rel->rd_refcnt != expected_refcnt)
2648 (errcode(ERRCODE_OBJECT_IN_USE),
2649 /* translator: first %s is a SQL command, eg ALTER TABLE */
2650 errmsg("cannot %s \"%s\" because "
2651 "it is being used by active queries in this session",
2652 stmt, RelationGetRelationName(rel))));
2654 if (rel->rd_rel->relkind != RELKIND_INDEX &&
2655 AfterTriggerPendingOnRel(RelationGetRelid(rel)))
2657 (errcode(ERRCODE_OBJECT_IN_USE),
2658 /* translator: first %s is a SQL command, eg ALTER TABLE */
2659 errmsg("cannot %s \"%s\" because "
2660 "it has pending trigger events",
2661 stmt, RelationGetRelationName(rel))));
2665 * AlterTableLookupRelation
2666 * Look up, and lock, the OID for the relation named by an alter table
2670 AlterTableLookupRelation(AlterTableStmt *stmt, LOCKMODE lockmode)
2672 return RangeVarGetRelidExtended(stmt->relation, lockmode, stmt->missing_ok, false,
2673 RangeVarCallbackForAlterRelation,
2679 * Execute ALTER TABLE, which can be a list of subcommands
2681 * ALTER TABLE is performed in three phases:
2682 * 1. Examine subcommands and perform pre-transformation checking.
2683 * 2. Update system catalogs.
2684 * 3. Scan table(s) to check new constraints, and optionally recopy
2685 * the data into new table(s).
2686 * Phase 3 is not performed unless one or more of the subcommands requires
2687 * it. The intention of this design is to allow multiple independent
2688 * updates of the table schema to be performed with only one pass over the
2691 * ATPrepCmd performs phase 1. A "work queue" entry is created for
2692 * each table to be affected (there may be multiple affected tables if the
2693 * commands traverse a table inheritance hierarchy). Also we do preliminary
2694 * validation of the subcommands, including parse transformation of those
2695 * expressions that need to be evaluated with respect to the old table
2698 * ATRewriteCatalogs performs phase 2 for each affected table. (Note that
2699 * phases 2 and 3 normally do no explicit recursion, since phase 1 already
2700 * did it --- although some subcommands have to recurse in phase 2 instead.)
2701 * Certain subcommands need to be performed before others to avoid
2702 * unnecessary conflicts; for example, DROP COLUMN should come before
2703 * ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
2704 * lists, one for each logical "pass" of phase 2.
2706 * ATRewriteTables performs phase 3 for those tables that need it.
2708 * Thanks to the magic of MVCC, an error anywhere along the way rolls back
2709 * the whole operation; we don't have to do anything special to clean up.
2711 * The caller must lock the relation, with an appropriate lock level
2712 * for the subcommands requested, using AlterTableGetLockLevel(stmt->cmds)
2713 * or higher. We pass the lock level down
2714 * so that we can apply it recursively to inherited tables. Note that the
2715 * lock level we want as we recurse might well be higher than required for
2716 * that specific subcommand. So we pass down the overall lock requirement,
2717 * rather than reassess it at lower levels.
2720 AlterTable(Oid relid, LOCKMODE lockmode, AlterTableStmt *stmt)
2724 /* Caller is required to provide an adequate lock. */
2725 rel = relation_open(relid, NoLock);
2727 CheckTableNotInUse(rel, "ALTER TABLE");
2730 rel, stmt->cmds, interpretInhOption(stmt->relation->inhOpt),
2735 * AlterTableInternal
2737 * ALTER TABLE with target specified by OID
2739 * We do not reject if the relation is already open, because it's quite
2740 * likely that one or more layers of caller have it open. That means it
2741 * is unsafe to use this entry point for alterations that could break
2742 * existing query plans. On the assumption it's not used for such, we
2743 * don't have to reject pending AFTER triggers, either.
2746 AlterTableInternal(Oid relid, List *cmds, bool recurse)
2749 LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
2751 rel = relation_open(relid, lockmode);
2753 ATController(NULL, rel, cmds, recurse, lockmode);
2757 * AlterTableGetLockLevel
2759 * Sets the overall lock level required for the supplied list of subcommands.
2760 * Policy for doing this set according to needs of AlterTable(), see
2761 * comments there for overall explanation.
2763 * Function is called before and after parsing, so it must give same
2764 * answer each time it is called. Some subcommands are transformed
2765 * into other subcommand types, so the transform must never be made to a
2766 * lower lock level than previously assigned. All transforms are noted below.
2768 * Since this is called before we lock the table we cannot use table metadata
2769 * to influence the type of lock we acquire.
2771 * There should be no lockmodes hardcoded into the subcommand functions. All
2772 * lockmode decisions for ALTER TABLE are made here only. The one exception is
2773 * ALTER TABLE RENAME which is treated as a different statement type T_RenameStmt
2774 * and does not travel through this section of code and cannot be combined with
2775 * any of the subcommands given here.
2777 * Note that Hot Standby only knows about AccessExclusiveLocks on the master
2778 * so any changes that might affect SELECTs running on standbys need to use
2779 * AccessExclusiveLocks even if you think a lesser lock would do, unless you
2780 * have a solution for that also.
2782 * Also note that pg_dump uses only an AccessShareLock, meaning that anything
2783 * that takes a lock less than AccessExclusiveLock can change object definitions
2784 * while pg_dump is running. Be careful to check that the appropriate data is
2785 * derived by pg_dump using an MVCC snapshot, rather than syscache lookups,
2786 * otherwise we might end up with an inconsistent dump that can't restore.
2789 AlterTableGetLockLevel(List *cmds)
2792 * This only works if we read catalog tables using MVCC snapshots.
2795 LOCKMODE lockmode = ShareUpdateExclusiveLock;
2799 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2800 LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
2802 switch (cmd->subtype)
2805 * These subcommands rewrite the heap, so require full locks.
2807 case AT_AddColumn: /* may rewrite heap, in some cases and visible
2809 case AT_SetTableSpace: /* must rewrite heap */
2810 case AT_AlterColumnType: /* must rewrite heap */
2811 case AT_AddOids: /* must rewrite heap */
2812 cmd_lockmode = AccessExclusiveLock;
2816 * These subcommands may require addition of toast tables. If
2817 * we add a toast table to a table currently being scanned, we
2818 * might miss data added to the new toast table by concurrent
2819 * insert transactions.
2821 case AT_SetStorage:/* may add toast tables, see
2822 * ATRewriteCatalogs() */
2823 cmd_lockmode = AccessExclusiveLock;
2827 * Removing constraints can affect SELECTs that have been
2828 * optimised assuming the constraint holds true.
2830 case AT_DropConstraint: /* as DROP INDEX */
2831 case AT_DropNotNull: /* may change some SQL plans */
2832 cmd_lockmode = AccessExclusiveLock;
2836 * Subcommands that may be visible to concurrent SELECTs
2838 case AT_DropColumn: /* change visible to SELECT */
2839 case AT_AddColumnToView: /* CREATE VIEW */
2840 case AT_DropOids: /* calls AT_DropColumn */
2841 case AT_EnableAlwaysRule: /* may change SELECT rules */
2842 case AT_EnableReplicaRule: /* may change SELECT rules */
2843 case AT_EnableRule: /* may change SELECT rules */
2844 case AT_DisableRule: /* may change SELECT rules */
2845 cmd_lockmode = AccessExclusiveLock;
2849 * Changing owner may remove implicit SELECT privileges
2851 case AT_ChangeOwner: /* change visible to SELECT */
2852 cmd_lockmode = AccessExclusiveLock;
2856 * Changing foreign table options may affect optimisation.
2858 case AT_GenericOptions:
2859 case AT_AlterColumnGenericOptions:
2860 cmd_lockmode = AccessExclusiveLock;
2864 * These subcommands affect write operations only. XXX
2865 * Theoretically, these could be ShareRowExclusiveLock.
2867 case AT_ColumnDefault:
2868 case AT_ProcessedConstraint: /* becomes AT_AddConstraint */
2869 case AT_AddConstraintRecurse: /* becomes AT_AddConstraint */
2870 case AT_ReAddConstraint: /* becomes AT_AddConstraint */
2872 case AT_EnableAlwaysTrig:
2873 case AT_EnableReplicaTrig:
2874 case AT_EnableTrigAll:
2875 case AT_EnableTrigUser:
2876 case AT_DisableTrig:
2877 case AT_DisableTrigAll:
2878 case AT_DisableTrigUser:
2879 case AT_AlterConstraint:
2880 case AT_AddIndex: /* from ADD CONSTRAINT */
2881 case AT_AddIndexConstraint:
2882 case AT_ReplicaIdentity:
2884 case AT_EnableRowSecurity:
2885 case AT_DisableRowSecurity:
2886 cmd_lockmode = AccessExclusiveLock;
2889 case AT_AddConstraint:
2890 if (IsA(cmd->def, Constraint))
2892 Constraint *con = (Constraint *) cmd->def;
2894 switch (con->contype)
2896 case CONSTR_EXCLUSION:
2897 case CONSTR_PRIMARY:
2901 * Cases essentially the same as CREATE INDEX. We
2902 * could reduce the lock strength to ShareLock if
2903 * we can work out how to allow concurrent catalog
2904 * updates. XXX Might be set down to
2905 * ShareRowExclusiveLock but requires further
2908 cmd_lockmode = AccessExclusiveLock;
2910 case CONSTR_FOREIGN:
2913 * We add triggers to both tables when we add a
2914 * Foreign Key, so the lock level must be at least
2915 * as strong as CREATE TRIGGER. XXX Might be set
2916 * down to ShareRowExclusiveLock though trigger
2917 * info is accessed by pg_get_triggerdef
2919 cmd_lockmode = AccessExclusiveLock;
2923 cmd_lockmode = AccessExclusiveLock;
2929 * These subcommands affect inheritance behaviour. Queries
2930 * started before us will continue to see the old inheritance
2931 * behaviour, while queries started after we commit will see
2932 * new behaviour. No need to prevent reads or writes to the
2933 * subtable while we hook it up though. Changing the TupDesc
2934 * may be a problem, so keep highest lock.
2937 case AT_DropInherit:
2938 cmd_lockmode = AccessExclusiveLock;
2942 * These subcommands affect implicit row type conversion. They
2943 * have affects similar to CREATE/DROP CAST on queries. don't
2944 * provide for invalidating parse trees as a result of such
2945 * changes, so we keep these at AccessExclusiveLock.
2949 cmd_lockmode = AccessExclusiveLock;
2953 * Only used by CREATE OR REPLACE VIEW which must conflict
2954 * with an SELECTs currently using the view.
2956 case AT_ReplaceRelOptions:
2957 cmd_lockmode = AccessExclusiveLock;
2961 * These subcommands affect general strategies for performance
2962 * and maintenance, though don't change the semantic results
2963 * from normal data reads and writes. Delaying an ALTER TABLE
2964 * behind currently active writes only delays the point where
2965 * the new strategy begins to take effect, so there is no
2966 * benefit in waiting. In this case the minimum restriction
2967 * applies: we don't currently allow concurrent catalog
2970 case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
2971 case AT_ClusterOn: /* Uses MVCC in getIndexes() */
2972 case AT_DropCluster: /* Uses MVCC in getIndexes() */
2973 case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
2974 case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
2975 cmd_lockmode = ShareUpdateExclusiveLock;
2979 case AT_SetUnLogged:
2980 cmd_lockmode = AccessExclusiveLock;
2983 case AT_ValidateConstraint: /* Uses MVCC in
2984 * getConstraints() */
2985 cmd_lockmode = ShareUpdateExclusiveLock;
2989 * Rel options are more complex than first appears. Options
2990 * are set here for tables, views and indexes; for historical
2991 * reasons these can all be used with ALTER TABLE, so we can't
2992 * decide between them using the basic grammar.
2994 * XXX Look in detail at each option to determine lock level,
2995 * e.g. cmd_lockmode = GetRelOptionsLockLevel((List *)
2998 case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
3000 case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
3002 cmd_lockmode = AccessExclusiveLock;
3006 elog(ERROR, "unrecognized alter table type: %d",
3007 (int) cmd->subtype);
3012 * Take the greatest lockmode from any subcommand
3014 if (cmd_lockmode > lockmode)
3015 lockmode = cmd_lockmode;
3022 * ATController provides top level control over the phases.
3024 * parsetree is passed in to allow it to be passed to event triggers
3028 ATController(AlterTableStmt *parsetree,
3029 Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
3034 /* Phase 1: preliminary examination of commands, create work queue */
3037 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3039 ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode);
3042 /* Close the relation, but keep lock until commit */
3043 relation_close(rel, NoLock);
3045 /* Phase 2: update system catalogs */
3046 ATRewriteCatalogs(&wqueue, lockmode);
3048 /* Phase 3: scan/rewrite tables as needed */
3049 ATRewriteTables(parsetree, &wqueue, lockmode);
3055 * Traffic cop for ALTER TABLE Phase 1 operations, including simple
3056 * recursion and permission checks.
3058 * Caller must have acquired appropriate lock type on relation already.
3059 * This lock should be held until commit.
3062 ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
3063 bool recurse, bool recursing, LOCKMODE lockmode)
3065 AlteredTableInfo *tab;
3066 int pass = AT_PASS_UNSET;
3068 /* Find or create work queue entry for this table */
3069 tab = ATGetQueueEntry(wqueue, rel);
3072 * Copy the original subcommand for each table. This avoids conflicts
3073 * when different child tables need to make different parse
3074 * transformations (for example, the same column may have different column
3075 * numbers in different children).
3077 cmd = copyObject(cmd);
3080 * Do permissions checking, recursion to child tables if needed, and any
3081 * additional phase-1 processing needed.
3083 switch (cmd->subtype)
3085 case AT_AddColumn: /* ADD COLUMN */
3086 ATSimplePermissions(rel,
3087 ATT_TABLE | ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
3088 ATPrepAddColumn(wqueue, rel, recurse, recursing, cmd, lockmode);
3089 /* Recursion occurs during execution phase */
3090 pass = AT_PASS_ADD_COL;
3092 case AT_AddColumnToView: /* add column via CREATE OR REPLACE
3094 ATSimplePermissions(rel, ATT_VIEW);
3095 ATPrepAddColumn(wqueue, rel, recurse, recursing, cmd, lockmode);
3096 /* Recursion occurs during execution phase */
3097 pass = AT_PASS_ADD_COL;
3099 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
3102 * We allow defaults on views so that INSERT into a view can have
3103 * default-ish behavior. This works because the rewriter
3104 * substitutes default values into INSERTs before it expands
3107 ATSimplePermissions(rel, ATT_TABLE | ATT_VIEW | ATT_FOREIGN_TABLE);
3108 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
3109 /* No command-specific prep needed */
3110 pass = cmd->def ? AT_PASS_ADD_CONSTR : AT_PASS_DROP;
3112 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
3113 ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
3114 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
3115 /* No command-specific prep needed */
3116 pass = AT_PASS_DROP;
3118 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
3119 ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
3120 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
3121 /* No command-specific prep needed */
3122 pass = AT_PASS_ADD_CONSTR;
3124 case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
3125 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
3126 /* Performs own permission checks */
3127 ATPrepSetStatistics(rel, cmd->name, cmd->def, lockmode);
3128 pass = AT_PASS_MISC;
3130 case AT_SetOptions: /* ALTER COLUMN SET ( options ) */
3131 case AT_ResetOptions: /* ALTER COLUMN RESET ( options ) */
3132 ATSimplePermissions(rel, ATT_TABLE | ATT_MATVIEW | ATT_INDEX | ATT_FOREIGN_TABLE);
3133 /* This command never recurses */
3134 pass = AT_PASS_MISC;
3136 case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
3137 ATSimplePermissions(rel, ATT_TABLE | ATT_MATVIEW);
3138 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
3139 /* No command-specific prep needed */
3140 pass = AT_PASS_MISC;
3142 case AT_DropColumn: /* DROP COLUMN */
3143 ATSimplePermissions(rel,
3144 ATT_TABLE | ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
3145 ATPrepDropColumn(wqueue, rel, recurse, recursing, cmd, lockmode);
3146 /* Recursion occurs during execution phase */
3147 pass = AT_PASS_DROP;
3149 case AT_AddIndex: /* ADD INDEX */
3150 ATSimplePermissions(rel, ATT_TABLE);
3151 /* This command never recurses */
3152 /* No command-specific prep needed */
3153 pass = AT_PASS_ADD_INDEX;
3155 case AT_AddConstraint: /* ADD CONSTRAINT */
3156 ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
3157 /* Recursion occurs during execution phase */
3158 /* No command-specific prep needed except saving recurse flag */
3160 cmd->subtype = AT_AddConstraintRecurse;
3161 pass = AT_PASS_ADD_CONSTR;
3163 case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
3164 ATSimplePermissions(rel, ATT_TABLE);
3165 /* This command never recurses */
3166 /* No command-specific prep needed */
3167 pass = AT_PASS_ADD_CONSTR;
3169 case AT_DropConstraint: /* DROP CONSTRAINT */
3170 ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
3171 /* Recursion occurs during execution phase */
3172 /* No command-specific prep needed except saving recurse flag */
3174 cmd->subtype = AT_DropConstraintRecurse;
3175 pass = AT_PASS_DROP;
3177 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
3178 ATSimplePermissions(rel,
3179 ATT_TABLE | ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
3180 /* Performs own recursion */
3181 ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd, lockmode);
3182 pass = AT_PASS_ALTER_TYPE;
3184 case AT_AlterColumnGenericOptions:
3185 ATSimplePermissions(rel, ATT_FOREIGN_TABLE);
3186 /* This command never recurses */
3187 /* No command-specific prep needed */
3188 pass = AT_PASS_MISC;
3190 case AT_ChangeOwner: /* ALTER OWNER */
3191 /* This command never recurses */
3192 /* No command-specific prep needed */
3193 pass = AT_PASS_MISC;
3195 case AT_ClusterOn: /* CLUSTER ON */
3196 case AT_DropCluster: /* SET WITHOUT CLUSTER */
3197 ATSimplePermissions(rel, ATT_TABLE | ATT_MATVIEW);
3198 /* These commands never recurse */
3199 /* No command-specific prep needed */
3200 pass = AT_PASS_MISC;
3202 case AT_SetLogged: /* SET LOGGED */
3203 ATSimplePermissions(rel, ATT_TABLE);
3204 tab->chgPersistence = ATPrepChangePersistence(rel, true);
3205 /* force rewrite if necessary; see comment in ATRewriteTables */
3206 if (tab->chgPersistence)
3208 tab->rewrite |= AT_REWRITE_ALTER_PERSISTENCE;
3209 tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
3211 pass = AT_PASS_MISC;
3213 case AT_SetUnLogged: /* SET UNLOGGED */
3214 ATSimplePermissions(rel, ATT_TABLE);
3215 tab->chgPersistence = ATPrepChangePersistence(rel, false);
3216 /* force rewrite if necessary; see comment in ATRewriteTables */
3217 if (tab->chgPersistence)
3219 tab->rewrite |= AT_REWRITE_ALTER_PERSISTENCE;
3220 tab->newrelpersistence = RELPERSISTENCE_UNLOGGED;
3222 pass = AT_PASS_MISC;
3224 case AT_AddOids: /* SET WITH OIDS */
3225 ATSimplePermissions(rel, ATT_TABLE);
3226 if (!rel->rd_rel->relhasoids || recursing)
3227 ATPrepAddOids(wqueue, rel, recurse, cmd, lockmode);
3228 /* Recursion occurs during execution phase */
3229 pass = AT_PASS_ADD_COL;
3231 case AT_DropOids: /* SET WITHOUT OIDS */
3232 ATSimplePermissions(rel, ATT_TABLE);
3233 /* Performs own recursion */
3234 if (rel->rd_rel->relhasoids)
3236 AlterTableCmd *dropCmd = makeNode(AlterTableCmd);
3238 dropCmd->subtype = AT_DropColumn;
3239 dropCmd->name = pstrdup("oid");
3240 dropCmd->behavior = cmd->behavior;
3241 ATPrepCmd(wqueue, rel, dropCmd, recurse, false, lockmode);
3243 pass = AT_PASS_DROP;
3245 case AT_SetTableSpace: /* SET TABLESPACE */
3246 ATSimplePermissions(rel, ATT_TABLE | ATT_MATVIEW | ATT_INDEX);
3247 /* This command never recurses */
3248 ATPrepSetTableSpace(tab, rel, cmd->name, lockmode);
3249 pass = AT_PASS_MISC; /* doesn't actually matter */
3251 case AT_SetRelOptions: /* SET (...) */
3252 case AT_ResetRelOptions: /* RESET (...) */
3253 case AT_ReplaceRelOptions: /* reset them all, then set just these */
3254 ATSimplePermissions(rel, ATT_TABLE | ATT_VIEW | ATT_MATVIEW | ATT_INDEX);
3255 /* This command never recurses */
3256 /* No command-specific prep needed */
3257 pass = AT_PASS_MISC;
3259 case AT_AddInherit: /* INHERIT */
3260 ATSimplePermissions(rel, ATT_TABLE);
3261 /* This command never recurses */
3262 ATPrepAddInherit(rel);
3263 pass = AT_PASS_MISC;
3265 case AT_AlterConstraint: /* ALTER CONSTRAINT */
3266 ATSimplePermissions(rel, ATT_TABLE);
3267 pass = AT_PASS_MISC;
3269 case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
3270 ATSimplePermissions(rel, ATT_TABLE);
3271 /* Recursion occurs during execution phase */
3272 /* No command-specific prep needed except saving recurse flag */
3274 cmd->subtype = AT_ValidateConstraintRecurse;
3275 pass = AT_PASS_MISC;
3277 case AT_ReplicaIdentity: /* REPLICA IDENTITY ... */
3278 ATSimplePermissions(rel, ATT_TABLE | ATT_MATVIEW);
3279 pass = AT_PASS_MISC;
3280 /* This command never recurses */
3281 /* No command-specific prep needed */
3283 case AT_EnableTrig: /* ENABLE TRIGGER variants */
3284 case AT_EnableAlwaysTrig:
3285 case AT_EnableReplicaTrig:
3286 case AT_EnableTrigAll:
3287 case AT_EnableTrigUser:
3288 case AT_DisableTrig: /* DISABLE TRIGGER variants */
3289 case AT_DisableTrigAll:
3290 case AT_DisableTrigUser:
3291 ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
3292 pass = AT_PASS_MISC;
3294 case AT_EnableRule: /* ENABLE/DISABLE RULE variants */
3295 case AT_EnableAlwaysRule:
3296 case AT_EnableReplicaRule:
3297 case AT_DisableRule:
3298 case AT_DropInherit: /* NO INHERIT */
3299 case AT_AddOf: /* OF */
3300 case AT_DropOf: /* NOT OF */
3301 case AT_EnableRowSecurity:
3302 case AT_DisableRowSecurity:
3303 ATSimplePermissions(rel, ATT_TABLE);
3304 /* These commands never recurse */
3305 /* No command-specific prep needed */
3306 pass = AT_PASS_MISC;
3308 case AT_GenericOptions:
3309 ATSimplePermissions(rel, ATT_FOREIGN_TABLE);
3310 /* No command-specific prep needed */
3311 pass = AT_PASS_MISC;
3314 elog(ERROR, "unrecognized alter table type: %d",
3315 (int) cmd->subtype);
3316 pass = AT_PASS_UNSET; /* keep compiler quiet */
3319 Assert(pass > AT_PASS_UNSET);
3321 /* Add the subcommand to the appropriate list for phase 2 */
3322 tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
3328 * Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
3329 * dispatched in a "safe" execution order (designed to avoid unnecessary
3333 ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode)
3339 * We process all the tables "in parallel", one pass at a time. This is
3340 * needed because we may have to propagate work from one table to another
3341 * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
3342 * re-adding of the foreign key constraint to the other table). Work can
3343 * only be propagated into later passes, however.
3345 for (pass = 0; pass < AT_NUM_PASSES; pass++)
3347 /* Go through each table that needs to be processed */
3348 foreach(ltab, *wqueue)
3350 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
3351 List *subcmds = tab->subcmds[pass];
3359 * Appropriate lock was obtained by phase 1, needn't get it again
3361 rel = relation_open(tab->relid, NoLock);
3363 foreach(lcmd, subcmds)
3364 ATExecCmd(wqueue, tab, rel, (AlterTableCmd *) lfirst(lcmd), lockmode);
3367 * After the ALTER TYPE pass, do cleanup work (this is not done in
3368 * ATExecAlterColumnType since it should be done only once if
3369 * multiple columns of a table are altered).
3371 if (pass == AT_PASS_ALTER_TYPE)
3372 ATPostAlterTypeCleanup(wqueue, tab, lockmode);
3374 relation_close(rel, NoLock);
3378 /* Check to see if a toast table must be added. */
3379 foreach(ltab, *wqueue)
3381 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
3383 if (tab->relkind == RELKIND_RELATION ||
3384 tab->relkind == RELKIND_MATVIEW)
3385 AlterTableCreateToastTable(tab->relid, (Datum) 0, lockmode);
3390 * ATExecCmd: dispatch a subcommand to appropriate execution routine
3393 ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
3394 AlterTableCmd *cmd, LOCKMODE lockmode)
3396 switch (cmd->subtype)
3398 case AT_AddColumn: /* ADD COLUMN */
3399 case AT_AddColumnToView: /* add column via CREATE OR REPLACE
3401 ATExecAddColumn(wqueue, tab, rel, (ColumnDef *) cmd->def,
3402 false, false, false, lockmode);
3404 case AT_AddColumnRecurse:
3405 ATExecAddColumn(wqueue, tab, rel, (ColumnDef *) cmd->def,
3406 false, true, false, lockmode);
3408 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
3409 ATExecColumnDefault(rel, cmd->name, cmd->def, lockmode);
3411 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
3412 ATExecDropNotNull(rel, cmd->name, lockmode);
3414 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
3415 ATExecSetNotNull(tab, rel, cmd->name, lockmode);
3417 case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
3418 ATExecSetStatistics(rel, cmd->name, cmd->def, lockmode);
3420 case AT_SetOptions: /* ALTER COLUMN SET ( options ) */
3421 ATExecSetOptions(rel, cmd->name, cmd->def, false, lockmode);
3423 case AT_ResetOptions: /* ALTER COLUMN RESET ( options ) */
3424 ATExecSetOptions(rel, cmd->name, cmd->def, true, lockmode);
3426 case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
3427 ATExecSetStorage(rel, cmd->name, cmd->def, lockmode);
3429 case AT_DropColumn: /* DROP COLUMN */
3430 ATExecDropColumn(wqueue, rel, cmd->name,
3431 cmd->behavior, false, false, cmd->missing_ok, lockmode);
3433 case AT_DropColumnRecurse: /* DROP COLUMN with recursion */
3434 ATExecDropColumn(wqueue, rel, cmd->name,
3435 cmd->behavior, true, false, cmd->missing_ok, lockmode);
3437 case AT_AddIndex: /* ADD INDEX */
3438 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false, lockmode);
3440 case AT_ReAddIndex: /* ADD INDEX */
3441 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true, lockmode);
3443 case AT_AddConstraint: /* ADD CONSTRAINT */
3444 ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
3445 false, false, lockmode);
3447 case AT_AddConstraintRecurse: /* ADD CONSTRAINT with recursion */
3448 ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
3449 true, false, lockmode);
3451 case AT_ReAddConstraint: /* Re-add pre-existing check
3453 ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
3454 false, true, lockmode);
3456 case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
3457 ATExecAddIndexConstraint(tab, rel, (IndexStmt *) cmd->def, lockmode);
3459 case AT_AlterConstraint: /* ALTER CONSTRAINT */
3460 ATExecAlterConstraint(rel, cmd, false, false, lockmode);
3462 case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
3463 ATExecValidateConstraint(rel, cmd->name, false, false, lockmode);
3465 case AT_ValidateConstraintRecurse: /* VALIDATE CONSTRAINT with
3467 ATExecValidateConstraint(rel, cmd->name, true, false, lockmode);
3469 case AT_DropConstraint: /* DROP CONSTRAINT */
3470 ATExecDropConstraint(rel, cmd->name, cmd->behavior,
3472 cmd->missing_ok, lockmode);
3474 case AT_DropConstraintRecurse: /* DROP CONSTRAINT with recursion */
3475 ATExecDropConstraint(rel, cmd->name, cmd->behavior,
3477 cmd->missing_ok, lockmode);
3479 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
3480 ATExecAlterColumnType(tab, rel, cmd, lockmode);
3482 case AT_AlterColumnGenericOptions: /* ALTER COLUMN OPTIONS */
3483 ATExecAlterColumnGenericOptions(rel, cmd->name, (List *) cmd->def, lockmode);
3485 case AT_ChangeOwner: /* ALTER OWNER */
3486 ATExecChangeOwner(RelationGetRelid(rel),
3487 get_role_oid(cmd->name, false),
3490 case AT_ClusterOn: /* CLUSTER ON */
3491 ATExecClusterOn(rel, cmd->name, lockmode);
3493 case AT_DropCluster: /* SET WITHOUT CLUSTER */
3494 ATExecDropCluster(rel, lockmode);
3496 case AT_SetLogged: /* SET LOGGED */
3497 case AT_SetUnLogged: /* SET UNLOGGED */
3499 case AT_AddOids: /* SET WITH OIDS */
3500 /* Use the ADD COLUMN code, unless prep decided to do nothing */
3501 if (cmd->def != NULL)
3502 ATExecAddColumn(wqueue, tab, rel, (ColumnDef *) cmd->def,
3503 true, false, false, lockmode);
3505 case AT_AddOidsRecurse: /* SET WITH OIDS */
3506 /* Use the ADD COLUMN code, unless prep decided to do nothing */
3507 if (cmd->def != NULL)
3508 ATExecAddColumn(wqueue, tab, rel, (ColumnDef *) cmd->def,
3509 true, true, false, lockmode);
3511 case AT_DropOids: /* SET WITHOUT OIDS */
3514 * Nothing to do here; we'll have generated a DropColumn
3515 * subcommand to do the real work
3518 case AT_SetTableSpace: /* SET TABLESPACE */
3521 * Nothing to do here; Phase 3 does the work
3524 case AT_SetRelOptions: /* SET (...) */
3525 case AT_ResetRelOptions: /* RESET (...) */
3526 case AT_ReplaceRelOptions: /* replace entire option list */
3527 ATExecSetRelOptions(rel, (List *) cmd->def, cmd->subtype, lockmode);
3529 case AT_EnableTrig: /* ENABLE TRIGGER name */
3530 ATExecEnableDisableTrigger(rel, cmd->name,
3531 TRIGGER_FIRES_ON_ORIGIN, false, lockmode);
3533 case AT_EnableAlwaysTrig: /* ENABLE ALWAYS TRIGGER name */
3534 ATExecEnableDisableTrigger(rel, cmd->name,
3535 TRIGGER_FIRES_ALWAYS, false, lockmode);
3537 case AT_EnableReplicaTrig: /* ENABLE REPLICA TRIGGER name */
3538 ATExecEnableDisableTrigger(rel, cmd->name,
3539 TRIGGER_FIRES_ON_REPLICA, false, lockmode);
3541 case AT_DisableTrig: /* DISABLE TRIGGER name */
3542 ATExecEnableDisableTrigger(rel, cmd->name,
3543 TRIGGER_DISABLED, false, lockmode);
3545 case AT_EnableTrigAll: /* ENABLE TRIGGER ALL */
3546 ATExecEnableDisableTrigger(rel, NULL,
3547 TRIGGER_FIRES_ON_ORIGIN, false, lockmode);
3549 case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
3550 ATExecEnableDisableTrigger(rel, NULL,
3551 TRIGGER_DISABLED, false, lockmode);
3553 case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
3554 ATExecEnableDisableTrigger(rel, NULL,
3555 TRIGGER_FIRES_ON_ORIGIN, true, lockmode);
3557 case AT_DisableTrigUser: /* DISABLE TRIGGER USER */
3558 ATExecEnableDisableTrigger(rel, NULL,
3559 TRIGGER_DISABLED, true, lockmode);
3562 case AT_EnableRule: /* ENABLE RULE name */
3563 ATExecEnableDisableRule(rel, cmd->name,
3564 RULE_FIRES_ON_ORIGIN, lockmode);
3566 case AT_EnableAlwaysRule: /* ENABLE ALWAYS RULE name */
3567 ATExecEnableDisableRule(rel, cmd->name,
3568 RULE_FIRES_ALWAYS, lockmode);
3570 case AT_EnableReplicaRule: /* ENABLE REPLICA RULE name */
3571 ATExecEnableDisableRule(rel, cmd->name,
3572 RULE_FIRES_ON_REPLICA, lockmode);
3574 case AT_DisableRule: /* DISABLE RULE name */
3575 ATExecEnableDisableRule(rel, cmd->name,
3576 RULE_DISABLED, lockmode);
3580 ATExecAddInherit(rel, (RangeVar *) cmd->def, lockmode);
3582 case AT_DropInherit:
3583 ATExecDropInherit(rel, (RangeVar *) cmd->def, lockmode);
3586 ATExecAddOf(rel, (TypeName *) cmd->def, lockmode);
3589 ATExecDropOf(rel, lockmode);
3591 case AT_ReplicaIdentity:
3592 ATExecReplicaIdentity(rel, (ReplicaIdentityStmt *) cmd->def, lockmode);
3594 case AT_EnableRowSecurity:
3595 ATExecEnableRowSecurity(rel);
3597 case AT_DisableRowSecurity:
3598 ATExecDisableRowSecurity(rel);
3600 case AT_GenericOptions:
3601 ATExecGenericOptions(rel, (List *) cmd->def);
3604 elog(ERROR, "unrecognized alter table type: %d",
3605 (int) cmd->subtype);
3610 * Bump the command counter to ensure the next subcommand in the sequence
3611 * can see the changes so far
3613 CommandCounterIncrement();
3617 * ATRewriteTables: ALTER TABLE phase 3
3620 ATRewriteTables(AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode)
3624 /* Go through each table that needs to be checked or rewritten */
3625 foreach(ltab, *wqueue)
3627 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
3629 /* Foreign tables have no storage. */
3630 if (tab->relkind == RELKIND_FOREIGN_TABLE)
3634 * If we change column data types or add/remove OIDs, the operation
3635 * has to be propagated to tables that use this table's rowtype as a
3636 * column type. tab->newvals will also be non-NULL in the case where
3637 * we're adding a column with a default. We choose to forbid that
3638 * case as well, since composite types might eventually support
3641 * (Eventually we'll probably need to check for composite type
3642 * dependencies even when we're just scanning the table without a
3643 * rewrite, but at the moment a composite type does not enforce any
3644 * constraints, so it's not necessary/appropriate to enforce them just
3647 if (tab->newvals != NIL || tab->rewrite > 0)
3651 rel = heap_open(tab->relid, NoLock);
3652 find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
3653 heap_close(rel, NoLock);
3657 * We only need to rewrite the table if at least one column needs to
3658 * be recomputed, we are adding/removing the OID column, or we are
3659 * changing its persistence.
3661 * There are two reasons for requiring a rewrite when changing
3662 * persistence: on one hand, we need to ensure that the buffers
3663 * belonging to each of the two relations are marked with or without
3664 * BM_PERMANENT properly. On the other hand, since rewriting creates
3665 * and assigns a new relfilenode, we automatically create or drop an
3666 * init fork for the relation as appropriate.
3668 if (tab->rewrite > 0)
3670 /* Build a temporary relation and copy data */
3676 OldHeap = heap_open(tab->relid, NoLock);
3679 * We don't support rewriting of system catalogs; there are too
3680 * many corner cases and too little benefit. In particular this
3681 * is certainly not going to work for mapped catalogs.
3683 if (IsSystemRelation(OldHeap))
3685 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3686 errmsg("cannot rewrite system relation \"%s\"",
3687 RelationGetRelationName(OldHeap))));
3689 if (RelationIsUsedAsCatalogTable(OldHeap))
3691 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3692 errmsg("cannot rewrite table \"%s\" used as a catalog table",
3693 RelationGetRelationName(OldHeap))));
3696 * Don't allow rewrite on temp tables of other backends ... their
3697 * local buffer manager is not going to cope.
3699 if (RELATION_IS_OTHER_TEMP(OldHeap))
3701 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3702 errmsg("cannot rewrite temporary tables of other sessions")));
3705 * Select destination tablespace (same as original unless user
3706 * requested a change)
3708 if (tab->newTableSpace)
3709 NewTableSpace = tab->newTableSpace;
3711 NewTableSpace = OldHeap->rd_rel->reltablespace;
3714 * Select persistence of transient table (same as original unless
3715 * user requested a change)
3717 persistence = tab->chgPersistence ?
3718 tab->newrelpersistence : OldHeap->rd_rel->relpersistence;
3720 heap_close(OldHeap, NoLock);
3723 * Fire off an Event Trigger now, before actually rewriting the
3726 * We don't support Event Trigger for nested commands anywhere,
3727 * here included, and parsetree is given NULL when coming from
3728 * AlterTableInternal.
3730 * And fire it only once.
3733 EventTriggerTableRewrite((Node *)parsetree,
3738 * Create transient table that will receive the modified data.
3740 * Ensure it is marked correctly as logged or unlogged. We have
3741 * to do this here so that buffers for the new relfilenode will
3742 * have the right persistence set, and at the same time ensure
3743 * that the original filenode's buffers will get read in with the
3744 * correct setting (i.e. the original one). Otherwise a rollback
3745 * after the rewrite would possibly result with buffers for the
3746 * original filenode having the wrong persistence setting.
3748 * NB: This relies on swap_relation_files() also swapping the
3749 * persistence. That wouldn't work for pg_class, but that can't be
3752 OIDNewHeap = make_new_heap(tab->relid, NewTableSpace, persistence,
3756 * Copy the heap data into the new table with the desired
3757 * modifications, and test the current data within the table
3758 * against new constraints generated by ALTER TABLE commands.
3760 ATRewriteTable(tab, OIDNewHeap, lockmode);
3763 * Swap the physical files of the old and new heaps, then rebuild
3764 * indexes and discard the old heap. We can use RecentXmin for
3765 * the table's new relfrozenxid because we rewrote all the tuples
3766 * in ATRewriteTable, so no older Xid remains in the table. Also,
3767 * we never try to swap toast tables by content, since we have no
3768 * interest in letting this code work on system catalogs.
3770 finish_heap_swap(tab->relid, OIDNewHeap,
3772 !OidIsValid(tab->newTableSpace),
3774 ReadNextMultiXactId(),
3780 * Test the current data within the table against new constraints
3781 * generated by ALTER TABLE commands, but don't rebuild data.
3783 if (tab->constraints != NIL || tab->new_notnull)
3784 ATRewriteTable(tab, InvalidOid, lockmode);
3787 * If we had SET TABLESPACE but no reason to reconstruct tuples,
3788 * just do a block-by-block copy.
3790 if (tab->newTableSpace)
3791 ATExecSetTableSpace(tab->relid, tab->newTableSpace, lockmode);
3796 * Foreign key constraints are checked in a final pass, since (a) it's
3797 * generally best to examine each one separately, and (b) it's at least
3798 * theoretically possible that we have changed both relations of the
3799 * foreign key, and we'd better have finished both rewrites before we try
3800 * to read the tables.
3802 foreach(ltab, *wqueue)
3804 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
3805 Relation rel = NULL;
3808 foreach(lcon, tab->constraints)
3810 NewConstraint *con = lfirst(lcon);
3812 if (con->contype == CONSTR_FOREIGN)
3814 Constraint *fkconstraint = (Constraint *) con->qual;
3819 /* Long since locked, no need for another */
3820 rel = heap_open(tab->relid, NoLock);
3823 refrel = heap_open(con->refrelid, RowShareLock);
3825 validateForeignKeyConstraint(fkconstraint->conname, rel, refrel,
3830 * No need to mark the constraint row as validated, we did
3831 * that when we inserted the row earlier.
3834 heap_close(refrel, NoLock);
3839 heap_close(rel, NoLock);
3844 * ATRewriteTable: scan or rewrite one table
3846 * OIDNewHeap is InvalidOid if we don't need to rewrite
3849 ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap, LOCKMODE lockmode)
3853 TupleDesc oldTupDesc;
3854 TupleDesc newTupDesc;
3855 bool needscan = false;
3856 List *notnull_attrs;
3861 BulkInsertState bistate;
3865 * Open the relation(s). We have surely already locked the existing
3868 oldrel = heap_open(tab->relid, NoLock);
3869 oldTupDesc = tab->oldDesc;
3870 newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
3872 if (OidIsValid(OIDNewHeap))
3873 newrel = heap_open(OIDNewHeap, lockmode);
3878 * Prepare a BulkInsertState and options for heap_insert. Because we're
3879 * building a new heap, we can skip WAL-logging and fsync it to disk at
3880 * the end instead (unless WAL-logging is required for archiving or
3881 * streaming replication). The FSM is empty too, so don't bother using it.
3885 mycid = GetCurrentCommandId(true);
3886 bistate = GetBulkInsertState();
3888 hi_options = HEAP_INSERT_SKIP_FSM;
3889 if (!XLogIsNeeded())
3890 hi_options |= HEAP_INSERT_SKIP_WAL;
3894 /* keep compiler quiet about using these uninitialized */
3901 * Generate the constraint and default execution states
3904 estate = CreateExecutorState();
3906 /* Build the needed expression execution states */
3907 foreach(l, tab->constraints)
3909 NewConstraint *con = lfirst(l);
3911 switch (con->contype)
3915 con->qualstate = (List *)
3916 ExecPrepareExpr((Expr *) con->qual, estate);
3918 case CONSTR_FOREIGN:
3919 /* Nothing to do here */
3922 elog(ERROR, "unrecognized constraint type: %d",
3923 (int) con->contype);
3927 foreach(l, tab->newvals)
3929 NewColumnValue *ex = lfirst(l);
3931 /* expr already planned */
3932 ex->exprstate = ExecInitExpr((Expr *) ex->expr, NULL);
3935 notnull_attrs = NIL;
3936 if (newrel || tab->new_notnull)
3939 * If we are rebuilding the tuples OR if we added any new NOT NULL
3940 * constraints, check all not-null constraints. This is a bit of
3941 * overkill but it minimizes risk of bugs, and heap_attisnull is a
3942 * pretty cheap test anyway.
3944 for (i = 0; i < newTupDesc->natts; i++)
3946 if (newTupDesc->attrs[i]->attnotnull &&
3947 !newTupDesc->attrs[i]->attisdropped)
3948 notnull_attrs = lappend_int(notnull_attrs, i);
3954 if (newrel || needscan)
3956 ExprContext *econtext;
3959 TupleTableSlot *oldslot;
3960 TupleTableSlot *newslot;
3963 MemoryContext oldCxt;
3964 List *dropped_attrs = NIL;
3970 (errmsg("rewriting table \"%s\"",
3971 RelationGetRelationName(oldrel))));
3974 (errmsg("verifying table \"%s\"",
3975 RelationGetRelationName(oldrel))));
3980 * All predicate locks on the tuples or pages are about to be made
3981 * invalid, because we move tuples around. Promote them to
3984 TransferPredicateLocksToHeapRelation(oldrel);
3987 econtext = GetPerTupleExprContext(estate);
3990 * Make tuple slots for old and new tuples. Note that even when the
3991 * tuples are the same, the tupDescs might not be (consider ADD COLUMN
3992 * without a default).
3994 oldslot = MakeSingleTupleTableSlot(oldTupDesc);
3995 newslot = MakeSingleTupleTableSlot(newTupDesc);
3997 /* Preallocate values/isnull arrays */
3998 i = Max(newTupDesc->natts, oldTupDesc->natts);
3999 values = (Datum *) palloc(i * sizeof(Datum));
4000 isnull = (bool *) palloc(i * sizeof(bool));
4001 memset(values, 0, i * sizeof(Datum));
4002 memset(isnull, true, i * sizeof(bool));
4005 * Any attributes that are dropped according to the new tuple
4006 * descriptor can be set to NULL. We precompute the list of dropped
4007 * attributes to avoid needing to do so in the per-tuple loop.
4009 for (i = 0; i < newTupDesc->natts; i++)
4011 if (newTupDesc->attrs[i]->attisdropped)
4012 dropped_attrs = lappend_int(dropped_attrs, i);
4016 * Scan through the rows, generating a new row if needed and then
4017 * checking all the constraints.
4019 snapshot = RegisterSnapshot(GetLatestSnapshot());
4020 scan = heap_beginscan(oldrel, snapshot, 0, NULL);
4023 * Switch to per-tuple memory context and reset it for each tuple
4024 * produced, so we don't leak memory.
4026 oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
4028 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
4030 if (tab->rewrite > 0)
4032 Oid tupOid = InvalidOid;
4034 /* Extract data from old tuple */
4035 heap_deform_tuple(tuple, oldTupDesc, values, isnull);
4036 if (oldTupDesc->tdhasoid)
4037 tupOid = HeapTupleGetOid(tuple);
4039 /* Set dropped attributes to null in new tuple */
4040 foreach(lc, dropped_attrs)
4041 isnull[lfirst_int(lc)] = true;
4044 * Process supplied expressions to replace selected columns.
4045 * Expression inputs come from the old tuple.
4047 ExecStoreTuple(tuple, oldslot, InvalidBuffer, false);
4048 econtext->ecxt_scantuple = oldslot;
4050 foreach(l, tab->newvals)
4052 NewColumnValue *ex = lfirst(l);
4054 values[ex->attnum - 1] = ExecEvalExpr(ex->exprstate,
4056 &isnull[ex->attnum - 1],
4061 * Form the new tuple. Note that we don't explicitly pfree it,
4062 * since the per-tuple memory context will be reset shortly.
4064 tuple = heap_form_tuple(newTupDesc, values, isnull);
4066 /* Preserve OID, if any */
4067 if (newTupDesc->tdhasoid)
4068 HeapTupleSetOid(tuple, tupOid);
4071 * Constraints might reference the tableoid column, so
4072 * initialize t_tableOid before evaluating them.
4074 tuple->t_tableOid = RelationGetRelid(oldrel);
4077 /* Now check any constraints on the possibly-changed tuple */
4078 ExecStoreTuple(tuple, newslot, InvalidBuffer, false);
4079 econtext->ecxt_scantuple = newslot;
4081 foreach(l, notnull_attrs)
4083 int attn = lfirst_int(l);
4085 if (heap_attisnull(tuple, attn + 1))
4087 (errcode(ERRCODE_NOT_NULL_VIOLATION),
4088 errmsg("column \"%s\" contains null values",
4089 NameStr(newTupDesc->attrs[attn]->attname)),
4090 errtablecol(oldrel, attn + 1)));
4093 foreach(l, tab->constraints)
4095 NewConstraint *con = lfirst(l);
4097 switch (con->contype)
4100 if (!ExecQual(con->qualstate, econtext, true))
4102 (errcode(ERRCODE_CHECK_VIOLATION),
4103 errmsg("check constraint \"%s\" is violated by some row",
4105 errtableconstraint(oldrel, con->name)));
4107 case CONSTR_FOREIGN:
4108 /* Nothing to do here */
4111 elog(ERROR, "unrecognized constraint type: %d",
4112 (int) con->contype);
4116 /* Write the tuple out to the new relation */
4118 heap_insert(newrel, tuple, mycid, hi_options, bistate);
4120 ResetExprContext(econtext);
4122 CHECK_FOR_INTERRUPTS();
4125 MemoryContextSwitchTo(oldCxt);
4127 UnregisterSnapshot(snapshot);
4129 ExecDropSingleTupleTableSlot(oldslot);
4130 ExecDropSingleTupleTableSlot(newslot);
4133 FreeExecutorState(estate);
4135 heap_close(oldrel, NoLock);
4138 FreeBulkInsertState(bistate);
4140 /* If we skipped writing WAL, then we need to sync the heap. */
4141 if (hi_options & HEAP_INSERT_SKIP_WAL)
4144 heap_close(newrel, NoLock);
4149 * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
4151 static AlteredTableInfo *
4152 ATGetQueueEntry(List **wqueue, Relation rel)
4154 Oid relid = RelationGetRelid(rel);
4155 AlteredTableInfo *tab;
4158 foreach(ltab, *wqueue)
4160 tab = (AlteredTableInfo *) lfirst(ltab);
4161 if (tab->relid == relid)
4166 * Not there, so add it. Note that we make a copy of the relation's
4167 * existing descriptor before anything interesting can happen to it.
4169 tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
4171 tab->relkind = rel->rd_rel->relkind;
4172 tab->oldDesc = CreateTupleDescCopy(RelationGetDescr(rel));
4173 tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
4174 tab->chgPersistence = false;
4176 *wqueue = lappend(*wqueue, tab);
4182 * ATSimplePermissions
4184 * - Ensure that it is a relation (or possibly a view)
4185 * - Ensure this user is the owner
4186 * - Ensure that it is not a system table
4189 ATSimplePermissions(Relation rel, int allowed_targets)
4193 switch (rel->rd_rel->relkind)
4195 case RELKIND_RELATION:
4196 actual_target = ATT_TABLE;
4199 actual_target = ATT_VIEW;
4201 case RELKIND_MATVIEW:
4202 actual_target = ATT_MATVIEW;
4205 actual_target = ATT_INDEX;
4207 case RELKIND_COMPOSITE_TYPE:
4208 actual_target = ATT_COMPOSITE_TYPE;
4210 case RELKIND_FOREIGN_TABLE:
4211 actual_target = ATT_FOREIGN_TABLE;
4218 /* Wrong target type? */
4219 if ((actual_target & allowed_targets) == 0)
4220 ATWrongRelkindError(rel, allowed_targets);
4222 /* Permissions checks */
4223 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
4224 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
4225 RelationGetRelationName(rel));
4227 if (!allowSystemTableMods && IsSystemRelation(rel))
4229 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4230 errmsg("permission denied: \"%s\" is a system catalog",
4231 RelationGetRelationName(rel))));
4235 * ATWrongRelkindError
4237 * Throw an error when a relation has been determined to be of the wrong
4241 ATWrongRelkindError(Relation rel, int allowed_targets)
4245 switch (allowed_targets)
4248 msg = _("\"%s\" is not a table");
4250 case ATT_TABLE | ATT_VIEW:
4251 msg = _("\"%s\" is not a table or view");
4253 case ATT_TABLE | ATT_VIEW | ATT_MATVIEW | ATT_INDEX:
4254 msg = _("\"%s\" is not a table, view, materialized view, or index");
4256 case ATT_TABLE | ATT_MATVIEW:
4257 msg = _("\"%s\" is not a table or materialized view");
4259 case ATT_TABLE | ATT_MATVIEW | ATT_INDEX:
4260 msg = _("\"%s\" is not a table, materialized view, or index");
4262 case ATT_TABLE | ATT_FOREIGN_TABLE:
4263 msg = _("\"%s\" is not a table or foreign table");
4265 case ATT_TABLE | ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE:
4266 msg = _("\"%s\" is not a table, composite type, or foreign table");
4268 case ATT_TABLE | ATT_MATVIEW | ATT_INDEX | ATT_FOREIGN_TABLE:
4269 msg = _("\"%s\" is not a table, materialized view, composite type, or foreign table");
4272 msg = _("\"%s\" is not a view");
4274 case ATT_FOREIGN_TABLE:
4275 msg = _("\"%s\" is not a foreign table");
4278 /* shouldn't get here, add all necessary cases above */
4279 msg = _("\"%s\" is of the wrong type");
4284 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4285 errmsg(msg, RelationGetRelationName(rel))));
4291 * Simple table recursion sufficient for most ALTER TABLE operations.
4292 * All direct and indirect children are processed in an unspecified order.
4293 * Note that if a child inherits from the original table via multiple
4294 * inheritance paths, it will be visited just once.
4297 ATSimpleRecursion(List **wqueue, Relation rel,
4298 AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode)
4301 * Propagate to children if desired. Non-table relations never have
4302 * children, so no need to search in that case.
4304 if (recurse && rel->rd_rel->relkind == RELKIND_RELATION)
4306 Oid relid = RelationGetRelid(rel);
4310 children = find_all_inheritors(relid, lockmode, NULL);
4313 * find_all_inheritors does the recursive search of the inheritance
4314 * hierarchy, so all we have to do is process all of the relids in the
4315 * list that it returns.
4317 foreach(child, children)
4319 Oid childrelid = lfirst_oid(child);
4322 if (childrelid == relid)
4324 /* find_all_inheritors already got lock */
4325 childrel = relation_open(childrelid, NoLock);
4326 CheckTableNotInUse(childrel, "ALTER TABLE");
4327 ATPrepCmd(wqueue, childrel, cmd, false, true, lockmode);
4328 relation_close(childrel, NoLock);
4334 * ATTypedTableRecursion
4336 * Propagate ALTER TYPE operations to the typed tables of that type.
4337 * Also check the RESTRICT/CASCADE behavior. Given CASCADE, also permit
4338 * recursion to inheritance children of the typed tables.
4341 ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
4347 Assert(rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
4349 children = find_typed_table_dependencies(rel->rd_rel->reltype,
4350 RelationGetRelationName(rel),
4353 foreach(child, children)
4355 Oid childrelid = lfirst_oid(child);
4358 childrel = relation_open(childrelid, lockmode);
4359 CheckTableNotInUse(childrel, "ALTER TABLE");
4360 ATPrepCmd(wqueue, childrel, cmd, true, true, lockmode);
4361 relation_close(childrel, NoLock);
4367 * find_composite_type_dependencies
4369 * Check to see if a composite type is being used as a column in some
4370 * other table (possibly nested several levels deep in composite types!).
4371 * Eventually, we'd like to propagate the check or rewrite operation
4372 * into other such tables, but for now, just error out if we find any.
4374 * Caller should provide either a table name or a type name (not both) to
4375 * report in the error message, if any.
4377 * We assume that functions and views depending on the type are not reasons
4378 * to reject the ALTER. (How safe is this really?)
4381 find_composite_type_dependencies(Oid typeOid, Relation origRelation,
4382 const char *origTypeName)
4386 SysScanDesc depScan;
4391 * We scan pg_depend to find those things that depend on the rowtype. (We
4392 * assume we can ignore refobjsubid for a rowtype.)
4394 depRel = heap_open(DependRelationId, AccessShareLock);
4396 ScanKeyInit(&key[0],
4397 Anum_pg_depend_refclassid,
4398 BTEqualStrategyNumber, F_OIDEQ,
4399 ObjectIdGetDatum(TypeRelationId));
4400 ScanKeyInit(&key[1],
4401 Anum_pg_depend_refobjid,
4402 BTEqualStrategyNumber, F_OIDEQ,
4403 ObjectIdGetDatum(typeOid));
4405 depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
4408 while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
4410 Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
4412 Form_pg_attribute att;
4414 /* Ignore dependees that aren't user columns of relations */
4415 /* (we assume system columns are never of rowtypes) */
4416 if (pg_depend->classid != RelationRelationId ||
4417 pg_depend->objsubid <= 0)
4420 rel = relation_open(pg_depend->objid, AccessShareLock);
4421 att = rel->rd_att->attrs[pg_depend->objsubid - 1];
4423 if (rel->rd_rel->relkind == RELKIND_RELATION ||
4424 rel->rd_rel->relkind == RELKIND_MATVIEW)
4428 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4429 errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
4431 RelationGetRelationName(rel),
4432 NameStr(att->attname))));
4433 else if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
4435 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4436 errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
4437 RelationGetRelationName(origRelation),
4438 RelationGetRelationName(rel),
4439 NameStr(att->attname))));
4440 else if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
4442 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4443 errmsg("cannot alter foreign table \"%s\" because column \"%s.%s\" uses its row type",
4444 RelationGetRelationName(origRelation),
4445 RelationGetRelationName(rel),
4446 NameStr(att->attname))));
4449 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4450 errmsg("cannot alter table \"%s\" because column \"%s.%s\" uses its row type",
4451 RelationGetRelationName(origRelation),
4452 RelationGetRelationName(rel),
4453 NameStr(att->attname))));
4455 else if (OidIsValid(rel->rd_rel->reltype))
4458 * A view or composite type itself isn't a problem, but we must
4459 * recursively check for indirect dependencies via its rowtype.
4461 find_composite_type_dependencies(rel->rd_rel->reltype,
4462 origRelation, origTypeName);
4465 relation_close(rel, AccessShareLock);
4468 systable_endscan(depScan);
4470 relation_close(depRel, AccessShareLock);
4473 * If there's an array type for the rowtype, must check for uses of it,
4476 arrayOid = get_array_type(typeOid);
4477 if (OidIsValid(arrayOid))
4478 find_composite_type_dependencies(arrayOid, origRelation, origTypeName);
4483 * find_typed_table_dependencies
4485 * Check to see if a composite type is being used as the type of a
4486 * typed table. Abort if any are found and behavior is RESTRICT.
4487 * Else return the list of tables.
4490 find_typed_table_dependencies(Oid typeOid, const char *typeName, DropBehavior behavior)
4498 classRel = heap_open(RelationRelationId, AccessShareLock);
4500 ScanKeyInit(&key[0],
4501 Anum_pg_class_reloftype,
4502 BTEqualStrategyNumber, F_OIDEQ,
4503 ObjectIdGetDatum(typeOid));
4505 scan = heap_beginscan_catalog(classRel, 1, key);
4507 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
4509 if (behavior == DROP_RESTRICT)
4511 (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
4512 errmsg("cannot alter type \"%s\" because it is the type of a typed table",
4514 errhint("Use ALTER ... CASCADE to alter the typed tables too.")));
4516 result = lappend_oid(result, HeapTupleGetOid(tuple));
4520 heap_close(classRel, AccessShareLock);
4529 * Check whether a type is suitable for CREATE TABLE OF/ALTER TABLE OF. If it
4530 * isn't suitable, throw an error. Currently, we require that the type
4531 * originated with CREATE TYPE AS. We could support any row type, but doing so
4532 * would require handling a number of extra corner cases in the DDL commands.
4535 check_of_type(HeapTuple typetuple)
4537 Form_pg_type typ = (Form_pg_type) GETSTRUCT(typetuple);
4538 bool typeOk = false;
4540 if (typ->typtype == TYPTYPE_COMPOSITE)
4542 Relation typeRelation;
4544 Assert(OidIsValid(typ->typrelid));
4545 typeRelation = relation_open(typ->typrelid, AccessShareLock);
4546 typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
4549 * Close the parent rel, but keep our AccessShareLock on it until xact
4550 * commit. That will prevent someone else from deleting or ALTERing
4551 * the type before the typed table creation/conversion commits.
4553 relation_close(typeRelation, NoLock);
4557 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4558 errmsg("type %s is not a composite type",
4559 format_type_be(HeapTupleGetOid(typetuple)))));
4564 * ALTER TABLE ADD COLUMN
4566 * Adds an additional attribute to a relation making the assumption that
4567 * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
4568 * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
4571 * ADD COLUMN cannot use the normal ALTER TABLE recursion mechanism, because we
4572 * have to decide at runtime whether to recurse or not depending on whether we
4573 * actually add a column or merely merge with an existing column. (We can't
4574 * check this in a static pre-pass because it won't handle multiple inheritance
4575 * situations correctly.)
4578 ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
4579 AlterTableCmd *cmd, LOCKMODE lockmode)
4581 if (rel->rd_rel->reloftype && !recursing)
4583 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4584 errmsg("cannot add column to typed table")));
4586 if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
4587 ATTypedTableRecursion(wqueue, rel, cmd, lockmode);
4590 cmd->subtype = AT_AddColumnRecurse;
4594 ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel,
4595 ColumnDef *colDef, bool isOid,
4596 bool recurse, bool recursing, LOCKMODE lockmode)
4598 Oid myrelid = RelationGetRelid(rel);
4602 FormData_pg_attribute attribute;
4605 HeapTuple typeTuple;
4613 AclResult aclresult;
4615 /* At top level, permission check was done in ATPrepCmd, else do it */
4617 ATSimplePermissions(rel, ATT_TABLE);
4619 attrdesc = heap_open(AttributeRelationId, RowExclusiveLock);
4622 * Are we adding the column to a recursion child? If so, check whether to
4623 * merge with an existing definition for the column. If we do merge, we
4624 * must not recurse. Children will already have the column, and recursing
4625 * into them would mess up attinhcount.
4627 if (colDef->inhcount > 0)
4631 /* Does child already have a column by this name? */
4632 tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
4633 if (HeapTupleIsValid(tuple))
4635 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
4640 /* Child column must match on type, typmod, and collation */
4641 typenameTypeIdAndMod(NULL, colDef->typeName, &ctypeId, &ctypmod);
4642 if (ctypeId != childatt->atttypid ||
4643 ctypmod != childatt->atttypmod)
4645 (errcode(ERRCODE_DATATYPE_MISMATCH),
4646 errmsg("child table \"%s\" has different type for column \"%s\"",
4647 RelationGetRelationName(rel), colDef->colname)));
4648 ccollid = GetColumnDefCollation(NULL, colDef, ctypeId);
4649 if (ccollid != childatt->attcollation)
4651 (errcode(ERRCODE_COLLATION_MISMATCH),
4652 errmsg("child table \"%s\" has different collation for column \"%s\"",
4653 RelationGetRelationName(rel), colDef->colname),
4654 errdetail("\"%s\" versus \"%s\"",
4655 get_collation_name(ccollid),
4656 get_collation_name(childatt->attcollation))));
4658 /* If it's OID, child column must actually be OID */
4659 if (isOid && childatt->attnum != ObjectIdAttributeNumber)
4661 (errcode(ERRCODE_DATATYPE_MISMATCH),
4662 errmsg("child table \"%s\" has a conflicting \"%s\" column",
4663 RelationGetRelationName(rel), colDef->colname)));
4665 /* Bump the existing child att's inhcount */
4666 childatt->attinhcount++;
4667 simple_heap_update(attrdesc, &tuple->t_self, tuple);
4668 CatalogUpdateIndexes(attrdesc, tuple);
4670 heap_freetuple(tuple);
4672 /* Inform the user about the merge */
4674 (errmsg("merging definition of column \"%s\" for child \"%s\"",
4675 colDef->colname, RelationGetRelationName(rel))));
4677 heap_close(attrdesc, RowExclusiveLock);
4682 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
4684 reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
4685 if (!HeapTupleIsValid(reltup))
4686 elog(ERROR, "cache lookup failed for relation %u", myrelid);
4687 relkind = ((Form_pg_class) GETSTRUCT(reltup))->relkind;
4689 /* new name should not already exist */
4690 check_for_column_name_collision(rel, colDef->colname);
4692 /* Determine the new attribute's number */
4694 newattnum = ObjectIdAttributeNumber;
4697 newattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts + 1;
4698 if (newattnum > MaxHeapAttributeNumber)
4700 (errcode(ERRCODE_TOO_MANY_COLUMNS),
4701 errmsg("tables can have at most %d columns",
4702 MaxHeapAttributeNumber)));
4705 typeTuple = typenameType(NULL, colDef->typeName, &typmod);
4706 tform = (Form_pg_type) GETSTRUCT(typeTuple);
4707 typeOid = HeapTupleGetOid(typeTuple);
4709 aclresult = pg_type_aclcheck(typeOid, GetUserId(), ACL_USAGE);
4710 if (aclresult != ACLCHECK_OK)
4711 aclcheck_error_type(aclresult, typeOid);
4713 collOid = GetColumnDefCollation(NULL, colDef, typeOid);
4715 /* make sure datatype is legal for a column */
4716 CheckAttributeType(colDef->colname, typeOid, collOid,
4717 list_make1_oid(rel->rd_rel->reltype),
4720 /* construct new attribute's pg_attribute entry */
4721 attribute.attrelid = myrelid;
4722 namestrcpy(&(attribute.attname), colDef->colname);
4723 attribute.atttypid = typeOid;
4724 attribute.attstattarget = (newattnum > 0) ? -1 : 0;
4725 attribute.attlen = tform->typlen;
4726 attribute.attcacheoff = -1;
4727 attribute.atttypmod = typmod;
4728 attribute.attnum = newattnum;
4729 attribute.attbyval = tform->typbyval;
4730 attribute.attndims = list_length(colDef->typeName->arrayBounds);
4731 attribute.attstorage = tform->typstorage;
4732 attribute.attalign = tform->typalign;
4733 attribute.attnotnull = colDef->is_not_null;
4734 attribute.atthasdef = false;
4735 attribute.attisdropped = false;
4736 attribute.attislocal = colDef->is_local;
4737 attribute.attinhcount = colDef->inhcount;
4738 attribute.attcollation = collOid;
4739 /* attribute.attacl is handled by InsertPgAttributeTuple */
4741 ReleaseSysCache(typeTuple);
4743 InsertPgAttributeTuple(attrdesc, &attribute, NULL);
4745 heap_close(attrdesc, RowExclusiveLock);
4748 * Update pg_class tuple as appropriate
4751 ((Form_pg_class) GETSTRUCT(reltup))->relhasoids = true;
4753 ((Form_pg_class) GETSTRUCT(reltup))->relnatts = newattnum;
4755 simple_heap_update(pgclass, &reltup->t_self, reltup);
4757 /* keep catalog indexes current */
4758 CatalogUpdateIndexes(pgclass, reltup);
4760 heap_freetuple(reltup);
4762 /* Post creation hook for new attribute */
4763 InvokeObjectPostCreateHook(RelationRelationId, myrelid, newattnum);
4765 heap_close(pgclass, RowExclusiveLock);
4767 /* Make the attribute's catalog entry visible */
4768 CommandCounterIncrement();
4771 * Store the DEFAULT, if any, in the catalogs
4773 if (colDef->raw_default)
4775 RawColumnDefault *rawEnt;
4777 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
4778 rawEnt->attnum = attribute.attnum;
4779 rawEnt->raw_default = copyObject(colDef->raw_default);
4782 * This function is intended for CREATE TABLE, so it processes a
4783 * _list_ of defaults, but we just do one.
4785 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
4786 false, true, false);
4788 /* Make the additional catalog changes visible */
4789 CommandCounterIncrement();
4793 * Tell Phase 3 to fill in the default expression, if there is one.
4795 * If there is no default, Phase 3 doesn't have to do anything, because
4796 * that effectively means that the default is NULL. The heap tuple access
4797 * routines always check for attnum > # of attributes in tuple, and return
4798 * NULL if so, so without any modification of the tuple data we will get
4799 * the effect of NULL values in the new column.
4801 * An exception occurs when the new column is of a domain type: the domain
4802 * might have a NOT NULL constraint, or a check constraint that indirectly
4803 * rejects nulls. If there are any domain constraints then we construct
4804 * an explicit NULL default value that will be passed through
4805 * CoerceToDomain processing. (This is a tad inefficient, since it causes
4806 * rewriting the table which we really don't have to do, but the present
4807 * design of domain processing doesn't offer any simple way of checking
4808 * the constraints more directly.)
4810 * Note: we use build_column_default, and not just the cooked default
4811 * returned by AddRelationNewConstraints, so that the right thing happens
4812 * when a datatype's default applies.
4814 * We skip this step completely for views and foreign tables. For a view,
4815 * we can only get here from CREATE OR REPLACE VIEW, which historically
4816 * doesn't set up defaults, not even for domain-typed columns. And in any
4817 * case we mustn't invoke Phase 3 on a view or foreign table, since they
4820 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE
4821 && relkind != RELKIND_FOREIGN_TABLE && attribute.attnum > 0)
4823 defval = (Expr *) build_column_default(rel, attribute.attnum);
4825 if (!defval && GetDomainConstraints(typeOid) != NIL)
4831 baseTypeMod = typmod;
4832 baseTypeId = getBaseTypeAndTypmod(typeOid, &baseTypeMod);
4833 baseTypeColl = get_typcollation(baseTypeId);
4834 defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod, baseTypeColl);
4835 defval = (Expr *) coerce_to_target_type(NULL,
4840 COERCION_ASSIGNMENT,
4841 COERCE_IMPLICIT_CAST,
4843 if (defval == NULL) /* should not happen */
4844 elog(ERROR, "failed to coerce base type to domain");
4849 NewColumnValue *newval;
4851 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
4852 newval->attnum = attribute.attnum;
4853 newval->expr = expression_planner(defval);
4855 tab->newvals = lappend(tab->newvals, newval);
4856 tab->rewrite |= AT_REWRITE_DEFAULT_VAL;
4860 * If the new column is NOT NULL, tell Phase 3 it needs to test that.
4861 * (Note we don't do this for an OID column. OID will be marked not
4862 * null, but since it's filled specially, there's no need to test
4865 tab->new_notnull |= colDef->is_not_null;
4869 * If we are adding an OID column, we have to tell Phase 3 to rewrite the
4870 * table to fix that.
4873 tab->rewrite |= AT_REWRITE_ALTER_OID;
4876 * Add needed dependency entries for the new column.
4878 add_column_datatype_dependency(myrelid, newattnum, attribute.atttypid);
4879 add_column_collation_dependency(myrelid, newattnum, attribute.attcollation);
4882 * Propagate to children as appropriate. Unlike most other ALTER
4883 * routines, we have to do this one level of recursion at a time; we can't
4884 * use find_all_inheritors to do it in one pass.
4886 children = find_inheritance_children(RelationGetRelid(rel), lockmode);
4889 * If we are told not to recurse, there had better not be any child
4890 * tables; else the addition would put them out of step.
4892 if (children && !recurse)
4894 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4895 errmsg("column must be added to child tables too")));
4897 /* Children should see column as singly inherited */
4900 colDef = copyObject(colDef);
4901 colDef->inhcount = 1;
4902 colDef->is_local = false;
4905 foreach(child, children)
4907 Oid childrelid = lfirst_oid(child);
4909 AlteredTableInfo *childtab;
4911 /* find_inheritance_children already got lock */
4912 childrel = heap_open(childrelid, NoLock);
4913 CheckTableNotInUse(childrel, "ALTER TABLE");
4915 /* Find or create work queue entry for this table */
4916 childtab = ATGetQueueEntry(wqueue, childrel);
4918 /* Recurse to child */
4919 ATExecAddColumn(wqueue, childtab, childrel,
4920 colDef, isOid, recurse, true, lockmode);
4922 heap_close(childrel, NoLock);
4927 * If a new or renamed column will collide with the name of an existing
4928 * column, error out.
4931 check_for_column_name_collision(Relation rel, const char *colname)
4937 * this test is deliberately not attisdropped-aware, since if one tries to
4938 * add a column matching a dropped column name, it's gonna fail anyway.
4940 attTuple = SearchSysCache2(ATTNAME,
4941 ObjectIdGetDatum(RelationGetRelid(rel)),
4942 PointerGetDatum(colname));
4943 if (!HeapTupleIsValid(attTuple))
4946 attnum = ((Form_pg_attribute) GETSTRUCT(attTuple))->attnum;
4947 ReleaseSysCache(attTuple);
4950 * We throw a different error message for conflicts with system column
4951 * names, since they are normally not shown and the user might otherwise
4952 * be confused about the reason for the conflict.
4956 (errcode(ERRCODE_DUPLICATE_COLUMN),
4957 errmsg("column name \"%s\" conflicts with a system column name",
4961 (errcode(ERRCODE_DUPLICATE_COLUMN),
4962 errmsg("column \"%s\" of relation \"%s\" already exists",
4963 colname, RelationGetRelationName(rel))));
4967 * Install a column's dependency on its datatype.
4970 add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
4972 ObjectAddress myself,
4975 myself.classId = RelationRelationId;
4976 myself.objectId = relid;
4977 myself.objectSubId = attnum;
4978 referenced.classId = TypeRelationId;
4979 referenced.objectId = typid;
4980 referenced.objectSubId = 0;
4981 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
4985 * Install a column's dependency on its collation.
4988 add_column_collation_dependency(Oid relid, int32 attnum, Oid collid)
4990 ObjectAddress myself,
4993 /* We know the default collation is pinned, so don't bother recording it */
4994 if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
4996 myself.classId = RelationRelationId;
4997 myself.objectId = relid;
4998 myself.objectSubId = attnum;
4999 referenced.classId = CollationRelationId;
5000 referenced.objectId = collid;
5001 referenced.objectSubId = 0;
5002 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
5007 * ALTER TABLE SET WITH OIDS
5009 * Basically this is an ADD COLUMN for the special OID column. We have
5010 * to cons up a ColumnDef node because the ADD COLUMN code needs one.
5013 ATPrepAddOids(List **wqueue, Relation rel, bool recurse, AlterTableCmd *cmd, LOCKMODE lockmode)
5015 /* If we're recursing to a child table, the ColumnDef is already set up */
5016 if (cmd->def == NULL)
5018 ColumnDef *cdef = makeNode(ColumnDef);
5020 cdef->colname = pstrdup("oid");
5021 cdef->typeName = makeTypeNameFromOid(OIDOID, -1);
5023 cdef->is_local = true;
5024 cdef->is_not_null = true;
5026 cdef->location = -1;
5027 cmd->def = (Node *) cdef;
5029 ATPrepAddColumn(wqueue, rel, recurse, false, cmd, lockmode);
5032 cmd->subtype = AT_AddOidsRecurse;
5036 * ALTER TABLE ALTER COLUMN DROP NOT NULL
5039 ATExecDropNotNull(Relation rel, const char *colName, LOCKMODE lockmode)
5045 ListCell *indexoidscan;
5048 * lookup the attribute
5050 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
5052 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5054 if (!HeapTupleIsValid(tuple))
5056 (errcode(ERRCODE_UNDEFINED_COLUMN),
5057 errmsg("column \"%s\" of relation \"%s\" does not exist",
5058 colName, RelationGetRelationName(rel))));
5060 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
5062 /* Prevent them from altering a system attribute */
5065 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5066 errmsg("cannot alter system column \"%s\"",
5070 * Check that the attribute is not in a primary key
5072 * Note: we'll throw error even if the pkey index is not valid.
5075 /* Loop over all indexes on the relation */
5076 indexoidlist = RelationGetIndexList(rel);
5078 foreach(indexoidscan, indexoidlist)
5080 Oid indexoid = lfirst_oid(indexoidscan);
5081 HeapTuple indexTuple;
5082 Form_pg_index indexStruct;
5085 indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
5086 if (!HeapTupleIsValid(indexTuple))
5087 elog(ERROR, "cache lookup failed for index %u", indexoid);
5088 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
5090 /* If the index is not a primary key, skip the check */
5091 if (indexStruct->indisprimary)
5094 * Loop over each attribute in the primary key and see if it
5095 * matches the to-be-altered attribute
5097 for (i = 0; i < indexStruct->indnatts; i++)
5099 if (indexStruct->indkey.values[i] == attnum)
5101 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5102 errmsg("column \"%s\" is in a primary key",
5107 ReleaseSysCache(indexTuple);
5110 list_free(indexoidlist);
5113 * Okay, actually perform the catalog change ... if needed
5115 if (((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
5117 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = FALSE;
5119 simple_heap_update(attr_rel, &tuple->t_self, tuple);
5121 /* keep the system catalog indexes current */
5122 CatalogUpdateIndexes(attr_rel, tuple);
5125 InvokeObjectPostAlterHook(RelationRelationId,
5126 RelationGetRelid(rel), attnum);
5128 heap_close(attr_rel, RowExclusiveLock);
5132 * ALTER TABLE ALTER COLUMN SET NOT NULL
5135 ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
5136 const char *colName, LOCKMODE lockmode)
5143 * lookup the attribute
5145 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
5147 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5149 if (!HeapTupleIsValid(tuple))
5151 (errcode(ERRCODE_UNDEFINED_COLUMN),
5152 errmsg("column \"%s\" of relation \"%s\" does not exist",
5153 colName, RelationGetRelationName(rel))));
5155 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
5157 /* Prevent them from altering a system attribute */
5160 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5161 errmsg("cannot alter system column \"%s\"",
5165 * Okay, actually perform the catalog change ... if needed
5167 if (!((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
5169 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = TRUE;
5171 simple_heap_update(attr_rel, &tuple->t_self, tuple);
5173 /* keep the system catalog indexes current */
5174 CatalogUpdateIndexes(attr_rel, tuple);
5176 /* Tell Phase 3 it needs to test the constraint */
5177 tab->new_notnull = true;
5180 InvokeObjectPostAlterHook(RelationRelationId,
5181 RelationGetRelid(rel), attnum);
5183 heap_close(attr_rel, RowExclusiveLock);
5187 * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
5190 ATExecColumnDefault(Relation rel, const char *colName,
5191 Node *newDefault, LOCKMODE lockmode)
5196 * get the number of the attribute
5198 attnum = get_attnum(RelationGetRelid(rel), colName);
5199 if (attnum == InvalidAttrNumber)
5201 (errcode(ERRCODE_UNDEFINED_COLUMN),
5202 errmsg("column \"%s\" of relation \"%s\" does not exist",
5203 colName, RelationGetRelationName(rel))));
5205 /* Prevent them from altering a system attribute */
5208 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5209 errmsg("cannot alter system column \"%s\"",
5213 * Remove any old default for the column. We use RESTRICT here for
5214 * safety, but at present we do not expect anything to depend on the
5217 * We treat removing the existing default as an internal operation when it
5218 * is preparatory to adding a new default, but as a user-initiated
5219 * operation when the user asked for a drop.
5221 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false,
5222 newDefault == NULL ? false : true);
5227 RawColumnDefault *rawEnt;
5229 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
5230 rawEnt->attnum = attnum;
5231 rawEnt->raw_default = newDefault;
5234 * This function is intended for CREATE TABLE, so it processes a
5235 * _list_ of defaults, but we just do one.
5237 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
5238 false, true, false);
5243 * ALTER TABLE ALTER COLUMN SET STATISTICS
5246 ATPrepSetStatistics(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
5249 * We do our own permission checking because (a) we want to allow SET
5250 * STATISTICS on indexes (for expressional index columns), and (b) we want
5251 * to allow SET STATISTICS on system catalogs without requiring
5252 * allowSystemTableMods to be turned on.
5254 if (rel->rd_rel->relkind != RELKIND_RELATION &&
5255 rel->rd_rel->relkind != RELKIND_MATVIEW &&
5256 rel->rd_rel->relkind != RELKIND_INDEX &&
5257 rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
5259 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5260 errmsg("\"%s\" is not a table, materialized view, index, or foreign table",
5261 RelationGetRelationName(rel))));
5263 /* Permissions checks */
5264 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
5265 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
5266 RelationGetRelationName(rel));
5270 ATExecSetStatistics(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
5273 Relation attrelation;
5275 Form_pg_attribute attrtuple;
5277 Assert(IsA(newValue, Integer));
5278 newtarget = intVal(newValue);
5281 * Limit target to a sane range
5286 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5287 errmsg("statistics target %d is too low",
5290 else if (newtarget > 10000)
5294 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5295 errmsg("lowering statistics target to %d",
5299 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
5301 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5303 if (!HeapTupleIsValid(tuple))
5305 (errcode(ERRCODE_UNDEFINED_COLUMN),
5306 errmsg("column \"%s\" of relation \"%s\" does not exist",
5307 colName, RelationGetRelationName(rel))));
5308 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
5310 if (attrtuple->attnum <= 0)
5312 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5313 errmsg("cannot alter system column \"%s\"",
5316 attrtuple->attstattarget = newtarget;
5318 simple_heap_update(attrelation, &tuple->t_self, tuple);
5320 /* keep system catalog indexes current */
5321 CatalogUpdateIndexes(attrelation, tuple);
5323 InvokeObjectPostAlterHook(RelationRelationId,
5324 RelationGetRelid(rel),
5326 heap_freetuple(tuple);
5328 heap_close(attrelation, RowExclusiveLock);
5332 ATExecSetOptions(Relation rel, const char *colName, Node *options,
5333 bool isReset, LOCKMODE lockmode)
5335 Relation attrelation;
5338 Form_pg_attribute attrtuple;
5342 Datum repl_val[Natts_pg_attribute];
5343 bool repl_null[Natts_pg_attribute];
5344 bool repl_repl[Natts_pg_attribute];
5346 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
5348 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
5350 if (!HeapTupleIsValid(tuple))
5352 (errcode(ERRCODE_UNDEFINED_COLUMN),
5353 errmsg("column \"%s\" of relation \"%s\" does not exist",
5354 colName, RelationGetRelationName(rel))));
5355 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
5357 if (attrtuple->attnum <= 0)
5359 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5360 errmsg("cannot alter system column \"%s\"",
5363 /* Generate new proposed attoptions (text array) */
5364 Assert(IsA(options, List));
5365 datum = SysCacheGetAttr(ATTNAME, tuple, Anum_pg_attribute_attoptions,
5367 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
5368 (List *) options, NULL, NULL, false,
5370 /* Validate new options */
5371 (void) attribute_reloptions(newOptions, true);
5373 /* Build new tuple. */
5374 memset(repl_null, false, sizeof(repl_null));
5375 memset(repl_repl, false, sizeof(repl_repl));
5376 if (newOptions != (Datum) 0)
5377 repl_val[Anum_pg_attribute_attoptions - 1] = newOptions;
5379 repl_null[Anum_pg_attribute_attoptions - 1] = true;
5380 repl_repl[Anum_pg_attribute_attoptions - 1] = true;
5381 newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrelation),
5382 repl_val, repl_null, repl_repl);
5384 /* Update system catalog. */
5385 simple_heap_update(attrelation, &newtuple->t_self, newtuple);
5386 CatalogUpdateIndexes(attrelation, newtuple);
5388 InvokeObjectPostAlterHook(RelationRelationId,
5389 RelationGetRelid(rel),
5391 heap_freetuple(newtuple);
5393 ReleaseSysCache(tuple);
5395 heap_close(attrelation, RowExclusiveLock);
5399 * ALTER TABLE ALTER COLUMN SET STORAGE
5402 ATExecSetStorage(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
5406 Relation attrelation;
5408 Form_pg_attribute attrtuple;
5410 Assert(IsA(newValue, String));
5411 storagemode = strVal(newValue);
5413 if (pg_strcasecmp(storagemode, "plain") == 0)
5415 else if (pg_strcasecmp(storagemode, "external") == 0)
5417 else if (pg_strcasecmp(storagemode, "extended") == 0)
5419 else if (pg_strcasecmp(storagemode, "main") == 0)
5424 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5425 errmsg("invalid storage type \"%s\"",
5427 newstorage = 0; /* keep compiler quiet */
5430 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
5432 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5434 if (!HeapTupleIsValid(tuple))
5436 (errcode(ERRCODE_UNDEFINED_COLUMN),
5437 errmsg("column \"%s\" of relation \"%s\" does not exist",
5438 colName, RelationGetRelationName(rel))));
5439 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
5441 if (attrtuple->attnum <= 0)
5443 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5444 errmsg("cannot alter system column \"%s\"",
5448 * safety check: do not allow toasted storage modes unless column datatype
5451 if (newstorage == 'p' || TypeIsToastable(attrtuple->atttypid))
5452 attrtuple->attstorage = newstorage;
5455 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5456 errmsg("column data type %s can only have storage PLAIN",
5457 format_type_be(attrtuple->atttypid))));
5459 simple_heap_update(attrelation, &tuple->t_self, tuple);
5461 /* keep system catalog indexes current */
5462 CatalogUpdateIndexes(attrelation, tuple);
5464 InvokeObjectPostAlterHook(RelationRelationId,
5465 RelationGetRelid(rel),
5468 heap_freetuple(tuple);
5470 heap_close(attrelation, RowExclusiveLock);
5475 * ALTER TABLE DROP COLUMN
5477 * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
5478 * because we have to decide at runtime whether to recurse or not depending
5479 * on whether attinhcount goes to zero or not. (We can't check this in a
5480 * static pre-pass because it won't handle multiple inheritance situations
5484 ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
5485 AlterTableCmd *cmd, LOCKMODE lockmode)
5487 if (rel->rd_rel->reloftype && !recursing)
5489 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5490 errmsg("cannot drop column from typed table")));
5492 if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
5493 ATTypedTableRecursion(wqueue, rel, cmd, lockmode);
5496 cmd->subtype = AT_DropColumnRecurse;
5500 ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
5501 DropBehavior behavior,
5502 bool recurse, bool recursing,
5503 bool missing_ok, LOCKMODE lockmode)
5506 Form_pg_attribute targetatt;
5509 ObjectAddress object;
5511 /* At top level, permission check was done in ATPrepCmd, else do it */
5513 ATSimplePermissions(rel, ATT_TABLE);
5516 * get the number of the attribute
5518 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
5519 if (!HeapTupleIsValid(tuple))
5524 (errcode(ERRCODE_UNDEFINED_COLUMN),
5525 errmsg("column \"%s\" of relation \"%s\" does not exist",
5526 colName, RelationGetRelationName(rel))));
5531 (errmsg("column \"%s\" of relation \"%s\" does not exist, skipping",
5532 colName, RelationGetRelationName(rel))));
5536 targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
5538 attnum = targetatt->attnum;
5540 /* Can't drop a system attribute, except OID */
5541 if (attnum <= 0 && attnum != ObjectIdAttributeNumber)
5543 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5544 errmsg("cannot drop system column \"%s\"",
5547 /* Don't drop inherited columns */
5548 if (targetatt->attinhcount > 0 && !recursing)
5550 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5551 errmsg("cannot drop inherited column \"%s\"",
5554 ReleaseSysCache(tuple);
5557 * Propagate to children as appropriate. Unlike most other ALTER
5558 * routines, we have to do this one level of recursion at a time; we can't
5559 * use find_all_inheritors to do it in one pass.
5561 children = find_inheritance_children(RelationGetRelid(rel), lockmode);
5568 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
5569 foreach(child, children)
5571 Oid childrelid = lfirst_oid(child);
5573 Form_pg_attribute childatt;
5575 /* find_inheritance_children already got lock */
5576 childrel = heap_open(childrelid, NoLock);
5577 CheckTableNotInUse(childrel, "ALTER TABLE");
5579 tuple = SearchSysCacheCopyAttName(childrelid, colName);
5580 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
5581 elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
5582 colName, childrelid);
5583 childatt = (Form_pg_attribute) GETSTRUCT(tuple);
5585 if (childatt->attinhcount <= 0) /* shouldn't happen */
5586 elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
5587 childrelid, colName);
5592 * If the child column has other definition sources, just
5593 * decrement its inheritance count; if not, recurse to delete
5596 if (childatt->attinhcount == 1 && !childatt->attislocal)
5598 /* Time to delete this child column, too */
5599 ATExecDropColumn(wqueue, childrel, colName,
5600 behavior, true, true,
5605 /* Child column must survive my deletion */
5606 childatt->attinhcount--;
5608 simple_heap_update(attr_rel, &tuple->t_self, tuple);
5610 /* keep the system catalog indexes current */
5611 CatalogUpdateIndexes(attr_rel, tuple);
5613 /* Make update visible */
5614 CommandCounterIncrement();
5620 * If we were told to drop ONLY in this table (no recursion),
5621 * we need to mark the inheritors' attributes as locally
5622 * defined rather than inherited.
5624 childatt->attinhcount--;
5625 childatt->attislocal = true;
5627 simple_heap_update(attr_rel, &tuple->t_self, tuple);
5629 /* keep the system catalog indexes current */
5630 CatalogUpdateIndexes(attr_rel, tuple);
5632 /* Make update visible */
5633 CommandCounterIncrement();
5636 heap_freetuple(tuple);
5638 heap_close(childrel, NoLock);
5640 heap_close(attr_rel, RowExclusiveLock);
5644 * Perform the actual column deletion
5646 object.classId = RelationRelationId;
5647 object.objectId = RelationGetRelid(rel);
5648 object.objectSubId = attnum;
5650 performDeletion(&object, behavior, 0);
5653 * If we dropped the OID column, must adjust pg_class.relhasoids and tell
5654 * Phase 3 to physically get rid of the column. We formerly left the
5655 * column in place physically, but this caused subtle problems. See
5656 * http://archives.postgresql.org/pgsql-hackers/2009-02/msg00363.php
5658 if (attnum == ObjectIdAttributeNumber)
5661 Form_pg_class tuple_class;
5662 AlteredTableInfo *tab;
5664 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
5666 tuple = SearchSysCacheCopy1(RELOID,
5667 ObjectIdGetDatum(RelationGetRelid(rel)));
5668 if (!HeapTupleIsValid(tuple))
5669 elog(ERROR, "cache lookup failed for relation %u",
5670 RelationGetRelid(rel));
5671 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
5673 tuple_class->relhasoids = false;
5674 simple_heap_update(class_rel, &tuple->t_self, tuple);
5676 /* Keep the catalog indexes up to date */
5677 CatalogUpdateIndexes(class_rel, tuple);
5679 heap_close(class_rel, RowExclusiveLock);
5681 /* Find or create work queue entry for this table */
5682 tab = ATGetQueueEntry(wqueue, rel);
5684 /* Tell Phase 3 to physically remove the OID column */
5685 tab->rewrite |= AT_REWRITE_ALTER_OID;
5690 * ALTER TABLE ADD INDEX
5692 * There is no such command in the grammar, but parse_utilcmd.c converts
5693 * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands. This lets
5694 * us schedule creation of the index at the appropriate time during ALTER.
5697 ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
5698 IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
5705 Assert(IsA(stmt, IndexStmt));
5706 Assert(!stmt->concurrent);
5708 /* suppress schema rights check when rebuilding existing index */
5709 check_rights = !is_rebuild;
5710 /* skip index build if phase 3 will do it or we're reusing an old one */
5711 skip_build = tab->rewrite > 0 || OidIsValid(stmt->oldNode);
5712 /* suppress notices when rebuilding existing index */
5715 /* The IndexStmt has already been through transformIndexStmt */
5717 new_index = DefineIndex(RelationGetRelid(rel),
5719 InvalidOid, /* no predefined OID */
5720 true, /* is_alter_table */
5726 * If TryReuseIndex() stashed a relfilenode for us, we used it for the new
5727 * index instead of building from scratch. The DROP of the old edition of
5728 * this index will have scheduled the storage for deletion at commit, so
5729 * cancel that pending deletion.
5731 if (OidIsValid(stmt->oldNode))
5733 Relation irel = index_open(new_index, NoLock);
5735 RelationPreserveStorage(irel->rd_node, true);
5736 index_close(irel, NoLock);
5741 * ALTER TABLE ADD CONSTRAINT USING INDEX
5744 ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
5745 IndexStmt *stmt, LOCKMODE lockmode)
5747 Oid index_oid = stmt->indexOid;
5750 IndexInfo *indexInfo;
5751 char *constraintName;
5752 char constraintType;
5754 Assert(IsA(stmt, IndexStmt));
5755 Assert(OidIsValid(index_oid));
5756 Assert(stmt->isconstraint);
5758 indexRel = index_open(index_oid, AccessShareLock);
5760 indexName = pstrdup(RelationGetRelationName(indexRel));
5762 indexInfo = BuildIndexInfo(indexRel);
5764 /* this should have been checked at parse time */
5765 if (!indexInfo->ii_Unique)
5766 elog(ERROR, "index \"%s\" is not unique", indexName);
5769 * Determine name to assign to constraint. We require a constraint to
5770 * have the same name as the underlying index; therefore, use the index's
5771 * existing name as the default constraint name, and if the user
5772 * explicitly gives some other name for the constraint, rename the index
5775 constraintName = stmt->idxname;
5776 if (constraintName == NULL)
5777 constraintName = indexName;
5778 else if (strcmp(constraintName, indexName) != 0)
5781 (errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index \"%s\" to \"%s\"",
5782 indexName, constraintName)));
5783 RenameRelationInternal(index_oid, constraintName, false);
5786 /* Extra checks needed if making primary key */
5788 index_check_primary_key(rel, indexInfo, true);
5790 /* Note we currently don't support EXCLUSION constraints here */
5792 constraintType = CONSTRAINT_PRIMARY;
5794 constraintType = CONSTRAINT_UNIQUE;
5796 /* Create the catalog entries for the constraint */
5797 index_constraint_create(rel,
5805 true, /* update pg_index */
5806 true, /* remove old dependencies */
5807 allowSystemTableMods,
5808 false); /* is_internal */
5810 index_close(indexRel, NoLock);
5814 * ALTER TABLE ADD CONSTRAINT
5817 ATExecAddConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
5818 Constraint *newConstraint, bool recurse, bool is_readd,
5821 Assert(IsA(newConstraint, Constraint));
5824 * Currently, we only expect to see CONSTR_CHECK and CONSTR_FOREIGN nodes
5825 * arriving here (see the preprocessing done in parse_utilcmd.c). Use a
5826 * switch anyway to make it easier to add more code later.
5828 switch (newConstraint->contype)
5831 ATAddCheckConstraint(wqueue, tab, rel,
5832 newConstraint, recurse, false, is_readd,
5836 case CONSTR_FOREIGN:
5839 * Note that we currently never recurse for FK constraints, so the
5840 * "recurse" flag is silently ignored.
5842 * Assign or validate constraint name
5844 if (newConstraint->conname)
5846 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
5847 RelationGetRelid(rel),
5848 RelationGetNamespace(rel),
5849 newConstraint->conname))
5851 (errcode(ERRCODE_DUPLICATE_OBJECT),
5852 errmsg("constraint \"%s\" for relation \"%s\" already exists",
5853 newConstraint->conname,
5854 RelationGetRelationName(rel))));
5857 newConstraint->conname =
5858 ChooseConstraintName(RelationGetRelationName(rel),
5859 strVal(linitial(newConstraint->fk_attrs)),
5861 RelationGetNamespace(rel),
5864 ATAddForeignKeyConstraint(tab, rel, newConstraint, lockmode);
5868 elog(ERROR, "unrecognized constraint type: %d",
5869 (int) newConstraint->contype);
5874 * Add a check constraint to a single table and its children
5876 * Subroutine for ATExecAddConstraint.
5878 * We must recurse to child tables during execution, rather than using
5879 * ALTER TABLE's normal prep-time recursion. The reason is that all the
5880 * constraints *must* be given the same name, else they won't be seen as
5881 * related later. If the user didn't explicitly specify a name, then
5882 * AddRelationNewConstraints would normally assign different names to the
5883 * child constraints. To fix that, we must capture the name assigned at
5884 * the parent table and pass that down.
5886 * When re-adding a previously existing constraint (during ALTER COLUMN TYPE),
5887 * we don't need to recurse here, because recursion will be carried out at a
5888 * higher level; the constraint name issue doesn't apply because the names
5889 * have already been assigned and are just being re-used. We need a separate
5890 * "is_readd" flag for that; just setting recurse=false would result in an
5891 * error if there are child tables.
5894 ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
5895 Constraint *constr, bool recurse, bool recursing,
5896 bool is_readd, LOCKMODE lockmode)
5903 /* At top level, permission check was done in ATPrepCmd, else do it */
5905 ATSimplePermissions(rel, ATT_TABLE);
5908 * Call AddRelationNewConstraints to do the work, making sure it works on
5909 * a copy of the Constraint so transformExpr can't modify the original. It
5910 * returns a list of cooked constraints.
5912 * If the constraint ends up getting merged with a pre-existing one, it's
5913 * omitted from the returned list, which is what we want: we do not need
5914 * to do any validation work. That can only happen at child tables,
5915 * though, since we disallow merging at the top level.
5917 newcons = AddRelationNewConstraints(rel, NIL,
5918 list_make1(copyObject(constr)),
5919 recursing, /* allow_merge */
5920 !recursing, /* is_local */
5921 is_readd); /* is_internal */
5923 /* Add each to-be-validated constraint to Phase 3's queue */
5924 foreach(lcon, newcons)
5926 CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
5928 if (!ccon->skip_validation)
5930 NewConstraint *newcon;
5932 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
5933 newcon->name = ccon->name;
5934 newcon->contype = ccon->contype;
5935 /* ExecQual wants implicit-AND format */
5936 newcon->qual = (Node *) make_ands_implicit((Expr *) ccon->expr);
5938 tab->constraints = lappend(tab->constraints, newcon);
5941 /* Save the actually assigned name if it was defaulted */
5942 if (constr->conname == NULL)
5943 constr->conname = ccon->name;
5946 /* At this point we must have a locked-down name to use */
5947 Assert(constr->conname != NULL);
5949 /* Advance command counter in case same table is visited multiple times */
5950 CommandCounterIncrement();
5953 * If the constraint got merged with an existing constraint, we're done.
5954 * We mustn't recurse to child tables in this case, because they've
5955 * already got the constraint, and visiting them again would lead to an
5956 * incorrect value for coninhcount.
5962 * If adding a NO INHERIT constraint, no need to find our children.
5963 * Likewise, in a re-add operation, we don't need to recurse (that will be
5964 * handled at higher levels).
5966 if (constr->is_no_inherit || is_readd)
5970 * Propagate to children as appropriate. Unlike most other ALTER
5971 * routines, we have to do this one level of recursion at a time; we can't
5972 * use find_all_inheritors to do it in one pass.
5974 children = find_inheritance_children(RelationGetRelid(rel), lockmode);
5977 * Check if ONLY was specified with ALTER TABLE. If so, allow the
5978 * contraint creation only if there are no children currently. Error out
5981 if (!recurse && children != NIL)
5983 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5984 errmsg("constraint must be added to child tables too")));
5986 foreach(child, children)
5988 Oid childrelid = lfirst_oid(child);
5990 AlteredTableInfo *childtab;
5992 /* find_inheritance_children already got lock */
5993 childrel = heap_open(childrelid, NoLock);
5994 CheckTableNotInUse(childrel, "ALTER TABLE");
5996 /* Find or create work queue entry for this table */
5997 childtab = ATGetQueueEntry(wqueue, childrel);
5999 /* Recurse to child */
6000 ATAddCheckConstraint(wqueue, childtab, childrel,
6001 constr, recurse, true, is_readd, lockmode);
6003 heap_close(childrel, NoLock);
6008 * Add a foreign-key constraint to a single table
6010 * Subroutine for ATExecAddConstraint. Must already hold exclusive
6011 * lock on the rel, and have done appropriate validity checks for it.
6012 * We do permissions checks here, however.
6015 ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
6016 Constraint *fkconstraint, LOCKMODE lockmode)
6019 int16 pkattnum[INDEX_MAX_KEYS];
6020 int16 fkattnum[INDEX_MAX_KEYS];
6021 Oid pktypoid[INDEX_MAX_KEYS];
6022 Oid fktypoid[INDEX_MAX_KEYS];
6023 Oid opclasses[INDEX_MAX_KEYS];
6024 Oid pfeqoperators[INDEX_MAX_KEYS];
6025 Oid ppeqoperators[INDEX_MAX_KEYS];
6026 Oid ffeqoperators[INDEX_MAX_KEYS];
6033 ListCell *old_pfeqop_item = list_head(fkconstraint->old_conpfeqop);
6036 * Grab an exclusive lock on the pk table, so that someone doesn't delete
6037 * rows out from under us. (Although a lesser lock would do for that
6038 * purpose, we'll need exclusive lock anyway to add triggers to the pk
6039 * table; trying to start with a lesser lock will just create a risk of
6042 if (OidIsValid(fkconstraint->old_pktable_oid))
6043 pkrel = heap_open(fkconstraint->old_pktable_oid, AccessExclusiveLock);
6045 pkrel = heap_openrv(fkconstraint->pktable, AccessExclusiveLock);
6048 * Validity checks (permission checks wait till we have the column
6051 if (pkrel->rd_rel->relkind != RELKIND_RELATION)
6053 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6054 errmsg("referenced relation \"%s\" is not a table",
6055 RelationGetRelationName(pkrel))));
6057 if (!allowSystemTableMods && IsSystemRelation(pkrel))
6059 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6060 errmsg("permission denied: \"%s\" is a system catalog",
6061 RelationGetRelationName(pkrel))));
6064 * References from permanent or unlogged tables to temp tables, and from
6065 * permanent tables to unlogged tables, are disallowed because the
6066 * referenced data can vanish out from under us. References from temp
6067 * tables to any other table type are also disallowed, because other
6068 * backends might need to run the RI triggers on the perm table, but they
6069 * can't reliably see tuples in the local buffers of other backends.
6071 switch (rel->rd_rel->relpersistence)
6073 case RELPERSISTENCE_PERMANENT:
6074 if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT)
6076 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6077 errmsg("constraints on permanent tables may reference only permanent tables")));
6079 case RELPERSISTENCE_UNLOGGED:
6080 if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT
6081 && pkrel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED)
6083 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6084 errmsg("constraints on unlogged tables may reference only permanent or unlogged tables")));
6086 case RELPERSISTENCE_TEMP:
6087 if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
6089 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6090 errmsg("constraints on temporary tables may reference only temporary tables")));
6091 if (!pkrel->rd_islocaltemp || !rel->rd_islocaltemp)
6093 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6094 errmsg("constraints on temporary tables must involve temporary tables of this session")));
6099 * Look up the referencing attributes to make sure they exist, and record
6100 * their attnums and type OIDs.
6102 MemSet(pkattnum, 0, sizeof(pkattnum));
6103 MemSet(fkattnum, 0, sizeof(fkattnum));
6104 MemSet(pktypoid, 0, sizeof(pktypoid));
6105 MemSet(fktypoid, 0, sizeof(fktypoid));
6106 MemSet(opclasses, 0, sizeof(opclasses));
6107 MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
6108 MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
6109 MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
6111 numfks = transformColumnNameList(RelationGetRelid(rel),
6112 fkconstraint->fk_attrs,
6113 fkattnum, fktypoid);
6116 * If the attribute list for the referenced table was omitted, lookup the
6117 * definition of the primary key and use it. Otherwise, validate the
6118 * supplied attribute list. In either case, discover the index OID and
6119 * index opclasses, and the attnums and type OIDs of the attributes.
6121 if (fkconstraint->pk_attrs == NIL)
6123 numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
6124 &fkconstraint->pk_attrs,
6130 numpks = transformColumnNameList(RelationGetRelid(pkrel),
6131 fkconstraint->pk_attrs,
6132 pkattnum, pktypoid);
6133 /* Look for an index matching the column list */
6134 indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
6139 * Now we can check permissions.
6141 checkFkeyPermissions(pkrel, pkattnum, numpks);
6142 checkFkeyPermissions(rel, fkattnum, numfks);
6145 * Look up the equality operators to use in the constraint.
6147 * Note that we have to be careful about the difference between the actual
6148 * PK column type and the opclass' declared input type, which might be
6149 * only binary-compatible with it. The declared opcintype is the right
6150 * thing to probe pg_amop with.
6152 if (numfks != numpks)
6154 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
6155 errmsg("number of referencing and referenced columns for foreign key disagree")));
6158 * On the strength of a previous constraint, we might avoid scanning
6159 * tables to validate this one. See below.
6161 old_check_ok = (fkconstraint->old_conpfeqop != NIL);
6162 Assert(!old_check_ok || numfks == list_length(fkconstraint->old_conpfeqop));
6164 for (i = 0; i < numpks; i++)
6166 Oid pktype = pktypoid[i];
6167 Oid fktype = fktypoid[i];
6170 Form_pg_opclass cla_tup;
6180 /* We need several fields out of the pg_opclass entry */
6181 cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclasses[i]));
6182 if (!HeapTupleIsValid(cla_ht))
6183 elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
6184 cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
6185 amid = cla_tup->opcmethod;
6186 opfamily = cla_tup->opcfamily;
6187 opcintype = cla_tup->opcintype;
6188 ReleaseSysCache(cla_ht);
6191 * Check it's a btree; currently this can never fail since no other
6192 * index AMs support unique indexes. If we ever did have other types
6193 * of unique indexes, we'd need a way to determine which operator
6194 * strategy number is equality. (Is it reasonable to insist that
6195 * every such index AM use btree's number for equality?)
6197 if (amid != BTREE_AM_OID)
6198 elog(ERROR, "only b-tree indexes are supported for foreign keys");
6199 eqstrategy = BTEqualStrategyNumber;
6202 * There had better be a primary equality operator for the index.
6203 * We'll use it for PK = PK comparisons.
6205 ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
6208 if (!OidIsValid(ppeqop))
6209 elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
6210 eqstrategy, opcintype, opcintype, opfamily);
6213 * Are there equality operators that take exactly the FK type? Assume
6214 * we should look through any domain here.
6216 fktyped = getBaseType(fktype);
6218 pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
6220 if (OidIsValid(pfeqop))
6222 pfeqop_right = fktyped;
6223 ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
6228 /* keep compiler quiet */
6229 pfeqop_right = InvalidOid;
6230 ffeqop = InvalidOid;
6233 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
6236 * Otherwise, look for an implicit cast from the FK type to the
6237 * opcintype, and if found, use the primary equality operator.
6238 * This is a bit tricky because opcintype might be a polymorphic
6239 * type such as ANYARRAY or ANYENUM; so what we have to test is
6240 * whether the two actual column types can be concurrently cast to
6241 * that type. (Otherwise, we'd fail to reject combinations such
6242 * as int[] and point[].)
6244 Oid input_typeids[2];
6245 Oid target_typeids[2];
6247 input_typeids[0] = pktype;
6248 input_typeids[1] = fktype;
6249 target_typeids[0] = opcintype;
6250 target_typeids[1] = opcintype;
6251 if (can_coerce_type(2, input_typeids, target_typeids,
6254 pfeqop = ffeqop = ppeqop;
6255 pfeqop_right = opcintype;
6259 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
6261 (errcode(ERRCODE_DATATYPE_MISMATCH),
6262 errmsg("foreign key constraint \"%s\" "
6263 "cannot be implemented",
6264 fkconstraint->conname),
6265 errdetail("Key columns \"%s\" and \"%s\" "
6266 "are of incompatible types: %s and %s.",
6267 strVal(list_nth(fkconstraint->fk_attrs, i)),
6268 strVal(list_nth(fkconstraint->pk_attrs, i)),
6269 format_type_be(fktype),
6270 format_type_be(pktype))));
6275 * When a pfeqop changes, revalidate the constraint. We could
6276 * permit intra-opfamily changes, but that adds subtle complexity
6277 * without any concrete benefit for core types. We need not
6278 * assess ppeqop or ffeqop, which RI_Initial_Check() does not use.
6280 old_check_ok = (pfeqop == lfirst_oid(old_pfeqop_item));
6281 old_pfeqop_item = lnext(old_pfeqop_item);
6287 CoercionPathType old_pathtype;
6288 CoercionPathType new_pathtype;
6293 * Identify coercion pathways from each of the old and new FK-side
6294 * column types to the right (foreign) operand type of the pfeqop.
6295 * We may assume that pg_constraint.conkey is not changing.
6297 old_fktype = tab->oldDesc->attrs[fkattnum[i] - 1]->atttypid;
6298 new_fktype = fktype;
6299 old_pathtype = findFkeyCast(pfeqop_right, old_fktype,
6301 new_pathtype = findFkeyCast(pfeqop_right, new_fktype,
6305 * Upon a change to the cast from the FK column to its pfeqop
6306 * operand, revalidate the constraint. For this evaluation, a
6307 * binary coercion cast is equivalent to no cast at all. While
6308 * type implementors should design implicit casts with an eye
6309 * toward consistency of operations like equality, we cannot
6310 * assume here that they have done so.
6312 * A function with a polymorphic argument could change behavior
6313 * arbitrarily in response to get_fn_expr_argtype(). Therefore,
6314 * when the cast destination is polymorphic, we only avoid
6315 * revalidation if the input type has not changed at all. Given
6316 * just the core data types and operator classes, this requirement
6317 * prevents no would-be optimizations.
6319 * If the cast converts from a base type to a domain thereon, then
6320 * that domain type must be the opcintype of the unique index.
6321 * Necessarily, the primary key column must then be of the domain
6322 * type. Since the constraint was previously valid, all values on
6323 * the foreign side necessarily exist on the primary side and in
6324 * turn conform to the domain. Consequently, we need not treat
6325 * domains specially here.
6327 * Since we require that all collations share the same notion of
6328 * equality (which they do, because texteq reduces to bitwise
6329 * equality), we don't compare collation here.
6331 * We need not directly consider the PK type. It's necessarily
6332 * binary coercible to the opcintype of the unique index column,
6333 * and ri_triggers.c will only deal with PK datums in terms of
6334 * that opcintype. Changing the opcintype also changes pfeqop.
6336 old_check_ok = (new_pathtype == old_pathtype &&
6337 new_castfunc == old_castfunc &&
6338 (!IsPolymorphicType(pfeqop_right) ||
6339 new_fktype == old_fktype));
6343 pfeqoperators[i] = pfeqop;
6344 ppeqoperators[i] = ppeqop;
6345 ffeqoperators[i] = ffeqop;
6349 * Record the FK constraint in pg_constraint.
6351 constrOid = CreateConstraintEntry(fkconstraint->conname,
6352 RelationGetNamespace(rel),
6354 fkconstraint->deferrable,
6355 fkconstraint->initdeferred,
6356 fkconstraint->initially_valid,
6357 RelationGetRelid(rel),
6360 InvalidOid, /* not a domain
6363 RelationGetRelid(pkrel),
6369 fkconstraint->fk_upd_action,
6370 fkconstraint->fk_del_action,
6371 fkconstraint->fk_matchtype,
6372 NULL, /* no exclusion constraint */
6373 NULL, /* no check constraint */
6378 true, /* isnoinherit */
6379 false); /* is_internal */
6382 * Create the triggers that will enforce the constraint.
6384 createForeignKeyTriggers(rel, RelationGetRelid(pkrel), fkconstraint,
6385 constrOid, indexOid);
6388 * Tell Phase 3 to check that the constraint is satisfied by existing
6389 * rows. We can skip this during table creation, when requested explicitly
6390 * by specifying NOT VALID in an ADD FOREIGN KEY command, and when we're
6391 * recreating a constraint following a SET DATA TYPE operation that did
6392 * not impugn its validity.
6394 if (!old_check_ok && !fkconstraint->skip_validation)
6396 NewConstraint *newcon;
6398 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
6399 newcon->name = fkconstraint->conname;
6400 newcon->contype = CONSTR_FOREIGN;
6401 newcon->refrelid = RelationGetRelid(pkrel);
6402 newcon->refindid = indexOid;
6403 newcon->conid = constrOid;
6404 newcon->qual = (Node *) fkconstraint;
6406 tab->constraints = lappend(tab->constraints, newcon);
6410 * Close pk table, but keep lock until we've committed.
6412 heap_close(pkrel, NoLock);
6416 * ALTER TABLE ALTER CONSTRAINT
6418 * Update the attributes of a constraint.
6420 * Currently only works for Foreign Key constraints.
6421 * Foreign keys do not inherit, so we purposely ignore the
6422 * recursion bit here, but we keep the API the same for when
6423 * other constraint types are supported.
6426 ATExecAlterConstraint(Relation rel, AlterTableCmd *cmd,
6427 bool recurse, bool recursing, LOCKMODE lockmode)
6433 Form_pg_constraint currcon = NULL;
6434 Constraint *cmdcon = NULL;
6437 Assert(IsA(cmd->def, Constraint));
6438 cmdcon = (Constraint *) cmd->def;
6440 conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
6443 * Find and check the target constraint
6446 Anum_pg_constraint_conrelid,
6447 BTEqualStrategyNumber, F_OIDEQ,
6448 ObjectIdGetDatum(RelationGetRelid(rel)));
6449 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
6450 true, NULL, 1, &key);
6452 while (HeapTupleIsValid(contuple = systable_getnext(scan)))
6454 currcon = (Form_pg_constraint) GETSTRUCT(contuple);
6455 if (strcmp(NameStr(currcon->conname), cmdcon->conname) == 0)
6464 (errcode(ERRCODE_UNDEFINED_OBJECT),
6465 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
6466 cmdcon->conname, RelationGetRelationName(rel))));
6468 if (currcon->contype != CONSTRAINT_FOREIGN)
6470 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6471 errmsg("constraint \"%s\" of relation \"%s\" is not a foreign key constraint",
6472 cmdcon->conname, RelationGetRelationName(rel))));
6474 if (currcon->condeferrable != cmdcon->deferrable ||
6475 currcon->condeferred != cmdcon->initdeferred)
6477 HeapTuple copyTuple;
6479 Form_pg_constraint copy_con;
6480 Form_pg_trigger copy_tg;
6486 * Now update the catalog, while we have the door open.
6488 copyTuple = heap_copytuple(contuple);
6489 copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
6490 copy_con->condeferrable = cmdcon->deferrable;
6491 copy_con->condeferred = cmdcon->initdeferred;
6492 simple_heap_update(conrel, ©Tuple->t_self, copyTuple);
6493 CatalogUpdateIndexes(conrel, copyTuple);
6495 InvokeObjectPostAlterHook(ConstraintRelationId,
6496 HeapTupleGetOid(contuple), 0);
6498 heap_freetuple(copyTuple);
6501 * Now we need to update the multiple entries in pg_trigger that
6502 * implement the constraint.
6504 tgrel = heap_open(TriggerRelationId, RowExclusiveLock);
6507 Anum_pg_trigger_tgconstraint,
6508 BTEqualStrategyNumber, F_OIDEQ,
6509 ObjectIdGetDatum(HeapTupleGetOid(contuple)));
6511 tgscan = systable_beginscan(tgrel, TriggerConstraintIndexId, true,
6514 while (HeapTupleIsValid(tgtuple = systable_getnext(tgscan)))
6516 copyTuple = heap_copytuple(tgtuple);
6517 copy_tg = (Form_pg_trigger) GETSTRUCT(copyTuple);
6518 copy_tg->tgdeferrable = cmdcon->deferrable;
6519 copy_tg->tginitdeferred = cmdcon->initdeferred;
6520 simple_heap_update(tgrel, ©Tuple->t_self, copyTuple);
6521 CatalogUpdateIndexes(tgrel, copyTuple);
6523 InvokeObjectPostAlterHook(TriggerRelationId,
6524 HeapTupleGetOid(tgtuple), 0);
6526 heap_freetuple(copyTuple);
6529 systable_endscan(tgscan);
6531 heap_close(tgrel, RowExclusiveLock);
6534 * Invalidate relcache so that others see the new attributes.
6536 CacheInvalidateRelcache(rel);
6539 systable_endscan(scan);
6541 heap_close(conrel, RowExclusiveLock);
6545 * ALTER TABLE VALIDATE CONSTRAINT
6547 * XXX The reason we handle recursion here rather than at Phase 1 is because
6548 * there's no good way to skip recursing when handling foreign keys: there is
6549 * no need to lock children in that case, yet we wouldn't be able to avoid
6550 * doing so at that level.
6553 ATExecValidateConstraint(Relation rel, char *constrName, bool recurse,
6554 bool recursing, LOCKMODE lockmode)
6560 Form_pg_constraint con = NULL;
6563 conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
6566 * Find and check the target constraint
6569 Anum_pg_constraint_conrelid,
6570 BTEqualStrategyNumber, F_OIDEQ,
6571 ObjectIdGetDatum(RelationGetRelid(rel)));
6572 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
6573 true, NULL, 1, &key);
6575 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
6577 con = (Form_pg_constraint) GETSTRUCT(tuple);
6578 if (strcmp(NameStr(con->conname), constrName) == 0)
6587 (errcode(ERRCODE_UNDEFINED_OBJECT),
6588 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
6589 constrName, RelationGetRelationName(rel))));
6591 if (con->contype != CONSTRAINT_FOREIGN &&
6592 con->contype != CONSTRAINT_CHECK)
6594 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6595 errmsg("constraint \"%s\" of relation \"%s\" is not a foreign key or check constraint",
6596 constrName, RelationGetRelationName(rel))));
6598 if (!con->convalidated)
6600 HeapTuple copyTuple;
6601 Form_pg_constraint copy_con;
6603 if (con->contype == CONSTRAINT_FOREIGN)
6605 Oid conid = HeapTupleGetOid(tuple);
6609 * Triggers are already in place on both tables, so a concurrent
6610 * write that alters the result here is not possible. Normally we
6611 * can run a query here to do the validation, which would only
6612 * require AccessShareLock. In some cases, it is possible that we
6613 * might need to fire triggers to perform the check, so we take a
6614 * lock at RowShareLock level just in case.
6616 refrel = heap_open(con->confrelid, RowShareLock);
6618 validateForeignKeyConstraint(constrName, rel, refrel,
6621 heap_close(refrel, NoLock);
6624 * Foreign keys do not inherit, so we purposely ignore the
6625 * recursion bit here
6628 else if (con->contype == CONSTRAINT_CHECK)
6630 List *children = NIL;
6634 * If we're recursing, the parent has already done this, so skip
6638 children = find_all_inheritors(RelationGetRelid(rel),
6642 * For CHECK constraints, we must ensure that we only mark the
6643 * constraint as validated on the parent if it's already validated
6646 * We recurse before validating on the parent, to reduce risk of
6649 foreach(child, children)
6651 Oid childoid = lfirst_oid(child);
6654 if (childoid == RelationGetRelid(rel))
6658 * If we are told not to recurse, there had better not be any
6659 * child tables; else the addition would put them out of step.
6663 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6664 errmsg("constraint must be validated on child tables too")));
6666 /* find_all_inheritors already got lock */
6667 childrel = heap_open(childoid, NoLock);
6669 ATExecValidateConstraint(childrel, constrName, false,
6671 heap_close(childrel, NoLock);
6674 validateCheckConstraint(rel, tuple);
6677 * Invalidate relcache so that others see the new validated
6680 CacheInvalidateRelcache(rel);
6684 * Now update the catalog, while we have the door open.
6686 copyTuple = heap_copytuple(tuple);
6687 copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
6688 copy_con->convalidated = true;
6689 simple_heap_update(conrel, ©Tuple->t_self, copyTuple);
6690 CatalogUpdateIndexes(conrel, copyTuple);
6692 InvokeObjectPostAlterHook(ConstraintRelationId,
6693 HeapTupleGetOid(tuple), 0);
6695 heap_freetuple(copyTuple);
6698 systable_endscan(scan);
6700 heap_close(conrel, RowExclusiveLock);
6705 * transformColumnNameList - transform list of column names
6707 * Lookup each name and return its attnum and type OID
6710 transformColumnNameList(Oid relId, List *colList,
6711 int16 *attnums, Oid *atttypids)
6719 char *attname = strVal(lfirst(l));
6722 atttuple = SearchSysCacheAttName(relId, attname);
6723 if (!HeapTupleIsValid(atttuple))
6725 (errcode(ERRCODE_UNDEFINED_COLUMN),
6726 errmsg("column \"%s\" referenced in foreign key constraint does not exist",
6728 if (attnum >= INDEX_MAX_KEYS)
6730 (errcode(ERRCODE_TOO_MANY_COLUMNS),
6731 errmsg("cannot have more than %d keys in a foreign key",
6733 attnums[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->attnum;
6734 atttypids[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->atttypid;
6735 ReleaseSysCache(atttuple);
6743 * transformFkeyGetPrimaryKey -
6745 * Look up the names, attnums, and types of the primary key attributes
6746 * for the pkrel. Also return the index OID and index opclasses of the
6747 * index supporting the primary key.
6749 * All parameters except pkrel are output parameters. Also, the function
6750 * return value is the number of attributes in the primary key.
6752 * Used when the column list in the REFERENCES specification is omitted.
6755 transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
6757 int16 *attnums, Oid *atttypids,
6761 ListCell *indexoidscan;
6762 HeapTuple indexTuple = NULL;
6763 Form_pg_index indexStruct = NULL;
6764 Datum indclassDatum;
6766 oidvector *indclass;
6770 * Get the list of index OIDs for the table from the relcache, and look up
6771 * each one in the pg_index syscache until we find one marked primary key
6772 * (hopefully there isn't more than one such). Insist it's valid, too.
6774 *indexOid = InvalidOid;
6776 indexoidlist = RelationGetIndexList(pkrel);
6778 foreach(indexoidscan, indexoidlist)
6780 Oid indexoid = lfirst_oid(indexoidscan);
6782 indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
6783 if (!HeapTupleIsValid(indexTuple))
6784 elog(ERROR, "cache lookup failed for index %u", indexoid);
6785 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
6786 if (indexStruct->indisprimary && IndexIsValid(indexStruct))
6789 * Refuse to use a deferrable primary key. This is per SQL spec,
6790 * and there would be a lot of interesting semantic problems if we
6791 * tried to allow it.
6793 if (!indexStruct->indimmediate)
6795 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6796 errmsg("cannot use a deferrable primary key for referenced table \"%s\"",
6797 RelationGetRelationName(pkrel))));
6799 *indexOid = indexoid;
6802 ReleaseSysCache(indexTuple);
6805 list_free(indexoidlist);
6808 * Check that we found it
6810 if (!OidIsValid(*indexOid))
6812 (errcode(ERRCODE_UNDEFINED_OBJECT),
6813 errmsg("there is no primary key for referenced table \"%s\"",
6814 RelationGetRelationName(pkrel))));
6816 /* Must get indclass the hard way */
6817 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
6818 Anum_pg_index_indclass, &isnull);
6820 indclass = (oidvector *) DatumGetPointer(indclassDatum);
6823 * Now build the list of PK attributes from the indkey definition (we
6824 * assume a primary key cannot have expressional elements)
6827 for (i = 0; i < indexStruct->indnatts; i++)
6829 int pkattno = indexStruct->indkey.values[i];
6831 attnums[i] = pkattno;
6832 atttypids[i] = attnumTypeId(pkrel, pkattno);
6833 opclasses[i] = indclass->values[i];
6834 *attnamelist = lappend(*attnamelist,
6835 makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
6838 ReleaseSysCache(indexTuple);
6844 * transformFkeyCheckAttrs -
6846 * Make sure that the attributes of a referenced table belong to a unique
6847 * (or primary key) constraint. Return the OID of the index supporting
6848 * the constraint, as well as the opclasses associated with the index
6852 transformFkeyCheckAttrs(Relation pkrel,
6853 int numattrs, int16 *attnums,
6854 Oid *opclasses) /* output parameter */
6856 Oid indexoid = InvalidOid;
6858 bool found_deferrable = false;
6860 ListCell *indexoidscan;
6865 * Reject duplicate appearances of columns in the referenced-columns list.
6866 * Such a case is forbidden by the SQL standard, and even if we thought it
6867 * useful to allow it, there would be ambiguity about how to match the
6868 * list to unique indexes (in particular, it'd be unclear which index
6869 * opclass goes with which FK column).
6871 for (i = 0; i < numattrs; i++)
6873 for (j = i + 1; j < numattrs; j++)
6875 if (attnums[i] == attnums[j])
6877 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
6878 errmsg("foreign key referenced-columns list must not contain duplicates")));
6883 * Get the list of index OIDs for the table from the relcache, and look up
6884 * each one in the pg_index syscache, and match unique indexes to the list
6885 * of attnums we are given.
6887 indexoidlist = RelationGetIndexList(pkrel);
6889 foreach(indexoidscan, indexoidlist)
6891 HeapTuple indexTuple;
6892 Form_pg_index indexStruct;
6894 indexoid = lfirst_oid(indexoidscan);
6895 indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
6896 if (!HeapTupleIsValid(indexTuple))
6897 elog(ERROR, "cache lookup failed for index %u", indexoid);
6898 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
6901 * Must have the right number of columns; must be unique and not a
6902 * partial index; forget it if there are any expressions, too. Invalid
6903 * indexes are out as well.
6905 if (indexStruct->indnatts == numattrs &&
6906 indexStruct->indisunique &&
6907 IndexIsValid(indexStruct) &&
6908 heap_attisnull(indexTuple, Anum_pg_index_indpred) &&
6909 heap_attisnull(indexTuple, Anum_pg_index_indexprs))
6911 Datum indclassDatum;
6913 oidvector *indclass;
6915 /* Must get indclass the hard way */
6916 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
6917 Anum_pg_index_indclass, &isnull);
6919 indclass = (oidvector *) DatumGetPointer(indclassDatum);
6922 * The given attnum list may match the index columns in any order.
6923 * Check for a match, and extract the appropriate opclasses while
6926 * We know that attnums[] is duplicate-free per the test at the
6927 * start of this function, and we checked above that the number of
6928 * index columns agrees, so if we find a match for each attnums[]
6929 * entry then we must have a one-to-one match in some order.
6931 for (i = 0; i < numattrs; i++)
6934 for (j = 0; j < numattrs; j++)
6936 if (attnums[i] == indexStruct->indkey.values[j])
6938 opclasses[i] = indclass->values[j];
6948 * Refuse to use a deferrable unique/primary key. This is per SQL
6949 * spec, and there would be a lot of interesting semantic problems
6950 * if we tried to allow it.
6952 if (found && !indexStruct->indimmediate)
6955 * Remember that we found an otherwise matching index, so that
6956 * we can generate a more appropriate error message.
6958 found_deferrable = true;
6962 ReleaseSysCache(indexTuple);
6969 if (found_deferrable)
6971 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6972 errmsg("cannot use a deferrable unique constraint for referenced table \"%s\"",
6973 RelationGetRelationName(pkrel))));
6976 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
6977 errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
6978 RelationGetRelationName(pkrel))));
6981 list_free(indexoidlist);
6989 * Wrapper around find_coercion_pathway() for ATAddForeignKeyConstraint().
6990 * Caller has equal regard for binary coercibility and for an exact match.
6992 static CoercionPathType
6993 findFkeyCast(Oid targetTypeId, Oid sourceTypeId, Oid *funcid)
6995 CoercionPathType ret;
6997 if (targetTypeId == sourceTypeId)
6999 ret = COERCION_PATH_RELABELTYPE;
7000 *funcid = InvalidOid;
7004 ret = find_coercion_pathway(targetTypeId, sourceTypeId,
7005 COERCION_IMPLICIT, funcid);
7006 if (ret == COERCION_PATH_NONE)
7007 /* A previously-relied-upon cast is now gone. */
7008 elog(ERROR, "could not find cast from %u to %u",
7009 sourceTypeId, targetTypeId);
7015 /* Permissions checks for ADD FOREIGN KEY */
7017 checkFkeyPermissions(Relation rel, int16 *attnums, int natts)
7019 Oid roleid = GetUserId();
7020 AclResult aclresult;
7023 /* Okay if we have relation-level REFERENCES permission */
7024 aclresult = pg_class_aclcheck(RelationGetRelid(rel), roleid,
7026 if (aclresult == ACLCHECK_OK)
7028 /* Else we must have REFERENCES on each column */
7029 for (i = 0; i < natts; i++)
7031 aclresult = pg_attribute_aclcheck(RelationGetRelid(rel), attnums[i],
7032 roleid, ACL_REFERENCES);
7033 if (aclresult != ACLCHECK_OK)
7034 aclcheck_error(aclresult, ACL_KIND_CLASS,
7035 RelationGetRelationName(rel));
7040 * Scan the existing rows in a table to verify they meet a proposed
7043 * The caller must have opened and locked the relation appropriately.
7046 validateCheckConstraint(Relation rel, HeapTuple constrtup)
7056 ExprContext *econtext;
7057 MemoryContext oldcxt;
7058 TupleTableSlot *slot;
7059 Form_pg_constraint constrForm;
7063 constrForm = (Form_pg_constraint) GETSTRUCT(constrtup);
7065 estate = CreateExecutorState();
7068 * XXX this tuple doesn't really come from a syscache, but this doesn't
7069 * matter to SysCacheGetAttr, because it only wants to be able to fetch
7072 val = SysCacheGetAttr(CONSTROID, constrtup, Anum_pg_constraint_conbin,
7075 elog(ERROR, "null conbin for constraint %u",
7076 HeapTupleGetOid(constrtup));
7077 conbin = TextDatumGetCString(val);
7078 origexpr = (Expr *) stringToNode(conbin);
7079 exprstate = (List *)
7080 ExecPrepareExpr((Expr *) make_ands_implicit(origexpr), estate);
7082 econtext = GetPerTupleExprContext(estate);
7083 tupdesc = RelationGetDescr(rel);
7084 slot = MakeSingleTupleTableSlot(tupdesc);
7085 econtext->ecxt_scantuple = slot;
7087 snapshot = RegisterSnapshot(GetLatestSnapshot());
7088 scan = heap_beginscan(rel, snapshot, 0, NULL);
7091 * Switch to per-tuple memory context and reset it for each tuple
7092 * produced, so we don't leak memory.
7094 oldcxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
7096 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
7098 ExecStoreTuple(tuple, slot, InvalidBuffer, false);
7100 if (!ExecQual(exprstate, econtext, true))
7102 (errcode(ERRCODE_CHECK_VIOLATION),
7103 errmsg("check constraint \"%s\" is violated by some row",
7104 NameStr(constrForm->conname)),
7105 errtableconstraint(rel, NameStr(constrForm->conname))));
7107 ResetExprContext(econtext);
7110 MemoryContextSwitchTo(oldcxt);
7112 UnregisterSnapshot(snapshot);
7113 ExecDropSingleTupleTableSlot(slot);
7114 FreeExecutorState(estate);
7118 * Scan the existing rows in a table to verify they meet a proposed FK
7121 * Caller must have opened and locked both relations appropriately.
7124 validateForeignKeyConstraint(char *conname,
7136 (errmsg("validating foreign key constraint \"%s\"", conname)));
7139 * Build a trigger call structure; we'll need it either way.
7141 MemSet(&trig, 0, sizeof(trig));
7142 trig.tgoid = InvalidOid;
7143 trig.tgname = conname;
7144 trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
7145 trig.tgisinternal = TRUE;
7146 trig.tgconstrrelid = RelationGetRelid(pkrel);
7147 trig.tgconstrindid = pkindOid;
7148 trig.tgconstraint = constraintOid;
7149 trig.tgdeferrable = FALSE;
7150 trig.tginitdeferred = FALSE;
7151 /* we needn't fill in tgargs or tgqual */
7154 * See if we can do it with a single LEFT JOIN query. A FALSE result
7155 * indicates we must proceed with the fire-the-trigger method.
7157 if (RI_Initial_Check(&trig, rel, pkrel))
7161 * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
7162 * if that tuple had just been inserted. If any of those fail, it should
7163 * ereport(ERROR) and that's that.
7165 snapshot = RegisterSnapshot(GetLatestSnapshot());
7166 scan = heap_beginscan(rel, snapshot, 0, NULL);
7168 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
7170 FunctionCallInfoData fcinfo;
7171 TriggerData trigdata;
7174 * Make a call to the trigger function
7176 * No parameters are passed, but we do set a context
7178 MemSet(&fcinfo, 0, sizeof(fcinfo));
7181 * We assume RI_FKey_check_ins won't look at flinfo...
7183 trigdata.type = T_TriggerData;
7184 trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
7185 trigdata.tg_relation = rel;
7186 trigdata.tg_trigtuple = tuple;
7187 trigdata.tg_newtuple = NULL;
7188 trigdata.tg_trigger = &trig;
7189 trigdata.tg_trigtuplebuf = scan->rs_cbuf;
7190 trigdata.tg_newtuplebuf = InvalidBuffer;
7192 fcinfo.context = (Node *) &trigdata;
7194 RI_FKey_check_ins(&fcinfo);
7198 UnregisterSnapshot(snapshot);
7202 CreateFKCheckTrigger(Oid myRelOid, Oid refRelOid, Constraint *fkconstraint,
7203 Oid constraintOid, Oid indexOid, bool on_insert)
7205 CreateTrigStmt *fk_trigger;
7208 * Note: for a self-referential FK (referencing and referenced tables are
7209 * the same), it is important that the ON UPDATE action fires before the
7210 * CHECK action, since both triggers will fire on the same row during an
7211 * UPDATE event; otherwise the CHECK trigger will be checking a non-final
7212 * state of the row. Triggers fire in name order, so we ensure this by
7213 * using names like "RI_ConstraintTrigger_a_NNNN" for the action triggers
7214 * and "RI_ConstraintTrigger_c_NNNN" for the check triggers.
7216 fk_trigger = makeNode(CreateTrigStmt);
7217 fk_trigger->trigname = "RI_ConstraintTrigger_c";
7218 fk_trigger->relation = NULL;
7219 fk_trigger->row = true;
7220 fk_trigger->timing = TRIGGER_TYPE_AFTER;
7222 /* Either ON INSERT or ON UPDATE */
7225 fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
7226 fk_trigger->events = TRIGGER_TYPE_INSERT;
7230 fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
7231 fk_trigger->events = TRIGGER_TYPE_UPDATE;
7234 fk_trigger->columns = NIL;
7235 fk_trigger->whenClause = NULL;
7236 fk_trigger->isconstraint = true;
7237 fk_trigger->deferrable = fkconstraint->deferrable;
7238 fk_trigger->initdeferred = fkconstraint->initdeferred;
7239 fk_trigger->constrrel = NULL;
7240 fk_trigger->args = NIL;
7242 (void) CreateTrigger(fk_trigger, NULL, myRelOid, refRelOid, constraintOid,
7245 /* Make changes-so-far visible */
7246 CommandCounterIncrement();
7250 * Create the triggers that implement an FK constraint.
7253 createForeignKeyTriggers(Relation rel, Oid refRelOid, Constraint *fkconstraint,
7254 Oid constraintOid, Oid indexOid)
7257 CreateTrigStmt *fk_trigger;
7259 myRelOid = RelationGetRelid(rel);
7261 /* Make changes-so-far visible */
7262 CommandCounterIncrement();
7265 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
7266 * DELETE action on the referenced table.
7268 fk_trigger = makeNode(CreateTrigStmt);
7269 fk_trigger->trigname = "RI_ConstraintTrigger_a";
7270 fk_trigger->relation = NULL;
7271 fk_trigger->row = true;
7272 fk_trigger->timing = TRIGGER_TYPE_AFTER;
7273 fk_trigger->events = TRIGGER_TYPE_DELETE;
7274 fk_trigger->columns = NIL;
7275 fk_trigger->whenClause = NULL;
7276 fk_trigger->isconstraint = true;
7277 fk_trigger->constrrel = NULL;
7278 switch (fkconstraint->fk_del_action)
7280 case FKCONSTR_ACTION_NOACTION:
7281 fk_trigger->deferrable = fkconstraint->deferrable;
7282 fk_trigger->initdeferred = fkconstraint->initdeferred;
7283 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
7285 case FKCONSTR_ACTION_RESTRICT:
7286 fk_trigger->deferrable = false;
7287 fk_trigger->initdeferred = false;
7288 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
7290 case FKCONSTR_ACTION_CASCADE:
7291 fk_trigger->deferrable = false;
7292 fk_trigger->initdeferred = false;
7293 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
7295 case FKCONSTR_ACTION_SETNULL:
7296 fk_trigger->deferrable = false;
7297 fk_trigger->initdeferred = false;
7298 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
7300 case FKCONSTR_ACTION_SETDEFAULT:
7301 fk_trigger->deferrable = false;
7302 fk_trigger->initdeferred = false;
7303 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
7306 elog(ERROR, "unrecognized FK action type: %d",
7307 (int) fkconstraint->fk_del_action);
7310 fk_trigger->args = NIL;
7312 (void) CreateTrigger(fk_trigger, NULL, refRelOid, myRelOid, constraintOid,
7315 /* Make changes-so-far visible */
7316 CommandCounterIncrement();
7319 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
7320 * UPDATE action on the referenced table.
7322 fk_trigger = makeNode(CreateTrigStmt);
7323 fk_trigger->trigname = "RI_ConstraintTrigger_a";
7324 fk_trigger->relation = NULL;
7325 fk_trigger->row = true;
7326 fk_trigger->timing = TRIGGER_TYPE_AFTER;
7327 fk_trigger->events = TRIGGER_TYPE_UPDATE;
7328 fk_trigger->columns = NIL;
7329 fk_trigger->whenClause = NULL;
7330 fk_trigger->isconstraint = true;
7331 fk_trigger->constrrel = NULL;
7332 switch (fkconstraint->fk_upd_action)
7334 case FKCONSTR_ACTION_NOACTION:
7335 fk_trigger->deferrable = fkconstraint->deferrable;
7336 fk_trigger->initdeferred = fkconstraint->initdeferred;
7337 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
7339 case FKCONSTR_ACTION_RESTRICT:
7340 fk_trigger->deferrable = false;
7341 fk_trigger->initdeferred = false;
7342 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
7344 case FKCONSTR_ACTION_CASCADE:
7345 fk_trigger->deferrable = false;
7346 fk_trigger->initdeferred = false;
7347 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
7349 case FKCONSTR_ACTION_SETNULL:
7350 fk_trigger->deferrable = false;
7351 fk_trigger->initdeferred = false;
7352 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
7354 case FKCONSTR_ACTION_SETDEFAULT:
7355 fk_trigger->deferrable = false;
7356 fk_trigger->initdeferred = false;
7357 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
7360 elog(ERROR, "unrecognized FK action type: %d",
7361 (int) fkconstraint->fk_upd_action);
7364 fk_trigger->args = NIL;
7366 (void) CreateTrigger(fk_trigger, NULL, refRelOid, myRelOid, constraintOid,
7369 /* Make changes-so-far visible */
7370 CommandCounterIncrement();
7373 * Build and execute CREATE CONSTRAINT TRIGGER statements for the CHECK
7374 * action for both INSERTs and UPDATEs on the referencing table.
7376 CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint, constraintOid,
7378 CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint, constraintOid,
7383 * ALTER TABLE DROP CONSTRAINT
7385 * Like DROP COLUMN, we can't use the normal ALTER TABLE recursion mechanism.
7388 ATExecDropConstraint(Relation rel, const char *constrName,
7389 DropBehavior behavior,
7390 bool recurse, bool recursing,
7391 bool missing_ok, LOCKMODE lockmode)
7396 Form_pg_constraint con;
7401 bool is_no_inherit_constraint = false;
7403 /* At top level, permission check was done in ATPrepCmd, else do it */
7405 ATSimplePermissions(rel, ATT_TABLE);
7407 conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
7410 * Find and drop the target constraint
7413 Anum_pg_constraint_conrelid,
7414 BTEqualStrategyNumber, F_OIDEQ,
7415 ObjectIdGetDatum(RelationGetRelid(rel)));
7416 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
7417 true, NULL, 1, &key);
7419 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
7421 ObjectAddress conobj;
7423 con = (Form_pg_constraint) GETSTRUCT(tuple);
7425 if (strcmp(NameStr(con->conname), constrName) != 0)
7428 /* Don't drop inherited constraints */
7429 if (con->coninhcount > 0 && !recursing)
7431 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7432 errmsg("cannot drop inherited constraint \"%s\" of relation \"%s\"",
7433 constrName, RelationGetRelationName(rel))));
7435 is_no_inherit_constraint = con->connoinherit;
7438 * Perform the actual constraint deletion
7440 conobj.classId = ConstraintRelationId;
7441 conobj.objectId = HeapTupleGetOid(tuple);
7442 conobj.objectSubId = 0;
7444 performDeletion(&conobj, behavior, 0);
7448 /* constraint found and dropped -- no need to keep looping */
7452 systable_endscan(scan);
7459 (errcode(ERRCODE_UNDEFINED_OBJECT),
7460 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
7461 constrName, RelationGetRelationName(rel))));
7466 (errmsg("constraint \"%s\" of relation \"%s\" does not exist, skipping",
7467 constrName, RelationGetRelationName(rel))));
7468 heap_close(conrel, RowExclusiveLock);
7474 * Propagate to children as appropriate. Unlike most other ALTER
7475 * routines, we have to do this one level of recursion at a time; we can't
7476 * use find_all_inheritors to do it in one pass.
7478 if (!is_no_inherit_constraint)
7479 children = find_inheritance_children(RelationGetRelid(rel), lockmode);
7483 foreach(child, children)
7485 Oid childrelid = lfirst_oid(child);
7487 HeapTuple copy_tuple;
7489 /* find_inheritance_children already got lock */
7490 childrel = heap_open(childrelid, NoLock);
7491 CheckTableNotInUse(childrel, "ALTER TABLE");
7494 Anum_pg_constraint_conrelid,
7495 BTEqualStrategyNumber, F_OIDEQ,
7496 ObjectIdGetDatum(childrelid));
7497 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
7498 true, NULL, 1, &key);
7500 /* scan for matching tuple - there should only be one */
7501 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
7503 con = (Form_pg_constraint) GETSTRUCT(tuple);
7505 /* Right now only CHECK constraints can be inherited */
7506 if (con->contype != CONSTRAINT_CHECK)
7509 if (strcmp(NameStr(con->conname), constrName) == 0)
7513 if (!HeapTupleIsValid(tuple))
7515 (errcode(ERRCODE_UNDEFINED_OBJECT),
7516 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
7518 RelationGetRelationName(childrel))));
7520 copy_tuple = heap_copytuple(tuple);
7522 systable_endscan(scan);
7524 con = (Form_pg_constraint) GETSTRUCT(copy_tuple);
7526 if (con->coninhcount <= 0) /* shouldn't happen */
7527 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
7528 childrelid, constrName);
7533 * If the child constraint has other definition sources, just
7534 * decrement its inheritance count; if not, recurse to delete it.
7536 if (con->coninhcount == 1 && !con->conislocal)
7538 /* Time to delete this child constraint, too */
7539 ATExecDropConstraint(childrel, constrName, behavior,
7545 /* Child constraint must survive my deletion */
7547 simple_heap_update(conrel, ©_tuple->t_self, copy_tuple);
7548 CatalogUpdateIndexes(conrel, copy_tuple);
7550 /* Make update visible */
7551 CommandCounterIncrement();
7557 * If we were told to drop ONLY in this table (no recursion), we
7558 * need to mark the inheritors' constraints as locally defined
7559 * rather than inherited.
7562 con->conislocal = true;
7564 simple_heap_update(conrel, ©_tuple->t_self, copy_tuple);
7565 CatalogUpdateIndexes(conrel, copy_tuple);
7567 /* Make update visible */
7568 CommandCounterIncrement();
7571 heap_freetuple(copy_tuple);
7573 heap_close(childrel, NoLock);
7576 heap_close(conrel, RowExclusiveLock);
7583 ATPrepAlterColumnType(List **wqueue,
7584 AlteredTableInfo *tab, Relation rel,
7585 bool recurse, bool recursing,
7586 AlterTableCmd *cmd, LOCKMODE lockmode)
7588 char *colName = cmd->name;
7589 ColumnDef *def = (ColumnDef *) cmd->def;
7590 TypeName *typeName = def->typeName;
7591 Node *transform = def->raw_default;
7593 Form_pg_attribute attTup;
7598 NewColumnValue *newval;
7599 ParseState *pstate = make_parsestate(NULL);
7600 AclResult aclresult;
7602 if (rel->rd_rel->reloftype && !recursing)
7604 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7605 errmsg("cannot alter column type of typed table")));
7607 /* lookup the attribute so we can check inheritance status */
7608 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
7609 if (!HeapTupleIsValid(tuple))
7611 (errcode(ERRCODE_UNDEFINED_COLUMN),
7612 errmsg("column \"%s\" of relation \"%s\" does not exist",
7613 colName, RelationGetRelationName(rel))));
7614 attTup = (Form_pg_attribute) GETSTRUCT(tuple);
7615 attnum = attTup->attnum;
7617 /* Can't alter a system attribute */
7620 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7621 errmsg("cannot alter system column \"%s\"",
7624 /* Don't alter inherited columns */
7625 if (attTup->attinhcount > 0 && !recursing)
7627 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7628 errmsg("cannot alter inherited column \"%s\"",
7631 /* Look up the target type */
7632 typenameTypeIdAndMod(NULL, typeName, &targettype, &targettypmod);
7634 aclresult = pg_type_aclcheck(targettype, GetUserId(), ACL_USAGE);
7635 if (aclresult != ACLCHECK_OK)
7636 aclcheck_error_type(aclresult, targettype);
7638 /* And the collation */
7639 targetcollid = GetColumnDefCollation(NULL, def, targettype);
7641 /* make sure datatype is legal for a column */
7642 CheckAttributeType(colName, targettype, targetcollid,
7643 list_make1_oid(rel->rd_rel->reltype),
7646 if (tab->relkind == RELKIND_RELATION)
7649 * Set up an expression to transform the old data value to the new
7650 * type. If a USING option was given, transform and use that
7651 * expression, else just take the old value and try to coerce it. We
7652 * do this first so that type incompatibility can be detected before
7653 * we waste effort, and because we need the expression to be parsed
7654 * against the original table row type.
7660 /* Expression must be able to access vars of old table */
7661 rte = addRangeTableEntryForRelation(pstate,
7666 addRTEtoQuery(pstate, rte, false, true, true);
7668 transform = transformExpr(pstate, transform,
7669 EXPR_KIND_ALTER_COL_TRANSFORM);
7671 /* It can't return a set */
7672 if (expression_returns_set(transform))
7674 (errcode(ERRCODE_DATATYPE_MISMATCH),
7675 errmsg("transform expression must not return a set")));
7679 transform = (Node *) makeVar(1, attnum,
7680 attTup->atttypid, attTup->atttypmod,
7681 attTup->attcollation,
7685 transform = coerce_to_target_type(pstate,
7686 transform, exprType(transform),
7687 targettype, targettypmod,
7688 COERCION_ASSIGNMENT,
7689 COERCE_IMPLICIT_CAST,
7691 if (transform == NULL)
7693 (errcode(ERRCODE_DATATYPE_MISMATCH),
7694 errmsg("column \"%s\" cannot be cast automatically to type %s",
7695 colName, format_type_be(targettype)),
7696 errhint("Specify a USING expression to perform the conversion.")));
7698 /* Fix collations after all else */
7699 assign_expr_collations(pstate, transform);
7701 /* Plan the expr now so we can accurately assess the need to rewrite. */
7702 transform = (Node *) expression_planner((Expr *) transform);
7705 * Add a work queue item to make ATRewriteTable update the column
7708 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
7709 newval->attnum = attnum;
7710 newval->expr = (Expr *) transform;
7712 tab->newvals = lappend(tab->newvals, newval);
7713 if (ATColumnChangeRequiresRewrite(transform, attnum))
7714 tab->rewrite |= AT_REWRITE_COLUMN_REWRITE;
7718 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7719 errmsg("\"%s\" is not a table",
7720 RelationGetRelationName(rel))));
7722 if (tab->relkind == RELKIND_COMPOSITE_TYPE ||
7723 tab->relkind == RELKIND_FOREIGN_TABLE)
7726 * For composite types, do this check now. Tables will check it later
7727 * when the table is being rewritten.
7729 find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
7732 ReleaseSysCache(tuple);
7735 * The recursion case is handled by ATSimpleRecursion. However, if we are
7736 * told not to recurse, there had better not be any child tables; else the
7737 * alter would put them out of step.
7740 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
7741 else if (!recursing &&
7742 find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL)
7744 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7745 errmsg("type of inherited column \"%s\" must be changed in child tables too",
7748 if (tab->relkind == RELKIND_COMPOSITE_TYPE)
7749 ATTypedTableRecursion(wqueue, rel, cmd, lockmode);
7753 * When the data type of a column is changed, a rewrite might not be required
7754 * if the new type is sufficiently identical to the old one, and the USING
7755 * clause isn't trying to insert some other value. It's safe to skip the
7756 * rewrite if the old type is binary coercible to the new type, or if the
7757 * new type is an unconstrained domain over the old type. In the case of a
7758 * constrained domain, we could get by with scanning the table and checking
7759 * the constraint rather than actually rewriting it, but we don't currently
7763 ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno)
7765 Assert(expr != NULL);
7769 /* only one varno, so no need to check that */
7770 if (IsA(expr, Var) &&((Var *) expr)->varattno == varattno)
7772 else if (IsA(expr, RelabelType))
7773 expr = (Node *) ((RelabelType *) expr)->arg;
7774 else if (IsA(expr, CoerceToDomain))
7776 CoerceToDomain *d = (CoerceToDomain *) expr;
7778 if (GetDomainConstraints(d->resulttype) != NIL)
7780 expr = (Node *) d->arg;
7788 ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
7789 AlterTableCmd *cmd, LOCKMODE lockmode)
7791 char *colName = cmd->name;
7792 ColumnDef *def = (ColumnDef *) cmd->def;
7793 TypeName *typeName = def->typeName;
7795 Form_pg_attribute attTup;
7797 HeapTuple typeTuple;
7803 Relation attrelation;
7809 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
7811 /* Look up the target column */
7812 heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
7813 if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
7815 (errcode(ERRCODE_UNDEFINED_COLUMN),
7816 errmsg("column \"%s\" of relation \"%s\" does not exist",
7817 colName, RelationGetRelationName(rel))));
7818 attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
7819 attnum = attTup->attnum;
7821 /* Check for multiple ALTER TYPE on same column --- can't cope */
7822 if (attTup->atttypid != tab->oldDesc->attrs[attnum - 1]->atttypid ||
7823 attTup->atttypmod != tab->oldDesc->attrs[attnum - 1]->atttypmod)
7825 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7826 errmsg("cannot alter type of column \"%s\" twice",
7829 /* Look up the target type (should not fail, since prep found it) */
7830 typeTuple = typenameType(NULL, typeName, &targettypmod);
7831 tform = (Form_pg_type) GETSTRUCT(typeTuple);
7832 targettype = HeapTupleGetOid(typeTuple);
7833 /* And the collation */
7834 targetcollid = GetColumnDefCollation(NULL, def, targettype);
7837 * If there is a default expression for the column, get it and ensure we
7838 * can coerce it to the new datatype. (We must do this before changing
7839 * the column type, because build_column_default itself will try to
7840 * coerce, and will not issue the error message we want if it fails.)
7842 * We remove any implicit coercion steps at the top level of the old
7843 * default expression; this has been agreed to satisfy the principle of
7844 * least surprise. (The conversion to the new column type should act like
7845 * it started from what the user sees as the stored expression, and the
7846 * implicit coercions aren't going to be shown.)
7848 if (attTup->atthasdef)
7850 defaultexpr = build_column_default(rel, attnum);
7851 Assert(defaultexpr);
7852 defaultexpr = strip_implicit_coercions(defaultexpr);
7853 defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
7854 defaultexpr, exprType(defaultexpr),
7855 targettype, targettypmod,
7856 COERCION_ASSIGNMENT,
7857 COERCE_IMPLICIT_CAST,
7859 if (defaultexpr == NULL)
7861 (errcode(ERRCODE_DATATYPE_MISMATCH),
7862 errmsg("default for column \"%s\" cannot be cast automatically to type %s",
7863 colName, format_type_be(targettype))));
7869 * Find everything that depends on the column (constraints, indexes, etc),
7870 * and record enough information to let us recreate the objects.
7872 * The actual recreation does not happen here, but only after we have
7873 * performed all the individual ALTER TYPE operations. We have to save
7874 * the info before executing ALTER TYPE, though, else the deparser will
7877 * There could be multiple entries for the same object, so we must check
7878 * to ensure we process each one only once. Note: we assume that an index
7879 * that implements a constraint will not show a direct dependency on the
7882 depRel = heap_open(DependRelationId, RowExclusiveLock);
7884 ScanKeyInit(&key[0],
7885 Anum_pg_depend_refclassid,
7886 BTEqualStrategyNumber, F_OIDEQ,
7887 ObjectIdGetDatum(RelationRelationId));
7888 ScanKeyInit(&key[1],
7889 Anum_pg_depend_refobjid,
7890 BTEqualStrategyNumber, F_OIDEQ,
7891 ObjectIdGetDatum(RelationGetRelid(rel)));
7892 ScanKeyInit(&key[2],
7893 Anum_pg_depend_refobjsubid,
7894 BTEqualStrategyNumber, F_INT4EQ,
7895 Int32GetDatum((int32) attnum));
7897 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
7900 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
7902 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
7903 ObjectAddress foundObject;
7905 /* We don't expect any PIN dependencies on columns */
7906 if (foundDep->deptype == DEPENDENCY_PIN)
7907 elog(ERROR, "cannot alter type of a pinned column");
7909 foundObject.classId = foundDep->classid;
7910 foundObject.objectId = foundDep->objid;
7911 foundObject.objectSubId = foundDep->objsubid;
7913 switch (getObjectClass(&foundObject))
7917 char relKind = get_rel_relkind(foundObject.objectId);
7919 if (relKind == RELKIND_INDEX)
7921 Assert(foundObject.objectSubId == 0);
7922 if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
7924 tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
7925 foundObject.objectId);
7926 tab->changedIndexDefs = lappend(tab->changedIndexDefs,
7927 pg_get_indexdef_string(foundObject.objectId));
7930 else if (relKind == RELKIND_SEQUENCE)
7933 * This must be a SERIAL column's sequence. We need
7934 * not do anything to it.
7936 Assert(foundObject.objectSubId == 0);
7940 /* Not expecting any other direct dependencies... */
7941 elog(ERROR, "unexpected object depending on column: %s",
7942 getObjectDescription(&foundObject));
7947 case OCLASS_CONSTRAINT:
7948 Assert(foundObject.objectSubId == 0);
7949 if (!list_member_oid(tab->changedConstraintOids,
7950 foundObject.objectId))
7952 char *defstring = pg_get_constraintdef_string(foundObject.objectId);
7955 * Put NORMAL dependencies at the front of the list and
7956 * AUTO dependencies at the back. This makes sure that
7957 * foreign-key constraints depending on this column will
7958 * be dropped before unique or primary-key constraints of
7959 * the column; which we must have because the FK
7960 * constraints depend on the indexes belonging to the
7961 * unique constraints.
7963 if (foundDep->deptype == DEPENDENCY_NORMAL)
7965 tab->changedConstraintOids =
7966 lcons_oid(foundObject.objectId,
7967 tab->changedConstraintOids);
7968 tab->changedConstraintDefs =
7970 tab->changedConstraintDefs);
7974 tab->changedConstraintOids =
7975 lappend_oid(tab->changedConstraintOids,
7976 foundObject.objectId);
7977 tab->changedConstraintDefs =
7978 lappend(tab->changedConstraintDefs,
7984 case OCLASS_REWRITE:
7985 /* XXX someday see if we can cope with revising views */
7987 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7988 errmsg("cannot alter type of a column used by a view or rule"),
7989 errdetail("%s depends on column \"%s\"",
7990 getObjectDescription(&foundObject),
7994 case OCLASS_TRIGGER:
7997 * A trigger can depend on a column because the column is
7998 * specified as an update target, or because the column is
7999 * used in the trigger's WHEN condition. The first case would
8000 * not require any extra work, but the second case would
8001 * require updating the WHEN expression, which will take a
8002 * significant amount of new code. Since we can't easily tell
8003 * which case applies, we punt for both. FIXME someday.
8006 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8007 errmsg("cannot alter type of a column used in a trigger definition"),
8008 errdetail("%s depends on column \"%s\"",
8009 getObjectDescription(&foundObject),
8016 * A policy can depend on a column because the column is
8017 * specified in the policy's USING or WITH CHECK qual
8018 * expressions. It might be possible to rewrite and recheck
8019 * the policy expression, but punt for now. It's certainly
8020 * easy enough to remove and recreate the policy; still,
8024 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8025 errmsg("cannot alter type of a column used in a policy definition"),
8026 errdetail("%s depends on column \"%s\"",
8027 getObjectDescription(&foundObject),
8031 case OCLASS_DEFAULT:
8034 * Ignore the column's default expression, since we will fix
8037 Assert(defaultexpr);
8043 case OCLASS_COLLATION:
8044 case OCLASS_CONVERSION:
8045 case OCLASS_LANGUAGE:
8046 case OCLASS_LARGEOBJECT:
8047 case OCLASS_OPERATOR:
8048 case OCLASS_OPCLASS:
8049 case OCLASS_OPFAMILY:
8053 case OCLASS_TSPARSER:
8055 case OCLASS_TSTEMPLATE:
8056 case OCLASS_TSCONFIG:
8058 case OCLASS_DATABASE:
8059 case OCLASS_TBLSPACE:
8061 case OCLASS_FOREIGN_SERVER:
8062 case OCLASS_USER_MAPPING:
8064 case OCLASS_EXTENSION:
8067 * We don't expect any of these sorts of objects to depend on
8070 elog(ERROR, "unexpected object depending on column: %s",
8071 getObjectDescription(&foundObject));
8075 elog(ERROR, "unrecognized object class: %u",
8076 foundObject.classId);
8080 systable_endscan(scan);
8083 * Now scan for dependencies of this column on other things. The only
8084 * thing we should find is the dependency on the column datatype, which we
8085 * want to remove, and possibly a collation dependency.
8087 ScanKeyInit(&key[0],
8088 Anum_pg_depend_classid,
8089 BTEqualStrategyNumber, F_OIDEQ,
8090 ObjectIdGetDatum(RelationRelationId));
8091 ScanKeyInit(&key[1],
8092 Anum_pg_depend_objid,
8093 BTEqualStrategyNumber, F_OIDEQ,
8094 ObjectIdGetDatum(RelationGetRelid(rel)));
8095 ScanKeyInit(&key[2],
8096 Anum_pg_depend_objsubid,
8097 BTEqualStrategyNumber, F_INT4EQ,
8098 Int32GetDatum((int32) attnum));
8100 scan = systable_beginscan(depRel, DependDependerIndexId, true,
8103 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
8105 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
8107 if (foundDep->deptype != DEPENDENCY_NORMAL)
8108 elog(ERROR, "found unexpected dependency type '%c'",
8110 if (!(foundDep->refclassid == TypeRelationId &&
8111 foundDep->refobjid == attTup->atttypid) &&
8112 !(foundDep->refclassid == CollationRelationId &&
8113 foundDep->refobjid == attTup->attcollation))
8114 elog(ERROR, "found unexpected dependency for column");
8116 simple_heap_delete(depRel, &depTup->t_self);
8119 systable_endscan(scan);
8121 heap_close(depRel, RowExclusiveLock);
8124 * Here we go --- change the recorded column type and collation. (Note
8125 * heapTup is a copy of the syscache entry, so okay to scribble on.)
8127 attTup->atttypid = targettype;
8128 attTup->atttypmod = targettypmod;
8129 attTup->attcollation = targetcollid;
8130 attTup->attndims = list_length(typeName->arrayBounds);
8131 attTup->attlen = tform->typlen;
8132 attTup->attbyval = tform->typbyval;
8133 attTup->attalign = tform->typalign;
8134 attTup->attstorage = tform->typstorage;
8136 ReleaseSysCache(typeTuple);
8138 simple_heap_update(attrelation, &heapTup->t_self, heapTup);
8140 /* keep system catalog indexes current */
8141 CatalogUpdateIndexes(attrelation, heapTup);
8143 heap_close(attrelation, RowExclusiveLock);
8145 /* Install dependencies on new datatype and collation */
8146 add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
8147 add_column_collation_dependency(RelationGetRelid(rel), attnum, targetcollid);
8150 * Drop any pg_statistic entry for the column, since it's now wrong type
8152 RemoveStatistics(RelationGetRelid(rel), attnum);
8154 InvokeObjectPostAlterHook(RelationRelationId,
8155 RelationGetRelid(rel), attnum);
8158 * Update the default, if present, by brute force --- remove and re-add
8159 * the default. Probably unsafe to take shortcuts, since the new version
8160 * may well have additional dependencies. (It's okay to do this now,
8161 * rather than after other ALTER TYPE commands, since the default won't
8162 * depend on other column types.)
8166 /* Must make new row visible since it will be updated again */
8167 CommandCounterIncrement();
8170 * We use RESTRICT here for safety, but at present we do not expect
8171 * anything to depend on the default.
8173 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true,
8176 StoreAttrDefault(rel, attnum, defaultexpr, true);
8180 heap_freetuple(heapTup);
8184 ATExecAlterColumnGenericOptions(Relation rel,
8185 const char *colName,
8191 ForeignServer *server;
8192 ForeignDataWrapper *fdw;
8196 Datum repl_val[Natts_pg_attribute];
8197 bool repl_null[Natts_pg_attribute];
8198 bool repl_repl[Natts_pg_attribute];
8200 Form_pg_foreign_table fttableform;
8201 Form_pg_attribute atttableform;
8206 /* First, determine FDW validator associated to the foreign table. */
8207 ftrel = heap_open(ForeignTableRelationId, AccessShareLock);
8208 tuple = SearchSysCache1(FOREIGNTABLEREL, rel->rd_id);
8209 if (!HeapTupleIsValid(tuple))
8211 (errcode(ERRCODE_UNDEFINED_OBJECT),
8212 errmsg("foreign table \"%s\" does not exist",
8213 RelationGetRelationName(rel))));
8214 fttableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
8215 server = GetForeignServer(fttableform->ftserver);
8216 fdw = GetForeignDataWrapper(server->fdwid);
8218 heap_close(ftrel, AccessShareLock);
8219 ReleaseSysCache(tuple);
8221 attrel = heap_open(AttributeRelationId, RowExclusiveLock);
8222 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
8223 if (!HeapTupleIsValid(tuple))
8225 (errcode(ERRCODE_UNDEFINED_COLUMN),
8226 errmsg("column \"%s\" of relation \"%s\" does not exist",
8227 colName, RelationGetRelationName(rel))));
8229 /* Prevent them from altering a system attribute */
8230 atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
8231 if (atttableform->attnum <= 0)
8233 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8234 errmsg("cannot alter system column \"%s\"", colName)));
8237 /* Initialize buffers for new tuple values */
8238 memset(repl_val, 0, sizeof(repl_val));
8239 memset(repl_null, false, sizeof(repl_null));
8240 memset(repl_repl, false, sizeof(repl_repl));
8242 /* Extract the current options */
8243 datum = SysCacheGetAttr(ATTNAME,
8245 Anum_pg_attribute_attfdwoptions,
8248 datum = PointerGetDatum(NULL);
8250 /* Transform the options */
8251 datum = transformGenericOptions(AttributeRelationId,
8256 if (PointerIsValid(DatumGetPointer(datum)))
8257 repl_val[Anum_pg_attribute_attfdwoptions - 1] = datum;
8259 repl_null[Anum_pg_attribute_attfdwoptions - 1] = true;
8261 repl_repl[Anum_pg_attribute_attfdwoptions - 1] = true;
8263 /* Everything looks good - update the tuple */
8265 newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrel),
8266 repl_val, repl_null, repl_repl);
8268 simple_heap_update(attrel, &newtuple->t_self, newtuple);
8269 CatalogUpdateIndexes(attrel, newtuple);
8271 InvokeObjectPostAlterHook(RelationRelationId,
8272 RelationGetRelid(rel),
8273 atttableform->attnum);
8275 ReleaseSysCache(tuple);
8277 heap_close(attrel, RowExclusiveLock);
8279 heap_freetuple(newtuple);
8283 * Cleanup after we've finished all the ALTER TYPE operations for a
8284 * particular relation. We have to drop and recreate all the indexes
8285 * and constraints that depend on the altered columns.
8288 ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)
8295 * Re-parse the index and constraint definitions, and attach them to the
8296 * appropriate work queue entries. We do this before dropping because in
8297 * the case of a FOREIGN KEY constraint, we might not yet have exclusive
8298 * lock on the table the constraint is attached to, and we need to get
8299 * that before dropping. It's safe because the parser won't actually look
8300 * at the catalogs to detect the existing entry.
8302 * We can't rely on the output of deparsing to tell us which relation to
8303 * operate on, because concurrent activity might have made the name
8304 * resolve differently. Instead, we've got to use the OID of the
8305 * constraint or index we're processing to figure out which relation to
8308 forboth(oid_item, tab->changedConstraintOids,
8309 def_item, tab->changedConstraintDefs)
8311 Oid oldId = lfirst_oid(oid_item);
8315 get_constraint_relation_oids(oldId, &relid, &confrelid);
8316 ATPostAlterTypeParse(oldId, relid, confrelid,
8317 (char *) lfirst(def_item),
8318 wqueue, lockmode, tab->rewrite);
8320 forboth(oid_item, tab->changedIndexOids,
8321 def_item, tab->changedIndexDefs)
8323 Oid oldId = lfirst_oid(oid_item);
8326 relid = IndexGetRelation(oldId, false);
8327 ATPostAlterTypeParse(oldId, relid, InvalidOid,
8328 (char *) lfirst(def_item),
8329 wqueue, lockmode, tab->rewrite);
8333 * Now we can drop the existing constraints and indexes --- constraints
8334 * first, since some of them might depend on the indexes. In fact, we
8335 * have to delete FOREIGN KEY constraints before UNIQUE constraints, but
8336 * we already ordered the constraint list to ensure that would happen. It
8337 * should be okay to use DROP_RESTRICT here, since nothing else should be
8338 * depending on these objects.
8340 foreach(oid_item, tab->changedConstraintOids)
8342 obj.classId = ConstraintRelationId;
8343 obj.objectId = lfirst_oid(oid_item);
8344 obj.objectSubId = 0;
8345 performDeletion(&obj, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
8348 foreach(oid_item, tab->changedIndexOids)
8350 obj.classId = RelationRelationId;
8351 obj.objectId = lfirst_oid(oid_item);
8352 obj.objectSubId = 0;
8353 performDeletion(&obj, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
8357 * The objects will get recreated during subsequent passes over the work
8363 ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
8364 List **wqueue, LOCKMODE lockmode, bool rewrite)
8366 List *raw_parsetree_list;
8367 List *querytree_list;
8368 ListCell *list_item;
8372 * We expect that we will get only ALTER TABLE and CREATE INDEX
8373 * statements. Hence, there is no need to pass them through
8374 * parse_analyze() or the rewriter, but instead we need to pass them
8375 * through parse_utilcmd.c to make them ready for execution.
8377 raw_parsetree_list = raw_parser(cmd);
8378 querytree_list = NIL;
8379 foreach(list_item, raw_parsetree_list)
8381 Node *stmt = (Node *) lfirst(list_item);
8383 if (IsA(stmt, IndexStmt))
8384 querytree_list = lappend(querytree_list,
8385 transformIndexStmt(oldRelId,
8388 else if (IsA(stmt, AlterTableStmt))
8389 querytree_list = list_concat(querytree_list,
8390 transformAlterTableStmt(oldRelId,
8391 (AlterTableStmt *) stmt,
8394 querytree_list = lappend(querytree_list, stmt);
8397 /* Caller should already have acquired whatever lock we need. */
8398 rel = relation_open(oldRelId, NoLock);
8401 * Attach each generated command to the proper place in the work queue.
8402 * Note this could result in creation of entirely new work-queue entries.
8404 * Also note that we have to tweak the command subtypes, because it turns
8405 * out that re-creation of indexes and constraints has to act a bit
8406 * differently from initial creation.
8408 foreach(list_item, querytree_list)
8410 Node *stm = (Node *) lfirst(list_item);
8411 AlteredTableInfo *tab;
8413 switch (nodeTag(stm))
8417 IndexStmt *stmt = (IndexStmt *) stm;
8418 AlterTableCmd *newcmd;
8421 TryReuseIndex(oldId, stmt);
8423 tab = ATGetQueueEntry(wqueue, rel);
8424 newcmd = makeNode(AlterTableCmd);
8425 newcmd->subtype = AT_ReAddIndex;
8426 newcmd->def = (Node *) stmt;
8427 tab->subcmds[AT_PASS_OLD_INDEX] =
8428 lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
8431 case T_AlterTableStmt:
8433 AlterTableStmt *stmt = (AlterTableStmt *) stm;
8436 tab = ATGetQueueEntry(wqueue, rel);
8437 foreach(lcmd, stmt->cmds)
8439 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
8442 switch (cmd->subtype)
8445 Assert(IsA(cmd->def, IndexStmt));
8447 TryReuseIndex(get_constraint_index(oldId),
8448 (IndexStmt *) cmd->def);
8449 cmd->subtype = AT_ReAddIndex;
8450 tab->subcmds[AT_PASS_OLD_INDEX] =
8451 lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
8453 case AT_AddConstraint:
8454 Assert(IsA(cmd->def, Constraint));
8455 con = (Constraint *) cmd->def;
8456 con->old_pktable_oid = refRelId;
8457 /* rewriting neither side of a FK */
8458 if (con->contype == CONSTR_FOREIGN &&
8459 !rewrite && tab->rewrite == 0)
8460 TryReuseForeignKey(oldId, con);
8461 cmd->subtype = AT_ReAddConstraint;
8462 tab->subcmds[AT_PASS_OLD_CONSTR] =
8463 lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
8466 elog(ERROR, "unexpected statement type: %d",
8467 (int) cmd->subtype);
8473 elog(ERROR, "unexpected statement type: %d",
8474 (int) nodeTag(stm));
8478 relation_close(rel, NoLock);
8482 * Subroutine for ATPostAlterTypeParse(). Calls out to CheckIndexCompatible()
8483 * for the real analysis, then mutates the IndexStmt based on that verdict.
8486 TryReuseIndex(Oid oldId, IndexStmt *stmt)
8488 if (CheckIndexCompatible(oldId,
8491 stmt->excludeOpNames))
8493 Relation irel = index_open(oldId, NoLock);
8495 stmt->oldNode = irel->rd_node.relNode;
8496 index_close(irel, NoLock);
8501 * Subroutine for ATPostAlterTypeParse().
8503 * Stash the old P-F equality operator into the Constraint node, for possible
8504 * use by ATAddForeignKeyConstraint() in determining whether revalidation of
8505 * this constraint can be skipped.
8508 TryReuseForeignKey(Oid oldId, Constraint *con)
8518 Assert(con->contype == CONSTR_FOREIGN);
8519 Assert(con->old_conpfeqop == NIL); /* already prepared this node */
8521 tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(oldId));
8522 if (!HeapTupleIsValid(tup)) /* should not happen */
8523 elog(ERROR, "cache lookup failed for constraint %u", oldId);
8525 adatum = SysCacheGetAttr(CONSTROID, tup,
8526 Anum_pg_constraint_conpfeqop, &isNull);
8528 elog(ERROR, "null conpfeqop for constraint %u", oldId);
8529 arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
8530 numkeys = ARR_DIMS(arr)[0];
8531 /* test follows the one in ri_FetchConstraintInfo() */
8532 if (ARR_NDIM(arr) != 1 ||
8534 ARR_ELEMTYPE(arr) != OIDOID)
8535 elog(ERROR, "conpfeqop is not a 1-D Oid array");
8536 rawarr = (Oid *) ARR_DATA_PTR(arr);
8538 /* stash a List of the operator Oids in our Constraint node */
8539 for (i = 0; i < numkeys; i++)
8540 con->old_conpfeqop = lcons_oid(rawarr[i], con->old_conpfeqop);
8542 ReleaseSysCache(tup);
8548 * recursing is true if we are recursing from a table to its indexes,
8549 * sequences, or toast table. We don't allow the ownership of those things to
8550 * be changed separately from the parent table. Also, we can skip permission
8551 * checks (this is necessary not just an optimization, else we'd fail to
8552 * handle toast tables properly).
8554 * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
8555 * free-standing composite type.
8558 ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
8560 Relation target_rel;
8563 Form_pg_class tuple_class;
8566 * Get exclusive lock till end of transaction on the target table. Use
8567 * relation_open so that we can work on indexes and sequences.
8569 target_rel = relation_open(relationOid, lockmode);
8571 /* Get its pg_class tuple, too */
8572 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
8574 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
8575 if (!HeapTupleIsValid(tuple))
8576 elog(ERROR, "cache lookup failed for relation %u", relationOid);
8577 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
8579 /* Can we change the ownership of this tuple? */
8580 switch (tuple_class->relkind)
8582 case RELKIND_RELATION:
8584 case RELKIND_MATVIEW:
8585 case RELKIND_FOREIGN_TABLE:
8586 /* ok to change owner */
8592 * Because ALTER INDEX OWNER used to be allowed, and in fact
8593 * is generated by old versions of pg_dump, we give a warning
8594 * and do nothing rather than erroring out. Also, to avoid
8595 * unnecessary chatter while restoring those old dumps, say
8596 * nothing at all if the command would be a no-op anyway.
8598 if (tuple_class->relowner != newOwnerId)
8600 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8601 errmsg("cannot change owner of index \"%s\"",
8602 NameStr(tuple_class->relname)),
8603 errhint("Change the ownership of the index's table, instead.")));
8604 /* quick hack to exit via the no-op path */
8605 newOwnerId = tuple_class->relowner;
8608 case RELKIND_SEQUENCE:
8610 tuple_class->relowner != newOwnerId)
8612 /* if it's an owned sequence, disallow changing it by itself */
8616 if (sequenceIsOwned(relationOid, &tableId, &colId))
8618 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8619 errmsg("cannot change owner of sequence \"%s\"",
8620 NameStr(tuple_class->relname)),
8621 errdetail("Sequence \"%s\" is linked to table \"%s\".",
8622 NameStr(tuple_class->relname),
8623 get_rel_name(tableId))));
8626 case RELKIND_COMPOSITE_TYPE:
8630 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8631 errmsg("\"%s\" is a composite type",
8632 NameStr(tuple_class->relname)),
8633 errhint("Use ALTER TYPE instead.")));
8635 case RELKIND_TOASTVALUE:
8641 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8642 errmsg("\"%s\" is not a table, view, sequence, or foreign table",
8643 NameStr(tuple_class->relname))));
8647 * If the new owner is the same as the existing owner, consider the
8648 * command to have succeeded. This is for dump restoration purposes.
8650 if (tuple_class->relowner != newOwnerId)
8652 Datum repl_val[Natts_pg_class];
8653 bool repl_null[Natts_pg_class];
8654 bool repl_repl[Natts_pg_class];
8660 /* skip permission checks when recursing to index or toast table */
8663 /* Superusers can always do it */
8666 Oid namespaceOid = tuple_class->relnamespace;
8667 AclResult aclresult;
8669 /* Otherwise, must be owner of the existing object */
8670 if (!pg_class_ownercheck(relationOid, GetUserId()))
8671 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
8672 RelationGetRelationName(target_rel));
8674 /* Must be able to become new owner */
8675 check_is_member_of_role(GetUserId(), newOwnerId);
8677 /* New owner must have CREATE privilege on namespace */
8678 aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
8680 if (aclresult != ACLCHECK_OK)
8681 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
8682 get_namespace_name(namespaceOid));
8686 memset(repl_null, false, sizeof(repl_null));
8687 memset(repl_repl, false, sizeof(repl_repl));
8689 repl_repl[Anum_pg_class_relowner - 1] = true;
8690 repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
8693 * Determine the modified ACL for the new owner. This is only
8694 * necessary when the ACL is non-null.
8696 aclDatum = SysCacheGetAttr(RELOID, tuple,
8697 Anum_pg_class_relacl,
8701 newAcl = aclnewowner(DatumGetAclP(aclDatum),
8702 tuple_class->relowner, newOwnerId);
8703 repl_repl[Anum_pg_class_relacl - 1] = true;
8704 repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
8707 newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
8709 simple_heap_update(class_rel, &newtuple->t_self, newtuple);
8710 CatalogUpdateIndexes(class_rel, newtuple);
8712 heap_freetuple(newtuple);
8715 * We must similarly update any per-column ACLs to reflect the new
8716 * owner; for neatness reasons that's split out as a subroutine.
8718 change_owner_fix_column_acls(relationOid,
8719 tuple_class->relowner,
8723 * Update owner dependency reference, if any. A composite type has
8724 * none, because it's tracked for the pg_type entry instead of here;
8725 * indexes and TOAST tables don't have their own entries either.
8727 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
8728 tuple_class->relkind != RELKIND_INDEX &&
8729 tuple_class->relkind != RELKIND_TOASTVALUE)
8730 changeDependencyOnOwner(RelationRelationId, relationOid,
8734 * Also change the ownership of the table's row type, if it has one
8736 if (tuple_class->relkind != RELKIND_INDEX)
8737 AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId,
8738 tuple_class->relkind == RELKIND_COMPOSITE_TYPE);
8741 * If we are operating on a table or materialized view, also change
8742 * the ownership of any indexes and sequences that belong to the
8743 * relation, as well as its toast table (if it has one).
8745 if (tuple_class->relkind == RELKIND_RELATION ||
8746 tuple_class->relkind == RELKIND_MATVIEW ||
8747 tuple_class->relkind == RELKIND_TOASTVALUE)
8749 List *index_oid_list;
8752 /* Find all the indexes belonging to this relation */
8753 index_oid_list = RelationGetIndexList(target_rel);
8755 /* For each index, recursively change its ownership */
8756 foreach(i, index_oid_list)
8757 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
8759 list_free(index_oid_list);
8762 if (tuple_class->relkind == RELKIND_RELATION ||
8763 tuple_class->relkind == RELKIND_MATVIEW)
8765 /* If it has a toast table, recurse to change its ownership */
8766 if (tuple_class->reltoastrelid != InvalidOid)
8767 ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
8770 /* If it has dependent sequences, recurse to change them too */
8771 change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
8775 InvokeObjectPostAlterHook(RelationRelationId, relationOid, 0);
8777 ReleaseSysCache(tuple);
8778 heap_close(class_rel, RowExclusiveLock);
8779 relation_close(target_rel, NoLock);
8783 * change_owner_fix_column_acls
8785 * Helper function for ATExecChangeOwner. Scan the columns of the table
8786 * and fix any non-null column ACLs to reflect the new owner.
8789 change_owner_fix_column_acls(Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
8791 Relation attRelation;
8794 HeapTuple attributeTuple;
8796 attRelation = heap_open(AttributeRelationId, RowExclusiveLock);
8797 ScanKeyInit(&key[0],
8798 Anum_pg_attribute_attrelid,
8799 BTEqualStrategyNumber, F_OIDEQ,
8800 ObjectIdGetDatum(relationOid));
8801 scan = systable_beginscan(attRelation, AttributeRelidNumIndexId,
8802 true, NULL, 1, key);
8803 while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
8805 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
8806 Datum repl_val[Natts_pg_attribute];
8807 bool repl_null[Natts_pg_attribute];
8808 bool repl_repl[Natts_pg_attribute];
8814 /* Ignore dropped columns */
8815 if (att->attisdropped)
8818 aclDatum = heap_getattr(attributeTuple,
8819 Anum_pg_attribute_attacl,
8820 RelationGetDescr(attRelation),
8822 /* Null ACLs do not require changes */
8826 memset(repl_null, false, sizeof(repl_null));
8827 memset(repl_repl, false, sizeof(repl_repl));
8829 newAcl = aclnewowner(DatumGetAclP(aclDatum),
8830 oldOwnerId, newOwnerId);
8831 repl_repl[Anum_pg_attribute_attacl - 1] = true;
8832 repl_val[Anum_pg_attribute_attacl - 1] = PointerGetDatum(newAcl);
8834 newtuple = heap_modify_tuple(attributeTuple,
8835 RelationGetDescr(attRelation),
8836 repl_val, repl_null, repl_repl);
8838 simple_heap_update(attRelation, &newtuple->t_self, newtuple);
8839 CatalogUpdateIndexes(attRelation, newtuple);
8841 heap_freetuple(newtuple);
8843 systable_endscan(scan);
8844 heap_close(attRelation, RowExclusiveLock);
8848 * change_owner_recurse_to_sequences
8850 * Helper function for ATExecChangeOwner. Examines pg_depend searching
8851 * for sequences that are dependent on serial columns, and changes their
8855 change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
8863 * SERIAL sequences are those having an auto dependency on one of the
8864 * table's columns (we don't care *which* column, exactly).
8866 depRel = heap_open(DependRelationId, AccessShareLock);
8868 ScanKeyInit(&key[0],
8869 Anum_pg_depend_refclassid,
8870 BTEqualStrategyNumber, F_OIDEQ,
8871 ObjectIdGetDatum(RelationRelationId));
8872 ScanKeyInit(&key[1],
8873 Anum_pg_depend_refobjid,
8874 BTEqualStrategyNumber, F_OIDEQ,
8875 ObjectIdGetDatum(relationOid));
8876 /* we leave refobjsubid unspecified */
8878 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
8881 while (HeapTupleIsValid(tup = systable_getnext(scan)))
8883 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
8886 /* skip dependencies other than auto dependencies on columns */
8887 if (depForm->refobjsubid == 0 ||
8888 depForm->classid != RelationRelationId ||
8889 depForm->objsubid != 0 ||
8890 depForm->deptype != DEPENDENCY_AUTO)
8893 /* Use relation_open just in case it's an index */
8894 seqRel = relation_open(depForm->objid, lockmode);
8896 /* skip non-sequence relations */
8897 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
8899 /* No need to keep the lock */
8900 relation_close(seqRel, lockmode);
8904 /* We don't need to close the sequence while we alter it. */
8905 ATExecChangeOwner(depForm->objid, newOwnerId, true, lockmode);
8907 /* Now we can close it. Keep the lock till end of transaction. */
8908 relation_close(seqRel, NoLock);
8911 systable_endscan(scan);
8913 relation_close(depRel, AccessShareLock);
8917 * ALTER TABLE CLUSTER ON
8919 * The only thing we have to do is to change the indisclustered bits.
8922 ATExecClusterOn(Relation rel, const char *indexName, LOCKMODE lockmode)
8926 indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
8928 if (!OidIsValid(indexOid))
8930 (errcode(ERRCODE_UNDEFINED_OBJECT),
8931 errmsg("index \"%s\" for table \"%s\" does not exist",
8932 indexName, RelationGetRelationName(rel))));
8934 /* Check index is valid to cluster on */
8935 check_index_is_clusterable(rel, indexOid, false, lockmode);
8937 /* And do the work */
8938 mark_index_clustered(rel, indexOid, false);
8942 * ALTER TABLE SET WITHOUT CLUSTER
8944 * We have to find any indexes on the table that have indisclustered bit
8945 * set and turn it off.
8948 ATExecDropCluster(Relation rel, LOCKMODE lockmode)
8950 mark_index_clustered(rel, InvalidOid, false);
8954 * ALTER TABLE SET TABLESPACE
8957 ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, char *tablespacename, LOCKMODE lockmode)
8961 /* Check that the tablespace exists */
8962 tablespaceId = get_tablespace_oid(tablespacename, false);
8964 /* Check permissions except when moving to database's default */
8965 if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
8967 AclResult aclresult;
8969 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(), ACL_CREATE);
8970 if (aclresult != ACLCHECK_OK)
8971 aclcheck_error(aclresult, ACL_KIND_TABLESPACE, tablespacename);
8974 /* Save info for Phase 3 to do the real work */
8975 if (OidIsValid(tab->newTableSpace))
8977 (errcode(ERRCODE_SYNTAX_ERROR),
8978 errmsg("cannot have multiple SET TABLESPACE subcommands")));
8980 tab->newTableSpace = tablespaceId;
8984 * Set, reset, or replace reloptions.
8987 ATExecSetRelOptions(Relation rel, List *defList, AlterTableType operation,
8997 Datum repl_val[Natts_pg_class];
8998 bool repl_null[Natts_pg_class];
8999 bool repl_repl[Natts_pg_class];
9000 static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
9002 if (defList == NIL && operation != AT_ReplaceRelOptions)
9003 return; /* nothing to do */
9005 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
9007 /* Fetch heap tuple */
9008 relid = RelationGetRelid(rel);
9009 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
9010 if (!HeapTupleIsValid(tuple))
9011 elog(ERROR, "cache lookup failed for relation %u", relid);
9013 if (operation == AT_ReplaceRelOptions)
9016 * If we're supposed to replace the reloptions list, we just pretend
9017 * there were none before.
9024 /* Get the old reloptions */
9025 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
9029 /* Generate new proposed reloptions (text array) */
9030 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
9031 defList, NULL, validnsps, false,
9032 operation == AT_ResetRelOptions);
9035 switch (rel->rd_rel->relkind)
9037 case RELKIND_RELATION:
9038 case RELKIND_TOASTVALUE:
9039 case RELKIND_MATVIEW:
9040 (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
9043 (void) view_reloptions(newOptions, true);
9046 (void) index_reloptions(rel->rd_am->amoptions, newOptions, true);
9050 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9051 errmsg("\"%s\" is not a table, view, materialized view, index, or TOAST table",
9052 RelationGetRelationName(rel))));
9056 /* Special-case validation of view options */
9057 if (rel->rd_rel->relkind == RELKIND_VIEW)
9059 Query *view_query = get_view_query(rel);
9060 List *view_options = untransformRelOptions(newOptions);
9062 bool check_option = false;
9064 foreach(cell, view_options)
9066 DefElem *defel = (DefElem *) lfirst(cell);
9068 if (pg_strcasecmp(defel->defname, "check_option") == 0)
9069 check_option = true;
9073 * If the check option is specified, look to see if the view is
9074 * actually auto-updatable or not.
9078 const char *view_updatable_error =
9079 view_query_is_auto_updatable(view_query, true);
9081 if (view_updatable_error)
9083 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9084 errmsg("WITH CHECK OPTION is supported only on automatically updatable views"),
9085 errhint("%s", view_updatable_error)));
9090 * All we need do here is update the pg_class row; the new options will be
9091 * propagated into relcaches during post-commit cache inval.
9093 memset(repl_val, 0, sizeof(repl_val));
9094 memset(repl_null, false, sizeof(repl_null));
9095 memset(repl_repl, false, sizeof(repl_repl));
9097 if (newOptions != (Datum) 0)
9098 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
9100 repl_null[Anum_pg_class_reloptions - 1] = true;
9102 repl_repl[Anum_pg_class_reloptions - 1] = true;
9104 newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
9105 repl_val, repl_null, repl_repl);
9107 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
9109 CatalogUpdateIndexes(pgclass, newtuple);
9111 InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
9113 heap_freetuple(newtuple);
9115 ReleaseSysCache(tuple);
9117 /* repeat the whole exercise for the toast table, if there's one */
9118 if (OidIsValid(rel->rd_rel->reltoastrelid))
9121 Oid toastid = rel->rd_rel->reltoastrelid;
9123 toastrel = heap_open(toastid, lockmode);
9125 /* Fetch heap tuple */
9126 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(toastid));
9127 if (!HeapTupleIsValid(tuple))
9128 elog(ERROR, "cache lookup failed for relation %u", toastid);
9130 if (operation == AT_ReplaceRelOptions)
9133 * If we're supposed to replace the reloptions list, we just
9134 * pretend there were none before.
9141 /* Get the old reloptions */
9142 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
9146 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
9147 defList, "toast", validnsps, false,
9148 operation == AT_ResetRelOptions);
9150 (void) heap_reloptions(RELKIND_TOASTVALUE, newOptions, true);
9152 memset(repl_val, 0, sizeof(repl_val));
9153 memset(repl_null, false, sizeof(repl_null));
9154 memset(repl_repl, false, sizeof(repl_repl));
9156 if (newOptions != (Datum) 0)
9157 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
9159 repl_null[Anum_pg_class_reloptions - 1] = true;
9161 repl_repl[Anum_pg_class_reloptions - 1] = true;
9163 newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
9164 repl_val, repl_null, repl_repl);
9166 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
9168 CatalogUpdateIndexes(pgclass, newtuple);
9170 InvokeObjectPostAlterHookArg(RelationRelationId,
9171 RelationGetRelid(toastrel), 0,
9174 heap_freetuple(newtuple);
9176 ReleaseSysCache(tuple);
9178 heap_close(toastrel, NoLock);
9181 heap_close(pgclass, RowExclusiveLock);
9185 * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
9186 * rewriting to be done, so we just want to copy the data as fast as possible.
9189 ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode)
9195 RelFileNode newrnode;
9196 SMgrRelation dstrel;
9199 Form_pg_class rd_rel;
9201 List *reltoastidxids = NIL;
9205 * Need lock here in case we are recursing to toast table or index
9207 rel = relation_open(tableOid, lockmode);
9210 * No work if no change in tablespace.
9212 oldTableSpace = rel->rd_rel->reltablespace;
9213 if (newTableSpace == oldTableSpace ||
9214 (newTableSpace == MyDatabaseTableSpace && oldTableSpace == 0))
9216 InvokeObjectPostAlterHook(RelationRelationId,
9217 RelationGetRelid(rel), 0);
9219 relation_close(rel, NoLock);
9224 * We cannot support moving mapped relations into different tablespaces.
9225 * (In particular this eliminates all shared catalogs.)
9227 if (RelationIsMapped(rel))
9229 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9230 errmsg("cannot move system relation \"%s\"",
9231 RelationGetRelationName(rel))));
9233 /* Can't move a non-shared relation into pg_global */
9234 if (newTableSpace == GLOBALTABLESPACE_OID)
9236 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
9237 errmsg("only shared relations can be placed in pg_global tablespace")));
9240 * Don't allow moving temp tables of other backends ... their local buffer
9241 * manager is not going to cope.
9243 if (RELATION_IS_OTHER_TEMP(rel))
9245 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9246 errmsg("cannot move temporary tables of other sessions")));
9248 reltoastrelid = rel->rd_rel->reltoastrelid;
9249 /* Fetch the list of indexes on toast relation if necessary */
9250 if (OidIsValid(reltoastrelid))
9252 Relation toastRel = relation_open(reltoastrelid, lockmode);
9254 reltoastidxids = RelationGetIndexList(toastRel);
9255 relation_close(toastRel, lockmode);
9258 /* Get a modifiable copy of the relation's pg_class row */
9259 pg_class = heap_open(RelationRelationId, RowExclusiveLock);
9261 tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(tableOid));
9262 if (!HeapTupleIsValid(tuple))
9263 elog(ERROR, "cache lookup failed for relation %u", tableOid);
9264 rd_rel = (Form_pg_class) GETSTRUCT(tuple);
9267 * Since we copy the file directly without looking at the shared buffers,
9268 * we'd better first flush out any pages of the source relation that are
9269 * in shared buffers. We assume no new changes will be made while we are
9270 * holding exclusive lock on the rel.
9272 FlushRelationBuffers(rel);
9275 * Relfilenodes are not unique in databases across tablespaces, so we need
9276 * to allocate a new one in the new tablespace.
9278 newrelfilenode = GetNewRelFileNode(newTableSpace, NULL,
9279 rel->rd_rel->relpersistence);
9281 /* Open old and new relation */
9282 newrnode = rel->rd_node;
9283 newrnode.relNode = newrelfilenode;
9284 newrnode.spcNode = newTableSpace;
9285 dstrel = smgropen(newrnode, rel->rd_backend);
9287 RelationOpenSmgr(rel);
9290 * Create and copy all forks of the relation, and schedule unlinking of
9291 * old physical files.
9293 * NOTE: any conflict in relfilenode value will be caught in
9294 * RelationCreateStorage().
9296 RelationCreateStorage(newrnode, rel->rd_rel->relpersistence);
9298 /* copy main fork */
9299 copy_relation_data(rel->rd_smgr, dstrel, MAIN_FORKNUM,
9300 rel->rd_rel->relpersistence);
9302 /* copy those extra forks that exist */
9303 for (forkNum = MAIN_FORKNUM + 1; forkNum <= MAX_FORKNUM; forkNum++)
9305 if (smgrexists(rel->rd_smgr, forkNum))
9307 smgrcreate(dstrel, forkNum, false);
9308 copy_relation_data(rel->rd_smgr, dstrel, forkNum,
9309 rel->rd_rel->relpersistence);
9313 /* drop old relation, and close new one */
9314 RelationDropStorage(rel);
9317 /* update the pg_class row */
9318 rd_rel->reltablespace = (newTableSpace == MyDatabaseTableSpace) ? InvalidOid : newTableSpace;
9319 rd_rel->relfilenode = newrelfilenode;
9320 simple_heap_update(pg_class, &tuple->t_self, tuple);
9321 CatalogUpdateIndexes(pg_class, tuple);
9323 InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
9325 heap_freetuple(tuple);
9327 heap_close(pg_class, RowExclusiveLock);
9329 relation_close(rel, NoLock);
9331 /* Make sure the reltablespace change is visible */
9332 CommandCounterIncrement();
9334 /* Move associated toast relation and/or indexes, too */
9335 if (OidIsValid(reltoastrelid))
9336 ATExecSetTableSpace(reltoastrelid, newTableSpace, lockmode);
9337 foreach(lc, reltoastidxids)
9338 ATExecSetTableSpace(lfirst_oid(lc), newTableSpace, lockmode);
9341 list_free(reltoastidxids);
9345 * Alter Table ALL ... SET TABLESPACE
9347 * Allows a user to move all objects of some type in a given tablespace in the
9348 * current database to another tablespace. Objects can be chosen based on the
9349 * owner of the object also, to allow users to move only their objects.
9350 * The user must have CREATE rights on the new tablespace, as usual. The main
9351 * permissions handling is done by the lower-level table move function.
9353 * All to-be-moved objects are locked first. If NOWAIT is specified and the
9354 * lock can't be acquired then we ereport(ERROR).
9357 AlterTableMoveAll(AlterTableMoveAllStmt *stmt)
9359 List *relations = NIL;
9365 Oid orig_tablespaceoid;
9366 Oid new_tablespaceoid;
9367 List *role_oids = roleNamesToIds(stmt->roles);
9369 /* Ensure we were not asked to move something we can't */
9370 if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
9371 stmt->objtype != OBJECT_MATVIEW)
9373 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
9374 errmsg("only tables, indexes, and materialized views exist in tablespaces")));
9376 /* Get the orig and new tablespace OIDs */
9377 orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
9378 new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
9380 /* Can't move shared relations in to or out of pg_global */
9381 /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
9382 if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
9383 new_tablespaceoid == GLOBALTABLESPACE_OID)
9385 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
9386 errmsg("cannot move relations in to or out of pg_global tablespace")));
9389 * Must have CREATE rights on the new tablespace, unless it is the
9390 * database default tablespace (which all users implicitly have CREATE
9393 if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
9395 AclResult aclresult;
9397 aclresult = pg_tablespace_aclcheck(new_tablespaceoid, GetUserId(),
9399 if (aclresult != ACLCHECK_OK)
9400 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
9401 get_tablespace_name(new_tablespaceoid));
9405 * Now that the checks are done, check if we should set either to
9406 * InvalidOid because it is our database's default tablespace.
9408 if (orig_tablespaceoid == MyDatabaseTableSpace)
9409 orig_tablespaceoid = InvalidOid;
9411 if (new_tablespaceoid == MyDatabaseTableSpace)
9412 new_tablespaceoid = InvalidOid;
9415 if (orig_tablespaceoid == new_tablespaceoid)
9416 return new_tablespaceoid;
9419 * Walk the list of objects in the tablespace and move them. This will
9420 * only find objects in our database, of course.
9422 ScanKeyInit(&key[0],
9423 Anum_pg_class_reltablespace,
9424 BTEqualStrategyNumber, F_OIDEQ,
9425 ObjectIdGetDatum(orig_tablespaceoid));
9427 rel = heap_open(RelationRelationId, AccessShareLock);
9428 scan = heap_beginscan_catalog(rel, 1, key);
9429 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
9431 Oid relOid = HeapTupleGetOid(tuple);
9432 Form_pg_class relForm;
9434 relForm = (Form_pg_class) GETSTRUCT(tuple);
9437 * Do not move objects in pg_catalog as part of this, if an admin
9438 * really wishes to do so, they can issue the individual ALTER
9439 * commands directly.
9441 * Also, explicitly avoid any shared tables, temp tables, or TOAST
9442 * (TOAST will be moved with the main table).
9444 if (IsSystemNamespace(relForm->relnamespace) || relForm->relisshared ||
9445 isAnyTempNamespace(relForm->relnamespace) ||
9446 relForm->relnamespace == PG_TOAST_NAMESPACE)
9449 /* Only move the object type requested */
9450 if ((stmt->objtype == OBJECT_TABLE &&
9451 relForm->relkind != RELKIND_RELATION) ||
9452 (stmt->objtype == OBJECT_INDEX &&
9453 relForm->relkind != RELKIND_INDEX) ||
9454 (stmt->objtype == OBJECT_MATVIEW &&
9455 relForm->relkind != RELKIND_MATVIEW))
9458 /* Check if we are only moving objects owned by certain roles */
9459 if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
9463 * Handle permissions-checking here since we are locking the tables
9464 * and also to avoid doing a bunch of work only to fail part-way. Note
9465 * that permissions will also be checked by AlterTableInternal().
9467 * Caller must be considered an owner on the table to move it.
9469 if (!pg_class_ownercheck(relOid, GetUserId()))
9470 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
9471 NameStr(relForm->relname));
9474 !ConditionalLockRelationOid(relOid, AccessExclusiveLock))
9476 (errcode(ERRCODE_OBJECT_IN_USE),
9477 errmsg("aborting because lock on relation \"%s\".\"%s\" is not available",
9478 get_namespace_name(relForm->relnamespace),
9479 NameStr(relForm->relname))));
9481 LockRelationOid(relOid, AccessExclusiveLock);
9483 /* Add to our list of objects to move */
9484 relations = lappend_oid(relations, relOid);
9488 heap_close(rel, AccessShareLock);
9490 if (relations == NIL)
9492 (errcode(ERRCODE_NO_DATA_FOUND),
9493 errmsg("no matching relations in tablespace \"%s\" found",
9494 orig_tablespaceoid == InvalidOid ? "(database default)" :
9495 get_tablespace_name(orig_tablespaceoid))));
9497 /* Everything is locked, loop through and move all of the relations. */
9498 foreach(l, relations)
9501 AlterTableCmd *cmd = makeNode(AlterTableCmd);
9503 cmd->subtype = AT_SetTableSpace;
9504 cmd->name = stmt->new_tablespacename;
9506 cmds = lappend(cmds, cmd);
9508 AlterTableInternal(lfirst_oid(l), cmds, false);
9511 return new_tablespaceoid;
9515 * Copy data, block by block
9518 copy_relation_data(SMgrRelation src, SMgrRelation dst,
9519 ForkNumber forkNum, char relpersistence)
9524 BlockNumber nblocks;
9528 * palloc the buffer so that it's MAXALIGN'd. If it were just a local
9529 * char[] array, the compiler might align it on any byte boundary, which
9530 * can seriously hurt transfer speed to and from the kernel; not to
9531 * mention possibly making log_newpage's accesses to the page header fail.
9533 buf = (char *) palloc(BLCKSZ);
9537 * We need to log the copied data in WAL iff WAL archiving/streaming is
9538 * enabled AND it's a permanent relation.
9540 use_wal = XLogIsNeeded() && relpersistence == RELPERSISTENCE_PERMANENT;
9542 nblocks = smgrnblocks(src, forkNum);
9544 for (blkno = 0; blkno < nblocks; blkno++)
9546 /* If we got a cancel signal during the copy of the data, quit */
9547 CHECK_FOR_INTERRUPTS();
9549 smgrread(src, forkNum, blkno, buf);
9551 if (!PageIsVerified(page, blkno))
9553 (errcode(ERRCODE_DATA_CORRUPTED),
9554 errmsg("invalid page in block %u of relation %s",
9556 relpathbackend(src->smgr_rnode.node,
9557 src->smgr_rnode.backend,
9561 * WAL-log the copied page. Unfortunately we don't know what kind of a
9562 * page this is, so we have to log the full page including any unused
9566 log_newpage(&dst->smgr_rnode.node, forkNum, blkno, page, false);
9568 PageSetChecksumInplace(page, blkno);
9571 * Now write the page. We say isTemp = true even if it's not a temp
9572 * rel, because there's no need for smgr to schedule an fsync for this
9573 * write; we'll do it ourselves below.
9575 smgrextend(dst, forkNum, blkno, buf, true);
9581 * If the rel is WAL-logged, must fsync before commit. We use heap_sync
9582 * to ensure that the toast table gets fsync'd too. (For a temp or
9583 * unlogged rel we don't care since the data will be gone after a crash
9586 * It's obvious that we must do this when not WAL-logging the copy. It's
9587 * less obvious that we have to do it even if we did WAL-log the copied
9588 * pages. The reason is that since we're copying outside shared buffers, a
9589 * CHECKPOINT occurring during the copy has no way to flush the previously
9590 * written data to disk (indeed it won't know the new rel even exists). A
9591 * crash later on would replay WAL from the checkpoint, therefore it
9592 * wouldn't replay our earlier WAL entries. If we do not fsync those pages
9593 * here, they might still not be on disk when the crash occurs.
9595 if (relpersistence == RELPERSISTENCE_PERMANENT)
9596 smgrimmedsync(dst, forkNum);
9600 * ALTER TABLE ENABLE/DISABLE TRIGGER
9602 * We just pass this off to trigger.c.
9605 ATExecEnableDisableTrigger(Relation rel, char *trigname,
9606 char fires_when, bool skip_system, LOCKMODE lockmode)
9608 EnableDisableTrigger(rel, trigname, fires_when, skip_system);
9612 * ALTER TABLE ENABLE/DISABLE RULE
9614 * We just pass this off to rewriteDefine.c.
9617 ATExecEnableDisableRule(Relation rel, char *trigname,
9618 char fires_when, LOCKMODE lockmode)
9620 EnableDisableRule(rel, trigname, fires_when);
9624 * ALTER TABLE INHERIT
9626 * Add a parent to the child's parents. This verifies that all the columns and
9627 * check constraints of the parent appear in the child and that they have the
9628 * same data types and expressions.
9631 ATPrepAddInherit(Relation child_rel)
9633 if (child_rel->rd_rel->reloftype)
9635 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9636 errmsg("cannot change inheritance of typed table")));
9640 ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode)
9642 Relation parent_rel,
9646 HeapTuple inheritsTuple;
9651 * A self-exclusive lock is needed here. See the similar case in
9652 * MergeAttributes() for a full explanation.
9654 parent_rel = heap_openrv(parent, ShareUpdateExclusiveLock);
9657 * Must be owner of both parent and child -- child was checked by
9658 * ATSimplePermissions call in ATPrepCmd
9660 ATSimplePermissions(parent_rel, ATT_TABLE);
9662 /* Permanent rels cannot inherit from temporary ones */
9663 if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
9664 child_rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
9666 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9667 errmsg("cannot inherit from temporary relation \"%s\"",
9668 RelationGetRelationName(parent_rel))));
9670 /* If parent rel is temp, it must belong to this session */
9671 if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
9672 !parent_rel->rd_islocaltemp)
9674 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9675 errmsg("cannot inherit from temporary relation of another session")));
9677 /* Ditto for the child */
9678 if (child_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
9679 !child_rel->rd_islocaltemp)
9681 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9682 errmsg("cannot inherit to temporary relation of another session")));
9685 * Check for duplicates in the list of parents, and determine the highest
9686 * inhseqno already present; we'll use the next one for the new parent.
9687 * (Note: get RowExclusiveLock because we will write pg_inherits below.)
9689 * Note: we do not reject the case where the child already inherits from
9690 * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
9692 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
9694 Anum_pg_inherits_inhrelid,
9695 BTEqualStrategyNumber, F_OIDEQ,
9696 ObjectIdGetDatum(RelationGetRelid(child_rel)));
9697 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
9698 true, NULL, 1, &key);
9700 /* inhseqno sequences start at 1 */
9702 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
9704 Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
9706 if (inh->inhparent == RelationGetRelid(parent_rel))
9708 (errcode(ERRCODE_DUPLICATE_TABLE),
9709 errmsg("relation \"%s\" would be inherited from more than once",
9710 RelationGetRelationName(parent_rel))));
9711 if (inh->inhseqno > inhseqno)
9712 inhseqno = inh->inhseqno;
9714 systable_endscan(scan);
9717 * Prevent circularity by seeing if proposed parent inherits from child.
9718 * (In particular, this disallows making a rel inherit from itself.)
9720 * This is not completely bulletproof because of race conditions: in
9721 * multi-level inheritance trees, someone else could concurrently be
9722 * making another inheritance link that closes the loop but does not join
9723 * either of the rels we have locked. Preventing that seems to require
9724 * exclusive locks on the entire inheritance tree, which is a cure worse
9725 * than the disease. find_all_inheritors() will cope with circularity
9726 * anyway, so don't sweat it too much.
9728 * We use weakest lock we can on child's children, namely AccessShareLock.
9730 children = find_all_inheritors(RelationGetRelid(child_rel),
9731 AccessShareLock, NULL);
9733 if (list_member_oid(children, RelationGetRelid(parent_rel)))
9735 (errcode(ERRCODE_DUPLICATE_TABLE),
9736 errmsg("circular inheritance not allowed"),
9737 errdetail("\"%s\" is already a child of \"%s\".",
9739 RelationGetRelationName(child_rel))));
9741 /* If parent has OIDs then child must have OIDs */
9742 if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
9744 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9745 errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
9746 RelationGetRelationName(child_rel),
9747 RelationGetRelationName(parent_rel))));
9749 /* Match up the columns and bump attinhcount as needed */
9750 MergeAttributesIntoExisting(child_rel, parent_rel);
9752 /* Match up the constraints and bump coninhcount as needed */
9753 MergeConstraintsIntoExisting(child_rel, parent_rel);
9756 * OK, it looks valid. Make the catalog entries that show inheritance.
9758 StoreCatalogInheritance1(RelationGetRelid(child_rel),
9759 RelationGetRelid(parent_rel),
9763 /* Now we're done with pg_inherits */
9764 heap_close(catalogRelation, RowExclusiveLock);
9766 /* keep our lock on the parent relation until commit */
9767 heap_close(parent_rel, NoLock);
9771 * Obtain the source-text form of the constraint expression for a check
9772 * constraint, given its pg_constraint tuple
9775 decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
9777 Form_pg_constraint con;
9782 con = (Form_pg_constraint) GETSTRUCT(contup);
9783 attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
9785 elog(ERROR, "null conbin for constraint %u", HeapTupleGetOid(contup));
9787 expr = DirectFunctionCall2(pg_get_expr, attr,
9788 ObjectIdGetDatum(con->conrelid));
9789 return TextDatumGetCString(expr);
9793 * Determine whether two check constraints are functionally equivalent
9795 * The test we apply is to see whether they reverse-compile to the same
9796 * source string. This insulates us from issues like whether attributes
9797 * have the same physical column numbers in parent and child relations.
9800 constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
9802 Form_pg_constraint acon = (Form_pg_constraint) GETSTRUCT(a);
9803 Form_pg_constraint bcon = (Form_pg_constraint) GETSTRUCT(b);
9805 if (acon->condeferrable != bcon->condeferrable ||
9806 acon->condeferred != bcon->condeferred ||
9807 strcmp(decompile_conbin(a, tupleDesc),
9808 decompile_conbin(b, tupleDesc)) != 0)
9815 * Check columns in child table match up with columns in parent, and increment
9816 * their attinhcount.
9818 * Called by ATExecAddInherit
9820 * Currently all parent columns must be found in child. Missing columns are an
9821 * error. One day we might consider creating new columns like CREATE TABLE
9822 * does. However, that is widely unpopular --- in the common use case of
9823 * partitioned tables it's a foot-gun.
9825 * The data type must match exactly. If the parent column is NOT NULL then
9826 * the child must be as well. Defaults are not compared, however.
9829 MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel)
9832 AttrNumber parent_attno;
9834 TupleDesc tupleDesc;
9837 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
9839 tupleDesc = RelationGetDescr(parent_rel);
9840 parent_natts = tupleDesc->natts;
9842 for (parent_attno = 1; parent_attno <= parent_natts; parent_attno++)
9844 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
9845 char *attributeName = NameStr(attribute->attname);
9847 /* Ignore dropped columns in the parent. */
9848 if (attribute->attisdropped)
9851 /* Find same column in child (matching on column name). */
9852 tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel),
9854 if (HeapTupleIsValid(tuple))
9856 /* Check they are same type, typmod, and collation */
9857 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
9859 if (attribute->atttypid != childatt->atttypid ||
9860 attribute->atttypmod != childatt->atttypmod)
9862 (errcode(ERRCODE_DATATYPE_MISMATCH),
9863 errmsg("child table \"%s\" has different type for column \"%s\"",
9864 RelationGetRelationName(child_rel),
9867 if (attribute->attcollation != childatt->attcollation)
9869 (errcode(ERRCODE_COLLATION_MISMATCH),
9870 errmsg("child table \"%s\" has different collation for column \"%s\"",
9871 RelationGetRelationName(child_rel),
9875 * Check child doesn't discard NOT NULL property. (Other
9876 * constraints are checked elsewhere.)
9878 if (attribute->attnotnull && !childatt->attnotnull)
9880 (errcode(ERRCODE_DATATYPE_MISMATCH),
9881 errmsg("column \"%s\" in child table must be marked NOT NULL",
9885 * OK, bump the child column's inheritance count. (If we fail
9886 * later on, this change will just roll back.)
9888 childatt->attinhcount++;
9889 simple_heap_update(attrrel, &tuple->t_self, tuple);
9890 CatalogUpdateIndexes(attrrel, tuple);
9891 heap_freetuple(tuple);
9896 (errcode(ERRCODE_DATATYPE_MISMATCH),
9897 errmsg("child table is missing column \"%s\"",
9902 heap_close(attrrel, RowExclusiveLock);
9906 * Check constraints in child table match up with constraints in parent,
9907 * and increment their coninhcount.
9909 * Constraints that are marked ONLY in the parent are ignored.
9911 * Called by ATExecAddInherit
9913 * Currently all constraints in parent must be present in the child. One day we
9914 * may consider adding new constraints like CREATE TABLE does.
9916 * XXX This is O(N^2) which may be an issue with tables with hundreds of
9917 * constraints. As long as tables have more like 10 constraints it shouldn't be
9918 * a problem though. Even 100 constraints ought not be the end of the world.
9920 * XXX See MergeWithExistingConstraint too if you change this code.
9923 MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
9925 Relation catalog_relation;
9926 TupleDesc tuple_desc;
9927 SysScanDesc parent_scan;
9928 ScanKeyData parent_key;
9929 HeapTuple parent_tuple;
9931 catalog_relation = heap_open(ConstraintRelationId, RowExclusiveLock);
9932 tuple_desc = RelationGetDescr(catalog_relation);
9934 /* Outer loop scans through the parent's constraint definitions */
9935 ScanKeyInit(&parent_key,
9936 Anum_pg_constraint_conrelid,
9937 BTEqualStrategyNumber, F_OIDEQ,
9938 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
9939 parent_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
9940 true, NULL, 1, &parent_key);
9942 while (HeapTupleIsValid(parent_tuple = systable_getnext(parent_scan)))
9944 Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(parent_tuple);
9945 SysScanDesc child_scan;
9946 ScanKeyData child_key;
9947 HeapTuple child_tuple;
9950 if (parent_con->contype != CONSTRAINT_CHECK)
9953 /* if the parent's constraint is marked NO INHERIT, it's not inherited */
9954 if (parent_con->connoinherit)
9957 /* Search for a child constraint matching this one */
9958 ScanKeyInit(&child_key,
9959 Anum_pg_constraint_conrelid,
9960 BTEqualStrategyNumber, F_OIDEQ,
9961 ObjectIdGetDatum(RelationGetRelid(child_rel)));
9962 child_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
9963 true, NULL, 1, &child_key);
9965 while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
9967 Form_pg_constraint child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
9968 HeapTuple child_copy;
9970 if (child_con->contype != CONSTRAINT_CHECK)
9973 if (strcmp(NameStr(parent_con->conname),
9974 NameStr(child_con->conname)) != 0)
9977 if (!constraints_equivalent(parent_tuple, child_tuple, tuple_desc))
9979 (errcode(ERRCODE_DATATYPE_MISMATCH),
9980 errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
9981 RelationGetRelationName(child_rel),
9982 NameStr(parent_con->conname))));
9984 /* If the constraint is "no inherit" then cannot merge */
9985 if (child_con->connoinherit)
9987 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
9988 errmsg("constraint \"%s\" conflicts with non-inherited constraint on child table \"%s\"",
9989 NameStr(child_con->conname),
9990 RelationGetRelationName(child_rel))));
9993 * OK, bump the child constraint's inheritance count. (If we fail
9994 * later on, this change will just roll back.)
9996 child_copy = heap_copytuple(child_tuple);
9997 child_con = (Form_pg_constraint) GETSTRUCT(child_copy);
9998 child_con->coninhcount++;
9999 simple_heap_update(catalog_relation, &child_copy->t_self, child_copy);
10000 CatalogUpdateIndexes(catalog_relation, child_copy);
10001 heap_freetuple(child_copy);
10007 systable_endscan(child_scan);
10011 (errcode(ERRCODE_DATATYPE_MISMATCH),
10012 errmsg("child table is missing constraint \"%s\"",
10013 NameStr(parent_con->conname))));
10016 systable_endscan(parent_scan);
10017 heap_close(catalog_relation, RowExclusiveLock);
10021 * ALTER TABLE NO INHERIT
10023 * Drop a parent from the child's parents. This just adjusts the attinhcount
10024 * and attislocal of the columns and removes the pg_inherit and pg_depend
10027 * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
10028 * up attislocal stays true, which means if a child is ever removed from a
10029 * parent then its columns will never be automatically dropped which may
10030 * surprise. But at least we'll never surprise by dropping columns someone
10031 * isn't expecting to be dropped which would actually mean data loss.
10033 * coninhcount and conislocal for inherited constraints are adjusted in
10034 * exactly the same way.
10037 ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode)
10039 Relation parent_rel;
10040 Relation catalogRelation;
10042 ScanKeyData key[3];
10043 HeapTuple inheritsTuple,
10047 bool found = false;
10050 * AccessShareLock on the parent is probably enough, seeing that DROP
10051 * TABLE doesn't lock parent tables at all. We need some lock since we'll
10052 * be inspecting the parent's schema.
10054 parent_rel = heap_openrv(parent, AccessShareLock);
10057 * We don't bother to check ownership of the parent table --- ownership of
10058 * the child is presumed enough rights.
10062 * Find and destroy the pg_inherits entry linking the two, or error out if
10065 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
10066 ScanKeyInit(&key[0],
10067 Anum_pg_inherits_inhrelid,
10068 BTEqualStrategyNumber, F_OIDEQ,
10069 ObjectIdGetDatum(RelationGetRelid(rel)));
10070 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
10071 true, NULL, 1, key);
10073 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
10077 inhparent = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
10078 if (inhparent == RelationGetRelid(parent_rel))
10080 simple_heap_delete(catalogRelation, &inheritsTuple->t_self);
10086 systable_endscan(scan);
10087 heap_close(catalogRelation, RowExclusiveLock);
10091 (errcode(ERRCODE_UNDEFINED_TABLE),
10092 errmsg("relation \"%s\" is not a parent of relation \"%s\"",
10093 RelationGetRelationName(parent_rel),
10094 RelationGetRelationName(rel))));
10097 * Search through child columns looking for ones matching parent rel
10099 catalogRelation = heap_open(AttributeRelationId, RowExclusiveLock);
10100 ScanKeyInit(&key[0],
10101 Anum_pg_attribute_attrelid,
10102 BTEqualStrategyNumber, F_OIDEQ,
10103 ObjectIdGetDatum(RelationGetRelid(rel)));
10104 scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
10105 true, NULL, 1, key);
10106 while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
10108 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
10110 /* Ignore if dropped or not inherited */
10111 if (att->attisdropped)
10113 if (att->attinhcount <= 0)
10116 if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
10117 NameStr(att->attname)))
10119 /* Decrement inhcount and possibly set islocal to true */
10120 HeapTuple copyTuple = heap_copytuple(attributeTuple);
10121 Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
10123 copy_att->attinhcount--;
10124 if (copy_att->attinhcount == 0)
10125 copy_att->attislocal = true;
10127 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
10128 CatalogUpdateIndexes(catalogRelation, copyTuple);
10129 heap_freetuple(copyTuple);
10132 systable_endscan(scan);
10133 heap_close(catalogRelation, RowExclusiveLock);
10136 * Likewise, find inherited check constraints and disinherit them. To do
10137 * this, we first need a list of the names of the parent's check
10138 * constraints. (We cheat a bit by only checking for name matches,
10139 * assuming that the expressions will match.)
10141 catalogRelation = heap_open(ConstraintRelationId, RowExclusiveLock);
10142 ScanKeyInit(&key[0],
10143 Anum_pg_constraint_conrelid,
10144 BTEqualStrategyNumber, F_OIDEQ,
10145 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
10146 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
10147 true, NULL, 1, key);
10151 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
10153 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
10155 if (con->contype == CONSTRAINT_CHECK)
10156 connames = lappend(connames, pstrdup(NameStr(con->conname)));
10159 systable_endscan(scan);
10161 /* Now scan the child's constraints */
10162 ScanKeyInit(&key[0],
10163 Anum_pg_constraint_conrelid,
10164 BTEqualStrategyNumber, F_OIDEQ,
10165 ObjectIdGetDatum(RelationGetRelid(rel)));
10166 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
10167 true, NULL, 1, key);
10169 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
10171 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
10175 if (con->contype != CONSTRAINT_CHECK)
10179 foreach(lc, connames)
10181 if (strcmp(NameStr(con->conname), (char *) lfirst(lc)) == 0)
10190 /* Decrement inhcount and possibly set islocal to true */
10191 HeapTuple copyTuple = heap_copytuple(constraintTuple);
10192 Form_pg_constraint copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
10194 if (copy_con->coninhcount <= 0) /* shouldn't happen */
10195 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
10196 RelationGetRelid(rel), NameStr(copy_con->conname));
10198 copy_con->coninhcount--;
10199 if (copy_con->coninhcount == 0)
10200 copy_con->conislocal = true;
10202 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
10203 CatalogUpdateIndexes(catalogRelation, copyTuple);
10204 heap_freetuple(copyTuple);
10208 systable_endscan(scan);
10209 heap_close(catalogRelation, RowExclusiveLock);
10211 drop_parent_dependency(RelationGetRelid(rel),
10212 RelationRelationId,
10213 RelationGetRelid(parent_rel));
10216 * Post alter hook of this inherits. Since object_access_hook doesn't take
10217 * multiple object identifiers, we relay oid of parent relation using
10218 * auxiliary_id argument.
10220 InvokeObjectPostAlterHookArg(InheritsRelationId,
10221 RelationGetRelid(rel), 0,
10222 RelationGetRelid(parent_rel), false);
10224 /* keep our lock on the parent relation until commit */
10225 heap_close(parent_rel, NoLock);
10229 * Drop the dependency created by StoreCatalogInheritance1 (CREATE TABLE
10230 * INHERITS/ALTER TABLE INHERIT -- refclassid will be RelationRelationId) or
10231 * heap_create_with_catalog (CREATE TABLE OF/ALTER TABLE OF -- refclassid will
10232 * be TypeRelationId). There's no convenient way to do this, so go trawling
10233 * through pg_depend.
10236 drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid)
10238 Relation catalogRelation;
10240 ScanKeyData key[3];
10241 HeapTuple depTuple;
10243 catalogRelation = heap_open(DependRelationId, RowExclusiveLock);
10245 ScanKeyInit(&key[0],
10246 Anum_pg_depend_classid,
10247 BTEqualStrategyNumber, F_OIDEQ,
10248 ObjectIdGetDatum(RelationRelationId));
10249 ScanKeyInit(&key[1],
10250 Anum_pg_depend_objid,
10251 BTEqualStrategyNumber, F_OIDEQ,
10252 ObjectIdGetDatum(relid));
10253 ScanKeyInit(&key[2],
10254 Anum_pg_depend_objsubid,
10255 BTEqualStrategyNumber, F_INT4EQ,
10258 scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
10261 while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
10263 Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
10265 if (dep->refclassid == refclassid &&
10266 dep->refobjid == refobjid &&
10267 dep->refobjsubid == 0 &&
10268 dep->deptype == DEPENDENCY_NORMAL)
10269 simple_heap_delete(catalogRelation, &depTuple->t_self);
10272 systable_endscan(scan);
10273 heap_close(catalogRelation, RowExclusiveLock);
10279 * Attach a table to a composite type, as though it had been created with CREATE
10280 * TABLE OF. All attname, atttypid, atttypmod and attcollation must match. The
10281 * subject table must not have inheritance parents. These restrictions ensure
10282 * that you cannot create a configuration impossible with CREATE TABLE OF alone.
10285 ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode)
10287 Oid relid = RelationGetRelid(rel);
10290 Relation inheritsRelation,
10294 AttrNumber table_attno,
10296 TupleDesc typeTupleDesc,
10298 ObjectAddress tableobj,
10300 HeapTuple classtuple;
10302 /* Validate the type. */
10303 typetuple = typenameType(NULL, ofTypename, NULL);
10304 check_of_type(typetuple);
10305 typeid = HeapTupleGetOid(typetuple);
10307 /* Fail if the table has any inheritance parents. */
10308 inheritsRelation = heap_open(InheritsRelationId, AccessShareLock);
10310 Anum_pg_inherits_inhrelid,
10311 BTEqualStrategyNumber, F_OIDEQ,
10312 ObjectIdGetDatum(relid));
10313 scan = systable_beginscan(inheritsRelation, InheritsRelidSeqnoIndexId,
10314 true, NULL, 1, &key);
10315 if (HeapTupleIsValid(systable_getnext(scan)))
10317 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10318 errmsg("typed tables cannot inherit")));
10319 systable_endscan(scan);
10320 heap_close(inheritsRelation, AccessShareLock);
10323 * Check the tuple descriptors for compatibility. Unlike inheritance, we
10324 * require that the order also match. However, attnotnull need not match.
10325 * Also unlike inheritance, we do not require matching relhasoids.
10327 typeTupleDesc = lookup_rowtype_tupdesc(typeid, -1);
10328 tableTupleDesc = RelationGetDescr(rel);
10330 for (type_attno = 1; type_attno <= typeTupleDesc->natts; type_attno++)
10332 Form_pg_attribute type_attr,
10334 const char *type_attname,
10337 /* Get the next non-dropped type attribute. */
10338 type_attr = typeTupleDesc->attrs[type_attno - 1];
10339 if (type_attr->attisdropped)
10341 type_attname = NameStr(type_attr->attname);
10343 /* Get the next non-dropped table attribute. */
10346 if (table_attno > tableTupleDesc->natts)
10348 (errcode(ERRCODE_DATATYPE_MISMATCH),
10349 errmsg("table is missing column \"%s\"",
10351 table_attr = tableTupleDesc->attrs[table_attno++ - 1];
10352 } while (table_attr->attisdropped);
10353 table_attname = NameStr(table_attr->attname);
10355 /* Compare name. */
10356 if (strncmp(table_attname, type_attname, NAMEDATALEN) != 0)
10358 (errcode(ERRCODE_DATATYPE_MISMATCH),
10359 errmsg("table has column \"%s\" where type requires \"%s\"",
10360 table_attname, type_attname)));
10362 /* Compare type. */
10363 if (table_attr->atttypid != type_attr->atttypid ||
10364 table_attr->atttypmod != type_attr->atttypmod ||
10365 table_attr->attcollation != type_attr->attcollation)
10367 (errcode(ERRCODE_DATATYPE_MISMATCH),
10368 errmsg("table \"%s\" has different type for column \"%s\"",
10369 RelationGetRelationName(rel), type_attname)));
10371 DecrTupleDescRefCount(typeTupleDesc);
10373 /* Any remaining columns at the end of the table had better be dropped. */
10374 for (; table_attno <= tableTupleDesc->natts; table_attno++)
10376 Form_pg_attribute table_attr = tableTupleDesc->attrs[table_attno - 1];
10378 if (!table_attr->attisdropped)
10380 (errcode(ERRCODE_DATATYPE_MISMATCH),
10381 errmsg("table has extra column \"%s\"",
10382 NameStr(table_attr->attname))));
10385 /* If the table was already typed, drop the existing dependency. */
10386 if (rel->rd_rel->reloftype)
10387 drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype);
10389 /* Record a dependency on the new type. */
10390 tableobj.classId = RelationRelationId;
10391 tableobj.objectId = relid;
10392 tableobj.objectSubId = 0;
10393 typeobj.classId = TypeRelationId;
10394 typeobj.objectId = typeid;
10395 typeobj.objectSubId = 0;
10396 recordDependencyOn(&tableobj, &typeobj, DEPENDENCY_NORMAL);
10398 /* Update pg_class.reloftype */
10399 relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
10400 classtuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
10401 if (!HeapTupleIsValid(classtuple))
10402 elog(ERROR, "cache lookup failed for relation %u", relid);
10403 ((Form_pg_class) GETSTRUCT(classtuple))->reloftype = typeid;
10404 simple_heap_update(relationRelation, &classtuple->t_self, classtuple);
10405 CatalogUpdateIndexes(relationRelation, classtuple);
10407 InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
10409 heap_freetuple(classtuple);
10410 heap_close(relationRelation, RowExclusiveLock);
10412 ReleaseSysCache(typetuple);
10416 * ALTER TABLE NOT OF
10418 * Detach a typed table from its originating type. Just clear reloftype and
10419 * remove the dependency.
10422 ATExecDropOf(Relation rel, LOCKMODE lockmode)
10424 Oid relid = RelationGetRelid(rel);
10425 Relation relationRelation;
10428 if (!OidIsValid(rel->rd_rel->reloftype))
10430 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10431 errmsg("\"%s\" is not a typed table",
10432 RelationGetRelationName(rel))));
10435 * We don't bother to check ownership of the type --- ownership of the
10436 * table is presumed enough rights. No lock required on the type, either.
10439 drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype);
10441 /* Clear pg_class.reloftype */
10442 relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
10443 tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
10444 if (!HeapTupleIsValid(tuple))
10445 elog(ERROR, "cache lookup failed for relation %u", relid);
10446 ((Form_pg_class) GETSTRUCT(tuple))->reloftype = InvalidOid;
10447 simple_heap_update(relationRelation, &tuple->t_self, tuple);
10448 CatalogUpdateIndexes(relationRelation, tuple);
10450 InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
10452 heap_freetuple(tuple);
10453 heap_close(relationRelation, RowExclusiveLock);
10457 * relation_mark_replica_identity: Update a table's replica identity
10459 * Iff ri_type = REPLICA_IDENTITY_INDEX, indexOid must be the Oid of a suitable
10460 * index. Otherwise, it should be InvalidOid.
10463 relation_mark_replica_identity(Relation rel, char ri_type, Oid indexOid,
10468 HeapTuple pg_class_tuple;
10469 HeapTuple pg_index_tuple;
10470 Form_pg_class pg_class_form;
10471 Form_pg_index pg_index_form;
10476 * Check whether relreplident has changed, and update it if so.
10478 pg_class = heap_open(RelationRelationId, RowExclusiveLock);
10479 pg_class_tuple = SearchSysCacheCopy1(RELOID,
10480 ObjectIdGetDatum(RelationGetRelid(rel)));
10481 if (!HeapTupleIsValid(pg_class_tuple))
10482 elog(ERROR, "cache lookup failed for relation \"%s\"",
10483 RelationGetRelationName(rel));
10484 pg_class_form = (Form_pg_class) GETSTRUCT(pg_class_tuple);
10485 if (pg_class_form->relreplident != ri_type)
10487 pg_class_form->relreplident = ri_type;
10488 simple_heap_update(pg_class, &pg_class_tuple->t_self, pg_class_tuple);
10489 CatalogUpdateIndexes(pg_class, pg_class_tuple);
10491 heap_close(pg_class, RowExclusiveLock);
10492 heap_freetuple(pg_class_tuple);
10495 * Check whether the correct index is marked indisreplident; if so, we're
10498 if (OidIsValid(indexOid))
10500 Assert(ri_type == REPLICA_IDENTITY_INDEX);
10502 pg_index_tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexOid));
10503 if (!HeapTupleIsValid(pg_index_tuple))
10504 elog(ERROR, "cache lookup failed for index %u", indexOid);
10505 pg_index_form = (Form_pg_index) GETSTRUCT(pg_index_tuple);
10507 if (pg_index_form->indisreplident)
10509 ReleaseSysCache(pg_index_tuple);
10512 ReleaseSysCache(pg_index_tuple);
10516 * Clear the indisreplident flag from any index that had it previously,
10517 * and set it for any index that should have it now.
10519 pg_index = heap_open(IndexRelationId, RowExclusiveLock);
10520 foreach(index, RelationGetIndexList(rel))
10522 Oid thisIndexOid = lfirst_oid(index);
10523 bool dirty = false;
10525 pg_index_tuple = SearchSysCacheCopy1(INDEXRELID,
10526 ObjectIdGetDatum(thisIndexOid));
10527 if (!HeapTupleIsValid(pg_index_tuple))
10528 elog(ERROR, "cache lookup failed for index %u", thisIndexOid);
10529 pg_index_form = (Form_pg_index) GETSTRUCT(pg_index_tuple);
10532 * Unset the bit if set. We know it's wrong because we checked this
10535 if (pg_index_form->indisreplident)
10538 pg_index_form->indisreplident = false;
10540 else if (thisIndexOid == indexOid)
10543 pg_index_form->indisreplident = true;
10548 simple_heap_update(pg_index, &pg_index_tuple->t_self, pg_index_tuple);
10549 CatalogUpdateIndexes(pg_index, pg_index_tuple);
10550 InvokeObjectPostAlterHookArg(IndexRelationId, thisIndexOid, 0,
10551 InvalidOid, is_internal);
10553 heap_freetuple(pg_index_tuple);
10556 heap_close(pg_index, RowExclusiveLock);
10560 * ALTER TABLE <name> REPLICA IDENTITY ...
10563 ATExecReplicaIdentity(Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode)
10569 if (stmt->identity_type == REPLICA_IDENTITY_DEFAULT)
10571 relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
10574 else if (stmt->identity_type == REPLICA_IDENTITY_FULL)
10576 relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
10579 else if (stmt->identity_type == REPLICA_IDENTITY_NOTHING)
10581 relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
10584 else if (stmt->identity_type == REPLICA_IDENTITY_INDEX)
10586 /* fallthrough */ ;
10589 elog(ERROR, "unexpected identity type %u", stmt->identity_type);
10592 /* Check that the index exists */
10593 indexOid = get_relname_relid(stmt->name, rel->rd_rel->relnamespace);
10594 if (!OidIsValid(indexOid))
10596 (errcode(ERRCODE_UNDEFINED_OBJECT),
10597 errmsg("index \"%s\" for table \"%s\" does not exist",
10598 stmt->name, RelationGetRelationName(rel))));
10600 indexRel = index_open(indexOid, ShareLock);
10602 /* Check that the index is on the relation we're altering. */
10603 if (indexRel->rd_index == NULL ||
10604 indexRel->rd_index->indrelid != RelationGetRelid(rel))
10606 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10607 errmsg("\"%s\" is not an index for table \"%s\"",
10608 RelationGetRelationName(indexRel),
10609 RelationGetRelationName(rel))));
10610 /* The AM must support uniqueness, and the index must in fact be unique. */
10611 if (!indexRel->rd_am->amcanunique || !indexRel->rd_index->indisunique)
10613 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10614 errmsg("cannot use non-unique index \"%s\" as replica identity",
10615 RelationGetRelationName(indexRel))));
10616 /* Deferred indexes are not guaranteed to be always unique. */
10617 if (!indexRel->rd_index->indimmediate)
10619 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10620 errmsg("cannot use non-immediate index \"%s\" as replica identity",
10621 RelationGetRelationName(indexRel))));
10622 /* Expression indexes aren't supported. */
10623 if (RelationGetIndexExpressions(indexRel) != NIL)
10625 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10626 errmsg("cannot use expression index \"%s\" as replica identity",
10627 RelationGetRelationName(indexRel))));
10628 /* Predicate indexes aren't supported. */
10629 if (RelationGetIndexPredicate(indexRel) != NIL)
10631 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10632 errmsg("cannot use partial index \"%s\" as replica identity",
10633 RelationGetRelationName(indexRel))));
10634 /* And neither are invalid indexes. */
10635 if (!IndexIsValid(indexRel->rd_index))
10637 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10638 errmsg("cannot use invalid index \"%s\" as replica identity",
10639 RelationGetRelationName(indexRel))));
10641 /* Check index for nullable columns. */
10642 for (key = 0; key < indexRel->rd_index->indnatts; key++)
10644 int16 attno = indexRel->rd_index->indkey.values[key];
10645 Form_pg_attribute attr;
10647 /* Of the system columns, only oid is indexable. */
10648 if (attno <= 0 && attno != ObjectIdAttributeNumber)
10649 elog(ERROR, "internal column %u in unique index \"%s\"",
10650 attno, RelationGetRelationName(indexRel));
10652 attr = rel->rd_att->attrs[attno - 1];
10653 if (!attr->attnotnull)
10655 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10656 errmsg("index \"%s\" cannot be used as replica identity because column \"%s\" is nullable",
10657 RelationGetRelationName(indexRel),
10658 NameStr(attr->attname))));
10661 /* This index is suitable for use as a replica identity. Mark it. */
10662 relation_mark_replica_identity(rel, stmt->identity_type, indexOid, true);
10664 index_close(indexRel, NoLock);
10668 * ALTER TABLE ENABLE/DISABLE ROW LEVEL SECURITY
10671 ATExecEnableRowSecurity(Relation rel)
10677 relid = RelationGetRelid(rel);
10679 pg_class = heap_open(RelationRelationId, RowExclusiveLock);
10681 tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
10683 if (!HeapTupleIsValid(tuple))
10684 elog(ERROR, "cache lookup failed for relation %u", relid);
10686 ((Form_pg_class) GETSTRUCT(tuple))->relrowsecurity = true;
10687 simple_heap_update(pg_class, &tuple->t_self, tuple);
10689 /* keep catalog indexes current */
10690 CatalogUpdateIndexes(pg_class, tuple);
10692 heap_close(pg_class, RowExclusiveLock);
10693 heap_freetuple(tuple);
10697 ATExecDisableRowSecurity(Relation rel)
10703 relid = RelationGetRelid(rel);
10705 /* Pull the record for this relation and update it */
10706 pg_class = heap_open(RelationRelationId, RowExclusiveLock);
10708 tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
10710 if (!HeapTupleIsValid(tuple))
10711 elog(ERROR, "cache lookup failed for relation %u", relid);
10713 ((Form_pg_class) GETSTRUCT(tuple))->relrowsecurity = false;
10714 simple_heap_update(pg_class, &tuple->t_self, tuple);
10716 /* keep catalog indexes current */
10717 CatalogUpdateIndexes(pg_class, tuple);
10719 heap_close(pg_class, RowExclusiveLock);
10720 heap_freetuple(tuple);
10724 * ALTER FOREIGN TABLE <name> OPTIONS (...)
10727 ATExecGenericOptions(Relation rel, List *options)
10730 ForeignServer *server;
10731 ForeignDataWrapper *fdw;
10734 Datum repl_val[Natts_pg_foreign_table];
10735 bool repl_null[Natts_pg_foreign_table];
10736 bool repl_repl[Natts_pg_foreign_table];
10738 Form_pg_foreign_table tableform;
10740 if (options == NIL)
10743 ftrel = heap_open(ForeignTableRelationId, RowExclusiveLock);
10745 tuple = SearchSysCacheCopy1(FOREIGNTABLEREL, rel->rd_id);
10746 if (!HeapTupleIsValid(tuple))
10748 (errcode(ERRCODE_UNDEFINED_OBJECT),
10749 errmsg("foreign table \"%s\" does not exist",
10750 RelationGetRelationName(rel))));
10751 tableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
10752 server = GetForeignServer(tableform->ftserver);
10753 fdw = GetForeignDataWrapper(server->fdwid);
10755 memset(repl_val, 0, sizeof(repl_val));
10756 memset(repl_null, false, sizeof(repl_null));
10757 memset(repl_repl, false, sizeof(repl_repl));
10759 /* Extract the current options */
10760 datum = SysCacheGetAttr(FOREIGNTABLEREL,
10762 Anum_pg_foreign_table_ftoptions,
10765 datum = PointerGetDatum(NULL);
10767 /* Transform the options */
10768 datum = transformGenericOptions(ForeignTableRelationId,
10771 fdw->fdwvalidator);
10773 if (PointerIsValid(DatumGetPointer(datum)))
10774 repl_val[Anum_pg_foreign_table_ftoptions - 1] = datum;
10776 repl_null[Anum_pg_foreign_table_ftoptions - 1] = true;
10778 repl_repl[Anum_pg_foreign_table_ftoptions - 1] = true;
10780 /* Everything looks good - update the tuple */
10782 tuple = heap_modify_tuple(tuple, RelationGetDescr(ftrel),
10783 repl_val, repl_null, repl_repl);
10785 simple_heap_update(ftrel, &tuple->t_self, tuple);
10786 CatalogUpdateIndexes(ftrel, tuple);
10788 InvokeObjectPostAlterHook(ForeignTableRelationId,
10789 RelationGetRelid(rel), 0);
10791 heap_close(ftrel, RowExclusiveLock);
10793 heap_freetuple(tuple);
10797 * Preparation phase for SET LOGGED/UNLOGGED
10799 * This verifies that we're not trying to change a temp table. Also,
10800 * existing foreign key constraints are checked to avoid ending up with
10801 * permanent tables referencing unlogged tables.
10803 * Return value is false if the operation is a no-op (in which case the
10804 * checks are skipped), otherwise true.
10807 ATPrepChangePersistence(Relation rel, bool toLogged)
10809 Relation pg_constraint;
10812 ScanKeyData skey[1];
10815 * Disallow changing status for a temp table. Also verify whether we can
10816 * get away with doing nothing; in such cases we don't need to run the
10817 * checks below, either.
10819 switch (rel->rd_rel->relpersistence)
10821 case RELPERSISTENCE_TEMP:
10823 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10824 errmsg("cannot change logged status of table %s",
10825 RelationGetRelationName(rel)),
10826 errdetail("Table %s is temporary.",
10827 RelationGetRelationName(rel)),
10830 case RELPERSISTENCE_PERMANENT:
10832 /* nothing to do */
10835 case RELPERSISTENCE_UNLOGGED:
10837 /* nothing to do */
10843 * Check existing foreign key constraints to preserve the invariant that
10844 * no permanent tables cannot reference unlogged ones. Self-referencing
10845 * foreign keys can safely be ignored.
10847 pg_constraint = heap_open(ConstraintRelationId, AccessShareLock);
10850 * Scan conrelid if changing to permanent, else confrelid. This also
10851 * determines whether a useful index exists.
10853 ScanKeyInit(&skey[0],
10854 toLogged ? Anum_pg_constraint_conrelid :
10855 Anum_pg_constraint_confrelid,
10856 BTEqualStrategyNumber, F_OIDEQ,
10857 ObjectIdGetDatum(RelationGetRelid(rel)));
10858 scan = systable_beginscan(pg_constraint,
10859 toLogged ? ConstraintRelidIndexId : InvalidOid,
10860 true, NULL, 1, skey);
10862 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
10864 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
10866 if (con->contype == CONSTRAINT_FOREIGN)
10869 Relation foreignrel;
10871 /* the opposite end of what we used as scankey */
10872 foreignrelid = toLogged ? con->confrelid : con->conrelid;
10874 /* ignore if self-referencing */
10875 if (RelationGetRelid(rel) == foreignrelid)
10878 foreignrel = relation_open(foreignrelid, AccessShareLock);
10882 if (foreignrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT)
10884 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10885 errmsg("cannot change status of table %s to logged",
10886 RelationGetRelationName(rel)),
10887 errdetail("Table %s references unlogged table %s.",
10888 RelationGetRelationName(rel),
10889 RelationGetRelationName(foreignrel)),
10890 errtableconstraint(rel, NameStr(con->conname))));
10894 if (foreignrel->rd_rel->relpersistence == RELPERSISTENCE_PERMANENT)
10896 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10897 errmsg("cannot change status of table %s to unlogged",
10898 RelationGetRelationName(rel)),
10899 errdetail("Logged table %s is referenced by table %s.",
10900 RelationGetRelationName(foreignrel),
10901 RelationGetRelationName(rel)),
10902 errtableconstraint(rel, NameStr(con->conname))));
10905 relation_close(foreignrel, AccessShareLock);
10909 systable_endscan(scan);
10911 heap_close(pg_constraint, AccessShareLock);
10917 * Execute ALTER TABLE SET SCHEMA
10920 AlterTableNamespace(AlterObjectSchemaStmt *stmt)
10927 ObjectAddresses *objsMoved;
10929 relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
10930 stmt->missing_ok, false,
10931 RangeVarCallbackForAlterRelation,
10934 if (!OidIsValid(relid))
10937 (errmsg("relation \"%s\" does not exist, skipping",
10938 stmt->relation->relname)));
10942 rel = relation_open(relid, NoLock);
10944 oldNspOid = RelationGetNamespace(rel);
10946 /* If it's an owned sequence, disallow moving it by itself. */
10947 if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
10952 if (sequenceIsOwned(relid, &tableId, &colId))
10954 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10955 errmsg("cannot move an owned sequence into another schema"),
10956 errdetail("Sequence \"%s\" is linked to table \"%s\".",
10957 RelationGetRelationName(rel),
10958 get_rel_name(tableId))));
10961 /* Get and lock schema OID and check its permissions. */
10962 newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
10963 nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
10965 /* common checks on switching namespaces */
10966 CheckSetNamespace(oldNspOid, nspOid, RelationRelationId, relid);
10968 objsMoved = new_object_addresses();
10969 AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
10970 free_object_addresses(objsMoved);
10972 /* close rel, but keep lock until commit */
10973 relation_close(rel, NoLock);
10979 * The guts of relocating a table or materialized view to another namespace:
10980 * besides moving the relation itself, its dependent objects are relocated to
10984 AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid,
10985 ObjectAddresses *objsMoved)
10989 Assert(objsMoved != NULL);
10991 /* OK, modify the pg_class row and pg_depend entry */
10992 classRel = heap_open(RelationRelationId, RowExclusiveLock);
10994 AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
10995 nspOid, true, objsMoved);
10997 /* Fix the table's row type too */
10998 AlterTypeNamespaceInternal(rel->rd_rel->reltype,
10999 nspOid, false, false, objsMoved);
11001 /* Fix other dependent stuff */
11002 if (rel->rd_rel->relkind == RELKIND_RELATION ||
11003 rel->rd_rel->relkind == RELKIND_MATVIEW)
11005 AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
11006 AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
11007 objsMoved, AccessExclusiveLock);
11008 AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
11012 heap_close(classRel, RowExclusiveLock);
11016 * The guts of relocating a relation to another namespace: fix the pg_class
11017 * entry, and the pg_depend entry if any. Caller must already have
11018 * opened and write-locked pg_class.
11021 AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
11022 Oid oldNspOid, Oid newNspOid,
11023 bool hasDependEntry,
11024 ObjectAddresses *objsMoved)
11026 HeapTuple classTup;
11027 Form_pg_class classForm;
11028 ObjectAddress thisobj;
11030 classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
11031 if (!HeapTupleIsValid(classTup))
11032 elog(ERROR, "cache lookup failed for relation %u", relOid);
11033 classForm = (Form_pg_class) GETSTRUCT(classTup);
11035 Assert(classForm->relnamespace == oldNspOid);
11037 thisobj.classId = RelationRelationId;
11038 thisobj.objectId = relOid;
11039 thisobj.objectSubId = 0;
11042 * Do nothing when there's nothing to do.
11044 if (!object_address_present(&thisobj, objsMoved))
11046 /* check for duplicate name (more friendly than unique-index failure) */
11047 if (get_relname_relid(NameStr(classForm->relname),
11048 newNspOid) != InvalidOid)
11050 (errcode(ERRCODE_DUPLICATE_TABLE),
11051 errmsg("relation \"%s\" already exists in schema \"%s\"",
11052 NameStr(classForm->relname),
11053 get_namespace_name(newNspOid))));
11055 /* classTup is a copy, so OK to scribble on */
11056 classForm->relnamespace = newNspOid;
11058 simple_heap_update(classRel, &classTup->t_self, classTup);
11059 CatalogUpdateIndexes(classRel, classTup);
11061 /* Update dependency on schema if caller said so */
11062 if (hasDependEntry &&
11063 changeDependencyFor(RelationRelationId,
11065 NamespaceRelationId,
11068 elog(ERROR, "failed to change schema dependency for relation \"%s\"",
11069 NameStr(classForm->relname));
11071 add_exact_object_address(&thisobj, objsMoved);
11073 InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
11076 heap_freetuple(classTup);
11080 * Move all indexes for the specified relation to another namespace.
11082 * Note: we assume adequate permission checking was done by the caller,
11083 * and that the caller has a suitable lock on the owning relation.
11086 AlterIndexNamespaces(Relation classRel, Relation rel,
11087 Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
11092 indexList = RelationGetIndexList(rel);
11094 foreach(l, indexList)
11096 Oid indexOid = lfirst_oid(l);
11097 ObjectAddress thisobj;
11099 thisobj.classId = RelationRelationId;
11100 thisobj.objectId = indexOid;
11101 thisobj.objectSubId = 0;
11104 * Note: currently, the index will not have its own dependency on the
11105 * namespace, so we don't need to do changeDependencyFor(). There's no
11106 * row type in pg_type, either.
11108 * XXX this objsMoved test may be pointless -- surely we have a single
11109 * dependency link from a relation to each index?
11111 if (!object_address_present(&thisobj, objsMoved))
11113 AlterRelationNamespaceInternal(classRel, indexOid,
11114 oldNspOid, newNspOid,
11116 add_exact_object_address(&thisobj, objsMoved);
11120 list_free(indexList);
11124 * Move all SERIAL-column sequences of the specified relation to another
11127 * Note: we assume adequate permission checking was done by the caller,
11128 * and that the caller has a suitable lock on the owning relation.
11131 AlterSeqNamespaces(Relation classRel, Relation rel,
11132 Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved,
11137 ScanKeyData key[2];
11141 * SERIAL sequences are those having an auto dependency on one of the
11142 * table's columns (we don't care *which* column, exactly).
11144 depRel = heap_open(DependRelationId, AccessShareLock);
11146 ScanKeyInit(&key[0],
11147 Anum_pg_depend_refclassid,
11148 BTEqualStrategyNumber, F_OIDEQ,
11149 ObjectIdGetDatum(RelationRelationId));
11150 ScanKeyInit(&key[1],
11151 Anum_pg_depend_refobjid,
11152 BTEqualStrategyNumber, F_OIDEQ,
11153 ObjectIdGetDatum(RelationGetRelid(rel)));
11154 /* we leave refobjsubid unspecified */
11156 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
11159 while (HeapTupleIsValid(tup = systable_getnext(scan)))
11161 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
11164 /* skip dependencies other than auto dependencies on columns */
11165 if (depForm->refobjsubid == 0 ||
11166 depForm->classid != RelationRelationId ||
11167 depForm->objsubid != 0 ||
11168 depForm->deptype != DEPENDENCY_AUTO)
11171 /* Use relation_open just in case it's an index */
11172 seqRel = relation_open(depForm->objid, lockmode);
11174 /* skip non-sequence relations */
11175 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
11177 /* No need to keep the lock */
11178 relation_close(seqRel, lockmode);
11182 /* Fix the pg_class and pg_depend entries */
11183 AlterRelationNamespaceInternal(classRel, depForm->objid,
11184 oldNspOid, newNspOid,
11188 * Sequences have entries in pg_type. We need to be careful to move
11189 * them to the new namespace, too.
11191 AlterTypeNamespaceInternal(RelationGetForm(seqRel)->reltype,
11192 newNspOid, false, false, objsMoved);
11194 /* Now we can close it. Keep the lock till end of transaction. */
11195 relation_close(seqRel, NoLock);
11198 systable_endscan(scan);
11200 relation_close(depRel, AccessShareLock);
11205 * This code supports
11206 * CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
11208 * Because we only support this for TEMP tables, it's sufficient to remember
11209 * the state in a backend-local data structure.
11213 * Register a newly-created relation's ON COMMIT action.
11216 register_on_commit_action(Oid relid, OnCommitAction action)
11219 MemoryContext oldcxt;
11222 * We needn't bother registering the relation unless there is an ON COMMIT
11223 * action we need to take.
11225 if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
11228 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
11230 oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
11232 oc->oncommit = action;
11233 oc->creating_subid = GetCurrentSubTransactionId();
11234 oc->deleting_subid = InvalidSubTransactionId;
11236 on_commits = lcons(oc, on_commits);
11238 MemoryContextSwitchTo(oldcxt);
11242 * Unregister any ON COMMIT action when a relation is deleted.
11244 * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
11247 remove_on_commit_action(Oid relid)
11251 foreach(l, on_commits)
11253 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
11255 if (oc->relid == relid)
11257 oc->deleting_subid = GetCurrentSubTransactionId();
11264 * Perform ON COMMIT actions.
11266 * This is invoked just before actually committing, since it's possible
11267 * to encounter errors.
11270 PreCommit_on_commit_actions(void)
11273 List *oids_to_truncate = NIL;
11275 foreach(l, on_commits)
11277 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
11279 /* Ignore entry if already dropped in this xact */
11280 if (oc->deleting_subid != InvalidSubTransactionId)
11283 switch (oc->oncommit)
11285 case ONCOMMIT_NOOP:
11286 case ONCOMMIT_PRESERVE_ROWS:
11287 /* Do nothing (there shouldn't be such entries, actually) */
11289 case ONCOMMIT_DELETE_ROWS:
11292 * If this transaction hasn't accessed any temporary
11293 * relations, we can skip truncating ON COMMIT DELETE ROWS
11294 * tables, as they must still be empty.
11296 if (MyXactAccessedTempRel)
11297 oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
11299 case ONCOMMIT_DROP:
11301 ObjectAddress object;
11303 object.classId = RelationRelationId;
11304 object.objectId = oc->relid;
11305 object.objectSubId = 0;
11308 * Since this is an automatic drop, rather than one
11309 * directly initiated by the user, we pass the
11310 * PERFORM_DELETION_INTERNAL flag.
11312 performDeletion(&object,
11313 DROP_CASCADE, PERFORM_DELETION_INTERNAL);
11316 * Note that table deletion will call
11317 * remove_on_commit_action, so the entry should get marked
11320 Assert(oc->deleting_subid != InvalidSubTransactionId);
11325 if (oids_to_truncate != NIL)
11327 heap_truncate(oids_to_truncate);
11328 CommandCounterIncrement(); /* XXX needed? */
11333 * Post-commit or post-abort cleanup for ON COMMIT management.
11335 * All we do here is remove no-longer-needed OnCommitItem entries.
11337 * During commit, remove entries that were deleted during this transaction;
11338 * during abort, remove those created during this transaction.
11341 AtEOXact_on_commit_actions(bool isCommit)
11343 ListCell *cur_item;
11344 ListCell *prev_item;
11347 cur_item = list_head(on_commits);
11349 while (cur_item != NULL)
11351 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
11353 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
11354 oc->creating_subid != InvalidSubTransactionId)
11356 /* cur_item must be removed */
11357 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
11360 cur_item = lnext(prev_item);
11362 cur_item = list_head(on_commits);
11366 /* cur_item must be preserved */
11367 oc->creating_subid = InvalidSubTransactionId;
11368 oc->deleting_subid = InvalidSubTransactionId;
11369 prev_item = cur_item;
11370 cur_item = lnext(prev_item);
11376 * Post-subcommit or post-subabort cleanup for ON COMMIT management.
11378 * During subabort, we can immediately remove entries created during this
11379 * subtransaction. During subcommit, just relabel entries marked during
11380 * this subtransaction as being the parent's responsibility.
11383 AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
11384 SubTransactionId parentSubid)
11386 ListCell *cur_item;
11387 ListCell *prev_item;
11390 cur_item = list_head(on_commits);
11392 while (cur_item != NULL)
11394 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
11396 if (!isCommit && oc->creating_subid == mySubid)
11398 /* cur_item must be removed */
11399 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
11402 cur_item = lnext(prev_item);
11404 cur_item = list_head(on_commits);
11408 /* cur_item must be preserved */
11409 if (oc->creating_subid == mySubid)
11410 oc->creating_subid = parentSubid;
11411 if (oc->deleting_subid == mySubid)
11412 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
11413 prev_item = cur_item;
11414 cur_item = lnext(prev_item);
11420 * This is intended as a callback for RangeVarGetRelidExtended(). It allows
11421 * the relation to be locked only if (1) it's a plain table, materialized
11422 * view, or TOAST table and (2) the current user is the owner (or the
11423 * superuser). This meets the permission-checking needs of CLUSTER, REINDEX
11424 * TABLE, and REFRESH MATERIALIZED VIEW; we expose it here so that it can be
11428 RangeVarCallbackOwnsTable(const RangeVar *relation,
11429 Oid relId, Oid oldRelId, void *arg)
11433 /* Nothing to do if the relation was not found. */
11434 if (!OidIsValid(relId))
11438 * If the relation does exist, check whether it's an index. But note that
11439 * the relation might have been dropped between the time we did the name
11440 * lookup and now. In that case, there's nothing to do.
11442 relkind = get_rel_relkind(relId);
11445 if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
11446 relkind != RELKIND_MATVIEW)
11448 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11449 errmsg("\"%s\" is not a table or materialized view", relation->relname)));
11451 /* Check permissions */
11452 if (!pg_class_ownercheck(relId, GetUserId()))
11453 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS, relation->relname);
11457 * Callback to RangeVarGetRelidExtended(), similar to
11458 * RangeVarCallbackOwnsTable() but without checks on the type of the relation.
11461 RangeVarCallbackOwnsRelation(const RangeVar *relation,
11462 Oid relId, Oid oldRelId, void *arg)
11466 /* Nothing to do if the relation was not found. */
11467 if (!OidIsValid(relId))
11470 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
11471 if (!HeapTupleIsValid(tuple)) /* should not happen */
11472 elog(ERROR, "cache lookup failed for relation %u", relId);
11474 if (!pg_class_ownercheck(relId, GetUserId()))
11475 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
11476 relation->relname);
11478 if (!allowSystemTableMods &&
11479 IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
11481 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
11482 errmsg("permission denied: \"%s\" is a system catalog",
11483 relation->relname)));
11485 ReleaseSysCache(tuple);
11489 * Common RangeVarGetRelid callback for rename, set schema, and alter table
11493 RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid,
11496 Node *stmt = (Node *) arg;
11497 ObjectType reltype;
11499 Form_pg_class classform;
11500 AclResult aclresult;
11503 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
11504 if (!HeapTupleIsValid(tuple))
11505 return; /* concurrently dropped */
11506 classform = (Form_pg_class) GETSTRUCT(tuple);
11507 relkind = classform->relkind;
11509 /* Must own relation. */
11510 if (!pg_class_ownercheck(relid, GetUserId()))
11511 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS, rv->relname);
11513 /* No system table modifications unless explicitly allowed. */
11514 if (!allowSystemTableMods && IsSystemClass(relid, classform))
11516 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
11517 errmsg("permission denied: \"%s\" is a system catalog",
11521 * Extract the specified relation type from the statement parse tree.
11523 * Also, for ALTER .. RENAME, check permissions: the user must (still)
11524 * have CREATE rights on the containing namespace.
11526 if (IsA(stmt, RenameStmt))
11528 aclresult = pg_namespace_aclcheck(classform->relnamespace,
11529 GetUserId(), ACL_CREATE);
11530 if (aclresult != ACLCHECK_OK)
11531 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
11532 get_namespace_name(classform->relnamespace));
11533 reltype = ((RenameStmt *) stmt)->renameType;
11535 else if (IsA(stmt, AlterObjectSchemaStmt))
11536 reltype = ((AlterObjectSchemaStmt *) stmt)->objectType;
11538 else if (IsA(stmt, AlterTableStmt))
11539 reltype = ((AlterTableStmt *) stmt)->relkind;
11542 reltype = OBJECT_TABLE; /* placate compiler */
11543 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(stmt));
11547 * For compatibility with prior releases, we allow ALTER TABLE to be used
11548 * with most other types of relations (but not composite types). We allow
11549 * similar flexibility for ALTER INDEX in the case of RENAME, but not
11550 * otherwise. Otherwise, the user must select the correct form of the
11551 * command for the relation at issue.
11553 if (reltype == OBJECT_SEQUENCE && relkind != RELKIND_SEQUENCE)
11555 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11556 errmsg("\"%s\" is not a sequence", rv->relname)));
11558 if (reltype == OBJECT_VIEW && relkind != RELKIND_VIEW)
11560 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11561 errmsg("\"%s\" is not a view", rv->relname)));
11563 if (reltype == OBJECT_MATVIEW && relkind != RELKIND_MATVIEW)
11565 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11566 errmsg("\"%s\" is not a materialized view", rv->relname)));
11568 if (reltype == OBJECT_FOREIGN_TABLE && relkind != RELKIND_FOREIGN_TABLE)
11570 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11571 errmsg("\"%s\" is not a foreign table", rv->relname)));
11573 if (reltype == OBJECT_TYPE && relkind != RELKIND_COMPOSITE_TYPE)
11575 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11576 errmsg("\"%s\" is not a composite type", rv->relname)));
11578 if (reltype == OBJECT_INDEX && relkind != RELKIND_INDEX
11579 && !IsA(stmt, RenameStmt))
11581 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11582 errmsg("\"%s\" is not an index", rv->relname)));
11585 * Don't allow ALTER TABLE on composite types. We want people to use ALTER
11588 if (reltype != OBJECT_TYPE && relkind == RELKIND_COMPOSITE_TYPE)
11590 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11591 errmsg("\"%s\" is a composite type", rv->relname),
11592 errhint("Use ALTER TYPE instead.")));
11595 * Don't allow ALTER TABLE .. SET SCHEMA on relations that can't be moved
11596 * to a different schema, such as indexes and TOAST tables.
11598 if (IsA(stmt, AlterObjectSchemaStmt) &&
11599 relkind != RELKIND_RELATION &&
11600 relkind != RELKIND_VIEW &&
11601 relkind != RELKIND_MATVIEW &&
11602 relkind != RELKIND_SEQUENCE &&
11603 relkind != RELKIND_FOREIGN_TABLE)
11605 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11606 errmsg("\"%s\" is not a table, view, materialized view, sequence, or foreign table",
11609 ReleaseSysCache(tuple);