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 bool is_view, 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.
438 * typaddress: if not null, it's set to the pg_type entry's address.
440 * Note that permissions checks are done against current user regardless of
441 * ownerId. A nonzero ownerId is used when someone is creating a relation
442 * "on behalf of" someone else, so we still want to see that the current user
443 * has permissions to do it.
445 * If successful, returns the address of the new relation.
446 * ----------------------------------------------------------------
449 DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId,
450 ObjectAddress *typaddress)
452 char relname[NAMEDATALEN];
454 List *schema = stmt->tableElts;
458 TupleDesc descriptor;
460 List *old_constraints;
464 List *cookedDefaults;
468 static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
470 ObjectAddress address;
473 * Truncate relname to appropriate length (probably a waste of time, as
474 * parser should have done this already).
476 StrNCpy(relname, stmt->relation->relname, NAMEDATALEN);
479 * Check consistency of arguments
481 if (stmt->oncommit != ONCOMMIT_NOOP
482 && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
484 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
485 errmsg("ON COMMIT can only be used on temporary tables")));
488 * Look up the namespace in which we are supposed to create the relation,
489 * check we have permission to create there, lock it against concurrent
490 * drop, and mark stmt->relation as RELPERSISTENCE_TEMP if a temporary
491 * namespace is selected.
494 RangeVarGetAndCheckCreationNamespace(stmt->relation, NoLock, NULL);
497 * Security check: disallow creating temp tables from security-restricted
498 * code. This is needed because calling code might not expect untrusted
499 * tables to appear in pg_temp at the front of its search path.
501 if (stmt->relation->relpersistence == RELPERSISTENCE_TEMP
502 && InSecurityRestrictedOperation())
504 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
505 errmsg("cannot create temporary table within security-restricted operation")));
508 * Select tablespace to use. If not specified, use default tablespace
509 * (which may in turn default to database's default).
511 if (stmt->tablespacename)
513 tablespaceId = get_tablespace_oid(stmt->tablespacename, false);
517 tablespaceId = GetDefaultTablespace(stmt->relation->relpersistence);
518 /* note InvalidOid is OK in this case */
521 /* Check permissions except when using database's default */
522 if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
526 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
528 if (aclresult != ACLCHECK_OK)
529 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
530 get_tablespace_name(tablespaceId));
533 /* In all cases disallow placing user relations in pg_global */
534 if (tablespaceId == GLOBALTABLESPACE_OID)
536 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
537 errmsg("only shared relations can be placed in pg_global tablespace")));
539 /* Identify user ID that will own the table */
540 if (!OidIsValid(ownerId))
541 ownerId = GetUserId();
544 * Parse and validate reloptions, if any.
546 reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, validnsps,
549 if (relkind == RELKIND_VIEW)
550 (void) view_reloptions(reloptions, true);
552 (void) heap_reloptions(relkind, reloptions, true);
554 if (stmt->ofTypename)
558 ofTypeId = typenameTypeId(NULL, stmt->ofTypename);
560 aclresult = pg_type_aclcheck(ofTypeId, GetUserId(), ACL_USAGE);
561 if (aclresult != ACLCHECK_OK)
562 aclcheck_error_type(aclresult, ofTypeId);
565 ofTypeId = InvalidOid;
568 * Look up inheritance ancestors and generate relation schema, including
569 * inherited attributes.
571 schema = MergeAttributes(schema, stmt->inhRelations,
572 stmt->relation->relpersistence,
573 &inheritOids, &old_constraints, &parentOidCount);
576 * Create a tuple descriptor from the relation schema. Note that this
577 * deals with column names, types, and NOT NULL constraints, but not
578 * default values or CHECK constraints; we handle those below.
580 descriptor = BuildDescForRelation(schema);
582 localHasOids = interpretOidsOption(stmt->options,
583 (relkind == RELKIND_RELATION));
584 descriptor->tdhasoid = (localHasOids || parentOidCount > 0);
587 * Find columns with default values and prepare for insertion of the
588 * defaults. Pre-cooked (that is, inherited) defaults go into a list of
589 * CookedConstraint structs that we'll pass to heap_create_with_catalog,
590 * while raw defaults go into a list of RawColumnDefault structs that will
591 * be processed by AddRelationNewConstraints. (We can't deal with raw
592 * expressions until we can do transformExpr.)
594 * We can set the atthasdef flags now in the tuple descriptor; this just
595 * saves StoreAttrDefault from having to do an immediate update of the
599 cookedDefaults = NIL;
602 foreach(listptr, schema)
604 ColumnDef *colDef = lfirst(listptr);
608 if (colDef->raw_default != NULL)
610 RawColumnDefault *rawEnt;
612 Assert(colDef->cooked_default == NULL);
614 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
615 rawEnt->attnum = attnum;
616 rawEnt->raw_default = colDef->raw_default;
617 rawDefaults = lappend(rawDefaults, rawEnt);
618 descriptor->attrs[attnum - 1]->atthasdef = true;
620 else if (colDef->cooked_default != NULL)
622 CookedConstraint *cooked;
624 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
625 cooked->contype = CONSTR_DEFAULT;
627 cooked->attnum = attnum;
628 cooked->expr = colDef->cooked_default;
629 cooked->skip_validation = false;
630 cooked->is_local = true; /* not used for defaults */
631 cooked->inhcount = 0; /* ditto */
632 cooked->is_no_inherit = false;
633 cookedDefaults = lappend(cookedDefaults, cooked);
634 descriptor->attrs[attnum - 1]->atthasdef = true;
639 * Create the relation. Inherited defaults and constraints are passed in
640 * for immediate handling --- since they don't need parsing, they can be
641 * stored immediately.
643 relationId = heap_create_with_catalog(relname,
651 list_concat(cookedDefaults,
654 stmt->relation->relpersistence,
662 allowSystemTableMods,
666 /* Store inheritance information for new rel. */
667 StoreCatalogInheritance(relationId, inheritOids);
670 * We must bump the command counter to make the newly-created relation
671 * tuple visible for opening.
673 CommandCounterIncrement();
676 * Open the new relation and acquire exclusive lock on it. This isn't
677 * really necessary for locking out other backends (since they can't see
678 * the new rel anyway until we commit), but it keeps the lock manager from
679 * complaining about deadlock risks.
681 rel = relation_open(relationId, AccessExclusiveLock);
684 * Now add any newly specified column default values and CHECK constraints
685 * to the new relation. These are passed to us in the form of raw
686 * parsetrees; we need to transform them to executable expression trees
687 * before they can be added. The most convenient way to do that is to
688 * apply the parser's transformExpr routine, but transformExpr doesn't
689 * work unless we have a pre-existing relation. So, the transformation has
690 * to be postponed to this final step of CREATE TABLE.
692 if (rawDefaults || stmt->constraints)
693 AddRelationNewConstraints(rel, rawDefaults, stmt->constraints,
696 ObjectAddressSet(address, RelationRelationId, relationId);
699 * Clean up. We keep lock on new relation (although it shouldn't be
700 * visible to anyone else anyway, until commit).
702 relation_close(rel, NoLock);
708 * Emit the right error or warning message for a "DROP" command issued on a
709 * non-existent relation
712 DropErrorMsgNonExistent(RangeVar *rel, char rightkind, bool missing_ok)
714 const struct dropmsgstrings *rentry;
716 if (rel->schemaname != NULL &&
717 !OidIsValid(LookupNamespaceNoError(rel->schemaname)))
722 (errcode(ERRCODE_UNDEFINED_SCHEMA),
723 errmsg("schema \"%s\" does not exist", rel->schemaname)));
728 (errmsg("schema \"%s\" does not exist, skipping",
734 for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
736 if (rentry->kind == rightkind)
741 (errcode(rentry->nonexistent_code),
742 errmsg(rentry->nonexistent_msg, rel->relname)));
746 ereport(NOTICE, (errmsg(rentry->skipping_msg, rel->relname)));
752 Assert(rentry->kind != '\0'); /* Should be impossible */
756 * Emit the right error message for a "DROP" command issued on a
757 * relation of the wrong type
760 DropErrorMsgWrongType(const char *relname, char wrongkind, char rightkind)
762 const struct dropmsgstrings *rentry;
763 const struct dropmsgstrings *wentry;
765 for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
766 if (rentry->kind == rightkind)
768 Assert(rentry->kind != '\0');
770 for (wentry = dropmsgstringarray; wentry->kind != '\0'; wentry++)
771 if (wentry->kind == wrongkind)
773 /* wrongkind could be something we don't have in our table... */
776 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
777 errmsg(rentry->nota_msg, relname),
778 (wentry->kind != '\0') ? errhint("%s", _(wentry->drophint_msg)) : 0));
783 * Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW,
784 * DROP MATERIALIZED VIEW, DROP FOREIGN TABLE
787 RemoveRelations(DropStmt *drop)
789 ObjectAddresses *objects;
793 LOCKMODE lockmode = AccessExclusiveLock;
795 /* DROP CONCURRENTLY uses a weaker lock, and has some restrictions */
796 if (drop->concurrent)
798 flags |= PERFORM_DELETION_CONCURRENTLY;
799 lockmode = ShareUpdateExclusiveLock;
800 Assert(drop->removeType == OBJECT_INDEX);
801 if (list_length(drop->objects) != 1)
803 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
804 errmsg("DROP INDEX CONCURRENTLY does not support dropping multiple objects")));
805 if (drop->behavior == DROP_CASCADE)
807 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
808 errmsg("DROP INDEX CONCURRENTLY does not support CASCADE")));
812 * First we identify all the relations, then we delete them in a single
813 * performMultipleDeletions() call. This is to avoid unwanted DROP
814 * RESTRICT errors if one of the relations depends on another.
817 /* Determine required relkind */
818 switch (drop->removeType)
821 relkind = RELKIND_RELATION;
825 relkind = RELKIND_INDEX;
828 case OBJECT_SEQUENCE:
829 relkind = RELKIND_SEQUENCE;
833 relkind = RELKIND_VIEW;
837 relkind = RELKIND_MATVIEW;
840 case OBJECT_FOREIGN_TABLE:
841 relkind = RELKIND_FOREIGN_TABLE;
845 elog(ERROR, "unrecognized drop object type: %d",
846 (int) drop->removeType);
847 relkind = 0; /* keep compiler quiet */
851 /* Lock and validate each relation; build a list of object addresses */
852 objects = new_object_addresses();
854 foreach(cell, drop->objects)
856 RangeVar *rel = makeRangeVarFromNameList((List *) lfirst(cell));
859 struct DropRelationCallbackState state;
862 * These next few steps are a great deal like relation_openrv, but we
863 * don't bother building a relcache entry since we don't need it.
865 * Check for shared-cache-inval messages before trying to access the
866 * relation. This is needed to cover the case where the name
867 * identifies a rel that has been dropped and recreated since the
868 * start of our transaction: if we don't flush the old syscache entry,
869 * then we'll latch onto that entry and suffer an error later.
871 AcceptInvalidationMessages();
873 /* Look up the appropriate relation using namespace search. */
874 state.relkind = relkind;
875 state.heapOid = InvalidOid;
876 state.concurrent = drop->concurrent;
877 relOid = RangeVarGetRelidExtended(rel, lockmode, true,
879 RangeVarCallbackForDropRelation,
883 if (!OidIsValid(relOid))
885 DropErrorMsgNonExistent(rel, relkind, drop->missing_ok);
889 /* OK, we're ready to delete this one */
890 obj.classId = RelationRelationId;
891 obj.objectId = relOid;
894 add_exact_object_address(&obj, objects);
897 performMultipleDeletions(objects, drop->behavior, flags);
899 free_object_addresses(objects);
903 * Before acquiring a table lock, check whether we have sufficient rights.
904 * In the case of DROP INDEX, also try to lock the table before the index.
907 RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid, Oid oldRelOid,
911 struct DropRelationCallbackState *state;
913 Form_pg_class classform;
914 LOCKMODE heap_lockmode;
916 state = (struct DropRelationCallbackState *) arg;
917 relkind = state->relkind;
918 heap_lockmode = state->concurrent ?
919 ShareUpdateExclusiveLock : AccessExclusiveLock;
922 * If we previously locked some other index's heap, and the name we're
923 * looking up no longer refers to that relation, release the now-useless
926 if (relOid != oldRelOid && OidIsValid(state->heapOid))
928 UnlockRelationOid(state->heapOid, heap_lockmode);
929 state->heapOid = InvalidOid;
932 /* Didn't find a relation, so no need for locking or permission checks. */
933 if (!OidIsValid(relOid))
936 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
937 if (!HeapTupleIsValid(tuple))
938 return; /* concurrently dropped, so nothing to do */
939 classform = (Form_pg_class) GETSTRUCT(tuple);
941 if (classform->relkind != relkind)
942 DropErrorMsgWrongType(rel->relname, classform->relkind, relkind);
944 /* Allow DROP to either table owner or schema owner */
945 if (!pg_class_ownercheck(relOid, GetUserId()) &&
946 !pg_namespace_ownercheck(classform->relnamespace, GetUserId()))
947 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
950 if (!allowSystemTableMods && IsSystemClass(relOid, classform))
952 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
953 errmsg("permission denied: \"%s\" is a system catalog",
956 ReleaseSysCache(tuple);
959 * In DROP INDEX, attempt to acquire lock on the parent table before
960 * locking the index. index_drop() will need this anyway, and since
961 * regular queries lock tables before their indexes, we risk deadlock if
962 * we do it the other way around. No error if we don't find a pg_index
963 * entry, though --- the relation may have been dropped.
965 if (relkind == RELKIND_INDEX && relOid != oldRelOid)
967 state->heapOid = IndexGetRelation(relOid, true);
968 if (OidIsValid(state->heapOid))
969 LockRelationOid(state->heapOid, heap_lockmode);
975 * Executes a TRUNCATE command.
977 * This is a multi-relation truncate. We first open and grab exclusive
978 * lock on all relations involved, checking permissions and otherwise
979 * verifying that the relation is OK for truncation. In CASCADE mode,
980 * relations having FK references to the targeted relations are automatically
981 * added to the group; in RESTRICT mode, we check that all FK references are
982 * internal to the group that's being truncated. Finally all the relations
983 * are truncated and reindexed.
986 ExecuteTruncate(TruncateStmt *stmt)
990 List *seq_relids = NIL;
992 ResultRelInfo *resultRelInfos;
993 ResultRelInfo *resultRelInfo;
994 SubTransactionId mySubid;
998 * Open, exclusive-lock, and check all the explicitly-specified relations
1000 foreach(cell, stmt->relations)
1002 RangeVar *rv = lfirst(cell);
1004 bool recurse = interpretInhOption(rv->inhOpt);
1007 rel = heap_openrv(rv, AccessExclusiveLock);
1008 myrelid = RelationGetRelid(rel);
1009 /* don't throw error for "TRUNCATE foo, foo" */
1010 if (list_member_oid(relids, myrelid))
1012 heap_close(rel, AccessExclusiveLock);
1015 truncate_check_rel(rel);
1016 rels = lappend(rels, rel);
1017 relids = lappend_oid(relids, myrelid);
1024 children = find_all_inheritors(myrelid, AccessExclusiveLock, NULL);
1026 foreach(child, children)
1028 Oid childrelid = lfirst_oid(child);
1030 if (list_member_oid(relids, childrelid))
1033 /* find_all_inheritors already got lock */
1034 rel = heap_open(childrelid, NoLock);
1035 truncate_check_rel(rel);
1036 rels = lappend(rels, rel);
1037 relids = lappend_oid(relids, childrelid);
1043 * In CASCADE mode, suck in all referencing relations as well. This
1044 * requires multiple iterations to find indirectly-dependent relations. At
1045 * each phase, we need to exclusive-lock new rels before looking for their
1046 * dependencies, else we might miss something. Also, we check each rel as
1047 * soon as we open it, to avoid a faux pas such as holding lock for a long
1048 * time on a rel we have no permissions for.
1050 if (stmt->behavior == DROP_CASCADE)
1056 newrelids = heap_truncate_find_FKs(relids);
1057 if (newrelids == NIL)
1058 break; /* nothing else to add */
1060 foreach(cell, newrelids)
1062 Oid relid = lfirst_oid(cell);
1065 rel = heap_open(relid, AccessExclusiveLock);
1067 (errmsg("truncate cascades to table \"%s\"",
1068 RelationGetRelationName(rel))));
1069 truncate_check_rel(rel);
1070 rels = lappend(rels, rel);
1071 relids = lappend_oid(relids, relid);
1077 * Check foreign key references. In CASCADE mode, this should be
1078 * unnecessary since we just pulled in all the references; but as a
1079 * cross-check, do it anyway if in an Assert-enabled build.
1081 #ifdef USE_ASSERT_CHECKING
1082 heap_truncate_check_FKs(rels, false);
1084 if (stmt->behavior == DROP_RESTRICT)
1085 heap_truncate_check_FKs(rels, false);
1089 * If we are asked to restart sequences, find all the sequences, lock them
1090 * (we need AccessExclusiveLock for ResetSequence), and check permissions.
1091 * We want to do this early since it's pointless to do all the truncation
1092 * work only to fail on sequence permissions.
1094 if (stmt->restart_seqs)
1098 Relation rel = (Relation) lfirst(cell);
1099 List *seqlist = getOwnedSequences(RelationGetRelid(rel));
1102 foreach(seqcell, seqlist)
1104 Oid seq_relid = lfirst_oid(seqcell);
1107 seq_rel = relation_open(seq_relid, AccessExclusiveLock);
1109 /* This check must match AlterSequence! */
1110 if (!pg_class_ownercheck(seq_relid, GetUserId()))
1111 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1112 RelationGetRelationName(seq_rel));
1114 seq_relids = lappend_oid(seq_relids, seq_relid);
1116 relation_close(seq_rel, NoLock);
1121 /* Prepare to catch AFTER triggers. */
1122 AfterTriggerBeginQuery();
1125 * To fire triggers, we'll need an EState as well as a ResultRelInfo for
1126 * each relation. We don't need to call ExecOpenIndices, though.
1128 estate = CreateExecutorState();
1129 resultRelInfos = (ResultRelInfo *)
1130 palloc(list_length(rels) * sizeof(ResultRelInfo));
1131 resultRelInfo = resultRelInfos;
1134 Relation rel = (Relation) lfirst(cell);
1136 InitResultRelInfo(resultRelInfo,
1138 0, /* dummy rangetable index */
1142 estate->es_result_relations = resultRelInfos;
1143 estate->es_num_result_relations = list_length(rels);
1146 * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
1147 * truncating (this is because one of them might throw an error). Also, if
1148 * we were to allow them to prevent statement execution, that would need
1149 * to be handled here.
1151 resultRelInfo = resultRelInfos;
1154 estate->es_result_relation_info = resultRelInfo;
1155 ExecBSTruncateTriggers(estate, resultRelInfo);
1160 * OK, truncate each table.
1162 mySubid = GetCurrentSubTransactionId();
1166 Relation rel = (Relation) lfirst(cell);
1169 * Normally, we need a transaction-safe truncation here. However, if
1170 * the table was either created in the current (sub)transaction or has
1171 * a new relfilenode in the current (sub)transaction, then we can just
1172 * truncate it in-place, because a rollback would cause the whole
1173 * table or the current physical file to be thrown away anyway.
1175 if (rel->rd_createSubid == mySubid ||
1176 rel->rd_newRelfilenodeSubid == mySubid)
1178 /* Immediate, non-rollbackable truncation is OK */
1179 heap_truncate_one_rel(rel);
1185 MultiXactId minmulti;
1188 * This effectively deletes all rows in the table, and may be done
1189 * in a serializable transaction. In that case we must record a
1190 * rw-conflict in to this transaction from each transaction
1191 * holding a predicate lock on the table.
1193 CheckTableForSerializableConflictIn(rel);
1195 minmulti = GetOldestMultiXactId();
1198 * Need the full transaction-safe pushups.
1200 * Create a new empty storage file for the relation, and assign it
1201 * as the relfilenode value. The old storage file is scheduled for
1202 * deletion at commit.
1204 RelationSetNewRelfilenode(rel, rel->rd_rel->relpersistence,
1205 RecentXmin, minmulti);
1206 if (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED)
1207 heap_create_init_fork(rel);
1209 heap_relid = RelationGetRelid(rel);
1210 toast_relid = rel->rd_rel->reltoastrelid;
1213 * The same for the toast table, if any.
1215 if (OidIsValid(toast_relid))
1217 rel = relation_open(toast_relid, AccessExclusiveLock);
1218 RelationSetNewRelfilenode(rel, rel->rd_rel->relpersistence,
1219 RecentXmin, minmulti);
1220 if (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED)
1221 heap_create_init_fork(rel);
1222 heap_close(rel, NoLock);
1226 * Reconstruct the indexes to match, and we're done.
1228 reindex_relation(heap_relid, REINDEX_REL_PROCESS_TOAST);
1231 pgstat_count_truncate(rel);
1235 * Restart owned sequences if we were asked to.
1237 foreach(cell, seq_relids)
1239 Oid seq_relid = lfirst_oid(cell);
1241 ResetSequence(seq_relid);
1245 * Process all AFTER STATEMENT TRUNCATE triggers.
1247 resultRelInfo = resultRelInfos;
1250 estate->es_result_relation_info = resultRelInfo;
1251 ExecASTruncateTriggers(estate, resultRelInfo);
1255 /* Handle queued AFTER triggers */
1256 AfterTriggerEndQuery(estate);
1258 /* We can clean up the EState now */
1259 FreeExecutorState(estate);
1261 /* And close the rels (can't do this while EState still holds refs) */
1264 Relation rel = (Relation) lfirst(cell);
1266 heap_close(rel, NoLock);
1271 * Check that a given rel is safe to truncate. Subroutine for ExecuteTruncate
1274 truncate_check_rel(Relation rel)
1276 AclResult aclresult;
1278 /* Only allow truncate on regular tables */
1279 if (rel->rd_rel->relkind != RELKIND_RELATION)
1281 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1282 errmsg("\"%s\" is not a table",
1283 RelationGetRelationName(rel))));
1285 /* Permissions checks */
1286 aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
1288 if (aclresult != ACLCHECK_OK)
1289 aclcheck_error(aclresult, ACL_KIND_CLASS,
1290 RelationGetRelationName(rel));
1292 if (!allowSystemTableMods && IsSystemRelation(rel))
1294 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1295 errmsg("permission denied: \"%s\" is a system catalog",
1296 RelationGetRelationName(rel))));
1299 * Don't allow truncate on temp tables of other backends ... their local
1300 * buffer manager is not going to cope.
1302 if (RELATION_IS_OTHER_TEMP(rel))
1304 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1305 errmsg("cannot truncate temporary tables of other sessions")));
1308 * Also check for active uses of the relation in the current transaction,
1309 * including open scans and pending AFTER trigger events.
1311 CheckTableNotInUse(rel, "TRUNCATE");
1316 * returns the name corresponding to a typstorage/attstorage enum value
1319 storage_name(char c)
1338 * Returns new schema given initial schema and superclasses.
1341 * 'schema' is the column/attribute definition for the table. (It's a list
1342 * of ColumnDef's.) It is destructively changed.
1343 * 'supers' is a list of names (as RangeVar nodes) of parent relations.
1344 * 'relpersistence' is a persistence type of the table.
1347 * 'supOids' receives a list of the OIDs of the parent relations.
1348 * 'supconstr' receives a list of constraints belonging to the parents,
1349 * updated as necessary to be valid for the child.
1350 * 'supOidCount' is set to the number of parents that have OID columns.
1353 * Completed schema list.
1356 * The order in which the attributes are inherited is very important.
1357 * Intuitively, the inherited attributes should come first. If a table
1358 * inherits from multiple parents, the order of those attributes are
1359 * according to the order of the parents specified in CREATE TABLE.
1361 * Here's an example:
1363 * create table person (name text, age int4, location point);
1364 * create table emp (salary int4, manager text) inherits(person);
1365 * create table student (gpa float8) inherits (person);
1366 * create table stud_emp (percent int4) inherits (emp, student);
1368 * The order of the attributes of stud_emp is:
1370 * person {1:name, 2:age, 3:location}
1372 * {6:gpa} student emp {4:salary, 5:manager}
1374 * stud_emp {7:percent}
1376 * If the same attribute name appears multiple times, then it appears
1377 * in the result table in the proper location for its first appearance.
1379 * Constraints (including NOT NULL constraints) for the child table
1380 * are the union of all relevant constraints, from both the child schema
1381 * and parent tables.
1383 * The default value for a child column is defined as:
1384 * (1) If the child schema specifies a default, that value is used.
1385 * (2) If neither the child nor any parent specifies a default, then
1386 * the column will not have a default.
1387 * (3) If conflicting defaults are inherited from different parents
1388 * (and not overridden by the child), an error is raised.
1389 * (4) Otherwise the inherited default is used.
1390 * Rule (3) is new in Postgres 7.1; in earlier releases you got a
1391 * rather arbitrary choice of which parent default to use.
1395 MergeAttributes(List *schema, List *supers, char relpersistence,
1396 List **supOids, List **supconstr, int *supOidCount)
1399 List *inhSchema = NIL;
1400 List *parentOids = NIL;
1401 List *constraints = NIL;
1402 int parentsWithOids = 0;
1403 bool have_bogus_defaults = false;
1405 static Node bogus_marker = {0}; /* marks conflicting defaults */
1408 * Check for and reject tables with too many columns. We perform this
1409 * check relatively early for two reasons: (a) we don't run the risk of
1410 * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
1411 * okay if we're processing <= 1600 columns, but could take minutes to
1412 * execute if the user attempts to create a table with hundreds of
1413 * thousands of columns.
1415 * Note that we also need to check that any we do not exceed this figure
1416 * after including columns from inherited relations.
1418 if (list_length(schema) > MaxHeapAttributeNumber)
1420 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1421 errmsg("tables can have at most %d columns",
1422 MaxHeapAttributeNumber)));
1425 * Check for duplicate names in the explicit list of attributes.
1427 * Although we might consider merging such entries in the same way that we
1428 * handle name conflicts for inherited attributes, it seems to make more
1429 * sense to assume such conflicts are errors.
1431 foreach(entry, schema)
1433 ColumnDef *coldef = lfirst(entry);
1434 ListCell *rest = lnext(entry);
1435 ListCell *prev = entry;
1437 if (coldef->typeName == NULL)
1440 * Typed table column option that does not belong to a column from
1441 * the type. This works because the columns from the type come
1442 * first in the list.
1445 (errcode(ERRCODE_UNDEFINED_COLUMN),
1446 errmsg("column \"%s\" does not exist",
1449 while (rest != NULL)
1451 ColumnDef *restdef = lfirst(rest);
1452 ListCell *next = lnext(rest); /* need to save it in case we
1455 if (strcmp(coldef->colname, restdef->colname) == 0)
1457 if (coldef->is_from_type)
1460 * merge the column options into the column from the type
1462 coldef->is_not_null = restdef->is_not_null;
1463 coldef->raw_default = restdef->raw_default;
1464 coldef->cooked_default = restdef->cooked_default;
1465 coldef->constraints = restdef->constraints;
1466 coldef->is_from_type = false;
1467 list_delete_cell(schema, rest, prev);
1471 (errcode(ERRCODE_DUPLICATE_COLUMN),
1472 errmsg("column \"%s\" specified more than once",
1481 * Scan the parents left-to-right, and merge their attributes to form a
1482 * list of inherited attributes (inhSchema). Also check to see if we need
1483 * to inherit an OID column.
1486 foreach(entry, supers)
1488 RangeVar *parent = (RangeVar *) lfirst(entry);
1490 TupleDesc tupleDesc;
1491 TupleConstr *constr;
1492 AttrNumber *newattno;
1493 AttrNumber parent_attno;
1496 * A self-exclusive lock is needed here. If two backends attempt to
1497 * add children to the same parent simultaneously, and that parent has
1498 * no pre-existing children, then both will attempt to update the
1499 * parent's relhassubclass field, leading to a "tuple concurrently
1500 * updated" error. Also, this interlocks against a concurrent ANALYZE
1501 * on the parent table, which might otherwise be attempting to clear
1502 * the parent's relhassubclass field, if its previous children were
1505 relation = heap_openrv(parent, ShareUpdateExclusiveLock);
1507 if (relation->rd_rel->relkind != RELKIND_RELATION)
1509 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1510 errmsg("inherited relation \"%s\" is not a table",
1512 /* Permanent rels cannot inherit from temporary ones */
1513 if (relpersistence != RELPERSISTENCE_TEMP &&
1514 relation->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
1516 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1517 errmsg("cannot inherit from temporary relation \"%s\"",
1520 /* If existing rel is temp, it must belong to this session */
1521 if (relation->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
1522 !relation->rd_islocaltemp)
1524 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1525 errmsg("cannot inherit from temporary relation of another session")));
1528 * We should have an UNDER permission flag for this, but for now,
1529 * demand that creator of a child table own the parent.
1531 if (!pg_class_ownercheck(RelationGetRelid(relation), GetUserId()))
1532 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1533 RelationGetRelationName(relation));
1536 * Reject duplications in the list of parents.
1538 if (list_member_oid(parentOids, RelationGetRelid(relation)))
1540 (errcode(ERRCODE_DUPLICATE_TABLE),
1541 errmsg("relation \"%s\" would be inherited from more than once",
1544 parentOids = lappend_oid(parentOids, RelationGetRelid(relation));
1546 if (relation->rd_rel->relhasoids)
1549 tupleDesc = RelationGetDescr(relation);
1550 constr = tupleDesc->constr;
1553 * newattno[] will contain the child-table attribute numbers for the
1554 * attributes of this parent table. (They are not the same for
1555 * parents after the first one, nor if we have dropped columns.)
1557 newattno = (AttrNumber *)
1558 palloc0(tupleDesc->natts * sizeof(AttrNumber));
1560 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1563 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
1564 char *attributeName = NameStr(attribute->attname);
1569 * Ignore dropped columns in the parent.
1571 if (attribute->attisdropped)
1572 continue; /* leave newattno entry as zero */
1575 * Does it conflict with some previously inherited column?
1577 exist_attno = findAttrByName(attributeName, inhSchema);
1578 if (exist_attno > 0)
1585 * Yes, try to merge the two column definitions. They must
1586 * have the same type, typmod, and collation.
1589 (errmsg("merging multiple inherited definitions of column \"%s\"",
1591 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1592 typenameTypeIdAndMod(NULL, def->typeName, &defTypeId, &deftypmod);
1593 if (defTypeId != attribute->atttypid ||
1594 deftypmod != attribute->atttypmod)
1596 (errcode(ERRCODE_DATATYPE_MISMATCH),
1597 errmsg("inherited column \"%s\" has a type conflict",
1599 errdetail("%s versus %s",
1600 TypeNameToString(def->typeName),
1601 format_type_be(attribute->atttypid))));
1602 defCollId = GetColumnDefCollation(NULL, def, defTypeId);
1603 if (defCollId != attribute->attcollation)
1605 (errcode(ERRCODE_COLLATION_MISMATCH),
1606 errmsg("inherited column \"%s\" has a collation conflict",
1608 errdetail("\"%s\" versus \"%s\"",
1609 get_collation_name(defCollId),
1610 get_collation_name(attribute->attcollation))));
1612 /* Copy storage parameter */
1613 if (def->storage == 0)
1614 def->storage = attribute->attstorage;
1615 else if (def->storage != attribute->attstorage)
1617 (errcode(ERRCODE_DATATYPE_MISMATCH),
1618 errmsg("inherited column \"%s\" has a storage parameter conflict",
1620 errdetail("%s versus %s",
1621 storage_name(def->storage),
1622 storage_name(attribute->attstorage))));
1625 /* Merge of NOT NULL constraints = OR 'em together */
1626 def->is_not_null |= attribute->attnotnull;
1627 /* Default and other constraints are handled below */
1628 newattno[parent_attno - 1] = exist_attno;
1633 * No, create a new inherited column
1635 def = makeNode(ColumnDef);
1636 def->colname = pstrdup(attributeName);
1637 def->typeName = makeTypeNameFromOid(attribute->atttypid,
1638 attribute->atttypmod);
1640 def->is_local = false;
1641 def->is_not_null = attribute->attnotnull;
1642 def->is_from_type = false;
1643 def->storage = attribute->attstorage;
1644 def->raw_default = NULL;
1645 def->cooked_default = NULL;
1646 def->collClause = NULL;
1647 def->collOid = attribute->attcollation;
1648 def->constraints = NIL;
1650 inhSchema = lappend(inhSchema, def);
1651 newattno[parent_attno - 1] = ++child_attno;
1655 * Copy default if any
1657 if (attribute->atthasdef)
1659 Node *this_default = NULL;
1660 AttrDefault *attrdef;
1663 /* Find default in constraint structure */
1664 Assert(constr != NULL);
1665 attrdef = constr->defval;
1666 for (i = 0; i < constr->num_defval; i++)
1668 if (attrdef[i].adnum == parent_attno)
1670 this_default = stringToNode(attrdef[i].adbin);
1674 Assert(this_default != NULL);
1677 * If default expr could contain any vars, we'd need to fix
1678 * 'em, but it can't; so default is ready to apply to child.
1680 * If we already had a default from some prior parent, check
1681 * to see if they are the same. If so, no problem; if not,
1682 * mark the column as having a bogus default. Below, we will
1683 * complain if the bogus default isn't overridden by the child
1686 Assert(def->raw_default == NULL);
1687 if (def->cooked_default == NULL)
1688 def->cooked_default = this_default;
1689 else if (!equal(def->cooked_default, this_default))
1691 def->cooked_default = &bogus_marker;
1692 have_bogus_defaults = true;
1698 * Now copy the CHECK constraints of this parent, adjusting attnos
1699 * using the completed newattno[] map. Identically named constraints
1700 * are merged if possible, else we throw error.
1702 if (constr && constr->num_check > 0)
1704 ConstrCheck *check = constr->check;
1707 for (i = 0; i < constr->num_check; i++)
1709 char *name = check[i].ccname;
1711 bool found_whole_row;
1713 /* ignore if the constraint is non-inheritable */
1714 if (check[i].ccnoinherit)
1717 /* Adjust Vars to match new table's column numbering */
1718 expr = map_variable_attnos(stringToNode(check[i].ccbin),
1720 newattno, tupleDesc->natts,
1724 * For the moment we have to reject whole-row variables. We
1725 * could convert them, if we knew the new table's rowtype OID,
1726 * but that hasn't been assigned yet.
1728 if (found_whole_row)
1730 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1731 errmsg("cannot convert whole-row table reference"),
1732 errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
1734 RelationGetRelationName(relation))));
1736 /* check for duplicate */
1737 if (!MergeCheckConstraint(constraints, name, expr))
1739 /* nope, this is a new one */
1740 CookedConstraint *cooked;
1742 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1743 cooked->contype = CONSTR_CHECK;
1744 cooked->name = pstrdup(name);
1745 cooked->attnum = 0; /* not used for constraints */
1746 cooked->expr = expr;
1747 cooked->skip_validation = false;
1748 cooked->is_local = false;
1749 cooked->inhcount = 1;
1750 cooked->is_no_inherit = false;
1751 constraints = lappend(constraints, cooked);
1759 * Close the parent rel, but keep our AccessShareLock on it until xact
1760 * commit. That will prevent someone else from deleting or ALTERing
1761 * the parent before the child is committed.
1763 heap_close(relation, NoLock);
1767 * If we had no inherited attributes, the result schema is just the
1768 * explicitly declared columns. Otherwise, we need to merge the declared
1769 * columns into the inherited schema list.
1771 if (inhSchema != NIL)
1773 int schema_attno = 0;
1775 foreach(entry, schema)
1777 ColumnDef *newdef = lfirst(entry);
1778 char *attributeName = newdef->colname;
1784 * Does it conflict with some previously inherited column?
1786 exist_attno = findAttrByName(attributeName, inhSchema);
1787 if (exist_attno > 0)
1798 * Yes, try to merge the two column definitions. They must
1799 * have the same type, typmod, and collation.
1801 if (exist_attno == schema_attno)
1803 (errmsg("merging column \"%s\" with inherited definition",
1807 (errmsg("moving and merging column \"%s\" with inherited definition", attributeName),
1808 errdetail("User-specified column moved to the position of the inherited column.")));
1809 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1810 typenameTypeIdAndMod(NULL, def->typeName, &defTypeId, &deftypmod);
1811 typenameTypeIdAndMod(NULL, newdef->typeName, &newTypeId, &newtypmod);
1812 if (defTypeId != newTypeId || deftypmod != newtypmod)
1814 (errcode(ERRCODE_DATATYPE_MISMATCH),
1815 errmsg("column \"%s\" has a type conflict",
1817 errdetail("%s versus %s",
1818 TypeNameToString(def->typeName),
1819 TypeNameToString(newdef->typeName))));
1820 defcollid = GetColumnDefCollation(NULL, def, defTypeId);
1821 newcollid = GetColumnDefCollation(NULL, newdef, newTypeId);
1822 if (defcollid != newcollid)
1824 (errcode(ERRCODE_COLLATION_MISMATCH),
1825 errmsg("column \"%s\" has a collation conflict",
1827 errdetail("\"%s\" versus \"%s\"",
1828 get_collation_name(defcollid),
1829 get_collation_name(newcollid))));
1831 /* Copy storage parameter */
1832 if (def->storage == 0)
1833 def->storage = newdef->storage;
1834 else if (newdef->storage != 0 && def->storage != newdef->storage)
1836 (errcode(ERRCODE_DATATYPE_MISMATCH),
1837 errmsg("column \"%s\" has a storage parameter conflict",
1839 errdetail("%s versus %s",
1840 storage_name(def->storage),
1841 storage_name(newdef->storage))));
1843 /* Mark the column as locally defined */
1844 def->is_local = true;
1845 /* Merge of NOT NULL constraints = OR 'em together */
1846 def->is_not_null |= newdef->is_not_null;
1847 /* If new def has a default, override previous default */
1848 if (newdef->raw_default != NULL)
1850 def->raw_default = newdef->raw_default;
1851 def->cooked_default = newdef->cooked_default;
1857 * No, attach new column to result schema
1859 inhSchema = lappend(inhSchema, newdef);
1866 * Check that we haven't exceeded the legal # of columns after merging
1867 * in inherited columns.
1869 if (list_length(schema) > MaxHeapAttributeNumber)
1871 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1872 errmsg("tables can have at most %d columns",
1873 MaxHeapAttributeNumber)));
1877 * If we found any conflicting parent default values, check to make sure
1878 * they were overridden by the child.
1880 if (have_bogus_defaults)
1882 foreach(entry, schema)
1884 ColumnDef *def = lfirst(entry);
1886 if (def->cooked_default == &bogus_marker)
1888 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
1889 errmsg("column \"%s\" inherits conflicting default values",
1891 errhint("To resolve the conflict, specify a default explicitly.")));
1895 *supOids = parentOids;
1896 *supconstr = constraints;
1897 *supOidCount = parentsWithOids;
1903 * MergeCheckConstraint
1904 * Try to merge an inherited CHECK constraint with previous ones
1906 * If we inherit identically-named constraints from multiple parents, we must
1907 * merge them, or throw an error if they don't have identical definitions.
1909 * constraints is a list of CookedConstraint structs for previous constraints.
1911 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
1912 * got a so-far-unique name, or throws error if conflict.
1915 MergeCheckConstraint(List *constraints, char *name, Node *expr)
1919 foreach(lc, constraints)
1921 CookedConstraint *ccon = (CookedConstraint *) lfirst(lc);
1923 Assert(ccon->contype == CONSTR_CHECK);
1925 /* Non-matching names never conflict */
1926 if (strcmp(ccon->name, name) != 0)
1929 if (equal(expr, ccon->expr))
1937 (errcode(ERRCODE_DUPLICATE_OBJECT),
1938 errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
1947 * StoreCatalogInheritance
1948 * Updates the system catalogs with proper inheritance information.
1950 * supers is a list of the OIDs of the new relation's direct ancestors.
1953 StoreCatalogInheritance(Oid relationId, List *supers)
1962 AssertArg(OidIsValid(relationId));
1968 * Store INHERITS information in pg_inherits using direct ancestors only.
1969 * Also enter dependencies on the direct ancestors, and make sure they are
1970 * marked with relhassubclass = true.
1972 * (Once upon a time, both direct and indirect ancestors were found here
1973 * and then entered into pg_ipl. Since that catalog doesn't exist
1974 * anymore, there's no need to look for indirect ancestors.)
1976 relation = heap_open(InheritsRelationId, RowExclusiveLock);
1979 foreach(entry, supers)
1981 Oid parentOid = lfirst_oid(entry);
1983 StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation);
1987 heap_close(relation, RowExclusiveLock);
1991 * Make catalog entries showing relationId as being an inheritance child
1992 * of parentOid. inhRelation is the already-opened pg_inherits catalog.
1995 StoreCatalogInheritance1(Oid relationId, Oid parentOid,
1996 int16 seqNumber, Relation inhRelation)
1998 TupleDesc desc = RelationGetDescr(inhRelation);
1999 Datum values[Natts_pg_inherits];
2000 bool nulls[Natts_pg_inherits];
2001 ObjectAddress childobject,
2006 * Make the pg_inherits entry
2008 values[Anum_pg_inherits_inhrelid - 1] = ObjectIdGetDatum(relationId);
2009 values[Anum_pg_inherits_inhparent - 1] = ObjectIdGetDatum(parentOid);
2010 values[Anum_pg_inherits_inhseqno - 1] = Int16GetDatum(seqNumber);
2012 memset(nulls, 0, sizeof(nulls));
2014 tuple = heap_form_tuple(desc, values, nulls);
2016 simple_heap_insert(inhRelation, tuple);
2018 CatalogUpdateIndexes(inhRelation, tuple);
2020 heap_freetuple(tuple);
2023 * Store a dependency too
2025 parentobject.classId = RelationRelationId;
2026 parentobject.objectId = parentOid;
2027 parentobject.objectSubId = 0;
2028 childobject.classId = RelationRelationId;
2029 childobject.objectId = relationId;
2030 childobject.objectSubId = 0;
2032 recordDependencyOn(&childobject, &parentobject, DEPENDENCY_NORMAL);
2035 * Post creation hook of this inheritance. Since object_access_hook
2036 * doesn't take multiple object identifiers, we relay oid of parent
2037 * relation using auxiliary_id argument.
2039 InvokeObjectPostAlterHookArg(InheritsRelationId,
2044 * Mark the parent as having subclasses.
2046 SetRelationHasSubclass(parentOid, true);
2050 * Look for an existing schema entry with the given name.
2052 * Returns the index (starting with 1) if attribute already exists in schema,
2056 findAttrByName(const char *attributeName, List *schema)
2063 ColumnDef *def = lfirst(s);
2065 if (strcmp(attributeName, def->colname) == 0)
2075 * SetRelationHasSubclass
2076 * Set the value of the relation's relhassubclass field in pg_class.
2078 * NOTE: caller must be holding an appropriate lock on the relation.
2079 * ShareUpdateExclusiveLock is sufficient.
2081 * NOTE: an important side-effect of this operation is that an SI invalidation
2082 * message is sent out to all backends --- including me --- causing plans
2083 * referencing the relation to be rebuilt with the new list of children.
2084 * This must happen even if we find that no change is needed in the pg_class
2088 SetRelationHasSubclass(Oid relationId, bool relhassubclass)
2090 Relation relationRelation;
2092 Form_pg_class classtuple;
2095 * Fetch a modifiable copy of the tuple, modify it, update pg_class.
2097 relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
2098 tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
2099 if (!HeapTupleIsValid(tuple))
2100 elog(ERROR, "cache lookup failed for relation %u", relationId);
2101 classtuple = (Form_pg_class) GETSTRUCT(tuple);
2103 if (classtuple->relhassubclass != relhassubclass)
2105 classtuple->relhassubclass = relhassubclass;
2106 simple_heap_update(relationRelation, &tuple->t_self, tuple);
2108 /* keep the catalog indexes up to date */
2109 CatalogUpdateIndexes(relationRelation, tuple);
2113 /* no need to change tuple, but force relcache rebuild anyway */
2114 CacheInvalidateRelcacheByTuple(tuple);
2117 heap_freetuple(tuple);
2118 heap_close(relationRelation, RowExclusiveLock);
2122 * renameatt_check - basic sanity checks before attribute rename
2125 renameatt_check(Oid myrelid, Form_pg_class classform, bool recursing)
2127 char relkind = classform->relkind;
2129 if (classform->reloftype && !recursing)
2131 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2132 errmsg("cannot rename column of typed table")));
2135 * Renaming the columns of sequences or toast tables doesn't actually
2136 * break anything from the system's point of view, since internal
2137 * references are by attnum. But it doesn't seem right to allow users to
2138 * change names that are hardcoded into the system, hence the following
2141 if (relkind != RELKIND_RELATION &&
2142 relkind != RELKIND_VIEW &&
2143 relkind != RELKIND_MATVIEW &&
2144 relkind != RELKIND_COMPOSITE_TYPE &&
2145 relkind != RELKIND_INDEX &&
2146 relkind != RELKIND_FOREIGN_TABLE)
2148 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2149 errmsg("\"%s\" is not a table, view, materialized view, composite type, index, or foreign table",
2150 NameStr(classform->relname))));
2153 * permissions checking. only the owner of a class can change its schema.
2155 if (!pg_class_ownercheck(myrelid, GetUserId()))
2156 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
2157 NameStr(classform->relname));
2158 if (!allowSystemTableMods && IsSystemClass(myrelid, classform))
2160 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2161 errmsg("permission denied: \"%s\" is a system catalog",
2162 NameStr(classform->relname))));
2166 * renameatt_internal - workhorse for renameatt
2168 * Return value is the attribute number in the 'myrelid' relation.
2171 renameatt_internal(Oid myrelid,
2172 const char *oldattname,
2173 const char *newattname,
2176 int expected_parents,
2177 DropBehavior behavior)
2179 Relation targetrelation;
2180 Relation attrelation;
2182 Form_pg_attribute attform;
2186 * Grab an exclusive lock on the target table, which we will NOT release
2187 * until end of transaction.
2189 targetrelation = relation_open(myrelid, AccessExclusiveLock);
2190 renameatt_check(myrelid, RelationGetForm(targetrelation), recursing);
2193 * if the 'recurse' flag is set then we are supposed to rename this
2194 * attribute in all classes that inherit from 'relname' (as well as in
2197 * any permissions or problems with duplicate attributes will cause the
2198 * whole transaction to abort, which is what we want -- all or nothing.
2208 * we need the number of parents for each child so that the recursive
2209 * calls to renameatt() can determine whether there are any parents
2210 * outside the inheritance hierarchy being processed.
2212 child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
2216 * find_all_inheritors does the recursive search of the inheritance
2217 * hierarchy, so all we have to do is process all of the relids in the
2218 * list that it returns.
2220 forboth(lo, child_oids, li, child_numparents)
2222 Oid childrelid = lfirst_oid(lo);
2223 int numparents = lfirst_int(li);
2225 if (childrelid == myrelid)
2227 /* note we need not recurse again */
2228 renameatt_internal(childrelid, oldattname, newattname, false, true, numparents, behavior);
2234 * If we are told not to recurse, there had better not be any child
2235 * tables; else the rename would put them out of step.
2237 * expected_parents will only be 0 if we are not already recursing.
2239 if (expected_parents == 0 &&
2240 find_inheritance_children(myrelid, NoLock) != NIL)
2242 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2243 errmsg("inherited column \"%s\" must be renamed in child tables too",
2247 /* rename attributes in typed tables of composite type */
2248 if (targetrelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
2253 child_oids = find_typed_table_dependencies(targetrelation->rd_rel->reltype,
2254 RelationGetRelationName(targetrelation),
2257 foreach(lo, child_oids)
2258 renameatt_internal(lfirst_oid(lo), oldattname, newattname, true, true, 0, behavior);
2261 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
2263 atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
2264 if (!HeapTupleIsValid(atttup))
2266 (errcode(ERRCODE_UNDEFINED_COLUMN),
2267 errmsg("column \"%s\" does not exist",
2269 attform = (Form_pg_attribute) GETSTRUCT(atttup);
2271 attnum = attform->attnum;
2274 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2275 errmsg("cannot rename system column \"%s\"",
2279 * if the attribute is inherited, forbid the renaming. if this is a
2280 * top-level call to renameatt(), then expected_parents will be 0, so the
2281 * effect of this code will be to prohibit the renaming if the attribute
2282 * is inherited at all. if this is a recursive call to renameatt(),
2283 * expected_parents will be the number of parents the current relation has
2284 * within the inheritance hierarchy being processed, so we'll prohibit the
2285 * renaming only if there are additional parents from elsewhere.
2287 if (attform->attinhcount > expected_parents)
2289 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2290 errmsg("cannot rename inherited column \"%s\"",
2293 /* new name should not already exist */
2294 check_for_column_name_collision(targetrelation, newattname);
2296 /* apply the update */
2297 namestrcpy(&(attform->attname), newattname);
2299 simple_heap_update(attrelation, &atttup->t_self, atttup);
2301 /* keep system catalog indexes current */
2302 CatalogUpdateIndexes(attrelation, atttup);
2304 InvokeObjectPostAlterHook(RelationRelationId, myrelid, attnum);
2306 heap_freetuple(atttup);
2308 heap_close(attrelation, RowExclusiveLock);
2310 relation_close(targetrelation, NoLock); /* close rel but keep lock */
2316 * Perform permissions and integrity checks before acquiring a relation lock.
2319 RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid,
2325 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
2326 if (!HeapTupleIsValid(tuple))
2327 return; /* concurrently dropped */
2328 form = (Form_pg_class) GETSTRUCT(tuple);
2329 renameatt_check(relid, form, false);
2330 ReleaseSysCache(tuple);
2334 * renameatt - changes the name of a attribute in a relation
2336 * The returned ObjectAddress is that of the renamed column.
2339 renameatt(RenameStmt *stmt)
2343 ObjectAddress address;
2345 /* lock level taken here should match renameatt_internal */
2346 relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
2347 stmt->missing_ok, false,
2348 RangeVarCallbackForRenameAttribute,
2351 if (!OidIsValid(relid))
2354 (errmsg("relation \"%s\" does not exist, skipping",
2355 stmt->relation->relname)));
2356 return InvalidObjectAddress;
2360 renameatt_internal(relid,
2361 stmt->subname, /* old att name */
2362 stmt->newname, /* new att name */
2363 interpretInhOption(stmt->relation->inhOpt), /* recursive? */
2364 false, /* recursing? */
2365 0, /* expected inhcount */
2368 ObjectAddressSubSet(address, RelationRelationId, relid, attnum);
2374 * same logic as renameatt_internal
2376 static ObjectAddress
2377 rename_constraint_internal(Oid myrelid,
2379 const char *oldconname,
2380 const char *newconname,
2383 int expected_parents)
2385 Relation targetrelation = NULL;
2388 Form_pg_constraint con;
2389 ObjectAddress address;
2391 AssertArg(!myrelid || !mytypid);
2395 constraintOid = get_domain_constraint_oid(mytypid, oldconname, false);
2399 targetrelation = relation_open(myrelid, AccessExclusiveLock);
2402 * don't tell it whether we're recursing; we allow changing typed
2405 renameatt_check(myrelid, RelationGetForm(targetrelation), false);
2407 constraintOid = get_relation_constraint_oid(myrelid, oldconname, false);
2410 tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
2411 if (!HeapTupleIsValid(tuple))
2412 elog(ERROR, "cache lookup failed for constraint %u",
2414 con = (Form_pg_constraint) GETSTRUCT(tuple);
2416 if (myrelid && con->contype == CONSTRAINT_CHECK && !con->connoinherit)
2425 child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
2428 forboth(lo, child_oids, li, child_numparents)
2430 Oid childrelid = lfirst_oid(lo);
2431 int numparents = lfirst_int(li);
2433 if (childrelid == myrelid)
2436 rename_constraint_internal(childrelid, InvalidOid, oldconname, newconname, false, true, numparents);
2441 if (expected_parents == 0 &&
2442 find_inheritance_children(myrelid, NoLock) != NIL)
2444 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2445 errmsg("inherited constraint \"%s\" must be renamed in child tables too",
2449 if (con->coninhcount > expected_parents)
2451 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2452 errmsg("cannot rename inherited constraint \"%s\"",
2457 && (con->contype == CONSTRAINT_PRIMARY
2458 || con->contype == CONSTRAINT_UNIQUE
2459 || con->contype == CONSTRAINT_EXCLUSION))
2460 /* rename the index; this renames the constraint as well */
2461 RenameRelationInternal(con->conindid, newconname, false);
2463 RenameConstraintById(constraintOid, newconname);
2465 ObjectAddressSet(address, ConstraintRelationId, constraintOid);
2467 ReleaseSysCache(tuple);
2470 relation_close(targetrelation, NoLock); /* close rel but keep lock */
2476 RenameConstraint(RenameStmt *stmt)
2478 Oid relid = InvalidOid;
2479 Oid typid = InvalidOid;
2481 if (stmt->renameType == OBJECT_DOMCONSTRAINT)
2486 typid = typenameTypeId(NULL, makeTypeNameFromNameList(stmt->object));
2487 rel = heap_open(TypeRelationId, RowExclusiveLock);
2488 tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2489 if (!HeapTupleIsValid(tup))
2490 elog(ERROR, "cache lookup failed for type %u", typid);
2491 checkDomainOwner(tup);
2492 ReleaseSysCache(tup);
2493 heap_close(rel, NoLock);
2497 /* lock level taken here should match rename_constraint_internal */
2498 relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
2500 RangeVarCallbackForRenameAttribute,
2505 rename_constraint_internal(relid, typid,
2508 stmt->relation ? interpretInhOption(stmt->relation->inhOpt) : false, /* recursive? */
2509 false, /* recursing? */
2510 0 /* expected inhcount */ );
2515 * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW/MATERIALIZED VIEW/FOREIGN TABLE
2519 RenameRelation(RenameStmt *stmt)
2522 ObjectAddress address;
2525 * Grab an exclusive lock on the target table, index, sequence, view,
2526 * materialized view, or foreign table, which we will NOT release until
2527 * end of transaction.
2529 * Lock level used here should match RenameRelationInternal, to avoid lock
2532 relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
2533 stmt->missing_ok, false,
2534 RangeVarCallbackForAlterRelation,
2537 if (!OidIsValid(relid))
2540 (errmsg("relation \"%s\" does not exist, skipping",
2541 stmt->relation->relname)));
2542 return InvalidObjectAddress;
2546 RenameRelationInternal(relid, stmt->newname, false);
2548 ObjectAddressSet(address, RelationRelationId, relid);
2554 * RenameRelationInternal - change the name of a relation
2556 * XXX - When renaming sequences, we don't bother to modify the
2557 * sequence name that is stored within the sequence itself
2558 * (this would cause problems with MVCC). In the future,
2559 * the sequence name should probably be removed from the
2560 * sequence, AFAIK there's no need for it to be there.
2563 RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal)
2565 Relation targetrelation;
2566 Relation relrelation; /* for RELATION relation */
2568 Form_pg_class relform;
2572 * Grab an exclusive lock on the target table, index, sequence, view,
2573 * materialized view, or foreign table, which we will NOT release until
2574 * end of transaction.
2576 targetrelation = relation_open(myrelid, AccessExclusiveLock);
2577 namespaceId = RelationGetNamespace(targetrelation);
2580 * Find relation's pg_class tuple, and make sure newrelname isn't in use.
2582 relrelation = heap_open(RelationRelationId, RowExclusiveLock);
2584 reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
2585 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
2586 elog(ERROR, "cache lookup failed for relation %u", myrelid);
2587 relform = (Form_pg_class) GETSTRUCT(reltup);
2589 if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
2591 (errcode(ERRCODE_DUPLICATE_TABLE),
2592 errmsg("relation \"%s\" already exists",
2596 * Update pg_class tuple with new relname. (Scribbling on reltup is OK
2597 * because it's a copy...)
2599 namestrcpy(&(relform->relname), newrelname);
2601 simple_heap_update(relrelation, &reltup->t_self, reltup);
2603 /* keep the system catalog indexes current */
2604 CatalogUpdateIndexes(relrelation, reltup);
2606 InvokeObjectPostAlterHookArg(RelationRelationId, myrelid, 0,
2607 InvalidOid, is_internal);
2609 heap_freetuple(reltup);
2610 heap_close(relrelation, RowExclusiveLock);
2613 * Also rename the associated type, if any.
2615 if (OidIsValid(targetrelation->rd_rel->reltype))
2616 RenameTypeInternal(targetrelation->rd_rel->reltype,
2617 newrelname, namespaceId);
2620 * Also rename the associated constraint, if any.
2622 if (targetrelation->rd_rel->relkind == RELKIND_INDEX)
2624 Oid constraintId = get_index_constraint(myrelid);
2626 if (OidIsValid(constraintId))
2627 RenameConstraintById(constraintId, newrelname);
2631 * Close rel, but keep exclusive lock!
2633 relation_close(targetrelation, NoLock);
2637 * Disallow ALTER TABLE (and similar commands) when the current backend has
2638 * any open reference to the target table besides the one just acquired by
2639 * the calling command; this implies there's an open cursor or active plan.
2640 * We need this check because our lock doesn't protect us against stomping
2641 * on our own foot, only other people's feet!
2643 * For ALTER TABLE, the only case known to cause serious trouble is ALTER
2644 * COLUMN TYPE, and some changes are obviously pretty benign, so this could
2645 * possibly be relaxed to only error out for certain types of alterations.
2646 * But the use-case for allowing any of these things is not obvious, so we
2647 * won't work hard at it for now.
2649 * We also reject these commands if there are any pending AFTER trigger events
2650 * for the rel. This is certainly necessary for the rewriting variants of
2651 * ALTER TABLE, because they don't preserve tuple TIDs and so the pending
2652 * events would try to fetch the wrong tuples. It might be overly cautious
2653 * in other cases, but again it seems better to err on the side of paranoia.
2655 * REINDEX calls this with "rel" referencing the index to be rebuilt; here
2656 * we are worried about active indexscans on the index. The trigger-event
2657 * check can be skipped, since we are doing no damage to the parent table.
2659 * The statement name (eg, "ALTER TABLE") is passed for use in error messages.
2662 CheckTableNotInUse(Relation rel, const char *stmt)
2664 int expected_refcnt;
2666 expected_refcnt = rel->rd_isnailed ? 2 : 1;
2667 if (rel->rd_refcnt != expected_refcnt)
2669 (errcode(ERRCODE_OBJECT_IN_USE),
2670 /* translator: first %s is a SQL command, eg ALTER TABLE */
2671 errmsg("cannot %s \"%s\" because "
2672 "it is being used by active queries in this session",
2673 stmt, RelationGetRelationName(rel))));
2675 if (rel->rd_rel->relkind != RELKIND_INDEX &&
2676 AfterTriggerPendingOnRel(RelationGetRelid(rel)))
2678 (errcode(ERRCODE_OBJECT_IN_USE),
2679 /* translator: first %s is a SQL command, eg ALTER TABLE */
2680 errmsg("cannot %s \"%s\" because "
2681 "it has pending trigger events",
2682 stmt, RelationGetRelationName(rel))));
2686 * AlterTableLookupRelation
2687 * Look up, and lock, the OID for the relation named by an alter table
2691 AlterTableLookupRelation(AlterTableStmt *stmt, LOCKMODE lockmode)
2693 return RangeVarGetRelidExtended(stmt->relation, lockmode, stmt->missing_ok, false,
2694 RangeVarCallbackForAlterRelation,
2700 * Execute ALTER TABLE, which can be a list of subcommands
2702 * ALTER TABLE is performed in three phases:
2703 * 1. Examine subcommands and perform pre-transformation checking.
2704 * 2. Update system catalogs.
2705 * 3. Scan table(s) to check new constraints, and optionally recopy
2706 * the data into new table(s).
2707 * Phase 3 is not performed unless one or more of the subcommands requires
2708 * it. The intention of this design is to allow multiple independent
2709 * updates of the table schema to be performed with only one pass over the
2712 * ATPrepCmd performs phase 1. A "work queue" entry is created for
2713 * each table to be affected (there may be multiple affected tables if the
2714 * commands traverse a table inheritance hierarchy). Also we do preliminary
2715 * validation of the subcommands, including parse transformation of those
2716 * expressions that need to be evaluated with respect to the old table
2719 * ATRewriteCatalogs performs phase 2 for each affected table. (Note that
2720 * phases 2 and 3 normally do no explicit recursion, since phase 1 already
2721 * did it --- although some subcommands have to recurse in phase 2 instead.)
2722 * Certain subcommands need to be performed before others to avoid
2723 * unnecessary conflicts; for example, DROP COLUMN should come before
2724 * ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
2725 * lists, one for each logical "pass" of phase 2.
2727 * ATRewriteTables performs phase 3 for those tables that need it.
2729 * Thanks to the magic of MVCC, an error anywhere along the way rolls back
2730 * the whole operation; we don't have to do anything special to clean up.
2732 * The caller must lock the relation, with an appropriate lock level
2733 * for the subcommands requested, using AlterTableGetLockLevel(stmt->cmds)
2734 * or higher. We pass the lock level down
2735 * so that we can apply it recursively to inherited tables. Note that the
2736 * lock level we want as we recurse might well be higher than required for
2737 * that specific subcommand. So we pass down the overall lock requirement,
2738 * rather than reassess it at lower levels.
2741 AlterTable(Oid relid, LOCKMODE lockmode, AlterTableStmt *stmt)
2745 /* Caller is required to provide an adequate lock. */
2746 rel = relation_open(relid, NoLock);
2748 CheckTableNotInUse(rel, "ALTER TABLE");
2751 rel, stmt->cmds, interpretInhOption(stmt->relation->inhOpt),
2756 * AlterTableInternal
2758 * ALTER TABLE with target specified by OID
2760 * We do not reject if the relation is already open, because it's quite
2761 * likely that one or more layers of caller have it open. That means it
2762 * is unsafe to use this entry point for alterations that could break
2763 * existing query plans. On the assumption it's not used for such, we
2764 * don't have to reject pending AFTER triggers, either.
2767 AlterTableInternal(Oid relid, List *cmds, bool recurse)
2770 LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
2772 rel = relation_open(relid, lockmode);
2774 ATController(NULL, rel, cmds, recurse, lockmode);
2778 * AlterTableGetLockLevel
2780 * Sets the overall lock level required for the supplied list of subcommands.
2781 * Policy for doing this set according to needs of AlterTable(), see
2782 * comments there for overall explanation.
2784 * Function is called before and after parsing, so it must give same
2785 * answer each time it is called. Some subcommands are transformed
2786 * into other subcommand types, so the transform must never be made to a
2787 * lower lock level than previously assigned. All transforms are noted below.
2789 * Since this is called before we lock the table we cannot use table metadata
2790 * to influence the type of lock we acquire.
2792 * There should be no lockmodes hardcoded into the subcommand functions. All
2793 * lockmode decisions for ALTER TABLE are made here only. The one exception is
2794 * ALTER TABLE RENAME which is treated as a different statement type T_RenameStmt
2795 * and does not travel through this section of code and cannot be combined with
2796 * any of the subcommands given here.
2798 * Note that Hot Standby only knows about AccessExclusiveLocks on the master
2799 * so any changes that might affect SELECTs running on standbys need to use
2800 * AccessExclusiveLocks even if you think a lesser lock would do, unless you
2801 * have a solution for that also.
2803 * Also note that pg_dump uses only an AccessShareLock, meaning that anything
2804 * that takes a lock less than AccessExclusiveLock can change object definitions
2805 * while pg_dump is running. Be careful to check that the appropriate data is
2806 * derived by pg_dump using an MVCC snapshot, rather than syscache lookups,
2807 * otherwise we might end up with an inconsistent dump that can't restore.
2810 AlterTableGetLockLevel(List *cmds)
2813 * This only works if we read catalog tables using MVCC snapshots.
2816 LOCKMODE lockmode = ShareUpdateExclusiveLock;
2820 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2821 LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
2823 switch (cmd->subtype)
2826 * These subcommands rewrite the heap, so require full locks.
2828 case AT_AddColumn: /* may rewrite heap, in some cases and visible
2830 case AT_SetTableSpace: /* must rewrite heap */
2831 case AT_AlterColumnType: /* must rewrite heap */
2832 case AT_AddOids: /* must rewrite heap */
2833 cmd_lockmode = AccessExclusiveLock;
2837 * These subcommands may require addition of toast tables. If
2838 * we add a toast table to a table currently being scanned, we
2839 * might miss data added to the new toast table by concurrent
2840 * insert transactions.
2842 case AT_SetStorage:/* may add toast tables, see
2843 * ATRewriteCatalogs() */
2844 cmd_lockmode = AccessExclusiveLock;
2848 * Removing constraints can affect SELECTs that have been
2849 * optimised assuming the constraint holds true.
2851 case AT_DropConstraint: /* as DROP INDEX */
2852 case AT_DropNotNull: /* may change some SQL plans */
2853 cmd_lockmode = AccessExclusiveLock;
2857 * Subcommands that may be visible to concurrent SELECTs
2859 case AT_DropColumn: /* change visible to SELECT */
2860 case AT_AddColumnToView: /* CREATE VIEW */
2861 case AT_DropOids: /* calls AT_DropColumn */
2862 case AT_EnableAlwaysRule: /* may change SELECT rules */
2863 case AT_EnableReplicaRule: /* may change SELECT rules */
2864 case AT_EnableRule: /* may change SELECT rules */
2865 case AT_DisableRule: /* may change SELECT rules */
2866 cmd_lockmode = AccessExclusiveLock;
2870 * Changing owner may remove implicit SELECT privileges
2872 case AT_ChangeOwner: /* change visible to SELECT */
2873 cmd_lockmode = AccessExclusiveLock;
2877 * Changing foreign table options may affect optimisation.
2879 case AT_GenericOptions:
2880 case AT_AlterColumnGenericOptions:
2881 cmd_lockmode = AccessExclusiveLock;
2885 * These subcommands affect write operations only. XXX
2886 * Theoretically, these could be ShareRowExclusiveLock.
2888 case AT_ColumnDefault:
2889 case AT_ProcessedConstraint: /* becomes AT_AddConstraint */
2890 case AT_AddConstraintRecurse: /* becomes AT_AddConstraint */
2891 case AT_ReAddConstraint: /* becomes AT_AddConstraint */
2893 case AT_EnableAlwaysTrig:
2894 case AT_EnableReplicaTrig:
2895 case AT_EnableTrigAll:
2896 case AT_EnableTrigUser:
2897 case AT_DisableTrig:
2898 case AT_DisableTrigAll:
2899 case AT_DisableTrigUser:
2900 case AT_AlterConstraint:
2901 case AT_AddIndex: /* from ADD CONSTRAINT */
2902 case AT_AddIndexConstraint:
2903 case AT_ReplicaIdentity:
2905 case AT_EnableRowSecurity:
2906 case AT_DisableRowSecurity:
2907 cmd_lockmode = AccessExclusiveLock;
2910 case AT_AddConstraint:
2911 if (IsA(cmd->def, Constraint))
2913 Constraint *con = (Constraint *) cmd->def;
2915 switch (con->contype)
2917 case CONSTR_EXCLUSION:
2918 case CONSTR_PRIMARY:
2922 * Cases essentially the same as CREATE INDEX. We
2923 * could reduce the lock strength to ShareLock if
2924 * we can work out how to allow concurrent catalog
2925 * updates. XXX Might be set down to
2926 * ShareRowExclusiveLock but requires further
2929 cmd_lockmode = AccessExclusiveLock;
2931 case CONSTR_FOREIGN:
2934 * We add triggers to both tables when we add a
2935 * Foreign Key, so the lock level must be at least
2936 * as strong as CREATE TRIGGER. XXX Might be set
2937 * down to ShareRowExclusiveLock though trigger
2938 * info is accessed by pg_get_triggerdef
2940 cmd_lockmode = AccessExclusiveLock;
2944 cmd_lockmode = AccessExclusiveLock;
2950 * These subcommands affect inheritance behaviour. Queries
2951 * started before us will continue to see the old inheritance
2952 * behaviour, while queries started after we commit will see
2953 * new behaviour. No need to prevent reads or writes to the
2954 * subtable while we hook it up though. Changing the TupDesc
2955 * may be a problem, so keep highest lock.
2958 case AT_DropInherit:
2959 cmd_lockmode = AccessExclusiveLock;
2963 * These subcommands affect implicit row type conversion. They
2964 * have affects similar to CREATE/DROP CAST on queries. don't
2965 * provide for invalidating parse trees as a result of such
2966 * changes, so we keep these at AccessExclusiveLock.
2970 cmd_lockmode = AccessExclusiveLock;
2974 * Only used by CREATE OR REPLACE VIEW which must conflict
2975 * with an SELECTs currently using the view.
2977 case AT_ReplaceRelOptions:
2978 cmd_lockmode = AccessExclusiveLock;
2982 * These subcommands affect general strategies for performance
2983 * and maintenance, though don't change the semantic results
2984 * from normal data reads and writes. Delaying an ALTER TABLE
2985 * behind currently active writes only delays the point where
2986 * the new strategy begins to take effect, so there is no
2987 * benefit in waiting. In this case the minimum restriction
2988 * applies: we don't currently allow concurrent catalog
2991 case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
2992 case AT_ClusterOn: /* Uses MVCC in getIndexes() */
2993 case AT_DropCluster: /* Uses MVCC in getIndexes() */
2994 case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
2995 case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
2996 cmd_lockmode = ShareUpdateExclusiveLock;
3000 case AT_SetUnLogged:
3001 cmd_lockmode = AccessExclusiveLock;
3004 case AT_ValidateConstraint: /* Uses MVCC in
3005 * getConstraints() */
3006 cmd_lockmode = ShareUpdateExclusiveLock;
3010 * Rel options are more complex than first appears. Options
3011 * are set here for tables, views and indexes; for historical
3012 * reasons these can all be used with ALTER TABLE, so we can't
3013 * decide between them using the basic grammar.
3015 * XXX Look in detail at each option to determine lock level,
3016 * e.g. cmd_lockmode = GetRelOptionsLockLevel((List *)
3019 case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
3021 case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
3023 cmd_lockmode = AccessExclusiveLock;
3027 elog(ERROR, "unrecognized alter table type: %d",
3028 (int) cmd->subtype);
3033 * Take the greatest lockmode from any subcommand
3035 if (cmd_lockmode > lockmode)
3036 lockmode = cmd_lockmode;
3043 * ATController provides top level control over the phases.
3045 * parsetree is passed in to allow it to be passed to event triggers
3049 ATController(AlterTableStmt *parsetree,
3050 Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
3055 /* Phase 1: preliminary examination of commands, create work queue */
3058 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3060 ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode);
3063 /* Close the relation, but keep lock until commit */
3064 relation_close(rel, NoLock);
3066 /* Phase 2: update system catalogs */
3067 ATRewriteCatalogs(&wqueue, lockmode);
3069 /* Phase 3: scan/rewrite tables as needed */
3070 ATRewriteTables(parsetree, &wqueue, lockmode);
3076 * Traffic cop for ALTER TABLE Phase 1 operations, including simple
3077 * recursion and permission checks.
3079 * Caller must have acquired appropriate lock type on relation already.
3080 * This lock should be held until commit.
3083 ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
3084 bool recurse, bool recursing, LOCKMODE lockmode)
3086 AlteredTableInfo *tab;
3087 int pass = AT_PASS_UNSET;
3089 /* Find or create work queue entry for this table */
3090 tab = ATGetQueueEntry(wqueue, rel);
3093 * Copy the original subcommand for each table. This avoids conflicts
3094 * when different child tables need to make different parse
3095 * transformations (for example, the same column may have different column
3096 * numbers in different children).
3098 cmd = copyObject(cmd);
3101 * Do permissions checking, recursion to child tables if needed, and any
3102 * additional phase-1 processing needed.
3104 switch (cmd->subtype)
3106 case AT_AddColumn: /* ADD COLUMN */
3107 ATSimplePermissions(rel,
3108 ATT_TABLE | ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
3109 ATPrepAddColumn(wqueue, rel, recurse, recursing, false, cmd,
3111 /* Recursion occurs during execution phase */
3112 pass = AT_PASS_ADD_COL;
3114 case AT_AddColumnToView: /* add column via CREATE OR REPLACE
3116 ATSimplePermissions(rel, ATT_VIEW);
3117 ATPrepAddColumn(wqueue, rel, recurse, recursing, true, cmd,
3119 /* Recursion occurs during execution phase */
3120 pass = AT_PASS_ADD_COL;
3122 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
3125 * We allow defaults on views so that INSERT into a view can have
3126 * default-ish behavior. This works because the rewriter
3127 * substitutes default values into INSERTs before it expands
3130 ATSimplePermissions(rel, ATT_TABLE | ATT_VIEW | ATT_FOREIGN_TABLE);
3131 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
3132 /* No command-specific prep needed */
3133 pass = cmd->def ? AT_PASS_ADD_CONSTR : AT_PASS_DROP;
3135 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
3136 ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
3137 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
3138 /* No command-specific prep needed */
3139 pass = AT_PASS_DROP;
3141 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
3142 ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
3143 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
3144 /* No command-specific prep needed */
3145 pass = AT_PASS_ADD_CONSTR;
3147 case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
3148 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
3149 /* Performs own permission checks */
3150 ATPrepSetStatistics(rel, cmd->name, cmd->def, lockmode);
3151 pass = AT_PASS_MISC;
3153 case AT_SetOptions: /* ALTER COLUMN SET ( options ) */
3154 case AT_ResetOptions: /* ALTER COLUMN RESET ( options ) */
3155 ATSimplePermissions(rel, ATT_TABLE | ATT_MATVIEW | ATT_INDEX | ATT_FOREIGN_TABLE);
3156 /* This command never recurses */
3157 pass = AT_PASS_MISC;
3159 case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
3160 ATSimplePermissions(rel, ATT_TABLE | ATT_MATVIEW);
3161 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
3162 /* No command-specific prep needed */
3163 pass = AT_PASS_MISC;
3165 case AT_DropColumn: /* DROP COLUMN */
3166 ATSimplePermissions(rel,
3167 ATT_TABLE | ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
3168 ATPrepDropColumn(wqueue, rel, recurse, recursing, cmd, lockmode);
3169 /* Recursion occurs during execution phase */
3170 pass = AT_PASS_DROP;
3172 case AT_AddIndex: /* ADD INDEX */
3173 ATSimplePermissions(rel, ATT_TABLE);
3174 /* This command never recurses */
3175 /* No command-specific prep needed */
3176 pass = AT_PASS_ADD_INDEX;
3178 case AT_AddConstraint: /* ADD CONSTRAINT */
3179 ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
3180 /* Recursion occurs during execution phase */
3181 /* No command-specific prep needed except saving recurse flag */
3183 cmd->subtype = AT_AddConstraintRecurse;
3184 pass = AT_PASS_ADD_CONSTR;
3186 case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
3187 ATSimplePermissions(rel, ATT_TABLE);
3188 /* This command never recurses */
3189 /* No command-specific prep needed */
3190 pass = AT_PASS_ADD_CONSTR;
3192 case AT_DropConstraint: /* DROP CONSTRAINT */
3193 ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
3194 /* Recursion occurs during execution phase */
3195 /* No command-specific prep needed except saving recurse flag */
3197 cmd->subtype = AT_DropConstraintRecurse;
3198 pass = AT_PASS_DROP;
3200 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
3201 ATSimplePermissions(rel,
3202 ATT_TABLE | ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
3203 /* Performs own recursion */
3204 ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd, lockmode);
3205 pass = AT_PASS_ALTER_TYPE;
3207 case AT_AlterColumnGenericOptions:
3208 ATSimplePermissions(rel, ATT_FOREIGN_TABLE);
3209 /* This command never recurses */
3210 /* No command-specific prep needed */
3211 pass = AT_PASS_MISC;
3213 case AT_ChangeOwner: /* ALTER OWNER */
3214 /* This command never recurses */
3215 /* No command-specific prep needed */
3216 pass = AT_PASS_MISC;
3218 case AT_ClusterOn: /* CLUSTER ON */
3219 case AT_DropCluster: /* SET WITHOUT CLUSTER */
3220 ATSimplePermissions(rel, ATT_TABLE | ATT_MATVIEW);
3221 /* These commands never recurse */
3222 /* No command-specific prep needed */
3223 pass = AT_PASS_MISC;
3225 case AT_SetLogged: /* SET LOGGED */
3226 ATSimplePermissions(rel, ATT_TABLE);
3227 tab->chgPersistence = ATPrepChangePersistence(rel, true);
3228 /* force rewrite if necessary; see comment in ATRewriteTables */
3229 if (tab->chgPersistence)
3231 tab->rewrite |= AT_REWRITE_ALTER_PERSISTENCE;
3232 tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
3234 pass = AT_PASS_MISC;
3236 case AT_SetUnLogged: /* SET UNLOGGED */
3237 ATSimplePermissions(rel, ATT_TABLE);
3238 tab->chgPersistence = ATPrepChangePersistence(rel, false);
3239 /* force rewrite if necessary; see comment in ATRewriteTables */
3240 if (tab->chgPersistence)
3242 tab->rewrite |= AT_REWRITE_ALTER_PERSISTENCE;
3243 tab->newrelpersistence = RELPERSISTENCE_UNLOGGED;
3245 pass = AT_PASS_MISC;
3247 case AT_AddOids: /* SET WITH OIDS */
3248 ATSimplePermissions(rel, ATT_TABLE);
3249 if (!rel->rd_rel->relhasoids || recursing)
3250 ATPrepAddOids(wqueue, rel, recurse, cmd, lockmode);
3251 /* Recursion occurs during execution phase */
3252 pass = AT_PASS_ADD_COL;
3254 case AT_DropOids: /* SET WITHOUT OIDS */
3255 ATSimplePermissions(rel, ATT_TABLE);
3256 /* Performs own recursion */
3257 if (rel->rd_rel->relhasoids)
3259 AlterTableCmd *dropCmd = makeNode(AlterTableCmd);
3261 dropCmd->subtype = AT_DropColumn;
3262 dropCmd->name = pstrdup("oid");
3263 dropCmd->behavior = cmd->behavior;
3264 ATPrepCmd(wqueue, rel, dropCmd, recurse, false, lockmode);
3266 pass = AT_PASS_DROP;
3268 case AT_SetTableSpace: /* SET TABLESPACE */
3269 ATSimplePermissions(rel, ATT_TABLE | ATT_MATVIEW | ATT_INDEX);
3270 /* This command never recurses */
3271 ATPrepSetTableSpace(tab, rel, cmd->name, lockmode);
3272 pass = AT_PASS_MISC; /* doesn't actually matter */
3274 case AT_SetRelOptions: /* SET (...) */
3275 case AT_ResetRelOptions: /* RESET (...) */
3276 case AT_ReplaceRelOptions: /* reset them all, then set just these */
3277 ATSimplePermissions(rel, ATT_TABLE | ATT_VIEW | ATT_MATVIEW | ATT_INDEX);
3278 /* This command never recurses */
3279 /* No command-specific prep needed */
3280 pass = AT_PASS_MISC;
3282 case AT_AddInherit: /* INHERIT */
3283 ATSimplePermissions(rel, ATT_TABLE);
3284 /* This command never recurses */
3285 ATPrepAddInherit(rel);
3286 pass = AT_PASS_MISC;
3288 case AT_AlterConstraint: /* ALTER CONSTRAINT */
3289 ATSimplePermissions(rel, ATT_TABLE);
3290 pass = AT_PASS_MISC;
3292 case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
3293 ATSimplePermissions(rel, ATT_TABLE);
3294 /* Recursion occurs during execution phase */
3295 /* No command-specific prep needed except saving recurse flag */
3297 cmd->subtype = AT_ValidateConstraintRecurse;
3298 pass = AT_PASS_MISC;
3300 case AT_ReplicaIdentity: /* REPLICA IDENTITY ... */
3301 ATSimplePermissions(rel, ATT_TABLE | ATT_MATVIEW);
3302 pass = AT_PASS_MISC;
3303 /* This command never recurses */
3304 /* No command-specific prep needed */
3306 case AT_EnableTrig: /* ENABLE TRIGGER variants */
3307 case AT_EnableAlwaysTrig:
3308 case AT_EnableReplicaTrig:
3309 case AT_EnableTrigAll:
3310 case AT_EnableTrigUser:
3311 case AT_DisableTrig: /* DISABLE TRIGGER variants */
3312 case AT_DisableTrigAll:
3313 case AT_DisableTrigUser:
3314 ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
3315 pass = AT_PASS_MISC;
3317 case AT_EnableRule: /* ENABLE/DISABLE RULE variants */
3318 case AT_EnableAlwaysRule:
3319 case AT_EnableReplicaRule:
3320 case AT_DisableRule:
3321 case AT_DropInherit: /* NO INHERIT */
3322 case AT_AddOf: /* OF */
3323 case AT_DropOf: /* NOT OF */
3324 case AT_EnableRowSecurity:
3325 case AT_DisableRowSecurity:
3326 ATSimplePermissions(rel, ATT_TABLE);
3327 /* These commands never recurse */
3328 /* No command-specific prep needed */
3329 pass = AT_PASS_MISC;
3331 case AT_GenericOptions:
3332 ATSimplePermissions(rel, ATT_FOREIGN_TABLE);
3333 /* No command-specific prep needed */
3334 pass = AT_PASS_MISC;
3337 elog(ERROR, "unrecognized alter table type: %d",
3338 (int) cmd->subtype);
3339 pass = AT_PASS_UNSET; /* keep compiler quiet */
3342 Assert(pass > AT_PASS_UNSET);
3344 /* Add the subcommand to the appropriate list for phase 2 */
3345 tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
3351 * Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
3352 * dispatched in a "safe" execution order (designed to avoid unnecessary
3356 ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode)
3362 * We process all the tables "in parallel", one pass at a time. This is
3363 * needed because we may have to propagate work from one table to another
3364 * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
3365 * re-adding of the foreign key constraint to the other table). Work can
3366 * only be propagated into later passes, however.
3368 for (pass = 0; pass < AT_NUM_PASSES; pass++)
3370 /* Go through each table that needs to be processed */
3371 foreach(ltab, *wqueue)
3373 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
3374 List *subcmds = tab->subcmds[pass];
3382 * Appropriate lock was obtained by phase 1, needn't get it again
3384 rel = relation_open(tab->relid, NoLock);
3386 foreach(lcmd, subcmds)
3387 ATExecCmd(wqueue, tab, rel, (AlterTableCmd *) lfirst(lcmd), lockmode);
3390 * After the ALTER TYPE pass, do cleanup work (this is not done in
3391 * ATExecAlterColumnType since it should be done only once if
3392 * multiple columns of a table are altered).
3394 if (pass == AT_PASS_ALTER_TYPE)
3395 ATPostAlterTypeCleanup(wqueue, tab, lockmode);
3397 relation_close(rel, NoLock);
3401 /* Check to see if a toast table must be added. */
3402 foreach(ltab, *wqueue)
3404 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
3406 if (tab->relkind == RELKIND_RELATION ||
3407 tab->relkind == RELKIND_MATVIEW)
3408 AlterTableCreateToastTable(tab->relid, (Datum) 0, lockmode);
3413 * ATExecCmd: dispatch a subcommand to appropriate execution routine
3416 ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
3417 AlterTableCmd *cmd, LOCKMODE lockmode)
3419 switch (cmd->subtype)
3421 case AT_AddColumn: /* ADD COLUMN */
3422 case AT_AddColumnToView: /* add column via CREATE OR REPLACE
3424 ATExecAddColumn(wqueue, tab, rel, (ColumnDef *) cmd->def,
3425 false, false, false, lockmode);
3427 case AT_AddColumnRecurse:
3428 ATExecAddColumn(wqueue, tab, rel, (ColumnDef *) cmd->def,
3429 false, true, false, lockmode);
3431 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
3432 ATExecColumnDefault(rel, cmd->name, cmd->def, lockmode);
3434 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
3435 ATExecDropNotNull(rel, cmd->name, lockmode);
3437 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
3438 ATExecSetNotNull(tab, rel, cmd->name, lockmode);
3440 case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
3441 ATExecSetStatistics(rel, cmd->name, cmd->def, lockmode);
3443 case AT_SetOptions: /* ALTER COLUMN SET ( options ) */
3444 ATExecSetOptions(rel, cmd->name, cmd->def, false, lockmode);
3446 case AT_ResetOptions: /* ALTER COLUMN RESET ( options ) */
3447 ATExecSetOptions(rel, cmd->name, cmd->def, true, lockmode);
3449 case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
3450 ATExecSetStorage(rel, cmd->name, cmd->def, lockmode);
3452 case AT_DropColumn: /* DROP COLUMN */
3453 ATExecDropColumn(wqueue, rel, cmd->name,
3454 cmd->behavior, false, false, cmd->missing_ok, lockmode);
3456 case AT_DropColumnRecurse: /* DROP COLUMN with recursion */
3457 ATExecDropColumn(wqueue, rel, cmd->name,
3458 cmd->behavior, true, false, cmd->missing_ok, lockmode);
3460 case AT_AddIndex: /* ADD INDEX */
3461 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false, lockmode);
3463 case AT_ReAddIndex: /* ADD INDEX */
3464 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true, lockmode);
3466 case AT_AddConstraint: /* ADD CONSTRAINT */
3467 ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
3468 false, false, lockmode);
3470 case AT_AddConstraintRecurse: /* ADD CONSTRAINT with recursion */
3471 ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
3472 true, false, lockmode);
3474 case AT_ReAddConstraint: /* Re-add pre-existing check
3476 ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
3477 false, true, lockmode);
3479 case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
3480 ATExecAddIndexConstraint(tab, rel, (IndexStmt *) cmd->def, lockmode);
3482 case AT_AlterConstraint: /* ALTER CONSTRAINT */
3483 ATExecAlterConstraint(rel, cmd, false, false, lockmode);
3485 case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
3486 ATExecValidateConstraint(rel, cmd->name, false, false, lockmode);
3488 case AT_ValidateConstraintRecurse: /* VALIDATE CONSTRAINT with
3490 ATExecValidateConstraint(rel, cmd->name, true, false, lockmode);
3492 case AT_DropConstraint: /* DROP CONSTRAINT */
3493 ATExecDropConstraint(rel, cmd->name, cmd->behavior,
3495 cmd->missing_ok, lockmode);
3497 case AT_DropConstraintRecurse: /* DROP CONSTRAINT with recursion */
3498 ATExecDropConstraint(rel, cmd->name, cmd->behavior,
3500 cmd->missing_ok, lockmode);
3502 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
3503 ATExecAlterColumnType(tab, rel, cmd, lockmode);
3505 case AT_AlterColumnGenericOptions: /* ALTER COLUMN OPTIONS */
3506 ATExecAlterColumnGenericOptions(rel, cmd->name, (List *) cmd->def, lockmode);
3508 case AT_ChangeOwner: /* ALTER OWNER */
3509 ATExecChangeOwner(RelationGetRelid(rel),
3510 get_rolespec_oid(cmd->newowner, false),
3513 case AT_ClusterOn: /* CLUSTER ON */
3514 ATExecClusterOn(rel, cmd->name, lockmode);
3516 case AT_DropCluster: /* SET WITHOUT CLUSTER */
3517 ATExecDropCluster(rel, lockmode);
3519 case AT_SetLogged: /* SET LOGGED */
3520 case AT_SetUnLogged: /* SET UNLOGGED */
3522 case AT_AddOids: /* SET WITH OIDS */
3523 /* Use the ADD COLUMN code, unless prep decided to do nothing */
3524 if (cmd->def != NULL)
3525 ATExecAddColumn(wqueue, tab, rel, (ColumnDef *) cmd->def,
3526 true, false, false, lockmode);
3528 case AT_AddOidsRecurse: /* SET WITH OIDS */
3529 /* Use the ADD COLUMN code, unless prep decided to do nothing */
3530 if (cmd->def != NULL)
3531 ATExecAddColumn(wqueue, tab, rel, (ColumnDef *) cmd->def,
3532 true, true, false, lockmode);
3534 case AT_DropOids: /* SET WITHOUT OIDS */
3537 * Nothing to do here; we'll have generated a DropColumn
3538 * subcommand to do the real work
3541 case AT_SetTableSpace: /* SET TABLESPACE */
3544 * Nothing to do here; Phase 3 does the work
3547 case AT_SetRelOptions: /* SET (...) */
3548 case AT_ResetRelOptions: /* RESET (...) */
3549 case AT_ReplaceRelOptions: /* replace entire option list */
3550 ATExecSetRelOptions(rel, (List *) cmd->def, cmd->subtype, lockmode);
3552 case AT_EnableTrig: /* ENABLE TRIGGER name */
3553 ATExecEnableDisableTrigger(rel, cmd->name,
3554 TRIGGER_FIRES_ON_ORIGIN, false, lockmode);
3556 case AT_EnableAlwaysTrig: /* ENABLE ALWAYS TRIGGER name */
3557 ATExecEnableDisableTrigger(rel, cmd->name,
3558 TRIGGER_FIRES_ALWAYS, false, lockmode);
3560 case AT_EnableReplicaTrig: /* ENABLE REPLICA TRIGGER name */
3561 ATExecEnableDisableTrigger(rel, cmd->name,
3562 TRIGGER_FIRES_ON_REPLICA, false, lockmode);
3564 case AT_DisableTrig: /* DISABLE TRIGGER name */
3565 ATExecEnableDisableTrigger(rel, cmd->name,
3566 TRIGGER_DISABLED, false, lockmode);
3568 case AT_EnableTrigAll: /* ENABLE TRIGGER ALL */
3569 ATExecEnableDisableTrigger(rel, NULL,
3570 TRIGGER_FIRES_ON_ORIGIN, false, lockmode);
3572 case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
3573 ATExecEnableDisableTrigger(rel, NULL,
3574 TRIGGER_DISABLED, false, lockmode);
3576 case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
3577 ATExecEnableDisableTrigger(rel, NULL,
3578 TRIGGER_FIRES_ON_ORIGIN, true, lockmode);
3580 case AT_DisableTrigUser: /* DISABLE TRIGGER USER */
3581 ATExecEnableDisableTrigger(rel, NULL,
3582 TRIGGER_DISABLED, true, lockmode);
3585 case AT_EnableRule: /* ENABLE RULE name */
3586 ATExecEnableDisableRule(rel, cmd->name,
3587 RULE_FIRES_ON_ORIGIN, lockmode);
3589 case AT_EnableAlwaysRule: /* ENABLE ALWAYS RULE name */
3590 ATExecEnableDisableRule(rel, cmd->name,
3591 RULE_FIRES_ALWAYS, lockmode);
3593 case AT_EnableReplicaRule: /* ENABLE REPLICA RULE name */
3594 ATExecEnableDisableRule(rel, cmd->name,
3595 RULE_FIRES_ON_REPLICA, lockmode);
3597 case AT_DisableRule: /* DISABLE RULE name */
3598 ATExecEnableDisableRule(rel, cmd->name,
3599 RULE_DISABLED, lockmode);
3603 ATExecAddInherit(rel, (RangeVar *) cmd->def, lockmode);
3605 case AT_DropInherit:
3606 ATExecDropInherit(rel, (RangeVar *) cmd->def, lockmode);
3609 ATExecAddOf(rel, (TypeName *) cmd->def, lockmode);
3612 ATExecDropOf(rel, lockmode);
3614 case AT_ReplicaIdentity:
3615 ATExecReplicaIdentity(rel, (ReplicaIdentityStmt *) cmd->def, lockmode);
3617 case AT_EnableRowSecurity:
3618 ATExecEnableRowSecurity(rel);
3620 case AT_DisableRowSecurity:
3621 ATExecDisableRowSecurity(rel);
3623 case AT_GenericOptions:
3624 ATExecGenericOptions(rel, (List *) cmd->def);
3627 elog(ERROR, "unrecognized alter table type: %d",
3628 (int) cmd->subtype);
3633 * Bump the command counter to ensure the next subcommand in the sequence
3634 * can see the changes so far
3636 CommandCounterIncrement();
3640 * ATRewriteTables: ALTER TABLE phase 3
3643 ATRewriteTables(AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode)
3647 /* Go through each table that needs to be checked or rewritten */
3648 foreach(ltab, *wqueue)
3650 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
3652 /* Foreign tables have no storage. */
3653 if (tab->relkind == RELKIND_FOREIGN_TABLE)
3657 * If we change column data types or add/remove OIDs, the operation
3658 * has to be propagated to tables that use this table's rowtype as a
3659 * column type. tab->newvals will also be non-NULL in the case where
3660 * we're adding a column with a default. We choose to forbid that
3661 * case as well, since composite types might eventually support
3664 * (Eventually we'll probably need to check for composite type
3665 * dependencies even when we're just scanning the table without a
3666 * rewrite, but at the moment a composite type does not enforce any
3667 * constraints, so it's not necessary/appropriate to enforce them just
3670 if (tab->newvals != NIL || tab->rewrite > 0)
3674 rel = heap_open(tab->relid, NoLock);
3675 find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
3676 heap_close(rel, NoLock);
3680 * We only need to rewrite the table if at least one column needs to
3681 * be recomputed, we are adding/removing the OID column, or we are
3682 * changing its persistence.
3684 * There are two reasons for requiring a rewrite when changing
3685 * persistence: on one hand, we need to ensure that the buffers
3686 * belonging to each of the two relations are marked with or without
3687 * BM_PERMANENT properly. On the other hand, since rewriting creates
3688 * and assigns a new relfilenode, we automatically create or drop an
3689 * init fork for the relation as appropriate.
3691 if (tab->rewrite > 0)
3693 /* Build a temporary relation and copy data */
3699 OldHeap = heap_open(tab->relid, NoLock);
3702 * We don't support rewriting of system catalogs; there are too
3703 * many corner cases and too little benefit. In particular this
3704 * is certainly not going to work for mapped catalogs.
3706 if (IsSystemRelation(OldHeap))
3708 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3709 errmsg("cannot rewrite system relation \"%s\"",
3710 RelationGetRelationName(OldHeap))));
3712 if (RelationIsUsedAsCatalogTable(OldHeap))
3714 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3715 errmsg("cannot rewrite table \"%s\" used as a catalog table",
3716 RelationGetRelationName(OldHeap))));
3719 * Don't allow rewrite on temp tables of other backends ... their
3720 * local buffer manager is not going to cope.
3722 if (RELATION_IS_OTHER_TEMP(OldHeap))
3724 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3725 errmsg("cannot rewrite temporary tables of other sessions")));
3728 * Select destination tablespace (same as original unless user
3729 * requested a change)
3731 if (tab->newTableSpace)
3732 NewTableSpace = tab->newTableSpace;
3734 NewTableSpace = OldHeap->rd_rel->reltablespace;
3737 * Select persistence of transient table (same as original unless
3738 * user requested a change)
3740 persistence = tab->chgPersistence ?
3741 tab->newrelpersistence : OldHeap->rd_rel->relpersistence;
3743 heap_close(OldHeap, NoLock);
3746 * Fire off an Event Trigger now, before actually rewriting the
3749 * We don't support Event Trigger for nested commands anywhere,
3750 * here included, and parsetree is given NULL when coming from
3751 * AlterTableInternal.
3753 * And fire it only once.
3756 EventTriggerTableRewrite((Node *)parsetree,
3761 * Create transient table that will receive the modified data.
3763 * Ensure it is marked correctly as logged or unlogged. We have
3764 * to do this here so that buffers for the new relfilenode will
3765 * have the right persistence set, and at the same time ensure
3766 * that the original filenode's buffers will get read in with the
3767 * correct setting (i.e. the original one). Otherwise a rollback
3768 * after the rewrite would possibly result with buffers for the
3769 * original filenode having the wrong persistence setting.
3771 * NB: This relies on swap_relation_files() also swapping the
3772 * persistence. That wouldn't work for pg_class, but that can't be
3775 OIDNewHeap = make_new_heap(tab->relid, NewTableSpace, persistence,
3779 * Copy the heap data into the new table with the desired
3780 * modifications, and test the current data within the table
3781 * against new constraints generated by ALTER TABLE commands.
3783 ATRewriteTable(tab, OIDNewHeap, lockmode);
3786 * Swap the physical files of the old and new heaps, then rebuild
3787 * indexes and discard the old heap. We can use RecentXmin for
3788 * the table's new relfrozenxid because we rewrote all the tuples
3789 * in ATRewriteTable, so no older Xid remains in the table. Also,
3790 * we never try to swap toast tables by content, since we have no
3791 * interest in letting this code work on system catalogs.
3793 finish_heap_swap(tab->relid, OIDNewHeap,
3795 !OidIsValid(tab->newTableSpace),
3797 ReadNextMultiXactId(),
3803 * Test the current data within the table against new constraints
3804 * generated by ALTER TABLE commands, but don't rebuild data.
3806 if (tab->constraints != NIL || tab->new_notnull)
3807 ATRewriteTable(tab, InvalidOid, lockmode);
3810 * If we had SET TABLESPACE but no reason to reconstruct tuples,
3811 * just do a block-by-block copy.
3813 if (tab->newTableSpace)
3814 ATExecSetTableSpace(tab->relid, tab->newTableSpace, lockmode);
3819 * Foreign key constraints are checked in a final pass, since (a) it's
3820 * generally best to examine each one separately, and (b) it's at least
3821 * theoretically possible that we have changed both relations of the
3822 * foreign key, and we'd better have finished both rewrites before we try
3823 * to read the tables.
3825 foreach(ltab, *wqueue)
3827 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
3828 Relation rel = NULL;
3831 foreach(lcon, tab->constraints)
3833 NewConstraint *con = lfirst(lcon);
3835 if (con->contype == CONSTR_FOREIGN)
3837 Constraint *fkconstraint = (Constraint *) con->qual;
3842 /* Long since locked, no need for another */
3843 rel = heap_open(tab->relid, NoLock);
3846 refrel = heap_open(con->refrelid, RowShareLock);
3848 validateForeignKeyConstraint(fkconstraint->conname, rel, refrel,
3853 * No need to mark the constraint row as validated, we did
3854 * that when we inserted the row earlier.
3857 heap_close(refrel, NoLock);
3862 heap_close(rel, NoLock);
3867 * ATRewriteTable: scan or rewrite one table
3869 * OIDNewHeap is InvalidOid if we don't need to rewrite
3872 ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap, LOCKMODE lockmode)
3876 TupleDesc oldTupDesc;
3877 TupleDesc newTupDesc;
3878 bool needscan = false;
3879 List *notnull_attrs;
3884 BulkInsertState bistate;
3888 * Open the relation(s). We have surely already locked the existing
3891 oldrel = heap_open(tab->relid, NoLock);
3892 oldTupDesc = tab->oldDesc;
3893 newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
3895 if (OidIsValid(OIDNewHeap))
3896 newrel = heap_open(OIDNewHeap, lockmode);
3901 * Prepare a BulkInsertState and options for heap_insert. Because we're
3902 * building a new heap, we can skip WAL-logging and fsync it to disk at
3903 * the end instead (unless WAL-logging is required for archiving or
3904 * streaming replication). The FSM is empty too, so don't bother using it.
3908 mycid = GetCurrentCommandId(true);
3909 bistate = GetBulkInsertState();
3911 hi_options = HEAP_INSERT_SKIP_FSM;
3912 if (!XLogIsNeeded())
3913 hi_options |= HEAP_INSERT_SKIP_WAL;
3917 /* keep compiler quiet about using these uninitialized */
3924 * Generate the constraint and default execution states
3927 estate = CreateExecutorState();
3929 /* Build the needed expression execution states */
3930 foreach(l, tab->constraints)
3932 NewConstraint *con = lfirst(l);
3934 switch (con->contype)
3938 con->qualstate = (List *)
3939 ExecPrepareExpr((Expr *) con->qual, estate);
3941 case CONSTR_FOREIGN:
3942 /* Nothing to do here */
3945 elog(ERROR, "unrecognized constraint type: %d",
3946 (int) con->contype);
3950 foreach(l, tab->newvals)
3952 NewColumnValue *ex = lfirst(l);
3954 /* expr already planned */
3955 ex->exprstate = ExecInitExpr((Expr *) ex->expr, NULL);
3958 notnull_attrs = NIL;
3959 if (newrel || tab->new_notnull)
3962 * If we are rebuilding the tuples OR if we added any new NOT NULL
3963 * constraints, check all not-null constraints. This is a bit of
3964 * overkill but it minimizes risk of bugs, and heap_attisnull is a
3965 * pretty cheap test anyway.
3967 for (i = 0; i < newTupDesc->natts; i++)
3969 if (newTupDesc->attrs[i]->attnotnull &&
3970 !newTupDesc->attrs[i]->attisdropped)
3971 notnull_attrs = lappend_int(notnull_attrs, i);
3977 if (newrel || needscan)
3979 ExprContext *econtext;
3982 TupleTableSlot *oldslot;
3983 TupleTableSlot *newslot;
3986 MemoryContext oldCxt;
3987 List *dropped_attrs = NIL;
3993 (errmsg("rewriting table \"%s\"",
3994 RelationGetRelationName(oldrel))));
3997 (errmsg("verifying table \"%s\"",
3998 RelationGetRelationName(oldrel))));
4003 * All predicate locks on the tuples or pages are about to be made
4004 * invalid, because we move tuples around. Promote them to
4007 TransferPredicateLocksToHeapRelation(oldrel);
4010 econtext = GetPerTupleExprContext(estate);
4013 * Make tuple slots for old and new tuples. Note that even when the
4014 * tuples are the same, the tupDescs might not be (consider ADD COLUMN
4015 * without a default).
4017 oldslot = MakeSingleTupleTableSlot(oldTupDesc);
4018 newslot = MakeSingleTupleTableSlot(newTupDesc);
4020 /* Preallocate values/isnull arrays */
4021 i = Max(newTupDesc->natts, oldTupDesc->natts);
4022 values = (Datum *) palloc(i * sizeof(Datum));
4023 isnull = (bool *) palloc(i * sizeof(bool));
4024 memset(values, 0, i * sizeof(Datum));
4025 memset(isnull, true, i * sizeof(bool));
4028 * Any attributes that are dropped according to the new tuple
4029 * descriptor can be set to NULL. We precompute the list of dropped
4030 * attributes to avoid needing to do so in the per-tuple loop.
4032 for (i = 0; i < newTupDesc->natts; i++)
4034 if (newTupDesc->attrs[i]->attisdropped)
4035 dropped_attrs = lappend_int(dropped_attrs, i);
4039 * Scan through the rows, generating a new row if needed and then
4040 * checking all the constraints.
4042 snapshot = RegisterSnapshot(GetLatestSnapshot());
4043 scan = heap_beginscan(oldrel, snapshot, 0, NULL);
4046 * Switch to per-tuple memory context and reset it for each tuple
4047 * produced, so we don't leak memory.
4049 oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
4051 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
4053 if (tab->rewrite > 0)
4055 Oid tupOid = InvalidOid;
4057 /* Extract data from old tuple */
4058 heap_deform_tuple(tuple, oldTupDesc, values, isnull);
4059 if (oldTupDesc->tdhasoid)
4060 tupOid = HeapTupleGetOid(tuple);
4062 /* Set dropped attributes to null in new tuple */
4063 foreach(lc, dropped_attrs)
4064 isnull[lfirst_int(lc)] = true;
4067 * Process supplied expressions to replace selected columns.
4068 * Expression inputs come from the old tuple.
4070 ExecStoreTuple(tuple, oldslot, InvalidBuffer, false);
4071 econtext->ecxt_scantuple = oldslot;
4073 foreach(l, tab->newvals)
4075 NewColumnValue *ex = lfirst(l);
4077 values[ex->attnum - 1] = ExecEvalExpr(ex->exprstate,
4079 &isnull[ex->attnum - 1],
4084 * Form the new tuple. Note that we don't explicitly pfree it,
4085 * since the per-tuple memory context will be reset shortly.
4087 tuple = heap_form_tuple(newTupDesc, values, isnull);
4089 /* Preserve OID, if any */
4090 if (newTupDesc->tdhasoid)
4091 HeapTupleSetOid(tuple, tupOid);
4094 * Constraints might reference the tableoid column, so
4095 * initialize t_tableOid before evaluating them.
4097 tuple->t_tableOid = RelationGetRelid(oldrel);
4100 /* Now check any constraints on the possibly-changed tuple */
4101 ExecStoreTuple(tuple, newslot, InvalidBuffer, false);
4102 econtext->ecxt_scantuple = newslot;
4104 foreach(l, notnull_attrs)
4106 int attn = lfirst_int(l);
4108 if (heap_attisnull(tuple, attn + 1))
4110 (errcode(ERRCODE_NOT_NULL_VIOLATION),
4111 errmsg("column \"%s\" contains null values",
4112 NameStr(newTupDesc->attrs[attn]->attname)),
4113 errtablecol(oldrel, attn + 1)));
4116 foreach(l, tab->constraints)
4118 NewConstraint *con = lfirst(l);
4120 switch (con->contype)
4123 if (!ExecQual(con->qualstate, econtext, true))
4125 (errcode(ERRCODE_CHECK_VIOLATION),
4126 errmsg("check constraint \"%s\" is violated by some row",
4128 errtableconstraint(oldrel, con->name)));
4130 case CONSTR_FOREIGN:
4131 /* Nothing to do here */
4134 elog(ERROR, "unrecognized constraint type: %d",
4135 (int) con->contype);
4139 /* Write the tuple out to the new relation */
4141 heap_insert(newrel, tuple, mycid, hi_options, bistate);
4143 ResetExprContext(econtext);
4145 CHECK_FOR_INTERRUPTS();
4148 MemoryContextSwitchTo(oldCxt);
4150 UnregisterSnapshot(snapshot);
4152 ExecDropSingleTupleTableSlot(oldslot);
4153 ExecDropSingleTupleTableSlot(newslot);
4156 FreeExecutorState(estate);
4158 heap_close(oldrel, NoLock);
4161 FreeBulkInsertState(bistate);
4163 /* If we skipped writing WAL, then we need to sync the heap. */
4164 if (hi_options & HEAP_INSERT_SKIP_WAL)
4167 heap_close(newrel, NoLock);
4172 * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
4174 static AlteredTableInfo *
4175 ATGetQueueEntry(List **wqueue, Relation rel)
4177 Oid relid = RelationGetRelid(rel);
4178 AlteredTableInfo *tab;
4181 foreach(ltab, *wqueue)
4183 tab = (AlteredTableInfo *) lfirst(ltab);
4184 if (tab->relid == relid)
4189 * Not there, so add it. Note that we make a copy of the relation's
4190 * existing descriptor before anything interesting can happen to it.
4192 tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
4194 tab->relkind = rel->rd_rel->relkind;
4195 tab->oldDesc = CreateTupleDescCopy(RelationGetDescr(rel));
4196 tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
4197 tab->chgPersistence = false;
4199 *wqueue = lappend(*wqueue, tab);
4205 * ATSimplePermissions
4207 * - Ensure that it is a relation (or possibly a view)
4208 * - Ensure this user is the owner
4209 * - Ensure that it is not a system table
4212 ATSimplePermissions(Relation rel, int allowed_targets)
4216 switch (rel->rd_rel->relkind)
4218 case RELKIND_RELATION:
4219 actual_target = ATT_TABLE;
4222 actual_target = ATT_VIEW;
4224 case RELKIND_MATVIEW:
4225 actual_target = ATT_MATVIEW;
4228 actual_target = ATT_INDEX;
4230 case RELKIND_COMPOSITE_TYPE:
4231 actual_target = ATT_COMPOSITE_TYPE;
4233 case RELKIND_FOREIGN_TABLE:
4234 actual_target = ATT_FOREIGN_TABLE;
4241 /* Wrong target type? */
4242 if ((actual_target & allowed_targets) == 0)
4243 ATWrongRelkindError(rel, allowed_targets);
4245 /* Permissions checks */
4246 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
4247 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
4248 RelationGetRelationName(rel));
4250 if (!allowSystemTableMods && IsSystemRelation(rel))
4252 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4253 errmsg("permission denied: \"%s\" is a system catalog",
4254 RelationGetRelationName(rel))));
4258 * ATWrongRelkindError
4260 * Throw an error when a relation has been determined to be of the wrong
4264 ATWrongRelkindError(Relation rel, int allowed_targets)
4268 switch (allowed_targets)
4271 msg = _("\"%s\" is not a table");
4273 case ATT_TABLE | ATT_VIEW:
4274 msg = _("\"%s\" is not a table or view");
4276 case ATT_TABLE | ATT_VIEW | ATT_MATVIEW | ATT_INDEX:
4277 msg = _("\"%s\" is not a table, view, materialized view, or index");
4279 case ATT_TABLE | ATT_MATVIEW:
4280 msg = _("\"%s\" is not a table or materialized view");
4282 case ATT_TABLE | ATT_MATVIEW | ATT_INDEX:
4283 msg = _("\"%s\" is not a table, materialized view, or index");
4285 case ATT_TABLE | ATT_FOREIGN_TABLE:
4286 msg = _("\"%s\" is not a table or foreign table");
4288 case ATT_TABLE | ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE:
4289 msg = _("\"%s\" is not a table, composite type, or foreign table");
4291 case ATT_TABLE | ATT_MATVIEW | ATT_INDEX | ATT_FOREIGN_TABLE:
4292 msg = _("\"%s\" is not a table, materialized view, composite type, or foreign table");
4295 msg = _("\"%s\" is not a view");
4297 case ATT_FOREIGN_TABLE:
4298 msg = _("\"%s\" is not a foreign table");
4301 /* shouldn't get here, add all necessary cases above */
4302 msg = _("\"%s\" is of the wrong type");
4307 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4308 errmsg(msg, RelationGetRelationName(rel))));
4314 * Simple table recursion sufficient for most ALTER TABLE operations.
4315 * All direct and indirect children are processed in an unspecified order.
4316 * Note that if a child inherits from the original table via multiple
4317 * inheritance paths, it will be visited just once.
4320 ATSimpleRecursion(List **wqueue, Relation rel,
4321 AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode)
4324 * Propagate to children if desired. Non-table relations never have
4325 * children, so no need to search in that case.
4327 if (recurse && rel->rd_rel->relkind == RELKIND_RELATION)
4329 Oid relid = RelationGetRelid(rel);
4333 children = find_all_inheritors(relid, lockmode, NULL);
4336 * find_all_inheritors does the recursive search of the inheritance
4337 * hierarchy, so all we have to do is process all of the relids in the
4338 * list that it returns.
4340 foreach(child, children)
4342 Oid childrelid = lfirst_oid(child);
4345 if (childrelid == relid)
4347 /* find_all_inheritors already got lock */
4348 childrel = relation_open(childrelid, NoLock);
4349 CheckTableNotInUse(childrel, "ALTER TABLE");
4350 ATPrepCmd(wqueue, childrel, cmd, false, true, lockmode);
4351 relation_close(childrel, NoLock);
4357 * ATTypedTableRecursion
4359 * Propagate ALTER TYPE operations to the typed tables of that type.
4360 * Also check the RESTRICT/CASCADE behavior. Given CASCADE, also permit
4361 * recursion to inheritance children of the typed tables.
4364 ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
4370 Assert(rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
4372 children = find_typed_table_dependencies(rel->rd_rel->reltype,
4373 RelationGetRelationName(rel),
4376 foreach(child, children)
4378 Oid childrelid = lfirst_oid(child);
4381 childrel = relation_open(childrelid, lockmode);
4382 CheckTableNotInUse(childrel, "ALTER TABLE");
4383 ATPrepCmd(wqueue, childrel, cmd, true, true, lockmode);
4384 relation_close(childrel, NoLock);
4390 * find_composite_type_dependencies
4392 * Check to see if a composite type is being used as a column in some
4393 * other table (possibly nested several levels deep in composite types!).
4394 * Eventually, we'd like to propagate the check or rewrite operation
4395 * into other such tables, but for now, just error out if we find any.
4397 * Caller should provide either a table name or a type name (not both) to
4398 * report in the error message, if any.
4400 * We assume that functions and views depending on the type are not reasons
4401 * to reject the ALTER. (How safe is this really?)
4404 find_composite_type_dependencies(Oid typeOid, Relation origRelation,
4405 const char *origTypeName)
4409 SysScanDesc depScan;
4414 * We scan pg_depend to find those things that depend on the rowtype. (We
4415 * assume we can ignore refobjsubid for a rowtype.)
4417 depRel = heap_open(DependRelationId, AccessShareLock);
4419 ScanKeyInit(&key[0],
4420 Anum_pg_depend_refclassid,
4421 BTEqualStrategyNumber, F_OIDEQ,
4422 ObjectIdGetDatum(TypeRelationId));
4423 ScanKeyInit(&key[1],
4424 Anum_pg_depend_refobjid,
4425 BTEqualStrategyNumber, F_OIDEQ,
4426 ObjectIdGetDatum(typeOid));
4428 depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
4431 while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
4433 Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
4435 Form_pg_attribute att;
4437 /* Ignore dependees that aren't user columns of relations */
4438 /* (we assume system columns are never of rowtypes) */
4439 if (pg_depend->classid != RelationRelationId ||
4440 pg_depend->objsubid <= 0)
4443 rel = relation_open(pg_depend->objid, AccessShareLock);
4444 att = rel->rd_att->attrs[pg_depend->objsubid - 1];
4446 if (rel->rd_rel->relkind == RELKIND_RELATION ||
4447 rel->rd_rel->relkind == RELKIND_MATVIEW)
4451 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4452 errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
4454 RelationGetRelationName(rel),
4455 NameStr(att->attname))));
4456 else if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
4458 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4459 errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
4460 RelationGetRelationName(origRelation),
4461 RelationGetRelationName(rel),
4462 NameStr(att->attname))));
4463 else if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
4465 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4466 errmsg("cannot alter foreign table \"%s\" because column \"%s.%s\" uses its row type",
4467 RelationGetRelationName(origRelation),
4468 RelationGetRelationName(rel),
4469 NameStr(att->attname))));
4472 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4473 errmsg("cannot alter table \"%s\" because column \"%s.%s\" uses its row type",
4474 RelationGetRelationName(origRelation),
4475 RelationGetRelationName(rel),
4476 NameStr(att->attname))));
4478 else if (OidIsValid(rel->rd_rel->reltype))
4481 * A view or composite type itself isn't a problem, but we must
4482 * recursively check for indirect dependencies via its rowtype.
4484 find_composite_type_dependencies(rel->rd_rel->reltype,
4485 origRelation, origTypeName);
4488 relation_close(rel, AccessShareLock);
4491 systable_endscan(depScan);
4493 relation_close(depRel, AccessShareLock);
4496 * If there's an array type for the rowtype, must check for uses of it,
4499 arrayOid = get_array_type(typeOid);
4500 if (OidIsValid(arrayOid))
4501 find_composite_type_dependencies(arrayOid, origRelation, origTypeName);
4506 * find_typed_table_dependencies
4508 * Check to see if a composite type is being used as the type of a
4509 * typed table. Abort if any are found and behavior is RESTRICT.
4510 * Else return the list of tables.
4513 find_typed_table_dependencies(Oid typeOid, const char *typeName, DropBehavior behavior)
4521 classRel = heap_open(RelationRelationId, AccessShareLock);
4523 ScanKeyInit(&key[0],
4524 Anum_pg_class_reloftype,
4525 BTEqualStrategyNumber, F_OIDEQ,
4526 ObjectIdGetDatum(typeOid));
4528 scan = heap_beginscan_catalog(classRel, 1, key);
4530 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
4532 if (behavior == DROP_RESTRICT)
4534 (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
4535 errmsg("cannot alter type \"%s\" because it is the type of a typed table",
4537 errhint("Use ALTER ... CASCADE to alter the typed tables too.")));
4539 result = lappend_oid(result, HeapTupleGetOid(tuple));
4543 heap_close(classRel, AccessShareLock);
4552 * Check whether a type is suitable for CREATE TABLE OF/ALTER TABLE OF. If it
4553 * isn't suitable, throw an error. Currently, we require that the type
4554 * originated with CREATE TYPE AS. We could support any row type, but doing so
4555 * would require handling a number of extra corner cases in the DDL commands.
4558 check_of_type(HeapTuple typetuple)
4560 Form_pg_type typ = (Form_pg_type) GETSTRUCT(typetuple);
4561 bool typeOk = false;
4563 if (typ->typtype == TYPTYPE_COMPOSITE)
4565 Relation typeRelation;
4567 Assert(OidIsValid(typ->typrelid));
4568 typeRelation = relation_open(typ->typrelid, AccessShareLock);
4569 typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
4572 * Close the parent rel, but keep our AccessShareLock on it until xact
4573 * commit. That will prevent someone else from deleting or ALTERing
4574 * the type before the typed table creation/conversion commits.
4576 relation_close(typeRelation, NoLock);
4580 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4581 errmsg("type %s is not a composite type",
4582 format_type_be(HeapTupleGetOid(typetuple)))));
4587 * ALTER TABLE ADD COLUMN
4589 * Adds an additional attribute to a relation making the assumption that
4590 * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
4591 * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
4594 * ADD COLUMN cannot use the normal ALTER TABLE recursion mechanism, because we
4595 * have to decide at runtime whether to recurse or not depending on whether we
4596 * actually add a column or merely merge with an existing column. (We can't
4597 * check this in a static pre-pass because it won't handle multiple inheritance
4598 * situations correctly.)
4601 ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
4602 bool is_view, AlterTableCmd *cmd, LOCKMODE lockmode)
4604 if (rel->rd_rel->reloftype && !recursing)
4606 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4607 errmsg("cannot add column to typed table")));
4609 if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
4610 ATTypedTableRecursion(wqueue, rel, cmd, lockmode);
4612 if (recurse && !is_view)
4613 cmd->subtype = AT_AddColumnRecurse;
4617 ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel,
4618 ColumnDef *colDef, bool isOid,
4619 bool recurse, bool recursing, LOCKMODE lockmode)
4621 Oid myrelid = RelationGetRelid(rel);
4625 FormData_pg_attribute attribute;
4628 HeapTuple typeTuple;
4636 AclResult aclresult;
4638 /* At top level, permission check was done in ATPrepCmd, else do it */
4640 ATSimplePermissions(rel, ATT_TABLE);
4642 attrdesc = heap_open(AttributeRelationId, RowExclusiveLock);
4645 * Are we adding the column to a recursion child? If so, check whether to
4646 * merge with an existing definition for the column. If we do merge, we
4647 * must not recurse. Children will already have the column, and recursing
4648 * into them would mess up attinhcount.
4650 if (colDef->inhcount > 0)
4654 /* Does child already have a column by this name? */
4655 tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
4656 if (HeapTupleIsValid(tuple))
4658 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
4663 /* Child column must match on type, typmod, and collation */
4664 typenameTypeIdAndMod(NULL, colDef->typeName, &ctypeId, &ctypmod);
4665 if (ctypeId != childatt->atttypid ||
4666 ctypmod != childatt->atttypmod)
4668 (errcode(ERRCODE_DATATYPE_MISMATCH),
4669 errmsg("child table \"%s\" has different type for column \"%s\"",
4670 RelationGetRelationName(rel), colDef->colname)));
4671 ccollid = GetColumnDefCollation(NULL, colDef, ctypeId);
4672 if (ccollid != childatt->attcollation)
4674 (errcode(ERRCODE_COLLATION_MISMATCH),
4675 errmsg("child table \"%s\" has different collation for column \"%s\"",
4676 RelationGetRelationName(rel), colDef->colname),
4677 errdetail("\"%s\" versus \"%s\"",
4678 get_collation_name(ccollid),
4679 get_collation_name(childatt->attcollation))));
4681 /* If it's OID, child column must actually be OID */
4682 if (isOid && childatt->attnum != ObjectIdAttributeNumber)
4684 (errcode(ERRCODE_DATATYPE_MISMATCH),
4685 errmsg("child table \"%s\" has a conflicting \"%s\" column",
4686 RelationGetRelationName(rel), colDef->colname)));
4688 /* Bump the existing child att's inhcount */
4689 childatt->attinhcount++;
4690 simple_heap_update(attrdesc, &tuple->t_self, tuple);
4691 CatalogUpdateIndexes(attrdesc, tuple);
4693 heap_freetuple(tuple);
4695 /* Inform the user about the merge */
4697 (errmsg("merging definition of column \"%s\" for child \"%s\"",
4698 colDef->colname, RelationGetRelationName(rel))));
4700 heap_close(attrdesc, RowExclusiveLock);
4705 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
4707 reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
4708 if (!HeapTupleIsValid(reltup))
4709 elog(ERROR, "cache lookup failed for relation %u", myrelid);
4710 relkind = ((Form_pg_class) GETSTRUCT(reltup))->relkind;
4712 /* new name should not already exist */
4713 check_for_column_name_collision(rel, colDef->colname);
4715 /* Determine the new attribute's number */
4717 newattnum = ObjectIdAttributeNumber;
4720 newattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts + 1;
4721 if (newattnum > MaxHeapAttributeNumber)
4723 (errcode(ERRCODE_TOO_MANY_COLUMNS),
4724 errmsg("tables can have at most %d columns",
4725 MaxHeapAttributeNumber)));
4728 typeTuple = typenameType(NULL, colDef->typeName, &typmod);
4729 tform = (Form_pg_type) GETSTRUCT(typeTuple);
4730 typeOid = HeapTupleGetOid(typeTuple);
4732 aclresult = pg_type_aclcheck(typeOid, GetUserId(), ACL_USAGE);
4733 if (aclresult != ACLCHECK_OK)
4734 aclcheck_error_type(aclresult, typeOid);
4736 collOid = GetColumnDefCollation(NULL, colDef, typeOid);
4738 /* make sure datatype is legal for a column */
4739 CheckAttributeType(colDef->colname, typeOid, collOid,
4740 list_make1_oid(rel->rd_rel->reltype),
4743 /* construct new attribute's pg_attribute entry */
4744 attribute.attrelid = myrelid;
4745 namestrcpy(&(attribute.attname), colDef->colname);
4746 attribute.atttypid = typeOid;
4747 attribute.attstattarget = (newattnum > 0) ? -1 : 0;
4748 attribute.attlen = tform->typlen;
4749 attribute.attcacheoff = -1;
4750 attribute.atttypmod = typmod;
4751 attribute.attnum = newattnum;
4752 attribute.attbyval = tform->typbyval;
4753 attribute.attndims = list_length(colDef->typeName->arrayBounds);
4754 attribute.attstorage = tform->typstorage;
4755 attribute.attalign = tform->typalign;
4756 attribute.attnotnull = colDef->is_not_null;
4757 attribute.atthasdef = false;
4758 attribute.attisdropped = false;
4759 attribute.attislocal = colDef->is_local;
4760 attribute.attinhcount = colDef->inhcount;
4761 attribute.attcollation = collOid;
4762 /* attribute.attacl is handled by InsertPgAttributeTuple */
4764 ReleaseSysCache(typeTuple);
4766 InsertPgAttributeTuple(attrdesc, &attribute, NULL);
4768 heap_close(attrdesc, RowExclusiveLock);
4771 * Update pg_class tuple as appropriate
4774 ((Form_pg_class) GETSTRUCT(reltup))->relhasoids = true;
4776 ((Form_pg_class) GETSTRUCT(reltup))->relnatts = newattnum;
4778 simple_heap_update(pgclass, &reltup->t_self, reltup);
4780 /* keep catalog indexes current */
4781 CatalogUpdateIndexes(pgclass, reltup);
4783 heap_freetuple(reltup);
4785 /* Post creation hook for new attribute */
4786 InvokeObjectPostCreateHook(RelationRelationId, myrelid, newattnum);
4788 heap_close(pgclass, RowExclusiveLock);
4790 /* Make the attribute's catalog entry visible */
4791 CommandCounterIncrement();
4794 * Store the DEFAULT, if any, in the catalogs
4796 if (colDef->raw_default)
4798 RawColumnDefault *rawEnt;
4800 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
4801 rawEnt->attnum = attribute.attnum;
4802 rawEnt->raw_default = copyObject(colDef->raw_default);
4805 * This function is intended for CREATE TABLE, so it processes a
4806 * _list_ of defaults, but we just do one.
4808 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
4809 false, true, false);
4811 /* Make the additional catalog changes visible */
4812 CommandCounterIncrement();
4816 * Tell Phase 3 to fill in the default expression, if there is one.
4818 * If there is no default, Phase 3 doesn't have to do anything, because
4819 * that effectively means that the default is NULL. The heap tuple access
4820 * routines always check for attnum > # of attributes in tuple, and return
4821 * NULL if so, so without any modification of the tuple data we will get
4822 * the effect of NULL values in the new column.
4824 * An exception occurs when the new column is of a domain type: the domain
4825 * might have a NOT NULL constraint, or a check constraint that indirectly
4826 * rejects nulls. If there are any domain constraints then we construct
4827 * an explicit NULL default value that will be passed through
4828 * CoerceToDomain processing. (This is a tad inefficient, since it causes
4829 * rewriting the table which we really don't have to do, but the present
4830 * design of domain processing doesn't offer any simple way of checking
4831 * the constraints more directly.)
4833 * Note: we use build_column_default, and not just the cooked default
4834 * returned by AddRelationNewConstraints, so that the right thing happens
4835 * when a datatype's default applies.
4837 * We skip this step completely for views and foreign tables. For a view,
4838 * we can only get here from CREATE OR REPLACE VIEW, which historically
4839 * doesn't set up defaults, not even for domain-typed columns. And in any
4840 * case we mustn't invoke Phase 3 on a view or foreign table, since they
4843 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE
4844 && relkind != RELKIND_FOREIGN_TABLE && attribute.attnum > 0)
4846 defval = (Expr *) build_column_default(rel, attribute.attnum);
4848 if (!defval && DomainHasConstraints(typeOid))
4854 baseTypeMod = typmod;
4855 baseTypeId = getBaseTypeAndTypmod(typeOid, &baseTypeMod);
4856 baseTypeColl = get_typcollation(baseTypeId);
4857 defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod, baseTypeColl);
4858 defval = (Expr *) coerce_to_target_type(NULL,
4863 COERCION_ASSIGNMENT,
4864 COERCE_IMPLICIT_CAST,
4866 if (defval == NULL) /* should not happen */
4867 elog(ERROR, "failed to coerce base type to domain");
4872 NewColumnValue *newval;
4874 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
4875 newval->attnum = attribute.attnum;
4876 newval->expr = expression_planner(defval);
4878 tab->newvals = lappend(tab->newvals, newval);
4879 tab->rewrite |= AT_REWRITE_DEFAULT_VAL;
4883 * If the new column is NOT NULL, tell Phase 3 it needs to test that.
4884 * (Note we don't do this for an OID column. OID will be marked not
4885 * null, but since it's filled specially, there's no need to test
4888 tab->new_notnull |= colDef->is_not_null;
4892 * If we are adding an OID column, we have to tell Phase 3 to rewrite the
4893 * table to fix that.
4896 tab->rewrite |= AT_REWRITE_ALTER_OID;
4899 * Add needed dependency entries for the new column.
4901 add_column_datatype_dependency(myrelid, newattnum, attribute.atttypid);
4902 add_column_collation_dependency(myrelid, newattnum, attribute.attcollation);
4905 * Propagate to children as appropriate. Unlike most other ALTER
4906 * routines, we have to do this one level of recursion at a time; we can't
4907 * use find_all_inheritors to do it in one pass.
4909 children = find_inheritance_children(RelationGetRelid(rel), lockmode);
4912 * If we are told not to recurse, there had better not be any child
4913 * tables; else the addition would put them out of step.
4915 if (children && !recurse)
4917 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4918 errmsg("column must be added to child tables too")));
4920 /* Children should see column as singly inherited */
4923 colDef = copyObject(colDef);
4924 colDef->inhcount = 1;
4925 colDef->is_local = false;
4928 foreach(child, children)
4930 Oid childrelid = lfirst_oid(child);
4932 AlteredTableInfo *childtab;
4934 /* find_inheritance_children already got lock */
4935 childrel = heap_open(childrelid, NoLock);
4936 CheckTableNotInUse(childrel, "ALTER TABLE");
4938 /* Find or create work queue entry for this table */
4939 childtab = ATGetQueueEntry(wqueue, childrel);
4941 /* Recurse to child */
4942 ATExecAddColumn(wqueue, childtab, childrel,
4943 colDef, isOid, recurse, true, lockmode);
4945 heap_close(childrel, NoLock);
4950 * If a new or renamed column will collide with the name of an existing
4951 * column, error out.
4954 check_for_column_name_collision(Relation rel, const char *colname)
4960 * this test is deliberately not attisdropped-aware, since if one tries to
4961 * add a column matching a dropped column name, it's gonna fail anyway.
4963 attTuple = SearchSysCache2(ATTNAME,
4964 ObjectIdGetDatum(RelationGetRelid(rel)),
4965 PointerGetDatum(colname));
4966 if (!HeapTupleIsValid(attTuple))
4969 attnum = ((Form_pg_attribute) GETSTRUCT(attTuple))->attnum;
4970 ReleaseSysCache(attTuple);
4973 * We throw a different error message for conflicts with system column
4974 * names, since they are normally not shown and the user might otherwise
4975 * be confused about the reason for the conflict.
4979 (errcode(ERRCODE_DUPLICATE_COLUMN),
4980 errmsg("column name \"%s\" conflicts with a system column name",
4984 (errcode(ERRCODE_DUPLICATE_COLUMN),
4985 errmsg("column \"%s\" of relation \"%s\" already exists",
4986 colname, RelationGetRelationName(rel))));
4990 * Install a column's dependency on its datatype.
4993 add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
4995 ObjectAddress myself,
4998 myself.classId = RelationRelationId;
4999 myself.objectId = relid;
5000 myself.objectSubId = attnum;
5001 referenced.classId = TypeRelationId;
5002 referenced.objectId = typid;
5003 referenced.objectSubId = 0;
5004 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
5008 * Install a column's dependency on its collation.
5011 add_column_collation_dependency(Oid relid, int32 attnum, Oid collid)
5013 ObjectAddress myself,
5016 /* We know the default collation is pinned, so don't bother recording it */
5017 if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
5019 myself.classId = RelationRelationId;
5020 myself.objectId = relid;
5021 myself.objectSubId = attnum;
5022 referenced.classId = CollationRelationId;
5023 referenced.objectId = collid;
5024 referenced.objectSubId = 0;
5025 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
5030 * ALTER TABLE SET WITH OIDS
5032 * Basically this is an ADD COLUMN for the special OID column. We have
5033 * to cons up a ColumnDef node because the ADD COLUMN code needs one.
5036 ATPrepAddOids(List **wqueue, Relation rel, bool recurse, AlterTableCmd *cmd, LOCKMODE lockmode)
5038 /* If we're recursing to a child table, the ColumnDef is already set up */
5039 if (cmd->def == NULL)
5041 ColumnDef *cdef = makeNode(ColumnDef);
5043 cdef->colname = pstrdup("oid");
5044 cdef->typeName = makeTypeNameFromOid(OIDOID, -1);
5046 cdef->is_local = true;
5047 cdef->is_not_null = true;
5049 cdef->location = -1;
5050 cmd->def = (Node *) cdef;
5052 ATPrepAddColumn(wqueue, rel, recurse, false, false, cmd, lockmode);
5055 cmd->subtype = AT_AddOidsRecurse;
5059 * ALTER TABLE ALTER COLUMN DROP NOT NULL
5062 ATExecDropNotNull(Relation rel, const char *colName, LOCKMODE lockmode)
5068 ListCell *indexoidscan;
5071 * lookup the attribute
5073 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
5075 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5077 if (!HeapTupleIsValid(tuple))
5079 (errcode(ERRCODE_UNDEFINED_COLUMN),
5080 errmsg("column \"%s\" of relation \"%s\" does not exist",
5081 colName, RelationGetRelationName(rel))));
5083 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
5085 /* Prevent them from altering a system attribute */
5088 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5089 errmsg("cannot alter system column \"%s\"",
5093 * Check that the attribute is not in a primary key
5095 * Note: we'll throw error even if the pkey index is not valid.
5098 /* Loop over all indexes on the relation */
5099 indexoidlist = RelationGetIndexList(rel);
5101 foreach(indexoidscan, indexoidlist)
5103 Oid indexoid = lfirst_oid(indexoidscan);
5104 HeapTuple indexTuple;
5105 Form_pg_index indexStruct;
5108 indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
5109 if (!HeapTupleIsValid(indexTuple))
5110 elog(ERROR, "cache lookup failed for index %u", indexoid);
5111 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
5113 /* If the index is not a primary key, skip the check */
5114 if (indexStruct->indisprimary)
5117 * Loop over each attribute in the primary key and see if it
5118 * matches the to-be-altered attribute
5120 for (i = 0; i < indexStruct->indnatts; i++)
5122 if (indexStruct->indkey.values[i] == attnum)
5124 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5125 errmsg("column \"%s\" is in a primary key",
5130 ReleaseSysCache(indexTuple);
5133 list_free(indexoidlist);
5136 * Okay, actually perform the catalog change ... if needed
5138 if (((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
5140 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = FALSE;
5142 simple_heap_update(attr_rel, &tuple->t_self, tuple);
5144 /* keep the system catalog indexes current */
5145 CatalogUpdateIndexes(attr_rel, tuple);
5148 InvokeObjectPostAlterHook(RelationRelationId,
5149 RelationGetRelid(rel), attnum);
5151 heap_close(attr_rel, RowExclusiveLock);
5155 * ALTER TABLE ALTER COLUMN SET NOT NULL
5158 ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
5159 const char *colName, LOCKMODE lockmode)
5166 * lookup the attribute
5168 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
5170 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5172 if (!HeapTupleIsValid(tuple))
5174 (errcode(ERRCODE_UNDEFINED_COLUMN),
5175 errmsg("column \"%s\" of relation \"%s\" does not exist",
5176 colName, RelationGetRelationName(rel))));
5178 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
5180 /* Prevent them from altering a system attribute */
5183 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5184 errmsg("cannot alter system column \"%s\"",
5188 * Okay, actually perform the catalog change ... if needed
5190 if (!((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
5192 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = TRUE;
5194 simple_heap_update(attr_rel, &tuple->t_self, tuple);
5196 /* keep the system catalog indexes current */
5197 CatalogUpdateIndexes(attr_rel, tuple);
5199 /* Tell Phase 3 it needs to test the constraint */
5200 tab->new_notnull = true;
5203 InvokeObjectPostAlterHook(RelationRelationId,
5204 RelationGetRelid(rel), attnum);
5206 heap_close(attr_rel, RowExclusiveLock);
5210 * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
5213 ATExecColumnDefault(Relation rel, const char *colName,
5214 Node *newDefault, LOCKMODE lockmode)
5219 * get the number of the attribute
5221 attnum = get_attnum(RelationGetRelid(rel), colName);
5222 if (attnum == InvalidAttrNumber)
5224 (errcode(ERRCODE_UNDEFINED_COLUMN),
5225 errmsg("column \"%s\" of relation \"%s\" does not exist",
5226 colName, RelationGetRelationName(rel))));
5228 /* Prevent them from altering a system attribute */
5231 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5232 errmsg("cannot alter system column \"%s\"",
5236 * Remove any old default for the column. We use RESTRICT here for
5237 * safety, but at present we do not expect anything to depend on the
5240 * We treat removing the existing default as an internal operation when it
5241 * is preparatory to adding a new default, but as a user-initiated
5242 * operation when the user asked for a drop.
5244 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false,
5245 newDefault == NULL ? false : true);
5250 RawColumnDefault *rawEnt;
5252 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
5253 rawEnt->attnum = attnum;
5254 rawEnt->raw_default = newDefault;
5257 * This function is intended for CREATE TABLE, so it processes a
5258 * _list_ of defaults, but we just do one.
5260 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
5261 false, true, false);
5266 * ALTER TABLE ALTER COLUMN SET STATISTICS
5269 ATPrepSetStatistics(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
5272 * We do our own permission checking because (a) we want to allow SET
5273 * STATISTICS on indexes (for expressional index columns), and (b) we want
5274 * to allow SET STATISTICS on system catalogs without requiring
5275 * allowSystemTableMods to be turned on.
5277 if (rel->rd_rel->relkind != RELKIND_RELATION &&
5278 rel->rd_rel->relkind != RELKIND_MATVIEW &&
5279 rel->rd_rel->relkind != RELKIND_INDEX &&
5280 rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
5282 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5283 errmsg("\"%s\" is not a table, materialized view, index, or foreign table",
5284 RelationGetRelationName(rel))));
5286 /* Permissions checks */
5287 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
5288 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
5289 RelationGetRelationName(rel));
5293 ATExecSetStatistics(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
5296 Relation attrelation;
5298 Form_pg_attribute attrtuple;
5300 Assert(IsA(newValue, Integer));
5301 newtarget = intVal(newValue);
5304 * Limit target to a sane range
5309 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5310 errmsg("statistics target %d is too low",
5313 else if (newtarget > 10000)
5317 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5318 errmsg("lowering statistics target to %d",
5322 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
5324 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5326 if (!HeapTupleIsValid(tuple))
5328 (errcode(ERRCODE_UNDEFINED_COLUMN),
5329 errmsg("column \"%s\" of relation \"%s\" does not exist",
5330 colName, RelationGetRelationName(rel))));
5331 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
5333 if (attrtuple->attnum <= 0)
5335 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5336 errmsg("cannot alter system column \"%s\"",
5339 attrtuple->attstattarget = newtarget;
5341 simple_heap_update(attrelation, &tuple->t_self, tuple);
5343 /* keep system catalog indexes current */
5344 CatalogUpdateIndexes(attrelation, tuple);
5346 InvokeObjectPostAlterHook(RelationRelationId,
5347 RelationGetRelid(rel),
5349 heap_freetuple(tuple);
5351 heap_close(attrelation, RowExclusiveLock);
5355 ATExecSetOptions(Relation rel, const char *colName, Node *options,
5356 bool isReset, LOCKMODE lockmode)
5358 Relation attrelation;
5361 Form_pg_attribute attrtuple;
5365 Datum repl_val[Natts_pg_attribute];
5366 bool repl_null[Natts_pg_attribute];
5367 bool repl_repl[Natts_pg_attribute];
5369 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
5371 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
5373 if (!HeapTupleIsValid(tuple))
5375 (errcode(ERRCODE_UNDEFINED_COLUMN),
5376 errmsg("column \"%s\" of relation \"%s\" does not exist",
5377 colName, RelationGetRelationName(rel))));
5378 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
5380 if (attrtuple->attnum <= 0)
5382 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5383 errmsg("cannot alter system column \"%s\"",
5386 /* Generate new proposed attoptions (text array) */
5387 Assert(IsA(options, List));
5388 datum = SysCacheGetAttr(ATTNAME, tuple, Anum_pg_attribute_attoptions,
5390 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
5391 (List *) options, NULL, NULL, false,
5393 /* Validate new options */
5394 (void) attribute_reloptions(newOptions, true);
5396 /* Build new tuple. */
5397 memset(repl_null, false, sizeof(repl_null));
5398 memset(repl_repl, false, sizeof(repl_repl));
5399 if (newOptions != (Datum) 0)
5400 repl_val[Anum_pg_attribute_attoptions - 1] = newOptions;
5402 repl_null[Anum_pg_attribute_attoptions - 1] = true;
5403 repl_repl[Anum_pg_attribute_attoptions - 1] = true;
5404 newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrelation),
5405 repl_val, repl_null, repl_repl);
5407 /* Update system catalog. */
5408 simple_heap_update(attrelation, &newtuple->t_self, newtuple);
5409 CatalogUpdateIndexes(attrelation, newtuple);
5411 InvokeObjectPostAlterHook(RelationRelationId,
5412 RelationGetRelid(rel),
5414 heap_freetuple(newtuple);
5416 ReleaseSysCache(tuple);
5418 heap_close(attrelation, RowExclusiveLock);
5422 * ALTER TABLE ALTER COLUMN SET STORAGE
5425 ATExecSetStorage(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
5429 Relation attrelation;
5431 Form_pg_attribute attrtuple;
5433 Assert(IsA(newValue, String));
5434 storagemode = strVal(newValue);
5436 if (pg_strcasecmp(storagemode, "plain") == 0)
5438 else if (pg_strcasecmp(storagemode, "external") == 0)
5440 else if (pg_strcasecmp(storagemode, "extended") == 0)
5442 else if (pg_strcasecmp(storagemode, "main") == 0)
5447 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5448 errmsg("invalid storage type \"%s\"",
5450 newstorage = 0; /* keep compiler quiet */
5453 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
5455 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5457 if (!HeapTupleIsValid(tuple))
5459 (errcode(ERRCODE_UNDEFINED_COLUMN),
5460 errmsg("column \"%s\" of relation \"%s\" does not exist",
5461 colName, RelationGetRelationName(rel))));
5462 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
5464 if (attrtuple->attnum <= 0)
5466 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5467 errmsg("cannot alter system column \"%s\"",
5471 * safety check: do not allow toasted storage modes unless column datatype
5474 if (newstorage == 'p' || TypeIsToastable(attrtuple->atttypid))
5475 attrtuple->attstorage = newstorage;
5478 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5479 errmsg("column data type %s can only have storage PLAIN",
5480 format_type_be(attrtuple->atttypid))));
5482 simple_heap_update(attrelation, &tuple->t_self, tuple);
5484 /* keep system catalog indexes current */
5485 CatalogUpdateIndexes(attrelation, tuple);
5487 InvokeObjectPostAlterHook(RelationRelationId,
5488 RelationGetRelid(rel),
5491 heap_freetuple(tuple);
5493 heap_close(attrelation, RowExclusiveLock);
5498 * ALTER TABLE DROP COLUMN
5500 * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
5501 * because we have to decide at runtime whether to recurse or not depending
5502 * on whether attinhcount goes to zero or not. (We can't check this in a
5503 * static pre-pass because it won't handle multiple inheritance situations
5507 ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
5508 AlterTableCmd *cmd, LOCKMODE lockmode)
5510 if (rel->rd_rel->reloftype && !recursing)
5512 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5513 errmsg("cannot drop column from typed table")));
5515 if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
5516 ATTypedTableRecursion(wqueue, rel, cmd, lockmode);
5519 cmd->subtype = AT_DropColumnRecurse;
5523 ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
5524 DropBehavior behavior,
5525 bool recurse, bool recursing,
5526 bool missing_ok, LOCKMODE lockmode)
5529 Form_pg_attribute targetatt;
5532 ObjectAddress object;
5534 /* At top level, permission check was done in ATPrepCmd, else do it */
5536 ATSimplePermissions(rel, ATT_TABLE);
5539 * get the number of the attribute
5541 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
5542 if (!HeapTupleIsValid(tuple))
5547 (errcode(ERRCODE_UNDEFINED_COLUMN),
5548 errmsg("column \"%s\" of relation \"%s\" does not exist",
5549 colName, RelationGetRelationName(rel))));
5554 (errmsg("column \"%s\" of relation \"%s\" does not exist, skipping",
5555 colName, RelationGetRelationName(rel))));
5559 targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
5561 attnum = targetatt->attnum;
5563 /* Can't drop a system attribute, except OID */
5564 if (attnum <= 0 && attnum != ObjectIdAttributeNumber)
5566 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5567 errmsg("cannot drop system column \"%s\"",
5570 /* Don't drop inherited columns */
5571 if (targetatt->attinhcount > 0 && !recursing)
5573 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5574 errmsg("cannot drop inherited column \"%s\"",
5577 ReleaseSysCache(tuple);
5580 * Propagate to children as appropriate. Unlike most other ALTER
5581 * routines, we have to do this one level of recursion at a time; we can't
5582 * use find_all_inheritors to do it in one pass.
5584 children = find_inheritance_children(RelationGetRelid(rel), lockmode);
5591 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
5592 foreach(child, children)
5594 Oid childrelid = lfirst_oid(child);
5596 Form_pg_attribute childatt;
5598 /* find_inheritance_children already got lock */
5599 childrel = heap_open(childrelid, NoLock);
5600 CheckTableNotInUse(childrel, "ALTER TABLE");
5602 tuple = SearchSysCacheCopyAttName(childrelid, colName);
5603 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
5604 elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
5605 colName, childrelid);
5606 childatt = (Form_pg_attribute) GETSTRUCT(tuple);
5608 if (childatt->attinhcount <= 0) /* shouldn't happen */
5609 elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
5610 childrelid, colName);
5615 * If the child column has other definition sources, just
5616 * decrement its inheritance count; if not, recurse to delete
5619 if (childatt->attinhcount == 1 && !childatt->attislocal)
5621 /* Time to delete this child column, too */
5622 ATExecDropColumn(wqueue, childrel, colName,
5623 behavior, true, true,
5628 /* Child column must survive my deletion */
5629 childatt->attinhcount--;
5631 simple_heap_update(attr_rel, &tuple->t_self, tuple);
5633 /* keep the system catalog indexes current */
5634 CatalogUpdateIndexes(attr_rel, tuple);
5636 /* Make update visible */
5637 CommandCounterIncrement();
5643 * If we were told to drop ONLY in this table (no recursion),
5644 * we need to mark the inheritors' attributes as locally
5645 * defined rather than inherited.
5647 childatt->attinhcount--;
5648 childatt->attislocal = true;
5650 simple_heap_update(attr_rel, &tuple->t_self, tuple);
5652 /* keep the system catalog indexes current */
5653 CatalogUpdateIndexes(attr_rel, tuple);
5655 /* Make update visible */
5656 CommandCounterIncrement();
5659 heap_freetuple(tuple);
5661 heap_close(childrel, NoLock);
5663 heap_close(attr_rel, RowExclusiveLock);
5667 * Perform the actual column deletion
5669 object.classId = RelationRelationId;
5670 object.objectId = RelationGetRelid(rel);
5671 object.objectSubId = attnum;
5673 performDeletion(&object, behavior, 0);
5676 * If we dropped the OID column, must adjust pg_class.relhasoids and tell
5677 * Phase 3 to physically get rid of the column. We formerly left the
5678 * column in place physically, but this caused subtle problems. See
5679 * http://archives.postgresql.org/pgsql-hackers/2009-02/msg00363.php
5681 if (attnum == ObjectIdAttributeNumber)
5684 Form_pg_class tuple_class;
5685 AlteredTableInfo *tab;
5687 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
5689 tuple = SearchSysCacheCopy1(RELOID,
5690 ObjectIdGetDatum(RelationGetRelid(rel)));
5691 if (!HeapTupleIsValid(tuple))
5692 elog(ERROR, "cache lookup failed for relation %u",
5693 RelationGetRelid(rel));
5694 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
5696 tuple_class->relhasoids = false;
5697 simple_heap_update(class_rel, &tuple->t_self, tuple);
5699 /* Keep the catalog indexes up to date */
5700 CatalogUpdateIndexes(class_rel, tuple);
5702 heap_close(class_rel, RowExclusiveLock);
5704 /* Find or create work queue entry for this table */
5705 tab = ATGetQueueEntry(wqueue, rel);
5707 /* Tell Phase 3 to physically remove the OID column */
5708 tab->rewrite |= AT_REWRITE_ALTER_OID;
5713 * ALTER TABLE ADD INDEX
5715 * There is no such command in the grammar, but parse_utilcmd.c converts
5716 * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands. This lets
5717 * us schedule creation of the index at the appropriate time during ALTER.
5720 ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
5721 IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
5726 ObjectAddress address;
5728 Assert(IsA(stmt, IndexStmt));
5729 Assert(!stmt->concurrent);
5731 /* The IndexStmt has already been through transformIndexStmt */
5732 Assert(stmt->transformed);
5734 /* suppress schema rights check when rebuilding existing index */
5735 check_rights = !is_rebuild;
5736 /* skip index build if phase 3 will do it or we're reusing an old one */
5737 skip_build = tab->rewrite > 0 || OidIsValid(stmt->oldNode);
5738 /* suppress notices when rebuilding existing index */
5741 address = DefineIndex(RelationGetRelid(rel),
5743 InvalidOid, /* no predefined OID */
5744 true, /* is_alter_table */
5750 * If TryReuseIndex() stashed a relfilenode for us, we used it for the new
5751 * index instead of building from scratch. The DROP of the old edition of
5752 * this index will have scheduled the storage for deletion at commit, so
5753 * cancel that pending deletion.
5755 if (OidIsValid(stmt->oldNode))
5757 Relation irel = index_open(address.objectId, NoLock);
5759 RelationPreserveStorage(irel->rd_node, true);
5760 index_close(irel, NoLock);
5765 * ALTER TABLE ADD CONSTRAINT USING INDEX
5768 ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
5769 IndexStmt *stmt, LOCKMODE lockmode)
5771 Oid index_oid = stmt->indexOid;
5774 IndexInfo *indexInfo;
5775 char *constraintName;
5776 char constraintType;
5778 Assert(IsA(stmt, IndexStmt));
5779 Assert(OidIsValid(index_oid));
5780 Assert(stmt->isconstraint);
5782 indexRel = index_open(index_oid, AccessShareLock);
5784 indexName = pstrdup(RelationGetRelationName(indexRel));
5786 indexInfo = BuildIndexInfo(indexRel);
5788 /* this should have been checked at parse time */
5789 if (!indexInfo->ii_Unique)
5790 elog(ERROR, "index \"%s\" is not unique", indexName);
5793 * Determine name to assign to constraint. We require a constraint to
5794 * have the same name as the underlying index; therefore, use the index's
5795 * existing name as the default constraint name, and if the user
5796 * explicitly gives some other name for the constraint, rename the index
5799 constraintName = stmt->idxname;
5800 if (constraintName == NULL)
5801 constraintName = indexName;
5802 else if (strcmp(constraintName, indexName) != 0)
5805 (errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index \"%s\" to \"%s\"",
5806 indexName, constraintName)));
5807 RenameRelationInternal(index_oid, constraintName, false);
5810 /* Extra checks needed if making primary key */
5812 index_check_primary_key(rel, indexInfo, true);
5814 /* Note we currently don't support EXCLUSION constraints here */
5816 constraintType = CONSTRAINT_PRIMARY;
5818 constraintType = CONSTRAINT_UNIQUE;
5820 /* Create the catalog entries for the constraint */
5821 index_constraint_create(rel,
5829 true, /* update pg_index */
5830 true, /* remove old dependencies */
5831 allowSystemTableMods,
5832 false); /* is_internal */
5834 index_close(indexRel, NoLock);
5838 * ALTER TABLE ADD CONSTRAINT
5841 ATExecAddConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
5842 Constraint *newConstraint, bool recurse, bool is_readd,
5845 Assert(IsA(newConstraint, Constraint));
5848 * Currently, we only expect to see CONSTR_CHECK and CONSTR_FOREIGN nodes
5849 * arriving here (see the preprocessing done in parse_utilcmd.c). Use a
5850 * switch anyway to make it easier to add more code later.
5852 switch (newConstraint->contype)
5855 ATAddCheckConstraint(wqueue, tab, rel,
5856 newConstraint, recurse, false, is_readd,
5860 case CONSTR_FOREIGN:
5863 * Note that we currently never recurse for FK constraints, so the
5864 * "recurse" flag is silently ignored.
5866 * Assign or validate constraint name
5868 if (newConstraint->conname)
5870 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
5871 RelationGetRelid(rel),
5872 RelationGetNamespace(rel),
5873 newConstraint->conname))
5875 (errcode(ERRCODE_DUPLICATE_OBJECT),
5876 errmsg("constraint \"%s\" for relation \"%s\" already exists",
5877 newConstraint->conname,
5878 RelationGetRelationName(rel))));
5881 newConstraint->conname =
5882 ChooseConstraintName(RelationGetRelationName(rel),
5883 strVal(linitial(newConstraint->fk_attrs)),
5885 RelationGetNamespace(rel),
5888 ATAddForeignKeyConstraint(tab, rel, newConstraint, lockmode);
5892 elog(ERROR, "unrecognized constraint type: %d",
5893 (int) newConstraint->contype);
5898 * Add a check constraint to a single table and its children
5900 * Subroutine for ATExecAddConstraint.
5902 * We must recurse to child tables during execution, rather than using
5903 * ALTER TABLE's normal prep-time recursion. The reason is that all the
5904 * constraints *must* be given the same name, else they won't be seen as
5905 * related later. If the user didn't explicitly specify a name, then
5906 * AddRelationNewConstraints would normally assign different names to the
5907 * child constraints. To fix that, we must capture the name assigned at
5908 * the parent table and pass that down.
5910 * When re-adding a previously existing constraint (during ALTER COLUMN TYPE),
5911 * we don't need to recurse here, because recursion will be carried out at a
5912 * higher level; the constraint name issue doesn't apply because the names
5913 * have already been assigned and are just being re-used. We need a separate
5914 * "is_readd" flag for that; just setting recurse=false would result in an
5915 * error if there are child tables.
5918 ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
5919 Constraint *constr, bool recurse, bool recursing,
5920 bool is_readd, LOCKMODE lockmode)
5927 /* At top level, permission check was done in ATPrepCmd, else do it */
5929 ATSimplePermissions(rel, ATT_TABLE);
5932 * Call AddRelationNewConstraints to do the work, making sure it works on
5933 * a copy of the Constraint so transformExpr can't modify the original. It
5934 * returns a list of cooked constraints.
5936 * If the constraint ends up getting merged with a pre-existing one, it's
5937 * omitted from the returned list, which is what we want: we do not need
5938 * to do any validation work. That can only happen at child tables,
5939 * though, since we disallow merging at the top level.
5941 newcons = AddRelationNewConstraints(rel, NIL,
5942 list_make1(copyObject(constr)),
5943 recursing, /* allow_merge */
5944 !recursing, /* is_local */
5945 is_readd); /* is_internal */
5947 /* Add each to-be-validated constraint to Phase 3's queue */
5948 foreach(lcon, newcons)
5950 CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
5952 if (!ccon->skip_validation)
5954 NewConstraint *newcon;
5956 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
5957 newcon->name = ccon->name;
5958 newcon->contype = ccon->contype;
5959 /* ExecQual wants implicit-AND format */
5960 newcon->qual = (Node *) make_ands_implicit((Expr *) ccon->expr);
5962 tab->constraints = lappend(tab->constraints, newcon);
5965 /* Save the actually assigned name if it was defaulted */
5966 if (constr->conname == NULL)
5967 constr->conname = ccon->name;
5970 /* At this point we must have a locked-down name to use */
5971 Assert(constr->conname != NULL);
5973 /* Advance command counter in case same table is visited multiple times */
5974 CommandCounterIncrement();
5977 * If the constraint got merged with an existing constraint, we're done.
5978 * We mustn't recurse to child tables in this case, because they've
5979 * already got the constraint, and visiting them again would lead to an
5980 * incorrect value for coninhcount.
5986 * If adding a NO INHERIT constraint, no need to find our children.
5987 * Likewise, in a re-add operation, we don't need to recurse (that will be
5988 * handled at higher levels).
5990 if (constr->is_no_inherit || is_readd)
5994 * Propagate to children as appropriate. Unlike most other ALTER
5995 * routines, we have to do this one level of recursion at a time; we can't
5996 * use find_all_inheritors to do it in one pass.
5998 children = find_inheritance_children(RelationGetRelid(rel), lockmode);
6001 * Check if ONLY was specified with ALTER TABLE. If so, allow the
6002 * contraint creation only if there are no children currently. Error out
6005 if (!recurse && children != NIL)
6007 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6008 errmsg("constraint must be added to child tables too")));
6010 foreach(child, children)
6012 Oid childrelid = lfirst_oid(child);
6014 AlteredTableInfo *childtab;
6016 /* find_inheritance_children already got lock */
6017 childrel = heap_open(childrelid, NoLock);
6018 CheckTableNotInUse(childrel, "ALTER TABLE");
6020 /* Find or create work queue entry for this table */
6021 childtab = ATGetQueueEntry(wqueue, childrel);
6023 /* Recurse to child */
6024 ATAddCheckConstraint(wqueue, childtab, childrel,
6025 constr, recurse, true, is_readd, lockmode);
6027 heap_close(childrel, NoLock);
6032 * Add a foreign-key constraint to a single table
6034 * Subroutine for ATExecAddConstraint. Must already hold exclusive
6035 * lock on the rel, and have done appropriate validity checks for it.
6036 * We do permissions checks here, however.
6039 ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
6040 Constraint *fkconstraint, LOCKMODE lockmode)
6043 int16 pkattnum[INDEX_MAX_KEYS];
6044 int16 fkattnum[INDEX_MAX_KEYS];
6045 Oid pktypoid[INDEX_MAX_KEYS];
6046 Oid fktypoid[INDEX_MAX_KEYS];
6047 Oid opclasses[INDEX_MAX_KEYS];
6048 Oid pfeqoperators[INDEX_MAX_KEYS];
6049 Oid ppeqoperators[INDEX_MAX_KEYS];
6050 Oid ffeqoperators[INDEX_MAX_KEYS];
6057 ListCell *old_pfeqop_item = list_head(fkconstraint->old_conpfeqop);
6060 * Grab an exclusive lock on the pk table, so that someone doesn't delete
6061 * rows out from under us. (Although a lesser lock would do for that
6062 * purpose, we'll need exclusive lock anyway to add triggers to the pk
6063 * table; trying to start with a lesser lock will just create a risk of
6066 if (OidIsValid(fkconstraint->old_pktable_oid))
6067 pkrel = heap_open(fkconstraint->old_pktable_oid, AccessExclusiveLock);
6069 pkrel = heap_openrv(fkconstraint->pktable, AccessExclusiveLock);
6072 * Validity checks (permission checks wait till we have the column
6075 if (pkrel->rd_rel->relkind != RELKIND_RELATION)
6077 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6078 errmsg("referenced relation \"%s\" is not a table",
6079 RelationGetRelationName(pkrel))));
6081 if (!allowSystemTableMods && IsSystemRelation(pkrel))
6083 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6084 errmsg("permission denied: \"%s\" is a system catalog",
6085 RelationGetRelationName(pkrel))));
6088 * References from permanent or unlogged tables to temp tables, and from
6089 * permanent tables to unlogged tables, are disallowed because the
6090 * referenced data can vanish out from under us. References from temp
6091 * tables to any other table type are also disallowed, because other
6092 * backends might need to run the RI triggers on the perm table, but they
6093 * can't reliably see tuples in the local buffers of other backends.
6095 switch (rel->rd_rel->relpersistence)
6097 case RELPERSISTENCE_PERMANENT:
6098 if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT)
6100 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6101 errmsg("constraints on permanent tables may reference only permanent tables")));
6103 case RELPERSISTENCE_UNLOGGED:
6104 if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT
6105 && pkrel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED)
6107 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6108 errmsg("constraints on unlogged tables may reference only permanent or unlogged tables")));
6110 case RELPERSISTENCE_TEMP:
6111 if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
6113 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6114 errmsg("constraints on temporary tables may reference only temporary tables")));
6115 if (!pkrel->rd_islocaltemp || !rel->rd_islocaltemp)
6117 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6118 errmsg("constraints on temporary tables must involve temporary tables of this session")));
6123 * Look up the referencing attributes to make sure they exist, and record
6124 * their attnums and type OIDs.
6126 MemSet(pkattnum, 0, sizeof(pkattnum));
6127 MemSet(fkattnum, 0, sizeof(fkattnum));
6128 MemSet(pktypoid, 0, sizeof(pktypoid));
6129 MemSet(fktypoid, 0, sizeof(fktypoid));
6130 MemSet(opclasses, 0, sizeof(opclasses));
6131 MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
6132 MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
6133 MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
6135 numfks = transformColumnNameList(RelationGetRelid(rel),
6136 fkconstraint->fk_attrs,
6137 fkattnum, fktypoid);
6140 * If the attribute list for the referenced table was omitted, lookup the
6141 * definition of the primary key and use it. Otherwise, validate the
6142 * supplied attribute list. In either case, discover the index OID and
6143 * index opclasses, and the attnums and type OIDs of the attributes.
6145 if (fkconstraint->pk_attrs == NIL)
6147 numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
6148 &fkconstraint->pk_attrs,
6154 numpks = transformColumnNameList(RelationGetRelid(pkrel),
6155 fkconstraint->pk_attrs,
6156 pkattnum, pktypoid);
6157 /* Look for an index matching the column list */
6158 indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
6163 * Now we can check permissions.
6165 checkFkeyPermissions(pkrel, pkattnum, numpks);
6166 checkFkeyPermissions(rel, fkattnum, numfks);
6169 * Look up the equality operators to use in the constraint.
6171 * Note that we have to be careful about the difference between the actual
6172 * PK column type and the opclass' declared input type, which might be
6173 * only binary-compatible with it. The declared opcintype is the right
6174 * thing to probe pg_amop with.
6176 if (numfks != numpks)
6178 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
6179 errmsg("number of referencing and referenced columns for foreign key disagree")));
6182 * On the strength of a previous constraint, we might avoid scanning
6183 * tables to validate this one. See below.
6185 old_check_ok = (fkconstraint->old_conpfeqop != NIL);
6186 Assert(!old_check_ok || numfks == list_length(fkconstraint->old_conpfeqop));
6188 for (i = 0; i < numpks; i++)
6190 Oid pktype = pktypoid[i];
6191 Oid fktype = fktypoid[i];
6194 Form_pg_opclass cla_tup;
6204 /* We need several fields out of the pg_opclass entry */
6205 cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclasses[i]));
6206 if (!HeapTupleIsValid(cla_ht))
6207 elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
6208 cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
6209 amid = cla_tup->opcmethod;
6210 opfamily = cla_tup->opcfamily;
6211 opcintype = cla_tup->opcintype;
6212 ReleaseSysCache(cla_ht);
6215 * Check it's a btree; currently this can never fail since no other
6216 * index AMs support unique indexes. If we ever did have other types
6217 * of unique indexes, we'd need a way to determine which operator
6218 * strategy number is equality. (Is it reasonable to insist that
6219 * every such index AM use btree's number for equality?)
6221 if (amid != BTREE_AM_OID)
6222 elog(ERROR, "only b-tree indexes are supported for foreign keys");
6223 eqstrategy = BTEqualStrategyNumber;
6226 * There had better be a primary equality operator for the index.
6227 * We'll use it for PK = PK comparisons.
6229 ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
6232 if (!OidIsValid(ppeqop))
6233 elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
6234 eqstrategy, opcintype, opcintype, opfamily);
6237 * Are there equality operators that take exactly the FK type? Assume
6238 * we should look through any domain here.
6240 fktyped = getBaseType(fktype);
6242 pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
6244 if (OidIsValid(pfeqop))
6246 pfeqop_right = fktyped;
6247 ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
6252 /* keep compiler quiet */
6253 pfeqop_right = InvalidOid;
6254 ffeqop = InvalidOid;
6257 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
6260 * Otherwise, look for an implicit cast from the FK type to the
6261 * opcintype, and if found, use the primary equality operator.
6262 * This is a bit tricky because opcintype might be a polymorphic
6263 * type such as ANYARRAY or ANYENUM; so what we have to test is
6264 * whether the two actual column types can be concurrently cast to
6265 * that type. (Otherwise, we'd fail to reject combinations such
6266 * as int[] and point[].)
6268 Oid input_typeids[2];
6269 Oid target_typeids[2];
6271 input_typeids[0] = pktype;
6272 input_typeids[1] = fktype;
6273 target_typeids[0] = opcintype;
6274 target_typeids[1] = opcintype;
6275 if (can_coerce_type(2, input_typeids, target_typeids,
6278 pfeqop = ffeqop = ppeqop;
6279 pfeqop_right = opcintype;
6283 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
6285 (errcode(ERRCODE_DATATYPE_MISMATCH),
6286 errmsg("foreign key constraint \"%s\" "
6287 "cannot be implemented",
6288 fkconstraint->conname),
6289 errdetail("Key columns \"%s\" and \"%s\" "
6290 "are of incompatible types: %s and %s.",
6291 strVal(list_nth(fkconstraint->fk_attrs, i)),
6292 strVal(list_nth(fkconstraint->pk_attrs, i)),
6293 format_type_be(fktype),
6294 format_type_be(pktype))));
6299 * When a pfeqop changes, revalidate the constraint. We could
6300 * permit intra-opfamily changes, but that adds subtle complexity
6301 * without any concrete benefit for core types. We need not
6302 * assess ppeqop or ffeqop, which RI_Initial_Check() does not use.
6304 old_check_ok = (pfeqop == lfirst_oid(old_pfeqop_item));
6305 old_pfeqop_item = lnext(old_pfeqop_item);
6311 CoercionPathType old_pathtype;
6312 CoercionPathType new_pathtype;
6317 * Identify coercion pathways from each of the old and new FK-side
6318 * column types to the right (foreign) operand type of the pfeqop.
6319 * We may assume that pg_constraint.conkey is not changing.
6321 old_fktype = tab->oldDesc->attrs[fkattnum[i] - 1]->atttypid;
6322 new_fktype = fktype;
6323 old_pathtype = findFkeyCast(pfeqop_right, old_fktype,
6325 new_pathtype = findFkeyCast(pfeqop_right, new_fktype,
6329 * Upon a change to the cast from the FK column to its pfeqop
6330 * operand, revalidate the constraint. For this evaluation, a
6331 * binary coercion cast is equivalent to no cast at all. While
6332 * type implementors should design implicit casts with an eye
6333 * toward consistency of operations like equality, we cannot
6334 * assume here that they have done so.
6336 * A function with a polymorphic argument could change behavior
6337 * arbitrarily in response to get_fn_expr_argtype(). Therefore,
6338 * when the cast destination is polymorphic, we only avoid
6339 * revalidation if the input type has not changed at all. Given
6340 * just the core data types and operator classes, this requirement
6341 * prevents no would-be optimizations.
6343 * If the cast converts from a base type to a domain thereon, then
6344 * that domain type must be the opcintype of the unique index.
6345 * Necessarily, the primary key column must then be of the domain
6346 * type. Since the constraint was previously valid, all values on
6347 * the foreign side necessarily exist on the primary side and in
6348 * turn conform to the domain. Consequently, we need not treat
6349 * domains specially here.
6351 * Since we require that all collations share the same notion of
6352 * equality (which they do, because texteq reduces to bitwise
6353 * equality), we don't compare collation here.
6355 * We need not directly consider the PK type. It's necessarily
6356 * binary coercible to the opcintype of the unique index column,
6357 * and ri_triggers.c will only deal with PK datums in terms of
6358 * that opcintype. Changing the opcintype also changes pfeqop.
6360 old_check_ok = (new_pathtype == old_pathtype &&
6361 new_castfunc == old_castfunc &&
6362 (!IsPolymorphicType(pfeqop_right) ||
6363 new_fktype == old_fktype));
6367 pfeqoperators[i] = pfeqop;
6368 ppeqoperators[i] = ppeqop;
6369 ffeqoperators[i] = ffeqop;
6373 * Record the FK constraint in pg_constraint.
6375 constrOid = CreateConstraintEntry(fkconstraint->conname,
6376 RelationGetNamespace(rel),
6378 fkconstraint->deferrable,
6379 fkconstraint->initdeferred,
6380 fkconstraint->initially_valid,
6381 RelationGetRelid(rel),
6384 InvalidOid, /* not a domain
6387 RelationGetRelid(pkrel),
6393 fkconstraint->fk_upd_action,
6394 fkconstraint->fk_del_action,
6395 fkconstraint->fk_matchtype,
6396 NULL, /* no exclusion constraint */
6397 NULL, /* no check constraint */
6402 true, /* isnoinherit */
6403 false); /* is_internal */
6406 * Create the triggers that will enforce the constraint.
6408 createForeignKeyTriggers(rel, RelationGetRelid(pkrel), fkconstraint,
6409 constrOid, indexOid);
6412 * Tell Phase 3 to check that the constraint is satisfied by existing
6413 * rows. We can skip this during table creation, when requested explicitly
6414 * by specifying NOT VALID in an ADD FOREIGN KEY command, and when we're
6415 * recreating a constraint following a SET DATA TYPE operation that did
6416 * not impugn its validity.
6418 if (!old_check_ok && !fkconstraint->skip_validation)
6420 NewConstraint *newcon;
6422 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
6423 newcon->name = fkconstraint->conname;
6424 newcon->contype = CONSTR_FOREIGN;
6425 newcon->refrelid = RelationGetRelid(pkrel);
6426 newcon->refindid = indexOid;
6427 newcon->conid = constrOid;
6428 newcon->qual = (Node *) fkconstraint;
6430 tab->constraints = lappend(tab->constraints, newcon);
6434 * Close pk table, but keep lock until we've committed.
6436 heap_close(pkrel, NoLock);
6440 * ALTER TABLE ALTER CONSTRAINT
6442 * Update the attributes of a constraint.
6444 * Currently only works for Foreign Key constraints.
6445 * Foreign keys do not inherit, so we purposely ignore the
6446 * recursion bit here, but we keep the API the same for when
6447 * other constraint types are supported.
6450 ATExecAlterConstraint(Relation rel, AlterTableCmd *cmd,
6451 bool recurse, bool recursing, LOCKMODE lockmode)
6457 Form_pg_constraint currcon = NULL;
6458 Constraint *cmdcon = NULL;
6461 Assert(IsA(cmd->def, Constraint));
6462 cmdcon = (Constraint *) cmd->def;
6464 conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
6467 * Find and check the target constraint
6470 Anum_pg_constraint_conrelid,
6471 BTEqualStrategyNumber, F_OIDEQ,
6472 ObjectIdGetDatum(RelationGetRelid(rel)));
6473 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
6474 true, NULL, 1, &key);
6476 while (HeapTupleIsValid(contuple = systable_getnext(scan)))
6478 currcon = (Form_pg_constraint) GETSTRUCT(contuple);
6479 if (strcmp(NameStr(currcon->conname), cmdcon->conname) == 0)
6488 (errcode(ERRCODE_UNDEFINED_OBJECT),
6489 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
6490 cmdcon->conname, RelationGetRelationName(rel))));
6492 if (currcon->contype != CONSTRAINT_FOREIGN)
6494 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6495 errmsg("constraint \"%s\" of relation \"%s\" is not a foreign key constraint",
6496 cmdcon->conname, RelationGetRelationName(rel))));
6498 if (currcon->condeferrable != cmdcon->deferrable ||
6499 currcon->condeferred != cmdcon->initdeferred)
6501 HeapTuple copyTuple;
6503 Form_pg_constraint copy_con;
6504 Form_pg_trigger copy_tg;
6510 * Now update the catalog, while we have the door open.
6512 copyTuple = heap_copytuple(contuple);
6513 copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
6514 copy_con->condeferrable = cmdcon->deferrable;
6515 copy_con->condeferred = cmdcon->initdeferred;
6516 simple_heap_update(conrel, ©Tuple->t_self, copyTuple);
6517 CatalogUpdateIndexes(conrel, copyTuple);
6519 InvokeObjectPostAlterHook(ConstraintRelationId,
6520 HeapTupleGetOid(contuple), 0);
6522 heap_freetuple(copyTuple);
6525 * Now we need to update the multiple entries in pg_trigger that
6526 * implement the constraint.
6528 tgrel = heap_open(TriggerRelationId, RowExclusiveLock);
6531 Anum_pg_trigger_tgconstraint,
6532 BTEqualStrategyNumber, F_OIDEQ,
6533 ObjectIdGetDatum(HeapTupleGetOid(contuple)));
6535 tgscan = systable_beginscan(tgrel, TriggerConstraintIndexId, true,
6538 while (HeapTupleIsValid(tgtuple = systable_getnext(tgscan)))
6540 copyTuple = heap_copytuple(tgtuple);
6541 copy_tg = (Form_pg_trigger) GETSTRUCT(copyTuple);
6542 copy_tg->tgdeferrable = cmdcon->deferrable;
6543 copy_tg->tginitdeferred = cmdcon->initdeferred;
6544 simple_heap_update(tgrel, ©Tuple->t_self, copyTuple);
6545 CatalogUpdateIndexes(tgrel, copyTuple);
6547 InvokeObjectPostAlterHook(TriggerRelationId,
6548 HeapTupleGetOid(tgtuple), 0);
6550 heap_freetuple(copyTuple);
6553 systable_endscan(tgscan);
6555 heap_close(tgrel, RowExclusiveLock);
6558 * Invalidate relcache so that others see the new attributes.
6560 CacheInvalidateRelcache(rel);
6563 systable_endscan(scan);
6565 heap_close(conrel, RowExclusiveLock);
6569 * ALTER TABLE VALIDATE CONSTRAINT
6571 * XXX The reason we handle recursion here rather than at Phase 1 is because
6572 * there's no good way to skip recursing when handling foreign keys: there is
6573 * no need to lock children in that case, yet we wouldn't be able to avoid
6574 * doing so at that level.
6577 ATExecValidateConstraint(Relation rel, char *constrName, bool recurse,
6578 bool recursing, LOCKMODE lockmode)
6584 Form_pg_constraint con = NULL;
6587 conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
6590 * Find and check the target constraint
6593 Anum_pg_constraint_conrelid,
6594 BTEqualStrategyNumber, F_OIDEQ,
6595 ObjectIdGetDatum(RelationGetRelid(rel)));
6596 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
6597 true, NULL, 1, &key);
6599 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
6601 con = (Form_pg_constraint) GETSTRUCT(tuple);
6602 if (strcmp(NameStr(con->conname), constrName) == 0)
6611 (errcode(ERRCODE_UNDEFINED_OBJECT),
6612 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
6613 constrName, RelationGetRelationName(rel))));
6615 if (con->contype != CONSTRAINT_FOREIGN &&
6616 con->contype != CONSTRAINT_CHECK)
6618 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6619 errmsg("constraint \"%s\" of relation \"%s\" is not a foreign key or check constraint",
6620 constrName, RelationGetRelationName(rel))));
6622 if (!con->convalidated)
6624 HeapTuple copyTuple;
6625 Form_pg_constraint copy_con;
6627 if (con->contype == CONSTRAINT_FOREIGN)
6629 Oid conid = HeapTupleGetOid(tuple);
6633 * Triggers are already in place on both tables, so a concurrent
6634 * write that alters the result here is not possible. Normally we
6635 * can run a query here to do the validation, which would only
6636 * require AccessShareLock. In some cases, it is possible that we
6637 * might need to fire triggers to perform the check, so we take a
6638 * lock at RowShareLock level just in case.
6640 refrel = heap_open(con->confrelid, RowShareLock);
6642 validateForeignKeyConstraint(constrName, rel, refrel,
6645 heap_close(refrel, NoLock);
6648 * Foreign keys do not inherit, so we purposely ignore the
6649 * recursion bit here
6652 else if (con->contype == CONSTRAINT_CHECK)
6654 List *children = NIL;
6658 * If we're recursing, the parent has already done this, so skip
6662 children = find_all_inheritors(RelationGetRelid(rel),
6666 * For CHECK constraints, we must ensure that we only mark the
6667 * constraint as validated on the parent if it's already validated
6670 * We recurse before validating on the parent, to reduce risk of
6673 foreach(child, children)
6675 Oid childoid = lfirst_oid(child);
6678 if (childoid == RelationGetRelid(rel))
6682 * If we are told not to recurse, there had better not be any
6683 * child tables; else the addition would put them out of step.
6687 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6688 errmsg("constraint must be validated on child tables too")));
6690 /* find_all_inheritors already got lock */
6691 childrel = heap_open(childoid, NoLock);
6693 ATExecValidateConstraint(childrel, constrName, false,
6695 heap_close(childrel, NoLock);
6698 validateCheckConstraint(rel, tuple);
6701 * Invalidate relcache so that others see the new validated
6704 CacheInvalidateRelcache(rel);
6708 * Now update the catalog, while we have the door open.
6710 copyTuple = heap_copytuple(tuple);
6711 copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
6712 copy_con->convalidated = true;
6713 simple_heap_update(conrel, ©Tuple->t_self, copyTuple);
6714 CatalogUpdateIndexes(conrel, copyTuple);
6716 InvokeObjectPostAlterHook(ConstraintRelationId,
6717 HeapTupleGetOid(tuple), 0);
6719 heap_freetuple(copyTuple);
6722 systable_endscan(scan);
6724 heap_close(conrel, RowExclusiveLock);
6729 * transformColumnNameList - transform list of column names
6731 * Lookup each name and return its attnum and type OID
6734 transformColumnNameList(Oid relId, List *colList,
6735 int16 *attnums, Oid *atttypids)
6743 char *attname = strVal(lfirst(l));
6746 atttuple = SearchSysCacheAttName(relId, attname);
6747 if (!HeapTupleIsValid(atttuple))
6749 (errcode(ERRCODE_UNDEFINED_COLUMN),
6750 errmsg("column \"%s\" referenced in foreign key constraint does not exist",
6752 if (attnum >= INDEX_MAX_KEYS)
6754 (errcode(ERRCODE_TOO_MANY_COLUMNS),
6755 errmsg("cannot have more than %d keys in a foreign key",
6757 attnums[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->attnum;
6758 atttypids[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->atttypid;
6759 ReleaseSysCache(atttuple);
6767 * transformFkeyGetPrimaryKey -
6769 * Look up the names, attnums, and types of the primary key attributes
6770 * for the pkrel. Also return the index OID and index opclasses of the
6771 * index supporting the primary key.
6773 * All parameters except pkrel are output parameters. Also, the function
6774 * return value is the number of attributes in the primary key.
6776 * Used when the column list in the REFERENCES specification is omitted.
6779 transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
6781 int16 *attnums, Oid *atttypids,
6785 ListCell *indexoidscan;
6786 HeapTuple indexTuple = NULL;
6787 Form_pg_index indexStruct = NULL;
6788 Datum indclassDatum;
6790 oidvector *indclass;
6794 * Get the list of index OIDs for the table from the relcache, and look up
6795 * each one in the pg_index syscache until we find one marked primary key
6796 * (hopefully there isn't more than one such). Insist it's valid, too.
6798 *indexOid = InvalidOid;
6800 indexoidlist = RelationGetIndexList(pkrel);
6802 foreach(indexoidscan, indexoidlist)
6804 Oid indexoid = lfirst_oid(indexoidscan);
6806 indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
6807 if (!HeapTupleIsValid(indexTuple))
6808 elog(ERROR, "cache lookup failed for index %u", indexoid);
6809 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
6810 if (indexStruct->indisprimary && IndexIsValid(indexStruct))
6813 * Refuse to use a deferrable primary key. This is per SQL spec,
6814 * and there would be a lot of interesting semantic problems if we
6815 * tried to allow it.
6817 if (!indexStruct->indimmediate)
6819 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6820 errmsg("cannot use a deferrable primary key for referenced table \"%s\"",
6821 RelationGetRelationName(pkrel))));
6823 *indexOid = indexoid;
6826 ReleaseSysCache(indexTuple);
6829 list_free(indexoidlist);
6832 * Check that we found it
6834 if (!OidIsValid(*indexOid))
6836 (errcode(ERRCODE_UNDEFINED_OBJECT),
6837 errmsg("there is no primary key for referenced table \"%s\"",
6838 RelationGetRelationName(pkrel))));
6840 /* Must get indclass the hard way */
6841 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
6842 Anum_pg_index_indclass, &isnull);
6844 indclass = (oidvector *) DatumGetPointer(indclassDatum);
6847 * Now build the list of PK attributes from the indkey definition (we
6848 * assume a primary key cannot have expressional elements)
6851 for (i = 0; i < indexStruct->indnatts; i++)
6853 int pkattno = indexStruct->indkey.values[i];
6855 attnums[i] = pkattno;
6856 atttypids[i] = attnumTypeId(pkrel, pkattno);
6857 opclasses[i] = indclass->values[i];
6858 *attnamelist = lappend(*attnamelist,
6859 makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
6862 ReleaseSysCache(indexTuple);
6868 * transformFkeyCheckAttrs -
6870 * Make sure that the attributes of a referenced table belong to a unique
6871 * (or primary key) constraint. Return the OID of the index supporting
6872 * the constraint, as well as the opclasses associated with the index
6876 transformFkeyCheckAttrs(Relation pkrel,
6877 int numattrs, int16 *attnums,
6878 Oid *opclasses) /* output parameter */
6880 Oid indexoid = InvalidOid;
6882 bool found_deferrable = false;
6884 ListCell *indexoidscan;
6889 * Reject duplicate appearances of columns in the referenced-columns list.
6890 * Such a case is forbidden by the SQL standard, and even if we thought it
6891 * useful to allow it, there would be ambiguity about how to match the
6892 * list to unique indexes (in particular, it'd be unclear which index
6893 * opclass goes with which FK column).
6895 for (i = 0; i < numattrs; i++)
6897 for (j = i + 1; j < numattrs; j++)
6899 if (attnums[i] == attnums[j])
6901 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
6902 errmsg("foreign key referenced-columns list must not contain duplicates")));
6907 * Get the list of index OIDs for the table from the relcache, and look up
6908 * each one in the pg_index syscache, and match unique indexes to the list
6909 * of attnums we are given.
6911 indexoidlist = RelationGetIndexList(pkrel);
6913 foreach(indexoidscan, indexoidlist)
6915 HeapTuple indexTuple;
6916 Form_pg_index indexStruct;
6918 indexoid = lfirst_oid(indexoidscan);
6919 indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
6920 if (!HeapTupleIsValid(indexTuple))
6921 elog(ERROR, "cache lookup failed for index %u", indexoid);
6922 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
6925 * Must have the right number of columns; must be unique and not a
6926 * partial index; forget it if there are any expressions, too. Invalid
6927 * indexes are out as well.
6929 if (indexStruct->indnatts == numattrs &&
6930 indexStruct->indisunique &&
6931 IndexIsValid(indexStruct) &&
6932 heap_attisnull(indexTuple, Anum_pg_index_indpred) &&
6933 heap_attisnull(indexTuple, Anum_pg_index_indexprs))
6935 Datum indclassDatum;
6937 oidvector *indclass;
6939 /* Must get indclass the hard way */
6940 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
6941 Anum_pg_index_indclass, &isnull);
6943 indclass = (oidvector *) DatumGetPointer(indclassDatum);
6946 * The given attnum list may match the index columns in any order.
6947 * Check for a match, and extract the appropriate opclasses while
6950 * We know that attnums[] is duplicate-free per the test at the
6951 * start of this function, and we checked above that the number of
6952 * index columns agrees, so if we find a match for each attnums[]
6953 * entry then we must have a one-to-one match in some order.
6955 for (i = 0; i < numattrs; i++)
6958 for (j = 0; j < numattrs; j++)
6960 if (attnums[i] == indexStruct->indkey.values[j])
6962 opclasses[i] = indclass->values[j];
6972 * Refuse to use a deferrable unique/primary key. This is per SQL
6973 * spec, and there would be a lot of interesting semantic problems
6974 * if we tried to allow it.
6976 if (found && !indexStruct->indimmediate)
6979 * Remember that we found an otherwise matching index, so that
6980 * we can generate a more appropriate error message.
6982 found_deferrable = true;
6986 ReleaseSysCache(indexTuple);
6993 if (found_deferrable)
6995 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6996 errmsg("cannot use a deferrable unique constraint for referenced table \"%s\"",
6997 RelationGetRelationName(pkrel))));
7000 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
7001 errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
7002 RelationGetRelationName(pkrel))));
7005 list_free(indexoidlist);
7013 * Wrapper around find_coercion_pathway() for ATAddForeignKeyConstraint().
7014 * Caller has equal regard for binary coercibility and for an exact match.
7016 static CoercionPathType
7017 findFkeyCast(Oid targetTypeId, Oid sourceTypeId, Oid *funcid)
7019 CoercionPathType ret;
7021 if (targetTypeId == sourceTypeId)
7023 ret = COERCION_PATH_RELABELTYPE;
7024 *funcid = InvalidOid;
7028 ret = find_coercion_pathway(targetTypeId, sourceTypeId,
7029 COERCION_IMPLICIT, funcid);
7030 if (ret == COERCION_PATH_NONE)
7031 /* A previously-relied-upon cast is now gone. */
7032 elog(ERROR, "could not find cast from %u to %u",
7033 sourceTypeId, targetTypeId);
7039 /* Permissions checks for ADD FOREIGN KEY */
7041 checkFkeyPermissions(Relation rel, int16 *attnums, int natts)
7043 Oid roleid = GetUserId();
7044 AclResult aclresult;
7047 /* Okay if we have relation-level REFERENCES permission */
7048 aclresult = pg_class_aclcheck(RelationGetRelid(rel), roleid,
7050 if (aclresult == ACLCHECK_OK)
7052 /* Else we must have REFERENCES on each column */
7053 for (i = 0; i < natts; i++)
7055 aclresult = pg_attribute_aclcheck(RelationGetRelid(rel), attnums[i],
7056 roleid, ACL_REFERENCES);
7057 if (aclresult != ACLCHECK_OK)
7058 aclcheck_error(aclresult, ACL_KIND_CLASS,
7059 RelationGetRelationName(rel));
7064 * Scan the existing rows in a table to verify they meet a proposed
7067 * The caller must have opened and locked the relation appropriately.
7070 validateCheckConstraint(Relation rel, HeapTuple constrtup)
7080 ExprContext *econtext;
7081 MemoryContext oldcxt;
7082 TupleTableSlot *slot;
7083 Form_pg_constraint constrForm;
7087 constrForm = (Form_pg_constraint) GETSTRUCT(constrtup);
7089 estate = CreateExecutorState();
7092 * XXX this tuple doesn't really come from a syscache, but this doesn't
7093 * matter to SysCacheGetAttr, because it only wants to be able to fetch
7096 val = SysCacheGetAttr(CONSTROID, constrtup, Anum_pg_constraint_conbin,
7099 elog(ERROR, "null conbin for constraint %u",
7100 HeapTupleGetOid(constrtup));
7101 conbin = TextDatumGetCString(val);
7102 origexpr = (Expr *) stringToNode(conbin);
7103 exprstate = (List *)
7104 ExecPrepareExpr((Expr *) make_ands_implicit(origexpr), estate);
7106 econtext = GetPerTupleExprContext(estate);
7107 tupdesc = RelationGetDescr(rel);
7108 slot = MakeSingleTupleTableSlot(tupdesc);
7109 econtext->ecxt_scantuple = slot;
7111 snapshot = RegisterSnapshot(GetLatestSnapshot());
7112 scan = heap_beginscan(rel, snapshot, 0, NULL);
7115 * Switch to per-tuple memory context and reset it for each tuple
7116 * produced, so we don't leak memory.
7118 oldcxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
7120 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
7122 ExecStoreTuple(tuple, slot, InvalidBuffer, false);
7124 if (!ExecQual(exprstate, econtext, true))
7126 (errcode(ERRCODE_CHECK_VIOLATION),
7127 errmsg("check constraint \"%s\" is violated by some row",
7128 NameStr(constrForm->conname)),
7129 errtableconstraint(rel, NameStr(constrForm->conname))));
7131 ResetExprContext(econtext);
7134 MemoryContextSwitchTo(oldcxt);
7136 UnregisterSnapshot(snapshot);
7137 ExecDropSingleTupleTableSlot(slot);
7138 FreeExecutorState(estate);
7142 * Scan the existing rows in a table to verify they meet a proposed FK
7145 * Caller must have opened and locked both relations appropriately.
7148 validateForeignKeyConstraint(char *conname,
7160 (errmsg("validating foreign key constraint \"%s\"", conname)));
7163 * Build a trigger call structure; we'll need it either way.
7165 MemSet(&trig, 0, sizeof(trig));
7166 trig.tgoid = InvalidOid;
7167 trig.tgname = conname;
7168 trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
7169 trig.tgisinternal = TRUE;
7170 trig.tgconstrrelid = RelationGetRelid(pkrel);
7171 trig.tgconstrindid = pkindOid;
7172 trig.tgconstraint = constraintOid;
7173 trig.tgdeferrable = FALSE;
7174 trig.tginitdeferred = FALSE;
7175 /* we needn't fill in tgargs or tgqual */
7178 * See if we can do it with a single LEFT JOIN query. A FALSE result
7179 * indicates we must proceed with the fire-the-trigger method.
7181 if (RI_Initial_Check(&trig, rel, pkrel))
7185 * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
7186 * if that tuple had just been inserted. If any of those fail, it should
7187 * ereport(ERROR) and that's that.
7189 snapshot = RegisterSnapshot(GetLatestSnapshot());
7190 scan = heap_beginscan(rel, snapshot, 0, NULL);
7192 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
7194 FunctionCallInfoData fcinfo;
7195 TriggerData trigdata;
7198 * Make a call to the trigger function
7200 * No parameters are passed, but we do set a context
7202 MemSet(&fcinfo, 0, sizeof(fcinfo));
7205 * We assume RI_FKey_check_ins won't look at flinfo...
7207 trigdata.type = T_TriggerData;
7208 trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
7209 trigdata.tg_relation = rel;
7210 trigdata.tg_trigtuple = tuple;
7211 trigdata.tg_newtuple = NULL;
7212 trigdata.tg_trigger = &trig;
7213 trigdata.tg_trigtuplebuf = scan->rs_cbuf;
7214 trigdata.tg_newtuplebuf = InvalidBuffer;
7216 fcinfo.context = (Node *) &trigdata;
7218 RI_FKey_check_ins(&fcinfo);
7222 UnregisterSnapshot(snapshot);
7226 CreateFKCheckTrigger(Oid myRelOid, Oid refRelOid, Constraint *fkconstraint,
7227 Oid constraintOid, Oid indexOid, bool on_insert)
7229 CreateTrigStmt *fk_trigger;
7232 * Note: for a self-referential FK (referencing and referenced tables are
7233 * the same), it is important that the ON UPDATE action fires before the
7234 * CHECK action, since both triggers will fire on the same row during an
7235 * UPDATE event; otherwise the CHECK trigger will be checking a non-final
7236 * state of the row. Triggers fire in name order, so we ensure this by
7237 * using names like "RI_ConstraintTrigger_a_NNNN" for the action triggers
7238 * and "RI_ConstraintTrigger_c_NNNN" for the check triggers.
7240 fk_trigger = makeNode(CreateTrigStmt);
7241 fk_trigger->trigname = "RI_ConstraintTrigger_c";
7242 fk_trigger->relation = NULL;
7243 fk_trigger->row = true;
7244 fk_trigger->timing = TRIGGER_TYPE_AFTER;
7246 /* Either ON INSERT or ON UPDATE */
7249 fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
7250 fk_trigger->events = TRIGGER_TYPE_INSERT;
7254 fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
7255 fk_trigger->events = TRIGGER_TYPE_UPDATE;
7258 fk_trigger->columns = NIL;
7259 fk_trigger->whenClause = NULL;
7260 fk_trigger->isconstraint = true;
7261 fk_trigger->deferrable = fkconstraint->deferrable;
7262 fk_trigger->initdeferred = fkconstraint->initdeferred;
7263 fk_trigger->constrrel = NULL;
7264 fk_trigger->args = NIL;
7266 (void) CreateTrigger(fk_trigger, NULL, myRelOid, refRelOid, constraintOid,
7269 /* Make changes-so-far visible */
7270 CommandCounterIncrement();
7274 * Create the triggers that implement an FK constraint.
7277 createForeignKeyTriggers(Relation rel, Oid refRelOid, Constraint *fkconstraint,
7278 Oid constraintOid, Oid indexOid)
7281 CreateTrigStmt *fk_trigger;
7283 myRelOid = RelationGetRelid(rel);
7285 /* Make changes-so-far visible */
7286 CommandCounterIncrement();
7289 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
7290 * DELETE action on the referenced table.
7292 fk_trigger = makeNode(CreateTrigStmt);
7293 fk_trigger->trigname = "RI_ConstraintTrigger_a";
7294 fk_trigger->relation = NULL;
7295 fk_trigger->row = true;
7296 fk_trigger->timing = TRIGGER_TYPE_AFTER;
7297 fk_trigger->events = TRIGGER_TYPE_DELETE;
7298 fk_trigger->columns = NIL;
7299 fk_trigger->whenClause = NULL;
7300 fk_trigger->isconstraint = true;
7301 fk_trigger->constrrel = NULL;
7302 switch (fkconstraint->fk_del_action)
7304 case FKCONSTR_ACTION_NOACTION:
7305 fk_trigger->deferrable = fkconstraint->deferrable;
7306 fk_trigger->initdeferred = fkconstraint->initdeferred;
7307 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
7309 case FKCONSTR_ACTION_RESTRICT:
7310 fk_trigger->deferrable = false;
7311 fk_trigger->initdeferred = false;
7312 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
7314 case FKCONSTR_ACTION_CASCADE:
7315 fk_trigger->deferrable = false;
7316 fk_trigger->initdeferred = false;
7317 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
7319 case FKCONSTR_ACTION_SETNULL:
7320 fk_trigger->deferrable = false;
7321 fk_trigger->initdeferred = false;
7322 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
7324 case FKCONSTR_ACTION_SETDEFAULT:
7325 fk_trigger->deferrable = false;
7326 fk_trigger->initdeferred = false;
7327 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
7330 elog(ERROR, "unrecognized FK action type: %d",
7331 (int) fkconstraint->fk_del_action);
7334 fk_trigger->args = NIL;
7336 (void) CreateTrigger(fk_trigger, NULL, refRelOid, myRelOid, constraintOid,
7339 /* Make changes-so-far visible */
7340 CommandCounterIncrement();
7343 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
7344 * UPDATE action on the referenced table.
7346 fk_trigger = makeNode(CreateTrigStmt);
7347 fk_trigger->trigname = "RI_ConstraintTrigger_a";
7348 fk_trigger->relation = NULL;
7349 fk_trigger->row = true;
7350 fk_trigger->timing = TRIGGER_TYPE_AFTER;
7351 fk_trigger->events = TRIGGER_TYPE_UPDATE;
7352 fk_trigger->columns = NIL;
7353 fk_trigger->whenClause = NULL;
7354 fk_trigger->isconstraint = true;
7355 fk_trigger->constrrel = NULL;
7356 switch (fkconstraint->fk_upd_action)
7358 case FKCONSTR_ACTION_NOACTION:
7359 fk_trigger->deferrable = fkconstraint->deferrable;
7360 fk_trigger->initdeferred = fkconstraint->initdeferred;
7361 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
7363 case FKCONSTR_ACTION_RESTRICT:
7364 fk_trigger->deferrable = false;
7365 fk_trigger->initdeferred = false;
7366 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
7368 case FKCONSTR_ACTION_CASCADE:
7369 fk_trigger->deferrable = false;
7370 fk_trigger->initdeferred = false;
7371 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
7373 case FKCONSTR_ACTION_SETNULL:
7374 fk_trigger->deferrable = false;
7375 fk_trigger->initdeferred = false;
7376 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
7378 case FKCONSTR_ACTION_SETDEFAULT:
7379 fk_trigger->deferrable = false;
7380 fk_trigger->initdeferred = false;
7381 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
7384 elog(ERROR, "unrecognized FK action type: %d",
7385 (int) fkconstraint->fk_upd_action);
7388 fk_trigger->args = NIL;
7390 (void) CreateTrigger(fk_trigger, NULL, refRelOid, myRelOid, constraintOid,
7393 /* Make changes-so-far visible */
7394 CommandCounterIncrement();
7397 * Build and execute CREATE CONSTRAINT TRIGGER statements for the CHECK
7398 * action for both INSERTs and UPDATEs on the referencing table.
7400 CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint, constraintOid,
7402 CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint, constraintOid,
7407 * ALTER TABLE DROP CONSTRAINT
7409 * Like DROP COLUMN, we can't use the normal ALTER TABLE recursion mechanism.
7412 ATExecDropConstraint(Relation rel, const char *constrName,
7413 DropBehavior behavior,
7414 bool recurse, bool recursing,
7415 bool missing_ok, LOCKMODE lockmode)
7420 Form_pg_constraint con;
7425 bool is_no_inherit_constraint = false;
7427 /* At top level, permission check was done in ATPrepCmd, else do it */
7429 ATSimplePermissions(rel, ATT_TABLE);
7431 conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
7434 * Find and drop the target constraint
7437 Anum_pg_constraint_conrelid,
7438 BTEqualStrategyNumber, F_OIDEQ,
7439 ObjectIdGetDatum(RelationGetRelid(rel)));
7440 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
7441 true, NULL, 1, &key);
7443 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
7445 ObjectAddress conobj;
7447 con = (Form_pg_constraint) GETSTRUCT(tuple);
7449 if (strcmp(NameStr(con->conname), constrName) != 0)
7452 /* Don't drop inherited constraints */
7453 if (con->coninhcount > 0 && !recursing)
7455 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7456 errmsg("cannot drop inherited constraint \"%s\" of relation \"%s\"",
7457 constrName, RelationGetRelationName(rel))));
7459 is_no_inherit_constraint = con->connoinherit;
7462 * Perform the actual constraint deletion
7464 conobj.classId = ConstraintRelationId;
7465 conobj.objectId = HeapTupleGetOid(tuple);
7466 conobj.objectSubId = 0;
7468 performDeletion(&conobj, behavior, 0);
7472 /* constraint found and dropped -- no need to keep looping */
7476 systable_endscan(scan);
7483 (errcode(ERRCODE_UNDEFINED_OBJECT),
7484 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
7485 constrName, RelationGetRelationName(rel))));
7490 (errmsg("constraint \"%s\" of relation \"%s\" does not exist, skipping",
7491 constrName, RelationGetRelationName(rel))));
7492 heap_close(conrel, RowExclusiveLock);
7498 * Propagate to children as appropriate. Unlike most other ALTER
7499 * routines, we have to do this one level of recursion at a time; we can't
7500 * use find_all_inheritors to do it in one pass.
7502 if (!is_no_inherit_constraint)
7503 children = find_inheritance_children(RelationGetRelid(rel), lockmode);
7507 foreach(child, children)
7509 Oid childrelid = lfirst_oid(child);
7511 HeapTuple copy_tuple;
7513 /* find_inheritance_children already got lock */
7514 childrel = heap_open(childrelid, NoLock);
7515 CheckTableNotInUse(childrel, "ALTER TABLE");
7518 Anum_pg_constraint_conrelid,
7519 BTEqualStrategyNumber, F_OIDEQ,
7520 ObjectIdGetDatum(childrelid));
7521 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
7522 true, NULL, 1, &key);
7524 /* scan for matching tuple - there should only be one */
7525 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
7527 con = (Form_pg_constraint) GETSTRUCT(tuple);
7529 /* Right now only CHECK constraints can be inherited */
7530 if (con->contype != CONSTRAINT_CHECK)
7533 if (strcmp(NameStr(con->conname), constrName) == 0)
7537 if (!HeapTupleIsValid(tuple))
7539 (errcode(ERRCODE_UNDEFINED_OBJECT),
7540 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
7542 RelationGetRelationName(childrel))));
7544 copy_tuple = heap_copytuple(tuple);
7546 systable_endscan(scan);
7548 con = (Form_pg_constraint) GETSTRUCT(copy_tuple);
7550 if (con->coninhcount <= 0) /* shouldn't happen */
7551 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
7552 childrelid, constrName);
7557 * If the child constraint has other definition sources, just
7558 * decrement its inheritance count; if not, recurse to delete it.
7560 if (con->coninhcount == 1 && !con->conislocal)
7562 /* Time to delete this child constraint, too */
7563 ATExecDropConstraint(childrel, constrName, behavior,
7569 /* Child constraint must survive my deletion */
7571 simple_heap_update(conrel, ©_tuple->t_self, copy_tuple);
7572 CatalogUpdateIndexes(conrel, copy_tuple);
7574 /* Make update visible */
7575 CommandCounterIncrement();
7581 * If we were told to drop ONLY in this table (no recursion), we
7582 * need to mark the inheritors' constraints as locally defined
7583 * rather than inherited.
7586 con->conislocal = true;
7588 simple_heap_update(conrel, ©_tuple->t_self, copy_tuple);
7589 CatalogUpdateIndexes(conrel, copy_tuple);
7591 /* Make update visible */
7592 CommandCounterIncrement();
7595 heap_freetuple(copy_tuple);
7597 heap_close(childrel, NoLock);
7600 heap_close(conrel, RowExclusiveLock);
7607 ATPrepAlterColumnType(List **wqueue,
7608 AlteredTableInfo *tab, Relation rel,
7609 bool recurse, bool recursing,
7610 AlterTableCmd *cmd, LOCKMODE lockmode)
7612 char *colName = cmd->name;
7613 ColumnDef *def = (ColumnDef *) cmd->def;
7614 TypeName *typeName = def->typeName;
7615 Node *transform = def->raw_default;
7617 Form_pg_attribute attTup;
7622 NewColumnValue *newval;
7623 ParseState *pstate = make_parsestate(NULL);
7624 AclResult aclresult;
7626 if (rel->rd_rel->reloftype && !recursing)
7628 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7629 errmsg("cannot alter column type of typed table")));
7631 /* lookup the attribute so we can check inheritance status */
7632 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
7633 if (!HeapTupleIsValid(tuple))
7635 (errcode(ERRCODE_UNDEFINED_COLUMN),
7636 errmsg("column \"%s\" of relation \"%s\" does not exist",
7637 colName, RelationGetRelationName(rel))));
7638 attTup = (Form_pg_attribute) GETSTRUCT(tuple);
7639 attnum = attTup->attnum;
7641 /* Can't alter a system attribute */
7644 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7645 errmsg("cannot alter system column \"%s\"",
7648 /* Don't alter inherited columns */
7649 if (attTup->attinhcount > 0 && !recursing)
7651 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7652 errmsg("cannot alter inherited column \"%s\"",
7655 /* Look up the target type */
7656 typenameTypeIdAndMod(NULL, typeName, &targettype, &targettypmod);
7658 aclresult = pg_type_aclcheck(targettype, GetUserId(), ACL_USAGE);
7659 if (aclresult != ACLCHECK_OK)
7660 aclcheck_error_type(aclresult, targettype);
7662 /* And the collation */
7663 targetcollid = GetColumnDefCollation(NULL, def, targettype);
7665 /* make sure datatype is legal for a column */
7666 CheckAttributeType(colName, targettype, targetcollid,
7667 list_make1_oid(rel->rd_rel->reltype),
7670 if (tab->relkind == RELKIND_RELATION)
7673 * Set up an expression to transform the old data value to the new
7674 * type. If a USING option was given, transform and use that
7675 * expression, else just take the old value and try to coerce it. We
7676 * do this first so that type incompatibility can be detected before
7677 * we waste effort, and because we need the expression to be parsed
7678 * against the original table row type.
7684 /* Expression must be able to access vars of old table */
7685 rte = addRangeTableEntryForRelation(pstate,
7690 addRTEtoQuery(pstate, rte, false, true, true);
7692 transform = transformExpr(pstate, transform,
7693 EXPR_KIND_ALTER_COL_TRANSFORM);
7695 /* It can't return a set */
7696 if (expression_returns_set(transform))
7698 (errcode(ERRCODE_DATATYPE_MISMATCH),
7699 errmsg("transform expression must not return a set")));
7703 transform = (Node *) makeVar(1, attnum,
7704 attTup->atttypid, attTup->atttypmod,
7705 attTup->attcollation,
7709 transform = coerce_to_target_type(pstate,
7710 transform, exprType(transform),
7711 targettype, targettypmod,
7712 COERCION_ASSIGNMENT,
7713 COERCE_IMPLICIT_CAST,
7715 if (transform == NULL)
7717 (errcode(ERRCODE_DATATYPE_MISMATCH),
7718 errmsg("column \"%s\" cannot be cast automatically to type %s",
7719 colName, format_type_be(targettype)),
7720 errhint("Specify a USING expression to perform the conversion.")));
7722 /* Fix collations after all else */
7723 assign_expr_collations(pstate, transform);
7725 /* Plan the expr now so we can accurately assess the need to rewrite. */
7726 transform = (Node *) expression_planner((Expr *) transform);
7729 * Add a work queue item to make ATRewriteTable update the column
7732 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
7733 newval->attnum = attnum;
7734 newval->expr = (Expr *) transform;
7736 tab->newvals = lappend(tab->newvals, newval);
7737 if (ATColumnChangeRequiresRewrite(transform, attnum))
7738 tab->rewrite |= AT_REWRITE_COLUMN_REWRITE;
7742 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7743 errmsg("\"%s\" is not a table",
7744 RelationGetRelationName(rel))));
7746 if (tab->relkind == RELKIND_COMPOSITE_TYPE ||
7747 tab->relkind == RELKIND_FOREIGN_TABLE)
7750 * For composite types, do this check now. Tables will check it later
7751 * when the table is being rewritten.
7753 find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
7756 ReleaseSysCache(tuple);
7759 * The recursion case is handled by ATSimpleRecursion. However, if we are
7760 * told not to recurse, there had better not be any child tables; else the
7761 * alter would put them out of step.
7764 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
7765 else if (!recursing &&
7766 find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL)
7768 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7769 errmsg("type of inherited column \"%s\" must be changed in child tables too",
7772 if (tab->relkind == RELKIND_COMPOSITE_TYPE)
7773 ATTypedTableRecursion(wqueue, rel, cmd, lockmode);
7777 * When the data type of a column is changed, a rewrite might not be required
7778 * if the new type is sufficiently identical to the old one, and the USING
7779 * clause isn't trying to insert some other value. It's safe to skip the
7780 * rewrite if the old type is binary coercible to the new type, or if the
7781 * new type is an unconstrained domain over the old type. In the case of a
7782 * constrained domain, we could get by with scanning the table and checking
7783 * the constraint rather than actually rewriting it, but we don't currently
7787 ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno)
7789 Assert(expr != NULL);
7793 /* only one varno, so no need to check that */
7794 if (IsA(expr, Var) &&((Var *) expr)->varattno == varattno)
7796 else if (IsA(expr, RelabelType))
7797 expr = (Node *) ((RelabelType *) expr)->arg;
7798 else if (IsA(expr, CoerceToDomain))
7800 CoerceToDomain *d = (CoerceToDomain *) expr;
7802 if (DomainHasConstraints(d->resulttype))
7804 expr = (Node *) d->arg;
7812 ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
7813 AlterTableCmd *cmd, LOCKMODE lockmode)
7815 char *colName = cmd->name;
7816 ColumnDef *def = (ColumnDef *) cmd->def;
7817 TypeName *typeName = def->typeName;
7819 Form_pg_attribute attTup;
7821 HeapTuple typeTuple;
7827 Relation attrelation;
7833 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
7835 /* Look up the target column */
7836 heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
7837 if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
7839 (errcode(ERRCODE_UNDEFINED_COLUMN),
7840 errmsg("column \"%s\" of relation \"%s\" does not exist",
7841 colName, RelationGetRelationName(rel))));
7842 attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
7843 attnum = attTup->attnum;
7845 /* Check for multiple ALTER TYPE on same column --- can't cope */
7846 if (attTup->atttypid != tab->oldDesc->attrs[attnum - 1]->atttypid ||
7847 attTup->atttypmod != tab->oldDesc->attrs[attnum - 1]->atttypmod)
7849 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7850 errmsg("cannot alter type of column \"%s\" twice",
7853 /* Look up the target type (should not fail, since prep found it) */
7854 typeTuple = typenameType(NULL, typeName, &targettypmod);
7855 tform = (Form_pg_type) GETSTRUCT(typeTuple);
7856 targettype = HeapTupleGetOid(typeTuple);
7857 /* And the collation */
7858 targetcollid = GetColumnDefCollation(NULL, def, targettype);
7861 * If there is a default expression for the column, get it and ensure we
7862 * can coerce it to the new datatype. (We must do this before changing
7863 * the column type, because build_column_default itself will try to
7864 * coerce, and will not issue the error message we want if it fails.)
7866 * We remove any implicit coercion steps at the top level of the old
7867 * default expression; this has been agreed to satisfy the principle of
7868 * least surprise. (The conversion to the new column type should act like
7869 * it started from what the user sees as the stored expression, and the
7870 * implicit coercions aren't going to be shown.)
7872 if (attTup->atthasdef)
7874 defaultexpr = build_column_default(rel, attnum);
7875 Assert(defaultexpr);
7876 defaultexpr = strip_implicit_coercions(defaultexpr);
7877 defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
7878 defaultexpr, exprType(defaultexpr),
7879 targettype, targettypmod,
7880 COERCION_ASSIGNMENT,
7881 COERCE_IMPLICIT_CAST,
7883 if (defaultexpr == NULL)
7885 (errcode(ERRCODE_DATATYPE_MISMATCH),
7886 errmsg("default for column \"%s\" cannot be cast automatically to type %s",
7887 colName, format_type_be(targettype))));
7893 * Find everything that depends on the column (constraints, indexes, etc),
7894 * and record enough information to let us recreate the objects.
7896 * The actual recreation does not happen here, but only after we have
7897 * performed all the individual ALTER TYPE operations. We have to save
7898 * the info before executing ALTER TYPE, though, else the deparser will
7901 * There could be multiple entries for the same object, so we must check
7902 * to ensure we process each one only once. Note: we assume that an index
7903 * that implements a constraint will not show a direct dependency on the
7906 depRel = heap_open(DependRelationId, RowExclusiveLock);
7908 ScanKeyInit(&key[0],
7909 Anum_pg_depend_refclassid,
7910 BTEqualStrategyNumber, F_OIDEQ,
7911 ObjectIdGetDatum(RelationRelationId));
7912 ScanKeyInit(&key[1],
7913 Anum_pg_depend_refobjid,
7914 BTEqualStrategyNumber, F_OIDEQ,
7915 ObjectIdGetDatum(RelationGetRelid(rel)));
7916 ScanKeyInit(&key[2],
7917 Anum_pg_depend_refobjsubid,
7918 BTEqualStrategyNumber, F_INT4EQ,
7919 Int32GetDatum((int32) attnum));
7921 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
7924 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
7926 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
7927 ObjectAddress foundObject;
7929 /* We don't expect any PIN dependencies on columns */
7930 if (foundDep->deptype == DEPENDENCY_PIN)
7931 elog(ERROR, "cannot alter type of a pinned column");
7933 foundObject.classId = foundDep->classid;
7934 foundObject.objectId = foundDep->objid;
7935 foundObject.objectSubId = foundDep->objsubid;
7937 switch (getObjectClass(&foundObject))
7941 char relKind = get_rel_relkind(foundObject.objectId);
7943 if (relKind == RELKIND_INDEX)
7945 Assert(foundObject.objectSubId == 0);
7946 if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
7948 tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
7949 foundObject.objectId);
7950 tab->changedIndexDefs = lappend(tab->changedIndexDefs,
7951 pg_get_indexdef_string(foundObject.objectId));
7954 else if (relKind == RELKIND_SEQUENCE)
7957 * This must be a SERIAL column's sequence. We need
7958 * not do anything to it.
7960 Assert(foundObject.objectSubId == 0);
7964 /* Not expecting any other direct dependencies... */
7965 elog(ERROR, "unexpected object depending on column: %s",
7966 getObjectDescription(&foundObject));
7971 case OCLASS_CONSTRAINT:
7972 Assert(foundObject.objectSubId == 0);
7973 if (!list_member_oid(tab->changedConstraintOids,
7974 foundObject.objectId))
7976 char *defstring = pg_get_constraintdef_string(foundObject.objectId);
7979 * Put NORMAL dependencies at the front of the list and
7980 * AUTO dependencies at the back. This makes sure that
7981 * foreign-key constraints depending on this column will
7982 * be dropped before unique or primary-key constraints of
7983 * the column; which we must have because the FK
7984 * constraints depend on the indexes belonging to the
7985 * unique constraints.
7987 if (foundDep->deptype == DEPENDENCY_NORMAL)
7989 tab->changedConstraintOids =
7990 lcons_oid(foundObject.objectId,
7991 tab->changedConstraintOids);
7992 tab->changedConstraintDefs =
7994 tab->changedConstraintDefs);
7998 tab->changedConstraintOids =
7999 lappend_oid(tab->changedConstraintOids,
8000 foundObject.objectId);
8001 tab->changedConstraintDefs =
8002 lappend(tab->changedConstraintDefs,
8008 case OCLASS_REWRITE:
8009 /* XXX someday see if we can cope with revising views */
8011 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8012 errmsg("cannot alter type of a column used by a view or rule"),
8013 errdetail("%s depends on column \"%s\"",
8014 getObjectDescription(&foundObject),
8018 case OCLASS_TRIGGER:
8021 * A trigger can depend on a column because the column is
8022 * specified as an update target, or because the column is
8023 * used in the trigger's WHEN condition. The first case would
8024 * not require any extra work, but the second case would
8025 * require updating the WHEN expression, which will take a
8026 * significant amount of new code. Since we can't easily tell
8027 * which case applies, we punt for both. FIXME someday.
8030 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8031 errmsg("cannot alter type of a column used in a trigger definition"),
8032 errdetail("%s depends on column \"%s\"",
8033 getObjectDescription(&foundObject),
8040 * A policy can depend on a column because the column is
8041 * specified in the policy's USING or WITH CHECK qual
8042 * expressions. It might be possible to rewrite and recheck
8043 * the policy expression, but punt for now. It's certainly
8044 * easy enough to remove and recreate the policy; still,
8048 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8049 errmsg("cannot alter type of a column used in a policy definition"),
8050 errdetail("%s depends on column \"%s\"",
8051 getObjectDescription(&foundObject),
8055 case OCLASS_DEFAULT:
8058 * Ignore the column's default expression, since we will fix
8061 Assert(defaultexpr);
8067 case OCLASS_COLLATION:
8068 case OCLASS_CONVERSION:
8069 case OCLASS_LANGUAGE:
8070 case OCLASS_LARGEOBJECT:
8071 case OCLASS_OPERATOR:
8072 case OCLASS_OPCLASS:
8073 case OCLASS_OPFAMILY:
8077 case OCLASS_TSPARSER:
8079 case OCLASS_TSTEMPLATE:
8080 case OCLASS_TSCONFIG:
8082 case OCLASS_DATABASE:
8083 case OCLASS_TBLSPACE:
8085 case OCLASS_FOREIGN_SERVER:
8086 case OCLASS_USER_MAPPING:
8088 case OCLASS_EXTENSION:
8091 * We don't expect any of these sorts of objects to depend on
8094 elog(ERROR, "unexpected object depending on column: %s",
8095 getObjectDescription(&foundObject));
8099 elog(ERROR, "unrecognized object class: %u",
8100 foundObject.classId);
8104 systable_endscan(scan);
8107 * Now scan for dependencies of this column on other things. The only
8108 * thing we should find is the dependency on the column datatype, which we
8109 * want to remove, and possibly a collation dependency.
8111 ScanKeyInit(&key[0],
8112 Anum_pg_depend_classid,
8113 BTEqualStrategyNumber, F_OIDEQ,
8114 ObjectIdGetDatum(RelationRelationId));
8115 ScanKeyInit(&key[1],
8116 Anum_pg_depend_objid,
8117 BTEqualStrategyNumber, F_OIDEQ,
8118 ObjectIdGetDatum(RelationGetRelid(rel)));
8119 ScanKeyInit(&key[2],
8120 Anum_pg_depend_objsubid,
8121 BTEqualStrategyNumber, F_INT4EQ,
8122 Int32GetDatum((int32) attnum));
8124 scan = systable_beginscan(depRel, DependDependerIndexId, true,
8127 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
8129 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
8131 if (foundDep->deptype != DEPENDENCY_NORMAL)
8132 elog(ERROR, "found unexpected dependency type '%c'",
8134 if (!(foundDep->refclassid == TypeRelationId &&
8135 foundDep->refobjid == attTup->atttypid) &&
8136 !(foundDep->refclassid == CollationRelationId &&
8137 foundDep->refobjid == attTup->attcollation))
8138 elog(ERROR, "found unexpected dependency for column");
8140 simple_heap_delete(depRel, &depTup->t_self);
8143 systable_endscan(scan);
8145 heap_close(depRel, RowExclusiveLock);
8148 * Here we go --- change the recorded column type and collation. (Note
8149 * heapTup is a copy of the syscache entry, so okay to scribble on.)
8151 attTup->atttypid = targettype;
8152 attTup->atttypmod = targettypmod;
8153 attTup->attcollation = targetcollid;
8154 attTup->attndims = list_length(typeName->arrayBounds);
8155 attTup->attlen = tform->typlen;
8156 attTup->attbyval = tform->typbyval;
8157 attTup->attalign = tform->typalign;
8158 attTup->attstorage = tform->typstorage;
8160 ReleaseSysCache(typeTuple);
8162 simple_heap_update(attrelation, &heapTup->t_self, heapTup);
8164 /* keep system catalog indexes current */
8165 CatalogUpdateIndexes(attrelation, heapTup);
8167 heap_close(attrelation, RowExclusiveLock);
8169 /* Install dependencies on new datatype and collation */
8170 add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
8171 add_column_collation_dependency(RelationGetRelid(rel), attnum, targetcollid);
8174 * Drop any pg_statistic entry for the column, since it's now wrong type
8176 RemoveStatistics(RelationGetRelid(rel), attnum);
8178 InvokeObjectPostAlterHook(RelationRelationId,
8179 RelationGetRelid(rel), attnum);
8182 * Update the default, if present, by brute force --- remove and re-add
8183 * the default. Probably unsafe to take shortcuts, since the new version
8184 * may well have additional dependencies. (It's okay to do this now,
8185 * rather than after other ALTER TYPE commands, since the default won't
8186 * depend on other column types.)
8190 /* Must make new row visible since it will be updated again */
8191 CommandCounterIncrement();
8194 * We use RESTRICT here for safety, but at present we do not expect
8195 * anything to depend on the default.
8197 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true,
8200 StoreAttrDefault(rel, attnum, defaultexpr, true);
8204 heap_freetuple(heapTup);
8208 ATExecAlterColumnGenericOptions(Relation rel,
8209 const char *colName,
8215 ForeignServer *server;
8216 ForeignDataWrapper *fdw;
8220 Datum repl_val[Natts_pg_attribute];
8221 bool repl_null[Natts_pg_attribute];
8222 bool repl_repl[Natts_pg_attribute];
8224 Form_pg_foreign_table fttableform;
8225 Form_pg_attribute atttableform;
8230 /* First, determine FDW validator associated to the foreign table. */
8231 ftrel = heap_open(ForeignTableRelationId, AccessShareLock);
8232 tuple = SearchSysCache1(FOREIGNTABLEREL, rel->rd_id);
8233 if (!HeapTupleIsValid(tuple))
8235 (errcode(ERRCODE_UNDEFINED_OBJECT),
8236 errmsg("foreign table \"%s\" does not exist",
8237 RelationGetRelationName(rel))));
8238 fttableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
8239 server = GetForeignServer(fttableform->ftserver);
8240 fdw = GetForeignDataWrapper(server->fdwid);
8242 heap_close(ftrel, AccessShareLock);
8243 ReleaseSysCache(tuple);
8245 attrel = heap_open(AttributeRelationId, RowExclusiveLock);
8246 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
8247 if (!HeapTupleIsValid(tuple))
8249 (errcode(ERRCODE_UNDEFINED_COLUMN),
8250 errmsg("column \"%s\" of relation \"%s\" does not exist",
8251 colName, RelationGetRelationName(rel))));
8253 /* Prevent them from altering a system attribute */
8254 atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
8255 if (atttableform->attnum <= 0)
8257 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8258 errmsg("cannot alter system column \"%s\"", colName)));
8261 /* Initialize buffers for new tuple values */
8262 memset(repl_val, 0, sizeof(repl_val));
8263 memset(repl_null, false, sizeof(repl_null));
8264 memset(repl_repl, false, sizeof(repl_repl));
8266 /* Extract the current options */
8267 datum = SysCacheGetAttr(ATTNAME,
8269 Anum_pg_attribute_attfdwoptions,
8272 datum = PointerGetDatum(NULL);
8274 /* Transform the options */
8275 datum = transformGenericOptions(AttributeRelationId,
8280 if (PointerIsValid(DatumGetPointer(datum)))
8281 repl_val[Anum_pg_attribute_attfdwoptions - 1] = datum;
8283 repl_null[Anum_pg_attribute_attfdwoptions - 1] = true;
8285 repl_repl[Anum_pg_attribute_attfdwoptions - 1] = true;
8287 /* Everything looks good - update the tuple */
8289 newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrel),
8290 repl_val, repl_null, repl_repl);
8292 simple_heap_update(attrel, &newtuple->t_self, newtuple);
8293 CatalogUpdateIndexes(attrel, newtuple);
8295 InvokeObjectPostAlterHook(RelationRelationId,
8296 RelationGetRelid(rel),
8297 atttableform->attnum);
8299 ReleaseSysCache(tuple);
8301 heap_close(attrel, RowExclusiveLock);
8303 heap_freetuple(newtuple);
8307 * Cleanup after we've finished all the ALTER TYPE operations for a
8308 * particular relation. We have to drop and recreate all the indexes
8309 * and constraints that depend on the altered columns.
8312 ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)
8319 * Re-parse the index and constraint definitions, and attach them to the
8320 * appropriate work queue entries. We do this before dropping because in
8321 * the case of a FOREIGN KEY constraint, we might not yet have exclusive
8322 * lock on the table the constraint is attached to, and we need to get
8323 * that before dropping. It's safe because the parser won't actually look
8324 * at the catalogs to detect the existing entry.
8326 * We can't rely on the output of deparsing to tell us which relation to
8327 * operate on, because concurrent activity might have made the name
8328 * resolve differently. Instead, we've got to use the OID of the
8329 * constraint or index we're processing to figure out which relation to
8332 forboth(oid_item, tab->changedConstraintOids,
8333 def_item, tab->changedConstraintDefs)
8335 Oid oldId = lfirst_oid(oid_item);
8339 get_constraint_relation_oids(oldId, &relid, &confrelid);
8340 ATPostAlterTypeParse(oldId, relid, confrelid,
8341 (char *) lfirst(def_item),
8342 wqueue, lockmode, tab->rewrite);
8344 forboth(oid_item, tab->changedIndexOids,
8345 def_item, tab->changedIndexDefs)
8347 Oid oldId = lfirst_oid(oid_item);
8350 relid = IndexGetRelation(oldId, false);
8351 ATPostAlterTypeParse(oldId, relid, InvalidOid,
8352 (char *) lfirst(def_item),
8353 wqueue, lockmode, tab->rewrite);
8357 * Now we can drop the existing constraints and indexes --- constraints
8358 * first, since some of them might depend on the indexes. In fact, we
8359 * have to delete FOREIGN KEY constraints before UNIQUE constraints, but
8360 * we already ordered the constraint list to ensure that would happen. It
8361 * should be okay to use DROP_RESTRICT here, since nothing else should be
8362 * depending on these objects.
8364 foreach(oid_item, tab->changedConstraintOids)
8366 obj.classId = ConstraintRelationId;
8367 obj.objectId = lfirst_oid(oid_item);
8368 obj.objectSubId = 0;
8369 performDeletion(&obj, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
8372 foreach(oid_item, tab->changedIndexOids)
8374 obj.classId = RelationRelationId;
8375 obj.objectId = lfirst_oid(oid_item);
8376 obj.objectSubId = 0;
8377 performDeletion(&obj, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
8381 * The objects will get recreated during subsequent passes over the work
8387 ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
8388 List **wqueue, LOCKMODE lockmode, bool rewrite)
8390 List *raw_parsetree_list;
8391 List *querytree_list;
8392 ListCell *list_item;
8396 * We expect that we will get only ALTER TABLE and CREATE INDEX
8397 * statements. Hence, there is no need to pass them through
8398 * parse_analyze() or the rewriter, but instead we need to pass them
8399 * through parse_utilcmd.c to make them ready for execution.
8401 raw_parsetree_list = raw_parser(cmd);
8402 querytree_list = NIL;
8403 foreach(list_item, raw_parsetree_list)
8405 Node *stmt = (Node *) lfirst(list_item);
8407 if (IsA(stmt, IndexStmt))
8408 querytree_list = lappend(querytree_list,
8409 transformIndexStmt(oldRelId,
8412 else if (IsA(stmt, AlterTableStmt))
8413 querytree_list = list_concat(querytree_list,
8414 transformAlterTableStmt(oldRelId,
8415 (AlterTableStmt *) stmt,
8418 querytree_list = lappend(querytree_list, stmt);
8421 /* Caller should already have acquired whatever lock we need. */
8422 rel = relation_open(oldRelId, NoLock);
8425 * Attach each generated command to the proper place in the work queue.
8426 * Note this could result in creation of entirely new work-queue entries.
8428 * Also note that we have to tweak the command subtypes, because it turns
8429 * out that re-creation of indexes and constraints has to act a bit
8430 * differently from initial creation.
8432 foreach(list_item, querytree_list)
8434 Node *stm = (Node *) lfirst(list_item);
8435 AlteredTableInfo *tab;
8437 switch (nodeTag(stm))
8441 IndexStmt *stmt = (IndexStmt *) stm;
8442 AlterTableCmd *newcmd;
8445 TryReuseIndex(oldId, stmt);
8447 tab = ATGetQueueEntry(wqueue, rel);
8448 newcmd = makeNode(AlterTableCmd);
8449 newcmd->subtype = AT_ReAddIndex;
8450 newcmd->def = (Node *) stmt;
8451 tab->subcmds[AT_PASS_OLD_INDEX] =
8452 lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
8455 case T_AlterTableStmt:
8457 AlterTableStmt *stmt = (AlterTableStmt *) stm;
8460 tab = ATGetQueueEntry(wqueue, rel);
8461 foreach(lcmd, stmt->cmds)
8463 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
8466 switch (cmd->subtype)
8469 Assert(IsA(cmd->def, IndexStmt));
8471 TryReuseIndex(get_constraint_index(oldId),
8472 (IndexStmt *) cmd->def);
8473 cmd->subtype = AT_ReAddIndex;
8474 tab->subcmds[AT_PASS_OLD_INDEX] =
8475 lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
8477 case AT_AddConstraint:
8478 Assert(IsA(cmd->def, Constraint));
8479 con = (Constraint *) cmd->def;
8480 con->old_pktable_oid = refRelId;
8481 /* rewriting neither side of a FK */
8482 if (con->contype == CONSTR_FOREIGN &&
8483 !rewrite && tab->rewrite == 0)
8484 TryReuseForeignKey(oldId, con);
8485 cmd->subtype = AT_ReAddConstraint;
8486 tab->subcmds[AT_PASS_OLD_CONSTR] =
8487 lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
8490 elog(ERROR, "unexpected statement type: %d",
8491 (int) cmd->subtype);
8497 elog(ERROR, "unexpected statement type: %d",
8498 (int) nodeTag(stm));
8502 relation_close(rel, NoLock);
8506 * Subroutine for ATPostAlterTypeParse(). Calls out to CheckIndexCompatible()
8507 * for the real analysis, then mutates the IndexStmt based on that verdict.
8510 TryReuseIndex(Oid oldId, IndexStmt *stmt)
8512 if (CheckIndexCompatible(oldId,
8515 stmt->excludeOpNames))
8517 Relation irel = index_open(oldId, NoLock);
8519 stmt->oldNode = irel->rd_node.relNode;
8520 index_close(irel, NoLock);
8525 * Subroutine for ATPostAlterTypeParse().
8527 * Stash the old P-F equality operator into the Constraint node, for possible
8528 * use by ATAddForeignKeyConstraint() in determining whether revalidation of
8529 * this constraint can be skipped.
8532 TryReuseForeignKey(Oid oldId, Constraint *con)
8542 Assert(con->contype == CONSTR_FOREIGN);
8543 Assert(con->old_conpfeqop == NIL); /* already prepared this node */
8545 tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(oldId));
8546 if (!HeapTupleIsValid(tup)) /* should not happen */
8547 elog(ERROR, "cache lookup failed for constraint %u", oldId);
8549 adatum = SysCacheGetAttr(CONSTROID, tup,
8550 Anum_pg_constraint_conpfeqop, &isNull);
8552 elog(ERROR, "null conpfeqop for constraint %u", oldId);
8553 arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
8554 numkeys = ARR_DIMS(arr)[0];
8555 /* test follows the one in ri_FetchConstraintInfo() */
8556 if (ARR_NDIM(arr) != 1 ||
8558 ARR_ELEMTYPE(arr) != OIDOID)
8559 elog(ERROR, "conpfeqop is not a 1-D Oid array");
8560 rawarr = (Oid *) ARR_DATA_PTR(arr);
8562 /* stash a List of the operator Oids in our Constraint node */
8563 for (i = 0; i < numkeys; i++)
8564 con->old_conpfeqop = lcons_oid(rawarr[i], con->old_conpfeqop);
8566 ReleaseSysCache(tup);
8572 * recursing is true if we are recursing from a table to its indexes,
8573 * sequences, or toast table. We don't allow the ownership of those things to
8574 * be changed separately from the parent table. Also, we can skip permission
8575 * checks (this is necessary not just an optimization, else we'd fail to
8576 * handle toast tables properly).
8578 * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
8579 * free-standing composite type.
8582 ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
8584 Relation target_rel;
8587 Form_pg_class tuple_class;
8590 * Get exclusive lock till end of transaction on the target table. Use
8591 * relation_open so that we can work on indexes and sequences.
8593 target_rel = relation_open(relationOid, lockmode);
8595 /* Get its pg_class tuple, too */
8596 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
8598 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
8599 if (!HeapTupleIsValid(tuple))
8600 elog(ERROR, "cache lookup failed for relation %u", relationOid);
8601 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
8603 /* Can we change the ownership of this tuple? */
8604 switch (tuple_class->relkind)
8606 case RELKIND_RELATION:
8608 case RELKIND_MATVIEW:
8609 case RELKIND_FOREIGN_TABLE:
8610 /* ok to change owner */
8616 * Because ALTER INDEX OWNER used to be allowed, and in fact
8617 * is generated by old versions of pg_dump, we give a warning
8618 * and do nothing rather than erroring out. Also, to avoid
8619 * unnecessary chatter while restoring those old dumps, say
8620 * nothing at all if the command would be a no-op anyway.
8622 if (tuple_class->relowner != newOwnerId)
8624 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8625 errmsg("cannot change owner of index \"%s\"",
8626 NameStr(tuple_class->relname)),
8627 errhint("Change the ownership of the index's table, instead.")));
8628 /* quick hack to exit via the no-op path */
8629 newOwnerId = tuple_class->relowner;
8632 case RELKIND_SEQUENCE:
8634 tuple_class->relowner != newOwnerId)
8636 /* if it's an owned sequence, disallow changing it by itself */
8640 if (sequenceIsOwned(relationOid, &tableId, &colId))
8642 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8643 errmsg("cannot change owner of sequence \"%s\"",
8644 NameStr(tuple_class->relname)),
8645 errdetail("Sequence \"%s\" is linked to table \"%s\".",
8646 NameStr(tuple_class->relname),
8647 get_rel_name(tableId))));
8650 case RELKIND_COMPOSITE_TYPE:
8654 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8655 errmsg("\"%s\" is a composite type",
8656 NameStr(tuple_class->relname)),
8657 errhint("Use ALTER TYPE instead.")));
8659 case RELKIND_TOASTVALUE:
8665 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8666 errmsg("\"%s\" is not a table, view, sequence, or foreign table",
8667 NameStr(tuple_class->relname))));
8671 * If the new owner is the same as the existing owner, consider the
8672 * command to have succeeded. This is for dump restoration purposes.
8674 if (tuple_class->relowner != newOwnerId)
8676 Datum repl_val[Natts_pg_class];
8677 bool repl_null[Natts_pg_class];
8678 bool repl_repl[Natts_pg_class];
8684 /* skip permission checks when recursing to index or toast table */
8687 /* Superusers can always do it */
8690 Oid namespaceOid = tuple_class->relnamespace;
8691 AclResult aclresult;
8693 /* Otherwise, must be owner of the existing object */
8694 if (!pg_class_ownercheck(relationOid, GetUserId()))
8695 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
8696 RelationGetRelationName(target_rel));
8698 /* Must be able to become new owner */
8699 check_is_member_of_role(GetUserId(), newOwnerId);
8701 /* New owner must have CREATE privilege on namespace */
8702 aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
8704 if (aclresult != ACLCHECK_OK)
8705 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
8706 get_namespace_name(namespaceOid));
8710 memset(repl_null, false, sizeof(repl_null));
8711 memset(repl_repl, false, sizeof(repl_repl));
8713 repl_repl[Anum_pg_class_relowner - 1] = true;
8714 repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
8717 * Determine the modified ACL for the new owner. This is only
8718 * necessary when the ACL is non-null.
8720 aclDatum = SysCacheGetAttr(RELOID, tuple,
8721 Anum_pg_class_relacl,
8725 newAcl = aclnewowner(DatumGetAclP(aclDatum),
8726 tuple_class->relowner, newOwnerId);
8727 repl_repl[Anum_pg_class_relacl - 1] = true;
8728 repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
8731 newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
8733 simple_heap_update(class_rel, &newtuple->t_self, newtuple);
8734 CatalogUpdateIndexes(class_rel, newtuple);
8736 heap_freetuple(newtuple);
8739 * We must similarly update any per-column ACLs to reflect the new
8740 * owner; for neatness reasons that's split out as a subroutine.
8742 change_owner_fix_column_acls(relationOid,
8743 tuple_class->relowner,
8747 * Update owner dependency reference, if any. A composite type has
8748 * none, because it's tracked for the pg_type entry instead of here;
8749 * indexes and TOAST tables don't have their own entries either.
8751 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
8752 tuple_class->relkind != RELKIND_INDEX &&
8753 tuple_class->relkind != RELKIND_TOASTVALUE)
8754 changeDependencyOnOwner(RelationRelationId, relationOid,
8758 * Also change the ownership of the table's row type, if it has one
8760 if (tuple_class->relkind != RELKIND_INDEX)
8761 AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId,
8762 tuple_class->relkind == RELKIND_COMPOSITE_TYPE);
8765 * If we are operating on a table or materialized view, also change
8766 * the ownership of any indexes and sequences that belong to the
8767 * relation, as well as its toast table (if it has one).
8769 if (tuple_class->relkind == RELKIND_RELATION ||
8770 tuple_class->relkind == RELKIND_MATVIEW ||
8771 tuple_class->relkind == RELKIND_TOASTVALUE)
8773 List *index_oid_list;
8776 /* Find all the indexes belonging to this relation */
8777 index_oid_list = RelationGetIndexList(target_rel);
8779 /* For each index, recursively change its ownership */
8780 foreach(i, index_oid_list)
8781 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
8783 list_free(index_oid_list);
8786 if (tuple_class->relkind == RELKIND_RELATION ||
8787 tuple_class->relkind == RELKIND_MATVIEW)
8789 /* If it has a toast table, recurse to change its ownership */
8790 if (tuple_class->reltoastrelid != InvalidOid)
8791 ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
8794 /* If it has dependent sequences, recurse to change them too */
8795 change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
8799 InvokeObjectPostAlterHook(RelationRelationId, relationOid, 0);
8801 ReleaseSysCache(tuple);
8802 heap_close(class_rel, RowExclusiveLock);
8803 relation_close(target_rel, NoLock);
8807 * change_owner_fix_column_acls
8809 * Helper function for ATExecChangeOwner. Scan the columns of the table
8810 * and fix any non-null column ACLs to reflect the new owner.
8813 change_owner_fix_column_acls(Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
8815 Relation attRelation;
8818 HeapTuple attributeTuple;
8820 attRelation = heap_open(AttributeRelationId, RowExclusiveLock);
8821 ScanKeyInit(&key[0],
8822 Anum_pg_attribute_attrelid,
8823 BTEqualStrategyNumber, F_OIDEQ,
8824 ObjectIdGetDatum(relationOid));
8825 scan = systable_beginscan(attRelation, AttributeRelidNumIndexId,
8826 true, NULL, 1, key);
8827 while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
8829 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
8830 Datum repl_val[Natts_pg_attribute];
8831 bool repl_null[Natts_pg_attribute];
8832 bool repl_repl[Natts_pg_attribute];
8838 /* Ignore dropped columns */
8839 if (att->attisdropped)
8842 aclDatum = heap_getattr(attributeTuple,
8843 Anum_pg_attribute_attacl,
8844 RelationGetDescr(attRelation),
8846 /* Null ACLs do not require changes */
8850 memset(repl_null, false, sizeof(repl_null));
8851 memset(repl_repl, false, sizeof(repl_repl));
8853 newAcl = aclnewowner(DatumGetAclP(aclDatum),
8854 oldOwnerId, newOwnerId);
8855 repl_repl[Anum_pg_attribute_attacl - 1] = true;
8856 repl_val[Anum_pg_attribute_attacl - 1] = PointerGetDatum(newAcl);
8858 newtuple = heap_modify_tuple(attributeTuple,
8859 RelationGetDescr(attRelation),
8860 repl_val, repl_null, repl_repl);
8862 simple_heap_update(attRelation, &newtuple->t_self, newtuple);
8863 CatalogUpdateIndexes(attRelation, newtuple);
8865 heap_freetuple(newtuple);
8867 systable_endscan(scan);
8868 heap_close(attRelation, RowExclusiveLock);
8872 * change_owner_recurse_to_sequences
8874 * Helper function for ATExecChangeOwner. Examines pg_depend searching
8875 * for sequences that are dependent on serial columns, and changes their
8879 change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
8887 * SERIAL sequences are those having an auto dependency on one of the
8888 * table's columns (we don't care *which* column, exactly).
8890 depRel = heap_open(DependRelationId, AccessShareLock);
8892 ScanKeyInit(&key[0],
8893 Anum_pg_depend_refclassid,
8894 BTEqualStrategyNumber, F_OIDEQ,
8895 ObjectIdGetDatum(RelationRelationId));
8896 ScanKeyInit(&key[1],
8897 Anum_pg_depend_refobjid,
8898 BTEqualStrategyNumber, F_OIDEQ,
8899 ObjectIdGetDatum(relationOid));
8900 /* we leave refobjsubid unspecified */
8902 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
8905 while (HeapTupleIsValid(tup = systable_getnext(scan)))
8907 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
8910 /* skip dependencies other than auto dependencies on columns */
8911 if (depForm->refobjsubid == 0 ||
8912 depForm->classid != RelationRelationId ||
8913 depForm->objsubid != 0 ||
8914 depForm->deptype != DEPENDENCY_AUTO)
8917 /* Use relation_open just in case it's an index */
8918 seqRel = relation_open(depForm->objid, lockmode);
8920 /* skip non-sequence relations */
8921 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
8923 /* No need to keep the lock */
8924 relation_close(seqRel, lockmode);
8928 /* We don't need to close the sequence while we alter it. */
8929 ATExecChangeOwner(depForm->objid, newOwnerId, true, lockmode);
8931 /* Now we can close it. Keep the lock till end of transaction. */
8932 relation_close(seqRel, NoLock);
8935 systable_endscan(scan);
8937 relation_close(depRel, AccessShareLock);
8941 * ALTER TABLE CLUSTER ON
8943 * The only thing we have to do is to change the indisclustered bits.
8946 ATExecClusterOn(Relation rel, const char *indexName, LOCKMODE lockmode)
8950 indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
8952 if (!OidIsValid(indexOid))
8954 (errcode(ERRCODE_UNDEFINED_OBJECT),
8955 errmsg("index \"%s\" for table \"%s\" does not exist",
8956 indexName, RelationGetRelationName(rel))));
8958 /* Check index is valid to cluster on */
8959 check_index_is_clusterable(rel, indexOid, false, lockmode);
8961 /* And do the work */
8962 mark_index_clustered(rel, indexOid, false);
8966 * ALTER TABLE SET WITHOUT CLUSTER
8968 * We have to find any indexes on the table that have indisclustered bit
8969 * set and turn it off.
8972 ATExecDropCluster(Relation rel, LOCKMODE lockmode)
8974 mark_index_clustered(rel, InvalidOid, false);
8978 * ALTER TABLE SET TABLESPACE
8981 ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, char *tablespacename, LOCKMODE lockmode)
8985 /* Check that the tablespace exists */
8986 tablespaceId = get_tablespace_oid(tablespacename, false);
8988 /* Check permissions except when moving to database's default */
8989 if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
8991 AclResult aclresult;
8993 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(), ACL_CREATE);
8994 if (aclresult != ACLCHECK_OK)
8995 aclcheck_error(aclresult, ACL_KIND_TABLESPACE, tablespacename);
8998 /* Save info for Phase 3 to do the real work */
8999 if (OidIsValid(tab->newTableSpace))
9001 (errcode(ERRCODE_SYNTAX_ERROR),
9002 errmsg("cannot have multiple SET TABLESPACE subcommands")));
9004 tab->newTableSpace = tablespaceId;
9008 * Set, reset, or replace reloptions.
9011 ATExecSetRelOptions(Relation rel, List *defList, AlterTableType operation,
9021 Datum repl_val[Natts_pg_class];
9022 bool repl_null[Natts_pg_class];
9023 bool repl_repl[Natts_pg_class];
9024 static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
9026 if (defList == NIL && operation != AT_ReplaceRelOptions)
9027 return; /* nothing to do */
9029 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
9031 /* Fetch heap tuple */
9032 relid = RelationGetRelid(rel);
9033 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
9034 if (!HeapTupleIsValid(tuple))
9035 elog(ERROR, "cache lookup failed for relation %u", relid);
9037 if (operation == AT_ReplaceRelOptions)
9040 * If we're supposed to replace the reloptions list, we just pretend
9041 * there were none before.
9048 /* Get the old reloptions */
9049 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
9053 /* Generate new proposed reloptions (text array) */
9054 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
9055 defList, NULL, validnsps, false,
9056 operation == AT_ResetRelOptions);
9059 switch (rel->rd_rel->relkind)
9061 case RELKIND_RELATION:
9062 case RELKIND_TOASTVALUE:
9063 case RELKIND_MATVIEW:
9064 (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
9067 (void) view_reloptions(newOptions, true);
9070 (void) index_reloptions(rel->rd_am->amoptions, newOptions, true);
9074 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9075 errmsg("\"%s\" is not a table, view, materialized view, index, or TOAST table",
9076 RelationGetRelationName(rel))));
9080 /* Special-case validation of view options */
9081 if (rel->rd_rel->relkind == RELKIND_VIEW)
9083 Query *view_query = get_view_query(rel);
9084 List *view_options = untransformRelOptions(newOptions);
9086 bool check_option = false;
9088 foreach(cell, view_options)
9090 DefElem *defel = (DefElem *) lfirst(cell);
9092 if (pg_strcasecmp(defel->defname, "check_option") == 0)
9093 check_option = true;
9097 * If the check option is specified, look to see if the view is
9098 * actually auto-updatable or not.
9102 const char *view_updatable_error =
9103 view_query_is_auto_updatable(view_query, true);
9105 if (view_updatable_error)
9107 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9108 errmsg("WITH CHECK OPTION is supported only on automatically updatable views"),
9109 errhint("%s", view_updatable_error)));
9114 * All we need do here is update the pg_class row; the new options will be
9115 * propagated into relcaches during post-commit cache inval.
9117 memset(repl_val, 0, sizeof(repl_val));
9118 memset(repl_null, false, sizeof(repl_null));
9119 memset(repl_repl, false, sizeof(repl_repl));
9121 if (newOptions != (Datum) 0)
9122 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
9124 repl_null[Anum_pg_class_reloptions - 1] = true;
9126 repl_repl[Anum_pg_class_reloptions - 1] = true;
9128 newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
9129 repl_val, repl_null, repl_repl);
9131 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
9133 CatalogUpdateIndexes(pgclass, newtuple);
9135 InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
9137 heap_freetuple(newtuple);
9139 ReleaseSysCache(tuple);
9141 /* repeat the whole exercise for the toast table, if there's one */
9142 if (OidIsValid(rel->rd_rel->reltoastrelid))
9145 Oid toastid = rel->rd_rel->reltoastrelid;
9147 toastrel = heap_open(toastid, lockmode);
9149 /* Fetch heap tuple */
9150 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(toastid));
9151 if (!HeapTupleIsValid(tuple))
9152 elog(ERROR, "cache lookup failed for relation %u", toastid);
9154 if (operation == AT_ReplaceRelOptions)
9157 * If we're supposed to replace the reloptions list, we just
9158 * pretend there were none before.
9165 /* Get the old reloptions */
9166 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
9170 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
9171 defList, "toast", validnsps, false,
9172 operation == AT_ResetRelOptions);
9174 (void) heap_reloptions(RELKIND_TOASTVALUE, newOptions, true);
9176 memset(repl_val, 0, sizeof(repl_val));
9177 memset(repl_null, false, sizeof(repl_null));
9178 memset(repl_repl, false, sizeof(repl_repl));
9180 if (newOptions != (Datum) 0)
9181 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
9183 repl_null[Anum_pg_class_reloptions - 1] = true;
9185 repl_repl[Anum_pg_class_reloptions - 1] = true;
9187 newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
9188 repl_val, repl_null, repl_repl);
9190 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
9192 CatalogUpdateIndexes(pgclass, newtuple);
9194 InvokeObjectPostAlterHookArg(RelationRelationId,
9195 RelationGetRelid(toastrel), 0,
9198 heap_freetuple(newtuple);
9200 ReleaseSysCache(tuple);
9202 heap_close(toastrel, NoLock);
9205 heap_close(pgclass, RowExclusiveLock);
9209 * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
9210 * rewriting to be done, so we just want to copy the data as fast as possible.
9213 ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode)
9219 RelFileNode newrnode;
9220 SMgrRelation dstrel;
9223 Form_pg_class rd_rel;
9225 List *reltoastidxids = NIL;
9229 * Need lock here in case we are recursing to toast table or index
9231 rel = relation_open(tableOid, lockmode);
9234 * No work if no change in tablespace.
9236 oldTableSpace = rel->rd_rel->reltablespace;
9237 if (newTableSpace == oldTableSpace ||
9238 (newTableSpace == MyDatabaseTableSpace && oldTableSpace == 0))
9240 InvokeObjectPostAlterHook(RelationRelationId,
9241 RelationGetRelid(rel), 0);
9243 relation_close(rel, NoLock);
9248 * We cannot support moving mapped relations into different tablespaces.
9249 * (In particular this eliminates all shared catalogs.)
9251 if (RelationIsMapped(rel))
9253 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9254 errmsg("cannot move system relation \"%s\"",
9255 RelationGetRelationName(rel))));
9257 /* Can't move a non-shared relation into pg_global */
9258 if (newTableSpace == GLOBALTABLESPACE_OID)
9260 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
9261 errmsg("only shared relations can be placed in pg_global tablespace")));
9264 * Don't allow moving temp tables of other backends ... their local buffer
9265 * manager is not going to cope.
9267 if (RELATION_IS_OTHER_TEMP(rel))
9269 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9270 errmsg("cannot move temporary tables of other sessions")));
9272 reltoastrelid = rel->rd_rel->reltoastrelid;
9273 /* Fetch the list of indexes on toast relation if necessary */
9274 if (OidIsValid(reltoastrelid))
9276 Relation toastRel = relation_open(reltoastrelid, lockmode);
9278 reltoastidxids = RelationGetIndexList(toastRel);
9279 relation_close(toastRel, lockmode);
9282 /* Get a modifiable copy of the relation's pg_class row */
9283 pg_class = heap_open(RelationRelationId, RowExclusiveLock);
9285 tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(tableOid));
9286 if (!HeapTupleIsValid(tuple))
9287 elog(ERROR, "cache lookup failed for relation %u", tableOid);
9288 rd_rel = (Form_pg_class) GETSTRUCT(tuple);
9291 * Since we copy the file directly without looking at the shared buffers,
9292 * we'd better first flush out any pages of the source relation that are
9293 * in shared buffers. We assume no new changes will be made while we are
9294 * holding exclusive lock on the rel.
9296 FlushRelationBuffers(rel);
9299 * Relfilenodes are not unique in databases across tablespaces, so we need
9300 * to allocate a new one in the new tablespace.
9302 newrelfilenode = GetNewRelFileNode(newTableSpace, NULL,
9303 rel->rd_rel->relpersistence);
9305 /* Open old and new relation */
9306 newrnode = rel->rd_node;
9307 newrnode.relNode = newrelfilenode;
9308 newrnode.spcNode = newTableSpace;
9309 dstrel = smgropen(newrnode, rel->rd_backend);
9311 RelationOpenSmgr(rel);
9314 * Create and copy all forks of the relation, and schedule unlinking of
9315 * old physical files.
9317 * NOTE: any conflict in relfilenode value will be caught in
9318 * RelationCreateStorage().
9320 RelationCreateStorage(newrnode, rel->rd_rel->relpersistence);
9322 /* copy main fork */
9323 copy_relation_data(rel->rd_smgr, dstrel, MAIN_FORKNUM,
9324 rel->rd_rel->relpersistence);
9326 /* copy those extra forks that exist */
9327 for (forkNum = MAIN_FORKNUM + 1; forkNum <= MAX_FORKNUM; forkNum++)
9329 if (smgrexists(rel->rd_smgr, forkNum))
9331 smgrcreate(dstrel, forkNum, false);
9332 copy_relation_data(rel->rd_smgr, dstrel, forkNum,
9333 rel->rd_rel->relpersistence);
9337 /* drop old relation, and close new one */
9338 RelationDropStorage(rel);
9341 /* update the pg_class row */
9342 rd_rel->reltablespace = (newTableSpace == MyDatabaseTableSpace) ? InvalidOid : newTableSpace;
9343 rd_rel->relfilenode = newrelfilenode;
9344 simple_heap_update(pg_class, &tuple->t_self, tuple);
9345 CatalogUpdateIndexes(pg_class, tuple);
9347 InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
9349 heap_freetuple(tuple);
9351 heap_close(pg_class, RowExclusiveLock);
9353 relation_close(rel, NoLock);
9355 /* Make sure the reltablespace change is visible */
9356 CommandCounterIncrement();
9358 /* Move associated toast relation and/or indexes, too */
9359 if (OidIsValid(reltoastrelid))
9360 ATExecSetTableSpace(reltoastrelid, newTableSpace, lockmode);
9361 foreach(lc, reltoastidxids)
9362 ATExecSetTableSpace(lfirst_oid(lc), newTableSpace, lockmode);
9365 list_free(reltoastidxids);
9369 * Alter Table ALL ... SET TABLESPACE
9371 * Allows a user to move all objects of some type in a given tablespace in the
9372 * current database to another tablespace. Objects can be chosen based on the
9373 * owner of the object also, to allow users to move only their objects.
9374 * The user must have CREATE rights on the new tablespace, as usual. The main
9375 * permissions handling is done by the lower-level table move function.
9377 * All to-be-moved objects are locked first. If NOWAIT is specified and the
9378 * lock can't be acquired then we ereport(ERROR).
9381 AlterTableMoveAll(AlterTableMoveAllStmt *stmt)
9383 List *relations = NIL;
9389 Oid orig_tablespaceoid;
9390 Oid new_tablespaceoid;
9391 List *role_oids = roleSpecsToIds(stmt->roles);
9393 /* Ensure we were not asked to move something we can't */
9394 if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
9395 stmt->objtype != OBJECT_MATVIEW)
9397 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
9398 errmsg("only tables, indexes, and materialized views exist in tablespaces")));
9400 /* Get the orig and new tablespace OIDs */
9401 orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
9402 new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
9404 /* Can't move shared relations in to or out of pg_global */
9405 /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
9406 if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
9407 new_tablespaceoid == GLOBALTABLESPACE_OID)
9409 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
9410 errmsg("cannot move relations in to or out of pg_global tablespace")));
9413 * Must have CREATE rights on the new tablespace, unless it is the
9414 * database default tablespace (which all users implicitly have CREATE
9417 if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
9419 AclResult aclresult;
9421 aclresult = pg_tablespace_aclcheck(new_tablespaceoid, GetUserId(),
9423 if (aclresult != ACLCHECK_OK)
9424 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
9425 get_tablespace_name(new_tablespaceoid));
9429 * Now that the checks are done, check if we should set either to
9430 * InvalidOid because it is our database's default tablespace.
9432 if (orig_tablespaceoid == MyDatabaseTableSpace)
9433 orig_tablespaceoid = InvalidOid;
9435 if (new_tablespaceoid == MyDatabaseTableSpace)
9436 new_tablespaceoid = InvalidOid;
9439 if (orig_tablespaceoid == new_tablespaceoid)
9440 return new_tablespaceoid;
9443 * Walk the list of objects in the tablespace and move them. This will
9444 * only find objects in our database, of course.
9446 ScanKeyInit(&key[0],
9447 Anum_pg_class_reltablespace,
9448 BTEqualStrategyNumber, F_OIDEQ,
9449 ObjectIdGetDatum(orig_tablespaceoid));
9451 rel = heap_open(RelationRelationId, AccessShareLock);
9452 scan = heap_beginscan_catalog(rel, 1, key);
9453 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
9455 Oid relOid = HeapTupleGetOid(tuple);
9456 Form_pg_class relForm;
9458 relForm = (Form_pg_class) GETSTRUCT(tuple);
9461 * Do not move objects in pg_catalog as part of this, if an admin
9462 * really wishes to do so, they can issue the individual ALTER
9463 * commands directly.
9465 * Also, explicitly avoid any shared tables, temp tables, or TOAST
9466 * (TOAST will be moved with the main table).
9468 if (IsSystemNamespace(relForm->relnamespace) || relForm->relisshared ||
9469 isAnyTempNamespace(relForm->relnamespace) ||
9470 relForm->relnamespace == PG_TOAST_NAMESPACE)
9473 /* Only move the object type requested */
9474 if ((stmt->objtype == OBJECT_TABLE &&
9475 relForm->relkind != RELKIND_RELATION) ||
9476 (stmt->objtype == OBJECT_INDEX &&
9477 relForm->relkind != RELKIND_INDEX) ||
9478 (stmt->objtype == OBJECT_MATVIEW &&
9479 relForm->relkind != RELKIND_MATVIEW))
9482 /* Check if we are only moving objects owned by certain roles */
9483 if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
9487 * Handle permissions-checking here since we are locking the tables
9488 * and also to avoid doing a bunch of work only to fail part-way. Note
9489 * that permissions will also be checked by AlterTableInternal().
9491 * Caller must be considered an owner on the table to move it.
9493 if (!pg_class_ownercheck(relOid, GetUserId()))
9494 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
9495 NameStr(relForm->relname));
9498 !ConditionalLockRelationOid(relOid, AccessExclusiveLock))
9500 (errcode(ERRCODE_OBJECT_IN_USE),
9501 errmsg("aborting because lock on relation \"%s\".\"%s\" is not available",
9502 get_namespace_name(relForm->relnamespace),
9503 NameStr(relForm->relname))));
9505 LockRelationOid(relOid, AccessExclusiveLock);
9507 /* Add to our list of objects to move */
9508 relations = lappend_oid(relations, relOid);
9512 heap_close(rel, AccessShareLock);
9514 if (relations == NIL)
9516 (errcode(ERRCODE_NO_DATA_FOUND),
9517 errmsg("no matching relations in tablespace \"%s\" found",
9518 orig_tablespaceoid == InvalidOid ? "(database default)" :
9519 get_tablespace_name(orig_tablespaceoid))));
9521 /* Everything is locked, loop through and move all of the relations. */
9522 foreach(l, relations)
9525 AlterTableCmd *cmd = makeNode(AlterTableCmd);
9527 cmd->subtype = AT_SetTableSpace;
9528 cmd->name = stmt->new_tablespacename;
9530 cmds = lappend(cmds, cmd);
9532 AlterTableInternal(lfirst_oid(l), cmds, false);
9535 return new_tablespaceoid;
9539 * Copy data, block by block
9542 copy_relation_data(SMgrRelation src, SMgrRelation dst,
9543 ForkNumber forkNum, char relpersistence)
9548 BlockNumber nblocks;
9552 * palloc the buffer so that it's MAXALIGN'd. If it were just a local
9553 * char[] array, the compiler might align it on any byte boundary, which
9554 * can seriously hurt transfer speed to and from the kernel; not to
9555 * mention possibly making log_newpage's accesses to the page header fail.
9557 buf = (char *) palloc(BLCKSZ);
9561 * We need to log the copied data in WAL iff WAL archiving/streaming is
9562 * enabled AND it's a permanent relation.
9564 use_wal = XLogIsNeeded() && relpersistence == RELPERSISTENCE_PERMANENT;
9566 nblocks = smgrnblocks(src, forkNum);
9568 for (blkno = 0; blkno < nblocks; blkno++)
9570 /* If we got a cancel signal during the copy of the data, quit */
9571 CHECK_FOR_INTERRUPTS();
9573 smgrread(src, forkNum, blkno, buf);
9575 if (!PageIsVerified(page, blkno))
9577 (errcode(ERRCODE_DATA_CORRUPTED),
9578 errmsg("invalid page in block %u of relation %s",
9580 relpathbackend(src->smgr_rnode.node,
9581 src->smgr_rnode.backend,
9585 * WAL-log the copied page. Unfortunately we don't know what kind of a
9586 * page this is, so we have to log the full page including any unused
9590 log_newpage(&dst->smgr_rnode.node, forkNum, blkno, page, false);
9592 PageSetChecksumInplace(page, blkno);
9595 * Now write the page. We say isTemp = true even if it's not a temp
9596 * rel, because there's no need for smgr to schedule an fsync for this
9597 * write; we'll do it ourselves below.
9599 smgrextend(dst, forkNum, blkno, buf, true);
9605 * If the rel is WAL-logged, must fsync before commit. We use heap_sync
9606 * to ensure that the toast table gets fsync'd too. (For a temp or
9607 * unlogged rel we don't care since the data will be gone after a crash
9610 * It's obvious that we must do this when not WAL-logging the copy. It's
9611 * less obvious that we have to do it even if we did WAL-log the copied
9612 * pages. The reason is that since we're copying outside shared buffers, a
9613 * CHECKPOINT occurring during the copy has no way to flush the previously
9614 * written data to disk (indeed it won't know the new rel even exists). A
9615 * crash later on would replay WAL from the checkpoint, therefore it
9616 * wouldn't replay our earlier WAL entries. If we do not fsync those pages
9617 * here, they might still not be on disk when the crash occurs.
9619 if (relpersistence == RELPERSISTENCE_PERMANENT)
9620 smgrimmedsync(dst, forkNum);
9624 * ALTER TABLE ENABLE/DISABLE TRIGGER
9626 * We just pass this off to trigger.c.
9629 ATExecEnableDisableTrigger(Relation rel, char *trigname,
9630 char fires_when, bool skip_system, LOCKMODE lockmode)
9632 EnableDisableTrigger(rel, trigname, fires_when, skip_system);
9636 * ALTER TABLE ENABLE/DISABLE RULE
9638 * We just pass this off to rewriteDefine.c.
9641 ATExecEnableDisableRule(Relation rel, char *trigname,
9642 char fires_when, LOCKMODE lockmode)
9644 EnableDisableRule(rel, trigname, fires_when);
9648 * ALTER TABLE INHERIT
9650 * Add a parent to the child's parents. This verifies that all the columns and
9651 * check constraints of the parent appear in the child and that they have the
9652 * same data types and expressions.
9655 ATPrepAddInherit(Relation child_rel)
9657 if (child_rel->rd_rel->reloftype)
9659 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9660 errmsg("cannot change inheritance of typed table")));
9664 ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode)
9666 Relation parent_rel,
9670 HeapTuple inheritsTuple;
9675 * A self-exclusive lock is needed here. See the similar case in
9676 * MergeAttributes() for a full explanation.
9678 parent_rel = heap_openrv(parent, ShareUpdateExclusiveLock);
9681 * Must be owner of both parent and child -- child was checked by
9682 * ATSimplePermissions call in ATPrepCmd
9684 ATSimplePermissions(parent_rel, ATT_TABLE);
9686 /* Permanent rels cannot inherit from temporary ones */
9687 if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
9688 child_rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
9690 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9691 errmsg("cannot inherit from temporary relation \"%s\"",
9692 RelationGetRelationName(parent_rel))));
9694 /* If parent rel is temp, it must belong to this session */
9695 if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
9696 !parent_rel->rd_islocaltemp)
9698 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9699 errmsg("cannot inherit from temporary relation of another session")));
9701 /* Ditto for the child */
9702 if (child_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
9703 !child_rel->rd_islocaltemp)
9705 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9706 errmsg("cannot inherit to temporary relation of another session")));
9709 * Check for duplicates in the list of parents, and determine the highest
9710 * inhseqno already present; we'll use the next one for the new parent.
9711 * (Note: get RowExclusiveLock because we will write pg_inherits below.)
9713 * Note: we do not reject the case where the child already inherits from
9714 * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
9716 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
9718 Anum_pg_inherits_inhrelid,
9719 BTEqualStrategyNumber, F_OIDEQ,
9720 ObjectIdGetDatum(RelationGetRelid(child_rel)));
9721 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
9722 true, NULL, 1, &key);
9724 /* inhseqno sequences start at 1 */
9726 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
9728 Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
9730 if (inh->inhparent == RelationGetRelid(parent_rel))
9732 (errcode(ERRCODE_DUPLICATE_TABLE),
9733 errmsg("relation \"%s\" would be inherited from more than once",
9734 RelationGetRelationName(parent_rel))));
9735 if (inh->inhseqno > inhseqno)
9736 inhseqno = inh->inhseqno;
9738 systable_endscan(scan);
9741 * Prevent circularity by seeing if proposed parent inherits from child.
9742 * (In particular, this disallows making a rel inherit from itself.)
9744 * This is not completely bulletproof because of race conditions: in
9745 * multi-level inheritance trees, someone else could concurrently be
9746 * making another inheritance link that closes the loop but does not join
9747 * either of the rels we have locked. Preventing that seems to require
9748 * exclusive locks on the entire inheritance tree, which is a cure worse
9749 * than the disease. find_all_inheritors() will cope with circularity
9750 * anyway, so don't sweat it too much.
9752 * We use weakest lock we can on child's children, namely AccessShareLock.
9754 children = find_all_inheritors(RelationGetRelid(child_rel),
9755 AccessShareLock, NULL);
9757 if (list_member_oid(children, RelationGetRelid(parent_rel)))
9759 (errcode(ERRCODE_DUPLICATE_TABLE),
9760 errmsg("circular inheritance not allowed"),
9761 errdetail("\"%s\" is already a child of \"%s\".",
9763 RelationGetRelationName(child_rel))));
9765 /* If parent has OIDs then child must have OIDs */
9766 if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
9768 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9769 errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
9770 RelationGetRelationName(child_rel),
9771 RelationGetRelationName(parent_rel))));
9773 /* Match up the columns and bump attinhcount as needed */
9774 MergeAttributesIntoExisting(child_rel, parent_rel);
9776 /* Match up the constraints and bump coninhcount as needed */
9777 MergeConstraintsIntoExisting(child_rel, parent_rel);
9780 * OK, it looks valid. Make the catalog entries that show inheritance.
9782 StoreCatalogInheritance1(RelationGetRelid(child_rel),
9783 RelationGetRelid(parent_rel),
9787 /* Now we're done with pg_inherits */
9788 heap_close(catalogRelation, RowExclusiveLock);
9790 /* keep our lock on the parent relation until commit */
9791 heap_close(parent_rel, NoLock);
9795 * Obtain the source-text form of the constraint expression for a check
9796 * constraint, given its pg_constraint tuple
9799 decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
9801 Form_pg_constraint con;
9806 con = (Form_pg_constraint) GETSTRUCT(contup);
9807 attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
9809 elog(ERROR, "null conbin for constraint %u", HeapTupleGetOid(contup));
9811 expr = DirectFunctionCall2(pg_get_expr, attr,
9812 ObjectIdGetDatum(con->conrelid));
9813 return TextDatumGetCString(expr);
9817 * Determine whether two check constraints are functionally equivalent
9819 * The test we apply is to see whether they reverse-compile to the same
9820 * source string. This insulates us from issues like whether attributes
9821 * have the same physical column numbers in parent and child relations.
9824 constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
9826 Form_pg_constraint acon = (Form_pg_constraint) GETSTRUCT(a);
9827 Form_pg_constraint bcon = (Form_pg_constraint) GETSTRUCT(b);
9829 if (acon->condeferrable != bcon->condeferrable ||
9830 acon->condeferred != bcon->condeferred ||
9831 strcmp(decompile_conbin(a, tupleDesc),
9832 decompile_conbin(b, tupleDesc)) != 0)
9839 * Check columns in child table match up with columns in parent, and increment
9840 * their attinhcount.
9842 * Called by ATExecAddInherit
9844 * Currently all parent columns must be found in child. Missing columns are an
9845 * error. One day we might consider creating new columns like CREATE TABLE
9846 * does. However, that is widely unpopular --- in the common use case of
9847 * partitioned tables it's a foot-gun.
9849 * The data type must match exactly. If the parent column is NOT NULL then
9850 * the child must be as well. Defaults are not compared, however.
9853 MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel)
9856 AttrNumber parent_attno;
9858 TupleDesc tupleDesc;
9861 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
9863 tupleDesc = RelationGetDescr(parent_rel);
9864 parent_natts = tupleDesc->natts;
9866 for (parent_attno = 1; parent_attno <= parent_natts; parent_attno++)
9868 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
9869 char *attributeName = NameStr(attribute->attname);
9871 /* Ignore dropped columns in the parent. */
9872 if (attribute->attisdropped)
9875 /* Find same column in child (matching on column name). */
9876 tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel),
9878 if (HeapTupleIsValid(tuple))
9880 /* Check they are same type, typmod, and collation */
9881 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
9883 if (attribute->atttypid != childatt->atttypid ||
9884 attribute->atttypmod != childatt->atttypmod)
9886 (errcode(ERRCODE_DATATYPE_MISMATCH),
9887 errmsg("child table \"%s\" has different type for column \"%s\"",
9888 RelationGetRelationName(child_rel),
9891 if (attribute->attcollation != childatt->attcollation)
9893 (errcode(ERRCODE_COLLATION_MISMATCH),
9894 errmsg("child table \"%s\" has different collation for column \"%s\"",
9895 RelationGetRelationName(child_rel),
9899 * Check child doesn't discard NOT NULL property. (Other
9900 * constraints are checked elsewhere.)
9902 if (attribute->attnotnull && !childatt->attnotnull)
9904 (errcode(ERRCODE_DATATYPE_MISMATCH),
9905 errmsg("column \"%s\" in child table must be marked NOT NULL",
9909 * OK, bump the child column's inheritance count. (If we fail
9910 * later on, this change will just roll back.)
9912 childatt->attinhcount++;
9913 simple_heap_update(attrrel, &tuple->t_self, tuple);
9914 CatalogUpdateIndexes(attrrel, tuple);
9915 heap_freetuple(tuple);
9920 (errcode(ERRCODE_DATATYPE_MISMATCH),
9921 errmsg("child table is missing column \"%s\"",
9926 heap_close(attrrel, RowExclusiveLock);
9930 * Check constraints in child table match up with constraints in parent,
9931 * and increment their coninhcount.
9933 * Constraints that are marked ONLY in the parent are ignored.
9935 * Called by ATExecAddInherit
9937 * Currently all constraints in parent must be present in the child. One day we
9938 * may consider adding new constraints like CREATE TABLE does.
9940 * XXX This is O(N^2) which may be an issue with tables with hundreds of
9941 * constraints. As long as tables have more like 10 constraints it shouldn't be
9942 * a problem though. Even 100 constraints ought not be the end of the world.
9944 * XXX See MergeWithExistingConstraint too if you change this code.
9947 MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
9949 Relation catalog_relation;
9950 TupleDesc tuple_desc;
9951 SysScanDesc parent_scan;
9952 ScanKeyData parent_key;
9953 HeapTuple parent_tuple;
9955 catalog_relation = heap_open(ConstraintRelationId, RowExclusiveLock);
9956 tuple_desc = RelationGetDescr(catalog_relation);
9958 /* Outer loop scans through the parent's constraint definitions */
9959 ScanKeyInit(&parent_key,
9960 Anum_pg_constraint_conrelid,
9961 BTEqualStrategyNumber, F_OIDEQ,
9962 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
9963 parent_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
9964 true, NULL, 1, &parent_key);
9966 while (HeapTupleIsValid(parent_tuple = systable_getnext(parent_scan)))
9968 Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(parent_tuple);
9969 SysScanDesc child_scan;
9970 ScanKeyData child_key;
9971 HeapTuple child_tuple;
9974 if (parent_con->contype != CONSTRAINT_CHECK)
9977 /* if the parent's constraint is marked NO INHERIT, it's not inherited */
9978 if (parent_con->connoinherit)
9981 /* Search for a child constraint matching this one */
9982 ScanKeyInit(&child_key,
9983 Anum_pg_constraint_conrelid,
9984 BTEqualStrategyNumber, F_OIDEQ,
9985 ObjectIdGetDatum(RelationGetRelid(child_rel)));
9986 child_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
9987 true, NULL, 1, &child_key);
9989 while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
9991 Form_pg_constraint child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
9992 HeapTuple child_copy;
9994 if (child_con->contype != CONSTRAINT_CHECK)
9997 if (strcmp(NameStr(parent_con->conname),
9998 NameStr(child_con->conname)) != 0)
10001 if (!constraints_equivalent(parent_tuple, child_tuple, tuple_desc))
10003 (errcode(ERRCODE_DATATYPE_MISMATCH),
10004 errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
10005 RelationGetRelationName(child_rel),
10006 NameStr(parent_con->conname))));
10008 /* If the constraint is "no inherit" then cannot merge */
10009 if (child_con->connoinherit)
10011 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
10012 errmsg("constraint \"%s\" conflicts with non-inherited constraint on child table \"%s\"",
10013 NameStr(child_con->conname),
10014 RelationGetRelationName(child_rel))));
10017 * OK, bump the child constraint's inheritance count. (If we fail
10018 * later on, this change will just roll back.)
10020 child_copy = heap_copytuple(child_tuple);
10021 child_con = (Form_pg_constraint) GETSTRUCT(child_copy);
10022 child_con->coninhcount++;
10023 simple_heap_update(catalog_relation, &child_copy->t_self, child_copy);
10024 CatalogUpdateIndexes(catalog_relation, child_copy);
10025 heap_freetuple(child_copy);
10031 systable_endscan(child_scan);
10035 (errcode(ERRCODE_DATATYPE_MISMATCH),
10036 errmsg("child table is missing constraint \"%s\"",
10037 NameStr(parent_con->conname))));
10040 systable_endscan(parent_scan);
10041 heap_close(catalog_relation, RowExclusiveLock);
10045 * ALTER TABLE NO INHERIT
10047 * Drop a parent from the child's parents. This just adjusts the attinhcount
10048 * and attislocal of the columns and removes the pg_inherit and pg_depend
10051 * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
10052 * up attislocal stays true, which means if a child is ever removed from a
10053 * parent then its columns will never be automatically dropped which may
10054 * surprise. But at least we'll never surprise by dropping columns someone
10055 * isn't expecting to be dropped which would actually mean data loss.
10057 * coninhcount and conislocal for inherited constraints are adjusted in
10058 * exactly the same way.
10061 ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode)
10063 Relation parent_rel;
10064 Relation catalogRelation;
10066 ScanKeyData key[3];
10067 HeapTuple inheritsTuple,
10071 bool found = false;
10074 * AccessShareLock on the parent is probably enough, seeing that DROP
10075 * TABLE doesn't lock parent tables at all. We need some lock since we'll
10076 * be inspecting the parent's schema.
10078 parent_rel = heap_openrv(parent, AccessShareLock);
10081 * We don't bother to check ownership of the parent table --- ownership of
10082 * the child is presumed enough rights.
10086 * Find and destroy the pg_inherits entry linking the two, or error out if
10089 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
10090 ScanKeyInit(&key[0],
10091 Anum_pg_inherits_inhrelid,
10092 BTEqualStrategyNumber, F_OIDEQ,
10093 ObjectIdGetDatum(RelationGetRelid(rel)));
10094 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
10095 true, NULL, 1, key);
10097 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
10101 inhparent = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
10102 if (inhparent == RelationGetRelid(parent_rel))
10104 simple_heap_delete(catalogRelation, &inheritsTuple->t_self);
10110 systable_endscan(scan);
10111 heap_close(catalogRelation, RowExclusiveLock);
10115 (errcode(ERRCODE_UNDEFINED_TABLE),
10116 errmsg("relation \"%s\" is not a parent of relation \"%s\"",
10117 RelationGetRelationName(parent_rel),
10118 RelationGetRelationName(rel))));
10121 * Search through child columns looking for ones matching parent rel
10123 catalogRelation = heap_open(AttributeRelationId, RowExclusiveLock);
10124 ScanKeyInit(&key[0],
10125 Anum_pg_attribute_attrelid,
10126 BTEqualStrategyNumber, F_OIDEQ,
10127 ObjectIdGetDatum(RelationGetRelid(rel)));
10128 scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
10129 true, NULL, 1, key);
10130 while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
10132 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
10134 /* Ignore if dropped or not inherited */
10135 if (att->attisdropped)
10137 if (att->attinhcount <= 0)
10140 if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
10141 NameStr(att->attname)))
10143 /* Decrement inhcount and possibly set islocal to true */
10144 HeapTuple copyTuple = heap_copytuple(attributeTuple);
10145 Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
10147 copy_att->attinhcount--;
10148 if (copy_att->attinhcount == 0)
10149 copy_att->attislocal = true;
10151 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
10152 CatalogUpdateIndexes(catalogRelation, copyTuple);
10153 heap_freetuple(copyTuple);
10156 systable_endscan(scan);
10157 heap_close(catalogRelation, RowExclusiveLock);
10160 * Likewise, find inherited check constraints and disinherit them. To do
10161 * this, we first need a list of the names of the parent's check
10162 * constraints. (We cheat a bit by only checking for name matches,
10163 * assuming that the expressions will match.)
10165 catalogRelation = heap_open(ConstraintRelationId, RowExclusiveLock);
10166 ScanKeyInit(&key[0],
10167 Anum_pg_constraint_conrelid,
10168 BTEqualStrategyNumber, F_OIDEQ,
10169 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
10170 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
10171 true, NULL, 1, key);
10175 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
10177 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
10179 if (con->contype == CONSTRAINT_CHECK)
10180 connames = lappend(connames, pstrdup(NameStr(con->conname)));
10183 systable_endscan(scan);
10185 /* Now scan the child's constraints */
10186 ScanKeyInit(&key[0],
10187 Anum_pg_constraint_conrelid,
10188 BTEqualStrategyNumber, F_OIDEQ,
10189 ObjectIdGetDatum(RelationGetRelid(rel)));
10190 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
10191 true, NULL, 1, key);
10193 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
10195 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
10199 if (con->contype != CONSTRAINT_CHECK)
10203 foreach(lc, connames)
10205 if (strcmp(NameStr(con->conname), (char *) lfirst(lc)) == 0)
10214 /* Decrement inhcount and possibly set islocal to true */
10215 HeapTuple copyTuple = heap_copytuple(constraintTuple);
10216 Form_pg_constraint copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
10218 if (copy_con->coninhcount <= 0) /* shouldn't happen */
10219 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
10220 RelationGetRelid(rel), NameStr(copy_con->conname));
10222 copy_con->coninhcount--;
10223 if (copy_con->coninhcount == 0)
10224 copy_con->conislocal = true;
10226 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
10227 CatalogUpdateIndexes(catalogRelation, copyTuple);
10228 heap_freetuple(copyTuple);
10232 systable_endscan(scan);
10233 heap_close(catalogRelation, RowExclusiveLock);
10235 drop_parent_dependency(RelationGetRelid(rel),
10236 RelationRelationId,
10237 RelationGetRelid(parent_rel));
10240 * Post alter hook of this inherits. Since object_access_hook doesn't take
10241 * multiple object identifiers, we relay oid of parent relation using
10242 * auxiliary_id argument.
10244 InvokeObjectPostAlterHookArg(InheritsRelationId,
10245 RelationGetRelid(rel), 0,
10246 RelationGetRelid(parent_rel), false);
10248 /* keep our lock on the parent relation until commit */
10249 heap_close(parent_rel, NoLock);
10253 * Drop the dependency created by StoreCatalogInheritance1 (CREATE TABLE
10254 * INHERITS/ALTER TABLE INHERIT -- refclassid will be RelationRelationId) or
10255 * heap_create_with_catalog (CREATE TABLE OF/ALTER TABLE OF -- refclassid will
10256 * be TypeRelationId). There's no convenient way to do this, so go trawling
10257 * through pg_depend.
10260 drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid)
10262 Relation catalogRelation;
10264 ScanKeyData key[3];
10265 HeapTuple depTuple;
10267 catalogRelation = heap_open(DependRelationId, RowExclusiveLock);
10269 ScanKeyInit(&key[0],
10270 Anum_pg_depend_classid,
10271 BTEqualStrategyNumber, F_OIDEQ,
10272 ObjectIdGetDatum(RelationRelationId));
10273 ScanKeyInit(&key[1],
10274 Anum_pg_depend_objid,
10275 BTEqualStrategyNumber, F_OIDEQ,
10276 ObjectIdGetDatum(relid));
10277 ScanKeyInit(&key[2],
10278 Anum_pg_depend_objsubid,
10279 BTEqualStrategyNumber, F_INT4EQ,
10282 scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
10285 while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
10287 Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
10289 if (dep->refclassid == refclassid &&
10290 dep->refobjid == refobjid &&
10291 dep->refobjsubid == 0 &&
10292 dep->deptype == DEPENDENCY_NORMAL)
10293 simple_heap_delete(catalogRelation, &depTuple->t_self);
10296 systable_endscan(scan);
10297 heap_close(catalogRelation, RowExclusiveLock);
10303 * Attach a table to a composite type, as though it had been created with CREATE
10304 * TABLE OF. All attname, atttypid, atttypmod and attcollation must match. The
10305 * subject table must not have inheritance parents. These restrictions ensure
10306 * that you cannot create a configuration impossible with CREATE TABLE OF alone.
10309 ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode)
10311 Oid relid = RelationGetRelid(rel);
10314 Relation inheritsRelation,
10318 AttrNumber table_attno,
10320 TupleDesc typeTupleDesc,
10322 ObjectAddress tableobj,
10324 HeapTuple classtuple;
10326 /* Validate the type. */
10327 typetuple = typenameType(NULL, ofTypename, NULL);
10328 check_of_type(typetuple);
10329 typeid = HeapTupleGetOid(typetuple);
10331 /* Fail if the table has any inheritance parents. */
10332 inheritsRelation = heap_open(InheritsRelationId, AccessShareLock);
10334 Anum_pg_inherits_inhrelid,
10335 BTEqualStrategyNumber, F_OIDEQ,
10336 ObjectIdGetDatum(relid));
10337 scan = systable_beginscan(inheritsRelation, InheritsRelidSeqnoIndexId,
10338 true, NULL, 1, &key);
10339 if (HeapTupleIsValid(systable_getnext(scan)))
10341 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10342 errmsg("typed tables cannot inherit")));
10343 systable_endscan(scan);
10344 heap_close(inheritsRelation, AccessShareLock);
10347 * Check the tuple descriptors for compatibility. Unlike inheritance, we
10348 * require that the order also match. However, attnotnull need not match.
10349 * Also unlike inheritance, we do not require matching relhasoids.
10351 typeTupleDesc = lookup_rowtype_tupdesc(typeid, -1);
10352 tableTupleDesc = RelationGetDescr(rel);
10354 for (type_attno = 1; type_attno <= typeTupleDesc->natts; type_attno++)
10356 Form_pg_attribute type_attr,
10358 const char *type_attname,
10361 /* Get the next non-dropped type attribute. */
10362 type_attr = typeTupleDesc->attrs[type_attno - 1];
10363 if (type_attr->attisdropped)
10365 type_attname = NameStr(type_attr->attname);
10367 /* Get the next non-dropped table attribute. */
10370 if (table_attno > tableTupleDesc->natts)
10372 (errcode(ERRCODE_DATATYPE_MISMATCH),
10373 errmsg("table is missing column \"%s\"",
10375 table_attr = tableTupleDesc->attrs[table_attno++ - 1];
10376 } while (table_attr->attisdropped);
10377 table_attname = NameStr(table_attr->attname);
10379 /* Compare name. */
10380 if (strncmp(table_attname, type_attname, NAMEDATALEN) != 0)
10382 (errcode(ERRCODE_DATATYPE_MISMATCH),
10383 errmsg("table has column \"%s\" where type requires \"%s\"",
10384 table_attname, type_attname)));
10386 /* Compare type. */
10387 if (table_attr->atttypid != type_attr->atttypid ||
10388 table_attr->atttypmod != type_attr->atttypmod ||
10389 table_attr->attcollation != type_attr->attcollation)
10391 (errcode(ERRCODE_DATATYPE_MISMATCH),
10392 errmsg("table \"%s\" has different type for column \"%s\"",
10393 RelationGetRelationName(rel), type_attname)));
10395 DecrTupleDescRefCount(typeTupleDesc);
10397 /* Any remaining columns at the end of the table had better be dropped. */
10398 for (; table_attno <= tableTupleDesc->natts; table_attno++)
10400 Form_pg_attribute table_attr = tableTupleDesc->attrs[table_attno - 1];
10402 if (!table_attr->attisdropped)
10404 (errcode(ERRCODE_DATATYPE_MISMATCH),
10405 errmsg("table has extra column \"%s\"",
10406 NameStr(table_attr->attname))));
10409 /* If the table was already typed, drop the existing dependency. */
10410 if (rel->rd_rel->reloftype)
10411 drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype);
10413 /* Record a dependency on the new type. */
10414 tableobj.classId = RelationRelationId;
10415 tableobj.objectId = relid;
10416 tableobj.objectSubId = 0;
10417 typeobj.classId = TypeRelationId;
10418 typeobj.objectId = typeid;
10419 typeobj.objectSubId = 0;
10420 recordDependencyOn(&tableobj, &typeobj, DEPENDENCY_NORMAL);
10422 /* Update pg_class.reloftype */
10423 relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
10424 classtuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
10425 if (!HeapTupleIsValid(classtuple))
10426 elog(ERROR, "cache lookup failed for relation %u", relid);
10427 ((Form_pg_class) GETSTRUCT(classtuple))->reloftype = typeid;
10428 simple_heap_update(relationRelation, &classtuple->t_self, classtuple);
10429 CatalogUpdateIndexes(relationRelation, classtuple);
10431 InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
10433 heap_freetuple(classtuple);
10434 heap_close(relationRelation, RowExclusiveLock);
10436 ReleaseSysCache(typetuple);
10440 * ALTER TABLE NOT OF
10442 * Detach a typed table from its originating type. Just clear reloftype and
10443 * remove the dependency.
10446 ATExecDropOf(Relation rel, LOCKMODE lockmode)
10448 Oid relid = RelationGetRelid(rel);
10449 Relation relationRelation;
10452 if (!OidIsValid(rel->rd_rel->reloftype))
10454 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10455 errmsg("\"%s\" is not a typed table",
10456 RelationGetRelationName(rel))));
10459 * We don't bother to check ownership of the type --- ownership of the
10460 * table is presumed enough rights. No lock required on the type, either.
10463 drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype);
10465 /* Clear pg_class.reloftype */
10466 relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
10467 tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
10468 if (!HeapTupleIsValid(tuple))
10469 elog(ERROR, "cache lookup failed for relation %u", relid);
10470 ((Form_pg_class) GETSTRUCT(tuple))->reloftype = InvalidOid;
10471 simple_heap_update(relationRelation, &tuple->t_self, tuple);
10472 CatalogUpdateIndexes(relationRelation, tuple);
10474 InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
10476 heap_freetuple(tuple);
10477 heap_close(relationRelation, RowExclusiveLock);
10481 * relation_mark_replica_identity: Update a table's replica identity
10483 * Iff ri_type = REPLICA_IDENTITY_INDEX, indexOid must be the Oid of a suitable
10484 * index. Otherwise, it should be InvalidOid.
10487 relation_mark_replica_identity(Relation rel, char ri_type, Oid indexOid,
10492 HeapTuple pg_class_tuple;
10493 HeapTuple pg_index_tuple;
10494 Form_pg_class pg_class_form;
10495 Form_pg_index pg_index_form;
10500 * Check whether relreplident has changed, and update it if so.
10502 pg_class = heap_open(RelationRelationId, RowExclusiveLock);
10503 pg_class_tuple = SearchSysCacheCopy1(RELOID,
10504 ObjectIdGetDatum(RelationGetRelid(rel)));
10505 if (!HeapTupleIsValid(pg_class_tuple))
10506 elog(ERROR, "cache lookup failed for relation \"%s\"",
10507 RelationGetRelationName(rel));
10508 pg_class_form = (Form_pg_class) GETSTRUCT(pg_class_tuple);
10509 if (pg_class_form->relreplident != ri_type)
10511 pg_class_form->relreplident = ri_type;
10512 simple_heap_update(pg_class, &pg_class_tuple->t_self, pg_class_tuple);
10513 CatalogUpdateIndexes(pg_class, pg_class_tuple);
10515 heap_close(pg_class, RowExclusiveLock);
10516 heap_freetuple(pg_class_tuple);
10519 * Check whether the correct index is marked indisreplident; if so, we're
10522 if (OidIsValid(indexOid))
10524 Assert(ri_type == REPLICA_IDENTITY_INDEX);
10526 pg_index_tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexOid));
10527 if (!HeapTupleIsValid(pg_index_tuple))
10528 elog(ERROR, "cache lookup failed for index %u", indexOid);
10529 pg_index_form = (Form_pg_index) GETSTRUCT(pg_index_tuple);
10531 if (pg_index_form->indisreplident)
10533 ReleaseSysCache(pg_index_tuple);
10536 ReleaseSysCache(pg_index_tuple);
10540 * Clear the indisreplident flag from any index that had it previously,
10541 * and set it for any index that should have it now.
10543 pg_index = heap_open(IndexRelationId, RowExclusiveLock);
10544 foreach(index, RelationGetIndexList(rel))
10546 Oid thisIndexOid = lfirst_oid(index);
10547 bool dirty = false;
10549 pg_index_tuple = SearchSysCacheCopy1(INDEXRELID,
10550 ObjectIdGetDatum(thisIndexOid));
10551 if (!HeapTupleIsValid(pg_index_tuple))
10552 elog(ERROR, "cache lookup failed for index %u", thisIndexOid);
10553 pg_index_form = (Form_pg_index) GETSTRUCT(pg_index_tuple);
10556 * Unset the bit if set. We know it's wrong because we checked this
10559 if (pg_index_form->indisreplident)
10562 pg_index_form->indisreplident = false;
10564 else if (thisIndexOid == indexOid)
10567 pg_index_form->indisreplident = true;
10572 simple_heap_update(pg_index, &pg_index_tuple->t_self, pg_index_tuple);
10573 CatalogUpdateIndexes(pg_index, pg_index_tuple);
10574 InvokeObjectPostAlterHookArg(IndexRelationId, thisIndexOid, 0,
10575 InvalidOid, is_internal);
10577 heap_freetuple(pg_index_tuple);
10580 heap_close(pg_index, RowExclusiveLock);
10584 * ALTER TABLE <name> REPLICA IDENTITY ...
10587 ATExecReplicaIdentity(Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode)
10593 if (stmt->identity_type == REPLICA_IDENTITY_DEFAULT)
10595 relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
10598 else if (stmt->identity_type == REPLICA_IDENTITY_FULL)
10600 relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
10603 else if (stmt->identity_type == REPLICA_IDENTITY_NOTHING)
10605 relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
10608 else if (stmt->identity_type == REPLICA_IDENTITY_INDEX)
10610 /* fallthrough */ ;
10613 elog(ERROR, "unexpected identity type %u", stmt->identity_type);
10616 /* Check that the index exists */
10617 indexOid = get_relname_relid(stmt->name, rel->rd_rel->relnamespace);
10618 if (!OidIsValid(indexOid))
10620 (errcode(ERRCODE_UNDEFINED_OBJECT),
10621 errmsg("index \"%s\" for table \"%s\" does not exist",
10622 stmt->name, RelationGetRelationName(rel))));
10624 indexRel = index_open(indexOid, ShareLock);
10626 /* Check that the index is on the relation we're altering. */
10627 if (indexRel->rd_index == NULL ||
10628 indexRel->rd_index->indrelid != RelationGetRelid(rel))
10630 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10631 errmsg("\"%s\" is not an index for table \"%s\"",
10632 RelationGetRelationName(indexRel),
10633 RelationGetRelationName(rel))));
10634 /* The AM must support uniqueness, and the index must in fact be unique. */
10635 if (!indexRel->rd_am->amcanunique || !indexRel->rd_index->indisunique)
10637 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10638 errmsg("cannot use non-unique index \"%s\" as replica identity",
10639 RelationGetRelationName(indexRel))));
10640 /* Deferred indexes are not guaranteed to be always unique. */
10641 if (!indexRel->rd_index->indimmediate)
10643 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10644 errmsg("cannot use non-immediate index \"%s\" as replica identity",
10645 RelationGetRelationName(indexRel))));
10646 /* Expression indexes aren't supported. */
10647 if (RelationGetIndexExpressions(indexRel) != NIL)
10649 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10650 errmsg("cannot use expression index \"%s\" as replica identity",
10651 RelationGetRelationName(indexRel))));
10652 /* Predicate indexes aren't supported. */
10653 if (RelationGetIndexPredicate(indexRel) != NIL)
10655 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10656 errmsg("cannot use partial index \"%s\" as replica identity",
10657 RelationGetRelationName(indexRel))));
10658 /* And neither are invalid indexes. */
10659 if (!IndexIsValid(indexRel->rd_index))
10661 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10662 errmsg("cannot use invalid index \"%s\" as replica identity",
10663 RelationGetRelationName(indexRel))));
10665 /* Check index for nullable columns. */
10666 for (key = 0; key < indexRel->rd_index->indnatts; key++)
10668 int16 attno = indexRel->rd_index->indkey.values[key];
10669 Form_pg_attribute attr;
10671 /* Of the system columns, only oid is indexable. */
10672 if (attno <= 0 && attno != ObjectIdAttributeNumber)
10673 elog(ERROR, "internal column %u in unique index \"%s\"",
10674 attno, RelationGetRelationName(indexRel));
10676 attr = rel->rd_att->attrs[attno - 1];
10677 if (!attr->attnotnull)
10679 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10680 errmsg("index \"%s\" cannot be used as replica identity because column \"%s\" is nullable",
10681 RelationGetRelationName(indexRel),
10682 NameStr(attr->attname))));
10685 /* This index is suitable for use as a replica identity. Mark it. */
10686 relation_mark_replica_identity(rel, stmt->identity_type, indexOid, true);
10688 index_close(indexRel, NoLock);
10692 * ALTER TABLE ENABLE/DISABLE ROW LEVEL SECURITY
10695 ATExecEnableRowSecurity(Relation rel)
10701 relid = RelationGetRelid(rel);
10703 pg_class = heap_open(RelationRelationId, RowExclusiveLock);
10705 tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
10707 if (!HeapTupleIsValid(tuple))
10708 elog(ERROR, "cache lookup failed for relation %u", relid);
10710 ((Form_pg_class) GETSTRUCT(tuple))->relrowsecurity = true;
10711 simple_heap_update(pg_class, &tuple->t_self, tuple);
10713 /* keep catalog indexes current */
10714 CatalogUpdateIndexes(pg_class, tuple);
10716 heap_close(pg_class, RowExclusiveLock);
10717 heap_freetuple(tuple);
10721 ATExecDisableRowSecurity(Relation rel)
10727 relid = RelationGetRelid(rel);
10729 /* Pull the record for this relation and update it */
10730 pg_class = heap_open(RelationRelationId, RowExclusiveLock);
10732 tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
10734 if (!HeapTupleIsValid(tuple))
10735 elog(ERROR, "cache lookup failed for relation %u", relid);
10737 ((Form_pg_class) GETSTRUCT(tuple))->relrowsecurity = false;
10738 simple_heap_update(pg_class, &tuple->t_self, tuple);
10740 /* keep catalog indexes current */
10741 CatalogUpdateIndexes(pg_class, tuple);
10743 heap_close(pg_class, RowExclusiveLock);
10744 heap_freetuple(tuple);
10748 * ALTER FOREIGN TABLE <name> OPTIONS (...)
10751 ATExecGenericOptions(Relation rel, List *options)
10754 ForeignServer *server;
10755 ForeignDataWrapper *fdw;
10758 Datum repl_val[Natts_pg_foreign_table];
10759 bool repl_null[Natts_pg_foreign_table];
10760 bool repl_repl[Natts_pg_foreign_table];
10762 Form_pg_foreign_table tableform;
10764 if (options == NIL)
10767 ftrel = heap_open(ForeignTableRelationId, RowExclusiveLock);
10769 tuple = SearchSysCacheCopy1(FOREIGNTABLEREL, rel->rd_id);
10770 if (!HeapTupleIsValid(tuple))
10772 (errcode(ERRCODE_UNDEFINED_OBJECT),
10773 errmsg("foreign table \"%s\" does not exist",
10774 RelationGetRelationName(rel))));
10775 tableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
10776 server = GetForeignServer(tableform->ftserver);
10777 fdw = GetForeignDataWrapper(server->fdwid);
10779 memset(repl_val, 0, sizeof(repl_val));
10780 memset(repl_null, false, sizeof(repl_null));
10781 memset(repl_repl, false, sizeof(repl_repl));
10783 /* Extract the current options */
10784 datum = SysCacheGetAttr(FOREIGNTABLEREL,
10786 Anum_pg_foreign_table_ftoptions,
10789 datum = PointerGetDatum(NULL);
10791 /* Transform the options */
10792 datum = transformGenericOptions(ForeignTableRelationId,
10795 fdw->fdwvalidator);
10797 if (PointerIsValid(DatumGetPointer(datum)))
10798 repl_val[Anum_pg_foreign_table_ftoptions - 1] = datum;
10800 repl_null[Anum_pg_foreign_table_ftoptions - 1] = true;
10802 repl_repl[Anum_pg_foreign_table_ftoptions - 1] = true;
10804 /* Everything looks good - update the tuple */
10806 tuple = heap_modify_tuple(tuple, RelationGetDescr(ftrel),
10807 repl_val, repl_null, repl_repl);
10809 simple_heap_update(ftrel, &tuple->t_self, tuple);
10810 CatalogUpdateIndexes(ftrel, tuple);
10812 InvokeObjectPostAlterHook(ForeignTableRelationId,
10813 RelationGetRelid(rel), 0);
10815 heap_close(ftrel, RowExclusiveLock);
10817 heap_freetuple(tuple);
10821 * Preparation phase for SET LOGGED/UNLOGGED
10823 * This verifies that we're not trying to change a temp table. Also,
10824 * existing foreign key constraints are checked to avoid ending up with
10825 * permanent tables referencing unlogged tables.
10827 * Return value is false if the operation is a no-op (in which case the
10828 * checks are skipped), otherwise true.
10831 ATPrepChangePersistence(Relation rel, bool toLogged)
10833 Relation pg_constraint;
10836 ScanKeyData skey[1];
10839 * Disallow changing status for a temp table. Also verify whether we can
10840 * get away with doing nothing; in such cases we don't need to run the
10841 * checks below, either.
10843 switch (rel->rd_rel->relpersistence)
10845 case RELPERSISTENCE_TEMP:
10847 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10848 errmsg("cannot change logged status of table %s",
10849 RelationGetRelationName(rel)),
10850 errdetail("Table %s is temporary.",
10851 RelationGetRelationName(rel)),
10854 case RELPERSISTENCE_PERMANENT:
10856 /* nothing to do */
10859 case RELPERSISTENCE_UNLOGGED:
10861 /* nothing to do */
10867 * Check existing foreign key constraints to preserve the invariant that
10868 * no permanent tables cannot reference unlogged ones. Self-referencing
10869 * foreign keys can safely be ignored.
10871 pg_constraint = heap_open(ConstraintRelationId, AccessShareLock);
10874 * Scan conrelid if changing to permanent, else confrelid. This also
10875 * determines whether a useful index exists.
10877 ScanKeyInit(&skey[0],
10878 toLogged ? Anum_pg_constraint_conrelid :
10879 Anum_pg_constraint_confrelid,
10880 BTEqualStrategyNumber, F_OIDEQ,
10881 ObjectIdGetDatum(RelationGetRelid(rel)));
10882 scan = systable_beginscan(pg_constraint,
10883 toLogged ? ConstraintRelidIndexId : InvalidOid,
10884 true, NULL, 1, skey);
10886 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
10888 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
10890 if (con->contype == CONSTRAINT_FOREIGN)
10893 Relation foreignrel;
10895 /* the opposite end of what we used as scankey */
10896 foreignrelid = toLogged ? con->confrelid : con->conrelid;
10898 /* ignore if self-referencing */
10899 if (RelationGetRelid(rel) == foreignrelid)
10902 foreignrel = relation_open(foreignrelid, AccessShareLock);
10906 if (foreignrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT)
10908 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10909 errmsg("cannot change status of table %s to logged",
10910 RelationGetRelationName(rel)),
10911 errdetail("Table %s references unlogged table %s.",
10912 RelationGetRelationName(rel),
10913 RelationGetRelationName(foreignrel)),
10914 errtableconstraint(rel, NameStr(con->conname))));
10918 if (foreignrel->rd_rel->relpersistence == RELPERSISTENCE_PERMANENT)
10920 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10921 errmsg("cannot change status of table %s to unlogged",
10922 RelationGetRelationName(rel)),
10923 errdetail("Logged table %s is referenced by table %s.",
10924 RelationGetRelationName(foreignrel),
10925 RelationGetRelationName(rel)),
10926 errtableconstraint(rel, NameStr(con->conname))));
10929 relation_close(foreignrel, AccessShareLock);
10933 systable_endscan(scan);
10935 heap_close(pg_constraint, AccessShareLock);
10941 * Execute ALTER TABLE SET SCHEMA
10944 AlterTableNamespace(AlterObjectSchemaStmt *stmt, Oid *oldschema)
10951 ObjectAddresses *objsMoved;
10952 ObjectAddress myself;
10954 relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
10955 stmt->missing_ok, false,
10956 RangeVarCallbackForAlterRelation,
10959 if (!OidIsValid(relid))
10962 (errmsg("relation \"%s\" does not exist, skipping",
10963 stmt->relation->relname)));
10964 return InvalidObjectAddress;
10967 rel = relation_open(relid, NoLock);
10969 oldNspOid = RelationGetNamespace(rel);
10971 /* If it's an owned sequence, disallow moving it by itself. */
10972 if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
10977 if (sequenceIsOwned(relid, &tableId, &colId))
10979 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10980 errmsg("cannot move an owned sequence into another schema"),
10981 errdetail("Sequence \"%s\" is linked to table \"%s\".",
10982 RelationGetRelationName(rel),
10983 get_rel_name(tableId))));
10986 /* Get and lock schema OID and check its permissions. */
10987 newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
10988 nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
10990 /* common checks on switching namespaces */
10991 CheckSetNamespace(oldNspOid, nspOid, RelationRelationId, relid);
10993 objsMoved = new_object_addresses();
10994 AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
10995 free_object_addresses(objsMoved);
10997 ObjectAddressSet(myself, RelationRelationId, relid);
11000 *oldschema = oldNspOid;
11002 /* close rel, but keep lock until commit */
11003 relation_close(rel, NoLock);
11009 * The guts of relocating a table or materialized view to another namespace:
11010 * besides moving the relation itself, its dependent objects are relocated to
11014 AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid,
11015 ObjectAddresses *objsMoved)
11019 Assert(objsMoved != NULL);
11021 /* OK, modify the pg_class row and pg_depend entry */
11022 classRel = heap_open(RelationRelationId, RowExclusiveLock);
11024 AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
11025 nspOid, true, objsMoved);
11027 /* Fix the table's row type too */
11028 AlterTypeNamespaceInternal(rel->rd_rel->reltype,
11029 nspOid, false, false, objsMoved);
11031 /* Fix other dependent stuff */
11032 if (rel->rd_rel->relkind == RELKIND_RELATION ||
11033 rel->rd_rel->relkind == RELKIND_MATVIEW)
11035 AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
11036 AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
11037 objsMoved, AccessExclusiveLock);
11038 AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
11042 heap_close(classRel, RowExclusiveLock);
11046 * The guts of relocating a relation to another namespace: fix the pg_class
11047 * entry, and the pg_depend entry if any. Caller must already have
11048 * opened and write-locked pg_class.
11051 AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
11052 Oid oldNspOid, Oid newNspOid,
11053 bool hasDependEntry,
11054 ObjectAddresses *objsMoved)
11056 HeapTuple classTup;
11057 Form_pg_class classForm;
11058 ObjectAddress thisobj;
11060 classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
11061 if (!HeapTupleIsValid(classTup))
11062 elog(ERROR, "cache lookup failed for relation %u", relOid);
11063 classForm = (Form_pg_class) GETSTRUCT(classTup);
11065 Assert(classForm->relnamespace == oldNspOid);
11067 thisobj.classId = RelationRelationId;
11068 thisobj.objectId = relOid;
11069 thisobj.objectSubId = 0;
11072 * Do nothing when there's nothing to do.
11074 if (!object_address_present(&thisobj, objsMoved))
11076 /* check for duplicate name (more friendly than unique-index failure) */
11077 if (get_relname_relid(NameStr(classForm->relname),
11078 newNspOid) != InvalidOid)
11080 (errcode(ERRCODE_DUPLICATE_TABLE),
11081 errmsg("relation \"%s\" already exists in schema \"%s\"",
11082 NameStr(classForm->relname),
11083 get_namespace_name(newNspOid))));
11085 /* classTup is a copy, so OK to scribble on */
11086 classForm->relnamespace = newNspOid;
11088 simple_heap_update(classRel, &classTup->t_self, classTup);
11089 CatalogUpdateIndexes(classRel, classTup);
11091 /* Update dependency on schema if caller said so */
11092 if (hasDependEntry &&
11093 changeDependencyFor(RelationRelationId,
11095 NamespaceRelationId,
11098 elog(ERROR, "failed to change schema dependency for relation \"%s\"",
11099 NameStr(classForm->relname));
11101 add_exact_object_address(&thisobj, objsMoved);
11103 InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
11106 heap_freetuple(classTup);
11110 * Move all indexes for the specified relation to another namespace.
11112 * Note: we assume adequate permission checking was done by the caller,
11113 * and that the caller has a suitable lock on the owning relation.
11116 AlterIndexNamespaces(Relation classRel, Relation rel,
11117 Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
11122 indexList = RelationGetIndexList(rel);
11124 foreach(l, indexList)
11126 Oid indexOid = lfirst_oid(l);
11127 ObjectAddress thisobj;
11129 thisobj.classId = RelationRelationId;
11130 thisobj.objectId = indexOid;
11131 thisobj.objectSubId = 0;
11134 * Note: currently, the index will not have its own dependency on the
11135 * namespace, so we don't need to do changeDependencyFor(). There's no
11136 * row type in pg_type, either.
11138 * XXX this objsMoved test may be pointless -- surely we have a single
11139 * dependency link from a relation to each index?
11141 if (!object_address_present(&thisobj, objsMoved))
11143 AlterRelationNamespaceInternal(classRel, indexOid,
11144 oldNspOid, newNspOid,
11146 add_exact_object_address(&thisobj, objsMoved);
11150 list_free(indexList);
11154 * Move all SERIAL-column sequences of the specified relation to another
11157 * Note: we assume adequate permission checking was done by the caller,
11158 * and that the caller has a suitable lock on the owning relation.
11161 AlterSeqNamespaces(Relation classRel, Relation rel,
11162 Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved,
11167 ScanKeyData key[2];
11171 * SERIAL sequences are those having an auto dependency on one of the
11172 * table's columns (we don't care *which* column, exactly).
11174 depRel = heap_open(DependRelationId, AccessShareLock);
11176 ScanKeyInit(&key[0],
11177 Anum_pg_depend_refclassid,
11178 BTEqualStrategyNumber, F_OIDEQ,
11179 ObjectIdGetDatum(RelationRelationId));
11180 ScanKeyInit(&key[1],
11181 Anum_pg_depend_refobjid,
11182 BTEqualStrategyNumber, F_OIDEQ,
11183 ObjectIdGetDatum(RelationGetRelid(rel)));
11184 /* we leave refobjsubid unspecified */
11186 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
11189 while (HeapTupleIsValid(tup = systable_getnext(scan)))
11191 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
11194 /* skip dependencies other than auto dependencies on columns */
11195 if (depForm->refobjsubid == 0 ||
11196 depForm->classid != RelationRelationId ||
11197 depForm->objsubid != 0 ||
11198 depForm->deptype != DEPENDENCY_AUTO)
11201 /* Use relation_open just in case it's an index */
11202 seqRel = relation_open(depForm->objid, lockmode);
11204 /* skip non-sequence relations */
11205 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
11207 /* No need to keep the lock */
11208 relation_close(seqRel, lockmode);
11212 /* Fix the pg_class and pg_depend entries */
11213 AlterRelationNamespaceInternal(classRel, depForm->objid,
11214 oldNspOid, newNspOid,
11218 * Sequences have entries in pg_type. We need to be careful to move
11219 * them to the new namespace, too.
11221 AlterTypeNamespaceInternal(RelationGetForm(seqRel)->reltype,
11222 newNspOid, false, false, objsMoved);
11224 /* Now we can close it. Keep the lock till end of transaction. */
11225 relation_close(seqRel, NoLock);
11228 systable_endscan(scan);
11230 relation_close(depRel, AccessShareLock);
11235 * This code supports
11236 * CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
11238 * Because we only support this for TEMP tables, it's sufficient to remember
11239 * the state in a backend-local data structure.
11243 * Register a newly-created relation's ON COMMIT action.
11246 register_on_commit_action(Oid relid, OnCommitAction action)
11249 MemoryContext oldcxt;
11252 * We needn't bother registering the relation unless there is an ON COMMIT
11253 * action we need to take.
11255 if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
11258 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
11260 oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
11262 oc->oncommit = action;
11263 oc->creating_subid = GetCurrentSubTransactionId();
11264 oc->deleting_subid = InvalidSubTransactionId;
11266 on_commits = lcons(oc, on_commits);
11268 MemoryContextSwitchTo(oldcxt);
11272 * Unregister any ON COMMIT action when a relation is deleted.
11274 * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
11277 remove_on_commit_action(Oid relid)
11281 foreach(l, on_commits)
11283 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
11285 if (oc->relid == relid)
11287 oc->deleting_subid = GetCurrentSubTransactionId();
11294 * Perform ON COMMIT actions.
11296 * This is invoked just before actually committing, since it's possible
11297 * to encounter errors.
11300 PreCommit_on_commit_actions(void)
11303 List *oids_to_truncate = NIL;
11305 foreach(l, on_commits)
11307 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
11309 /* Ignore entry if already dropped in this xact */
11310 if (oc->deleting_subid != InvalidSubTransactionId)
11313 switch (oc->oncommit)
11315 case ONCOMMIT_NOOP:
11316 case ONCOMMIT_PRESERVE_ROWS:
11317 /* Do nothing (there shouldn't be such entries, actually) */
11319 case ONCOMMIT_DELETE_ROWS:
11322 * If this transaction hasn't accessed any temporary
11323 * relations, we can skip truncating ON COMMIT DELETE ROWS
11324 * tables, as they must still be empty.
11326 if (MyXactAccessedTempRel)
11327 oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
11329 case ONCOMMIT_DROP:
11331 ObjectAddress object;
11333 object.classId = RelationRelationId;
11334 object.objectId = oc->relid;
11335 object.objectSubId = 0;
11338 * Since this is an automatic drop, rather than one
11339 * directly initiated by the user, we pass the
11340 * PERFORM_DELETION_INTERNAL flag.
11342 performDeletion(&object,
11343 DROP_CASCADE, PERFORM_DELETION_INTERNAL);
11346 * Note that table deletion will call
11347 * remove_on_commit_action, so the entry should get marked
11350 Assert(oc->deleting_subid != InvalidSubTransactionId);
11355 if (oids_to_truncate != NIL)
11357 heap_truncate(oids_to_truncate);
11358 CommandCounterIncrement(); /* XXX needed? */
11363 * Post-commit or post-abort cleanup for ON COMMIT management.
11365 * All we do here is remove no-longer-needed OnCommitItem entries.
11367 * During commit, remove entries that were deleted during this transaction;
11368 * during abort, remove those created during this transaction.
11371 AtEOXact_on_commit_actions(bool isCommit)
11373 ListCell *cur_item;
11374 ListCell *prev_item;
11377 cur_item = list_head(on_commits);
11379 while (cur_item != NULL)
11381 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
11383 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
11384 oc->creating_subid != InvalidSubTransactionId)
11386 /* cur_item must be removed */
11387 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
11390 cur_item = lnext(prev_item);
11392 cur_item = list_head(on_commits);
11396 /* cur_item must be preserved */
11397 oc->creating_subid = InvalidSubTransactionId;
11398 oc->deleting_subid = InvalidSubTransactionId;
11399 prev_item = cur_item;
11400 cur_item = lnext(prev_item);
11406 * Post-subcommit or post-subabort cleanup for ON COMMIT management.
11408 * During subabort, we can immediately remove entries created during this
11409 * subtransaction. During subcommit, just relabel entries marked during
11410 * this subtransaction as being the parent's responsibility.
11413 AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
11414 SubTransactionId parentSubid)
11416 ListCell *cur_item;
11417 ListCell *prev_item;
11420 cur_item = list_head(on_commits);
11422 while (cur_item != NULL)
11424 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
11426 if (!isCommit && oc->creating_subid == mySubid)
11428 /* cur_item must be removed */
11429 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
11432 cur_item = lnext(prev_item);
11434 cur_item = list_head(on_commits);
11438 /* cur_item must be preserved */
11439 if (oc->creating_subid == mySubid)
11440 oc->creating_subid = parentSubid;
11441 if (oc->deleting_subid == mySubid)
11442 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
11443 prev_item = cur_item;
11444 cur_item = lnext(prev_item);
11450 * This is intended as a callback for RangeVarGetRelidExtended(). It allows
11451 * the relation to be locked only if (1) it's a plain table, materialized
11452 * view, or TOAST table and (2) the current user is the owner (or the
11453 * superuser). This meets the permission-checking needs of CLUSTER, REINDEX
11454 * TABLE, and REFRESH MATERIALIZED VIEW; we expose it here so that it can be
11458 RangeVarCallbackOwnsTable(const RangeVar *relation,
11459 Oid relId, Oid oldRelId, void *arg)
11463 /* Nothing to do if the relation was not found. */
11464 if (!OidIsValid(relId))
11468 * If the relation does exist, check whether it's an index. But note that
11469 * the relation might have been dropped between the time we did the name
11470 * lookup and now. In that case, there's nothing to do.
11472 relkind = get_rel_relkind(relId);
11475 if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
11476 relkind != RELKIND_MATVIEW)
11478 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11479 errmsg("\"%s\" is not a table or materialized view", relation->relname)));
11481 /* Check permissions */
11482 if (!pg_class_ownercheck(relId, GetUserId()))
11483 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS, relation->relname);
11487 * Callback to RangeVarGetRelidExtended(), similar to
11488 * RangeVarCallbackOwnsTable() but without checks on the type of the relation.
11491 RangeVarCallbackOwnsRelation(const RangeVar *relation,
11492 Oid relId, Oid oldRelId, void *arg)
11496 /* Nothing to do if the relation was not found. */
11497 if (!OidIsValid(relId))
11500 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
11501 if (!HeapTupleIsValid(tuple)) /* should not happen */
11502 elog(ERROR, "cache lookup failed for relation %u", relId);
11504 if (!pg_class_ownercheck(relId, GetUserId()))
11505 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
11506 relation->relname);
11508 if (!allowSystemTableMods &&
11509 IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
11511 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
11512 errmsg("permission denied: \"%s\" is a system catalog",
11513 relation->relname)));
11515 ReleaseSysCache(tuple);
11519 * Common RangeVarGetRelid callback for rename, set schema, and alter table
11523 RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid,
11526 Node *stmt = (Node *) arg;
11527 ObjectType reltype;
11529 Form_pg_class classform;
11530 AclResult aclresult;
11533 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
11534 if (!HeapTupleIsValid(tuple))
11535 return; /* concurrently dropped */
11536 classform = (Form_pg_class) GETSTRUCT(tuple);
11537 relkind = classform->relkind;
11539 /* Must own relation. */
11540 if (!pg_class_ownercheck(relid, GetUserId()))
11541 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS, rv->relname);
11543 /* No system table modifications unless explicitly allowed. */
11544 if (!allowSystemTableMods && IsSystemClass(relid, classform))
11546 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
11547 errmsg("permission denied: \"%s\" is a system catalog",
11551 * Extract the specified relation type from the statement parse tree.
11553 * Also, for ALTER .. RENAME, check permissions: the user must (still)
11554 * have CREATE rights on the containing namespace.
11556 if (IsA(stmt, RenameStmt))
11558 aclresult = pg_namespace_aclcheck(classform->relnamespace,
11559 GetUserId(), ACL_CREATE);
11560 if (aclresult != ACLCHECK_OK)
11561 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
11562 get_namespace_name(classform->relnamespace));
11563 reltype = ((RenameStmt *) stmt)->renameType;
11565 else if (IsA(stmt, AlterObjectSchemaStmt))
11566 reltype = ((AlterObjectSchemaStmt *) stmt)->objectType;
11568 else if (IsA(stmt, AlterTableStmt))
11569 reltype = ((AlterTableStmt *) stmt)->relkind;
11572 reltype = OBJECT_TABLE; /* placate compiler */
11573 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(stmt));
11577 * For compatibility with prior releases, we allow ALTER TABLE to be used
11578 * with most other types of relations (but not composite types). We allow
11579 * similar flexibility for ALTER INDEX in the case of RENAME, but not
11580 * otherwise. Otherwise, the user must select the correct form of the
11581 * command for the relation at issue.
11583 if (reltype == OBJECT_SEQUENCE && relkind != RELKIND_SEQUENCE)
11585 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11586 errmsg("\"%s\" is not a sequence", rv->relname)));
11588 if (reltype == OBJECT_VIEW && relkind != RELKIND_VIEW)
11590 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11591 errmsg("\"%s\" is not a view", rv->relname)));
11593 if (reltype == OBJECT_MATVIEW && relkind != RELKIND_MATVIEW)
11595 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11596 errmsg("\"%s\" is not a materialized view", rv->relname)));
11598 if (reltype == OBJECT_FOREIGN_TABLE && relkind != RELKIND_FOREIGN_TABLE)
11600 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11601 errmsg("\"%s\" is not a foreign table", rv->relname)));
11603 if (reltype == OBJECT_TYPE && relkind != RELKIND_COMPOSITE_TYPE)
11605 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11606 errmsg("\"%s\" is not a composite type", rv->relname)));
11608 if (reltype == OBJECT_INDEX && relkind != RELKIND_INDEX
11609 && !IsA(stmt, RenameStmt))
11611 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11612 errmsg("\"%s\" is not an index", rv->relname)));
11615 * Don't allow ALTER TABLE on composite types. We want people to use ALTER
11618 if (reltype != OBJECT_TYPE && relkind == RELKIND_COMPOSITE_TYPE)
11620 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11621 errmsg("\"%s\" is a composite type", rv->relname),
11622 errhint("Use ALTER TYPE instead.")));
11625 * Don't allow ALTER TABLE .. SET SCHEMA on relations that can't be moved
11626 * to a different schema, such as indexes and TOAST tables.
11628 if (IsA(stmt, AlterObjectSchemaStmt) &&
11629 relkind != RELKIND_RELATION &&
11630 relkind != RELKIND_VIEW &&
11631 relkind != RELKIND_MATVIEW &&
11632 relkind != RELKIND_SEQUENCE &&
11633 relkind != RELKIND_FOREIGN_TABLE)
11635 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11636 errmsg("\"%s\" is not a table, view, materialized view, sequence, or foreign table",
11639 ReleaseSysCache(tuple);