1 /*-------------------------------------------------------------------------
4 * Commands for creating and altering table structures and settings
6 * Portions Copyright (c) 1996-2013, 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/heapam_xlog.h"
20 #include "access/multixact.h"
21 #include "access/reloptions.h"
22 #include "access/relscan.h"
23 #include "access/sysattr.h"
24 #include "access/xact.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/sequence.h"
50 #include "commands/tablecmds.h"
51 #include "commands/tablespace.h"
52 #include "commands/trigger.h"
53 #include "commands/typecmds.h"
54 #include "common/relpath.h"
55 #include "executor/executor.h"
56 #include "foreign/foreign.h"
57 #include "miscadmin.h"
58 #include "nodes/makefuncs.h"
59 #include "nodes/nodeFuncs.h"
60 #include "nodes/parsenodes.h"
61 #include "optimizer/clauses.h"
62 #include "optimizer/planner.h"
63 #include "parser/parse_clause.h"
64 #include "parser/parse_coerce.h"
65 #include "parser/parse_collate.h"
66 #include "parser/parse_expr.h"
67 #include "parser/parse_oper.h"
68 #include "parser/parse_relation.h"
69 #include "parser/parse_type.h"
70 #include "parser/parse_utilcmd.h"
71 #include "parser/parser.h"
72 #include "rewrite/rewriteDefine.h"
73 #include "rewrite/rewriteHandler.h"
74 #include "rewrite/rewriteManip.h"
75 #include "storage/bufmgr.h"
76 #include "storage/lmgr.h"
77 #include "storage/lock.h"
78 #include "storage/predicate.h"
79 #include "storage/smgr.h"
80 #include "utils/acl.h"
81 #include "utils/builtins.h"
82 #include "utils/fmgroids.h"
83 #include "utils/inval.h"
84 #include "utils/lsyscache.h"
85 #include "utils/memutils.h"
86 #include "utils/relcache.h"
87 #include "utils/snapmgr.h"
88 #include "utils/syscache.h"
89 #include "utils/tqual.h"
90 #include "utils/typcache.h"
94 * ON COMMIT action list
96 typedef struct OnCommitItem
98 Oid relid; /* relid of relation */
99 OnCommitAction oncommit; /* what to do at end of xact */
102 * If this entry was created during the current transaction,
103 * creating_subid is the ID of the creating subxact; if created in a prior
104 * transaction, creating_subid is zero. If deleted during the current
105 * transaction, deleting_subid is the ID of the deleting subxact; if no
106 * deletion request is pending, deleting_subid is zero.
108 SubTransactionId creating_subid;
109 SubTransactionId deleting_subid;
112 static List *on_commits = NIL;
116 * State information for ALTER TABLE
118 * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
119 * structs, one for each table modified by the operation (the named table
120 * plus any child tables that are affected). We save lists of subcommands
121 * to apply to this table (possibly modified by parse transformation steps);
122 * these lists will be executed in Phase 2. If a Phase 3 step is needed,
123 * necessary information is stored in the constraints and newvals lists.
125 * Phase 2 is divided into multiple passes; subcommands are executed in
126 * a pass determined by subcommand type.
129 #define AT_PASS_UNSET -1 /* UNSET will cause ERROR */
130 #define AT_PASS_DROP 0 /* DROP (all flavors) */
131 #define AT_PASS_ALTER_TYPE 1 /* ALTER COLUMN TYPE */
132 #define AT_PASS_OLD_INDEX 2 /* re-add existing indexes */
133 #define AT_PASS_OLD_CONSTR 3 /* re-add existing constraints */
134 #define AT_PASS_COL_ATTRS 4 /* set other column attributes */
135 /* We could support a RENAME COLUMN pass here, but not currently used */
136 #define AT_PASS_ADD_COL 5 /* ADD COLUMN */
137 #define AT_PASS_ADD_INDEX 6 /* ADD indexes */
138 #define AT_PASS_ADD_CONSTR 7 /* ADD constraints, defaults */
139 #define AT_PASS_MISC 8 /* other stuff */
140 #define AT_NUM_PASSES 9
142 typedef struct AlteredTableInfo
144 /* Information saved before any work commences: */
145 Oid relid; /* Relation to work on */
146 char relkind; /* Its relkind */
147 TupleDesc oldDesc; /* Pre-modification tuple descriptor */
148 /* Information saved by Phase 1 for Phase 2: */
149 List *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
150 /* Information saved by Phases 1/2 for Phase 3: */
151 List *constraints; /* List of NewConstraint */
152 List *newvals; /* List of NewColumnValue */
153 bool new_notnull; /* T if we added new NOT NULL constraints */
154 bool rewrite; /* T if a rewrite is forced */
155 Oid newTableSpace; /* new tablespace; 0 means no change */
156 /* Objects to rebuild after completing ALTER TYPE operations */
157 List *changedConstraintOids; /* OIDs of constraints to rebuild */
158 List *changedConstraintDefs; /* string definitions of same */
159 List *changedIndexOids; /* OIDs of indexes to rebuild */
160 List *changedIndexDefs; /* string definitions of same */
163 /* Struct describing one new constraint to check in Phase 3 scan */
164 /* Note: new NOT NULL constraints are handled elsewhere */
165 typedef struct NewConstraint
167 char *name; /* Constraint name, or NULL if none */
168 ConstrType contype; /* CHECK or FOREIGN */
169 Oid refrelid; /* PK rel, if FOREIGN */
170 Oid refindid; /* OID of PK's index, if FOREIGN */
171 Oid conid; /* OID of pg_constraint entry, if FOREIGN */
172 Node *qual; /* Check expr or CONSTR_FOREIGN Constraint */
173 List *qualstate; /* Execution state for CHECK */
177 * Struct describing one new column value that needs to be computed during
178 * Phase 3 copy (this could be either a new column with a non-null default, or
179 * a column that we're changing the type of). Columns without such an entry
180 * are just copied from the old table during ATRewriteTable. Note that the
181 * expr is an expression over *old* table values.
183 typedef struct NewColumnValue
185 AttrNumber attnum; /* which column */
186 Expr *expr; /* expression to compute */
187 ExprState *exprstate; /* execution state */
191 * Error-reporting support for RemoveRelations
193 struct dropmsgstrings
196 int nonexistent_code;
197 const char *nonexistent_msg;
198 const char *skipping_msg;
199 const char *nota_msg;
200 const char *drophint_msg;
203 static const struct dropmsgstrings dropmsgstringarray[] = {
205 ERRCODE_UNDEFINED_TABLE,
206 gettext_noop("table \"%s\" does not exist"),
207 gettext_noop("table \"%s\" does not exist, skipping"),
208 gettext_noop("\"%s\" is not a table"),
209 gettext_noop("Use DROP TABLE to remove a table.")},
211 ERRCODE_UNDEFINED_TABLE,
212 gettext_noop("sequence \"%s\" does not exist"),
213 gettext_noop("sequence \"%s\" does not exist, skipping"),
214 gettext_noop("\"%s\" is not a sequence"),
215 gettext_noop("Use DROP SEQUENCE to remove a sequence.")},
217 ERRCODE_UNDEFINED_TABLE,
218 gettext_noop("view \"%s\" does not exist"),
219 gettext_noop("view \"%s\" does not exist, skipping"),
220 gettext_noop("\"%s\" is not a view"),
221 gettext_noop("Use DROP VIEW to remove a view.")},
223 ERRCODE_UNDEFINED_TABLE,
224 gettext_noop("materialized view \"%s\" does not exist"),
225 gettext_noop("materialized view \"%s\" does not exist, skipping"),
226 gettext_noop("\"%s\" is not a materialized view"),
227 gettext_noop("Use DROP MATERIALIZED VIEW to remove a materialized view.")},
229 ERRCODE_UNDEFINED_OBJECT,
230 gettext_noop("index \"%s\" does not exist"),
231 gettext_noop("index \"%s\" does not exist, skipping"),
232 gettext_noop("\"%s\" is not an index"),
233 gettext_noop("Use DROP INDEX to remove an index.")},
234 {RELKIND_COMPOSITE_TYPE,
235 ERRCODE_UNDEFINED_OBJECT,
236 gettext_noop("type \"%s\" does not exist"),
237 gettext_noop("type \"%s\" does not exist, skipping"),
238 gettext_noop("\"%s\" is not a type"),
239 gettext_noop("Use DROP TYPE to remove a type.")},
240 {RELKIND_FOREIGN_TABLE,
241 ERRCODE_UNDEFINED_OBJECT,
242 gettext_noop("foreign table \"%s\" does not exist"),
243 gettext_noop("foreign table \"%s\" does not exist, skipping"),
244 gettext_noop("\"%s\" is not a foreign table"),
245 gettext_noop("Use DROP FOREIGN TABLE to remove a foreign table.")},
246 {'\0', 0, NULL, NULL, NULL, NULL}
249 struct DropRelationCallbackState
256 /* Alter table target-type flags for ATSimplePermissions */
257 #define ATT_TABLE 0x0001
258 #define ATT_VIEW 0x0002
259 #define ATT_MATVIEW 0x0004
260 #define ATT_INDEX 0x0008
261 #define ATT_COMPOSITE_TYPE 0x0010
262 #define ATT_FOREIGN_TABLE 0x0020
264 static void truncate_check_rel(Relation rel);
265 static List *MergeAttributes(List *schema, List *supers, char relpersistence,
266 List **supOids, List **supconstr, int *supOidCount);
267 static bool MergeCheckConstraint(List *constraints, char *name, Node *expr);
268 static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel);
269 static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
270 static void StoreCatalogInheritance(Oid relationId, List *supers);
271 static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
272 int16 seqNumber, Relation inhRelation);
273 static int findAttrByName(const char *attributeName, List *schema);
274 static void AlterIndexNamespaces(Relation classRel, Relation rel,
275 Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved);
276 static void AlterSeqNamespaces(Relation classRel, Relation rel,
277 Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved,
279 static void ATExecAlterConstraint(Relation rel, AlterTableCmd *cmd,
280 bool recurse, bool recursing, LOCKMODE lockmode);
281 static void ATExecValidateConstraint(Relation rel, char *constrName,
282 bool recurse, bool recursing, LOCKMODE lockmode);
283 static int transformColumnNameList(Oid relId, List *colList,
284 int16 *attnums, Oid *atttypids);
285 static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
287 int16 *attnums, Oid *atttypids,
289 static Oid transformFkeyCheckAttrs(Relation pkrel,
290 int numattrs, int16 *attnums,
292 static void checkFkeyPermissions(Relation rel, int16 *attnums, int natts);
293 static CoercionPathType findFkeyCast(Oid targetTypeId, Oid sourceTypeId,
295 static void validateCheckConstraint(Relation rel, HeapTuple constrtup);
296 static void validateForeignKeyConstraint(char *conname,
297 Relation rel, Relation pkrel,
298 Oid pkindOid, Oid constraintOid);
299 static void createForeignKeyTriggers(Relation rel, Constraint *fkconstraint,
300 Oid constraintOid, Oid indexOid);
301 static void ATController(Relation rel, List *cmds, bool recurse, LOCKMODE lockmode);
302 static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
303 bool recurse, bool recursing, LOCKMODE lockmode);
304 static void ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode);
305 static void ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
306 AlterTableCmd *cmd, LOCKMODE lockmode);
307 static void ATRewriteTables(List **wqueue, LOCKMODE lockmode);
308 static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap, LOCKMODE lockmode);
309 static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
310 static void ATSimplePermissions(Relation rel, int allowed_targets);
311 static void ATWrongRelkindError(Relation rel, int allowed_targets);
312 static void ATSimpleRecursion(List **wqueue, Relation rel,
313 AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode);
314 static void ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
316 static List *find_typed_table_dependencies(Oid typeOid, const char *typeName,
317 DropBehavior behavior);
318 static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
319 AlterTableCmd *cmd, LOCKMODE lockmode);
320 static void ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel,
321 ColumnDef *colDef, bool isOid,
322 bool recurse, bool recursing, LOCKMODE lockmode);
323 static void check_for_column_name_collision(Relation rel, const char *colname);
324 static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
325 static void add_column_collation_dependency(Oid relid, int32 attnum, Oid collid);
326 static void ATPrepAddOids(List **wqueue, Relation rel, bool recurse,
327 AlterTableCmd *cmd, LOCKMODE lockmode);
328 static void ATExecDropNotNull(Relation rel, const char *colName, LOCKMODE lockmode);
329 static void ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
330 const char *colName, LOCKMODE lockmode);
331 static void ATExecColumnDefault(Relation rel, const char *colName,
332 Node *newDefault, LOCKMODE lockmode);
333 static void ATPrepSetStatistics(Relation rel, const char *colName,
334 Node *newValue, LOCKMODE lockmode);
335 static void ATExecSetStatistics(Relation rel, const char *colName,
336 Node *newValue, LOCKMODE lockmode);
337 static void ATExecSetOptions(Relation rel, const char *colName,
338 Node *options, bool isReset, LOCKMODE lockmode);
339 static void ATExecSetStorage(Relation rel, const char *colName,
340 Node *newValue, LOCKMODE lockmode);
341 static void ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
342 AlterTableCmd *cmd, LOCKMODE lockmode);
343 static void ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
344 DropBehavior behavior,
345 bool recurse, bool recursing,
346 bool missing_ok, LOCKMODE lockmode);
347 static void ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
348 IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode);
349 static void ATExecAddConstraint(List **wqueue,
350 AlteredTableInfo *tab, Relation rel,
351 Constraint *newConstraint, bool recurse, bool is_readd,
353 static void ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
354 IndexStmt *stmt, LOCKMODE lockmode);
355 static void ATAddCheckConstraint(List **wqueue,
356 AlteredTableInfo *tab, Relation rel,
358 bool recurse, bool recursing, bool is_readd,
360 static void ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
361 Constraint *fkconstraint, LOCKMODE lockmode);
362 static void ATExecDropConstraint(Relation rel, const char *constrName,
363 DropBehavior behavior,
364 bool recurse, bool recursing,
365 bool missing_ok, LOCKMODE lockmode);
366 static void ATPrepAlterColumnType(List **wqueue,
367 AlteredTableInfo *tab, Relation rel,
368 bool recurse, bool recursing,
369 AlterTableCmd *cmd, LOCKMODE lockmode);
370 static bool ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno);
371 static void ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
372 AlterTableCmd *cmd, LOCKMODE lockmode);
373 static void ATExecAlterColumnGenericOptions(Relation rel, const char *colName,
374 List *options, LOCKMODE lockmode);
375 static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode);
376 static void ATPostAlterTypeParse(Oid oldId, char *cmd,
377 List **wqueue, LOCKMODE lockmode, bool rewrite);
378 static void TryReuseIndex(Oid oldId, IndexStmt *stmt);
379 static void TryReuseForeignKey(Oid oldId, Constraint *con);
380 static void change_owner_fix_column_acls(Oid relationOid,
381 Oid oldOwnerId, Oid newOwnerId);
382 static void change_owner_recurse_to_sequences(Oid relationOid,
383 Oid newOwnerId, LOCKMODE lockmode);
384 static void ATExecClusterOn(Relation rel, const char *indexName, LOCKMODE lockmode);
385 static void ATExecDropCluster(Relation rel, LOCKMODE lockmode);
386 static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
387 char *tablespacename, LOCKMODE lockmode);
388 static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode);
389 static void ATExecSetRelOptions(Relation rel, List *defList,
390 AlterTableType operation,
392 static void ATExecEnableDisableTrigger(Relation rel, char *trigname,
393 char fires_when, bool skip_system, LOCKMODE lockmode);
394 static void ATExecEnableDisableRule(Relation rel, char *rulename,
395 char fires_when, LOCKMODE lockmode);
396 static void ATPrepAddInherit(Relation child_rel);
397 static void ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode);
398 static void ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode);
399 static void drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid);
400 static void ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode);
401 static void ATExecDropOf(Relation rel, LOCKMODE lockmode);
402 static void ATExecGenericOptions(Relation rel, List *options);
404 static void copy_relation_data(SMgrRelation rel, SMgrRelation dst,
405 ForkNumber forkNum, char relpersistence);
406 static const char *storage_name(char c);
408 static void RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid,
409 Oid oldRelOid, void *arg);
410 static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid,
411 Oid oldrelid, void *arg);
414 /* ----------------------------------------------------------------
416 * Creates a new relation.
418 * stmt carries parsetree information from an ordinary CREATE TABLE statement.
419 * The other arguments are used to extend the behavior for other cases:
420 * relkind: relkind to assign to the new relation
421 * ownerId: if not InvalidOid, use this as the new relation's owner.
423 * Note that permissions checks are done against current user regardless of
424 * ownerId. A nonzero ownerId is used when someone is creating a relation
425 * "on behalf of" someone else, so we still want to see that the current user
426 * has permissions to do it.
428 * If successful, returns the OID of the new relation.
429 * ----------------------------------------------------------------
432 DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId)
434 char relname[NAMEDATALEN];
436 List *schema = stmt->tableElts;
440 TupleDesc descriptor;
442 List *old_constraints;
446 List *cookedDefaults;
450 static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
454 * Truncate relname to appropriate length (probably a waste of time, as
455 * parser should have done this already).
457 StrNCpy(relname, stmt->relation->relname, NAMEDATALEN);
460 * Check consistency of arguments
462 if (stmt->oncommit != ONCOMMIT_NOOP
463 && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
465 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
466 errmsg("ON COMMIT can only be used on temporary tables")));
467 if (stmt->constraints != NIL && relkind == RELKIND_FOREIGN_TABLE)
469 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
470 errmsg("constraints are not supported on foreign tables")));
473 * Look up the namespace in which we are supposed to create the relation,
474 * check we have permission to create there, lock it against concurrent
475 * drop, and mark stmt->relation as RELPERSISTENCE_TEMP if a temporary
476 * namespace is selected.
479 RangeVarGetAndCheckCreationNamespace(stmt->relation, NoLock, NULL);
482 * Security check: disallow creating temp tables from security-restricted
483 * code. This is needed because calling code might not expect untrusted
484 * tables to appear in pg_temp at the front of its search path.
486 if (stmt->relation->relpersistence == RELPERSISTENCE_TEMP
487 && InSecurityRestrictedOperation())
489 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
490 errmsg("cannot create temporary table within security-restricted operation")));
493 * Select tablespace to use. If not specified, use default tablespace
494 * (which may in turn default to database's default).
496 if (stmt->tablespacename)
498 tablespaceId = get_tablespace_oid(stmt->tablespacename, false);
502 tablespaceId = GetDefaultTablespace(stmt->relation->relpersistence);
503 /* note InvalidOid is OK in this case */
506 /* Check permissions except when using database's default */
507 if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
511 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
513 if (aclresult != ACLCHECK_OK)
514 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
515 get_tablespace_name(tablespaceId));
518 /* In all cases disallow placing user relations in pg_global */
519 if (tablespaceId == GLOBALTABLESPACE_OID)
521 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
522 errmsg("only shared relations can be placed in pg_global tablespace")));
524 /* Identify user ID that will own the table */
525 if (!OidIsValid(ownerId))
526 ownerId = GetUserId();
529 * Parse and validate reloptions, if any.
531 reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, validnsps,
534 (void) heap_reloptions(relkind, reloptions, true);
536 if (stmt->ofTypename)
540 ofTypeId = typenameTypeId(NULL, stmt->ofTypename);
542 aclresult = pg_type_aclcheck(ofTypeId, GetUserId(), ACL_USAGE);
543 if (aclresult != ACLCHECK_OK)
544 aclcheck_error_type(aclresult, ofTypeId);
547 ofTypeId = InvalidOid;
550 * Look up inheritance ancestors and generate relation schema, including
551 * inherited attributes.
553 schema = MergeAttributes(schema, stmt->inhRelations,
554 stmt->relation->relpersistence,
555 &inheritOids, &old_constraints, &parentOidCount);
558 * Create a tuple descriptor from the relation schema. Note that this
559 * deals with column names, types, and NOT NULL constraints, but not
560 * default values or CHECK constraints; we handle those below.
562 descriptor = BuildDescForRelation(schema);
564 localHasOids = interpretOidsOption(stmt->options,
565 (relkind == RELKIND_RELATION ||
566 relkind == RELKIND_FOREIGN_TABLE));
567 descriptor->tdhasoid = (localHasOids || parentOidCount > 0);
570 * Find columns with default values and prepare for insertion of the
571 * defaults. Pre-cooked (that is, inherited) defaults go into a list of
572 * CookedConstraint structs that we'll pass to heap_create_with_catalog,
573 * while raw defaults go into a list of RawColumnDefault structs that will
574 * be processed by AddRelationNewConstraints. (We can't deal with raw
575 * expressions until we can do transformExpr.)
577 * We can set the atthasdef flags now in the tuple descriptor; this just
578 * saves StoreAttrDefault from having to do an immediate update of the
582 cookedDefaults = NIL;
585 foreach(listptr, schema)
587 ColumnDef *colDef = lfirst(listptr);
591 if (colDef->raw_default != NULL)
593 RawColumnDefault *rawEnt;
595 Assert(colDef->cooked_default == NULL);
597 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
598 rawEnt->attnum = attnum;
599 rawEnt->raw_default = colDef->raw_default;
600 rawDefaults = lappend(rawDefaults, rawEnt);
601 descriptor->attrs[attnum - 1]->atthasdef = true;
603 else if (colDef->cooked_default != NULL)
605 CookedConstraint *cooked;
607 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
608 cooked->contype = CONSTR_DEFAULT;
610 cooked->attnum = attnum;
611 cooked->expr = colDef->cooked_default;
612 cooked->skip_validation = false;
613 cooked->is_local = true; /* not used for defaults */
614 cooked->inhcount = 0; /* ditto */
615 cooked->is_no_inherit = false;
616 cookedDefaults = lappend(cookedDefaults, cooked);
617 descriptor->attrs[attnum - 1]->atthasdef = true;
622 * Create the relation. Inherited defaults and constraints are passed in
623 * for immediate handling --- since they don't need parsing, they can be
624 * stored immediately.
626 relationId = heap_create_with_catalog(relname,
634 list_concat(cookedDefaults,
637 stmt->relation->relpersistence,
645 allowSystemTableMods,
648 /* Store inheritance information for new rel. */
649 StoreCatalogInheritance(relationId, inheritOids);
652 * We must bump the command counter to make the newly-created relation
653 * tuple visible for opening.
655 CommandCounterIncrement();
658 * Open the new relation and acquire exclusive lock on it. This isn't
659 * really necessary for locking out other backends (since they can't see
660 * the new rel anyway until we commit), but it keeps the lock manager from
661 * complaining about deadlock risks.
663 rel = relation_open(relationId, AccessExclusiveLock);
666 * Now add any newly specified column default values and CHECK constraints
667 * to the new relation. These are passed to us in the form of raw
668 * parsetrees; we need to transform them to executable expression trees
669 * before they can be added. The most convenient way to do that is to
670 * apply the parser's transformExpr routine, but transformExpr doesn't
671 * work unless we have a pre-existing relation. So, the transformation has
672 * to be postponed to this final step of CREATE TABLE.
674 if (rawDefaults || stmt->constraints)
675 AddRelationNewConstraints(rel, rawDefaults, stmt->constraints,
679 * Clean up. We keep lock on new relation (although it shouldn't be
680 * visible to anyone else anyway, until commit).
682 relation_close(rel, NoLock);
688 * Emit the right error or warning message for a "DROP" command issued on a
689 * non-existent relation
692 DropErrorMsgNonExistent(const char *relname, char rightkind, bool missing_ok)
694 const struct dropmsgstrings *rentry;
696 for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
698 if (rentry->kind == rightkind)
703 (errcode(rentry->nonexistent_code),
704 errmsg(rentry->nonexistent_msg, relname)));
708 ereport(NOTICE, (errmsg(rentry->skipping_msg, relname)));
714 Assert(rentry->kind != '\0'); /* Should be impossible */
718 * Emit the right error message for a "DROP" command issued on a
719 * relation of the wrong type
722 DropErrorMsgWrongType(const char *relname, char wrongkind, char rightkind)
724 const struct dropmsgstrings *rentry;
725 const struct dropmsgstrings *wentry;
727 for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
728 if (rentry->kind == rightkind)
730 Assert(rentry->kind != '\0');
732 for (wentry = dropmsgstringarray; wentry->kind != '\0'; wentry++)
733 if (wentry->kind == wrongkind)
735 /* wrongkind could be something we don't have in our table... */
738 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
739 errmsg(rentry->nota_msg, relname),
740 (wentry->kind != '\0') ? errhint("%s", _(wentry->drophint_msg)) : 0));
745 * Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW,
746 * DROP MATERIALIZED VIEW, DROP FOREIGN TABLE
749 RemoveRelations(DropStmt *drop)
751 ObjectAddresses *objects;
755 LOCKMODE lockmode = AccessExclusiveLock;
757 /* DROP CONCURRENTLY uses a weaker lock, and has some restrictions */
758 if (drop->concurrent)
760 flags |= PERFORM_DELETION_CONCURRENTLY;
761 lockmode = ShareUpdateExclusiveLock;
762 Assert(drop->removeType == OBJECT_INDEX);
763 if (list_length(drop->objects) != 1)
765 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
766 errmsg("DROP INDEX CONCURRENTLY does not support dropping multiple objects")));
767 if (drop->behavior == DROP_CASCADE)
769 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
770 errmsg("DROP INDEX CONCURRENTLY does not support CASCADE")));
774 * First we identify all the relations, then we delete them in a single
775 * performMultipleDeletions() call. This is to avoid unwanted DROP
776 * RESTRICT errors if one of the relations depends on another.
779 /* Determine required relkind */
780 switch (drop->removeType)
783 relkind = RELKIND_RELATION;
787 relkind = RELKIND_INDEX;
790 case OBJECT_SEQUENCE:
791 relkind = RELKIND_SEQUENCE;
795 relkind = RELKIND_VIEW;
799 relkind = RELKIND_MATVIEW;
802 case OBJECT_FOREIGN_TABLE:
803 relkind = RELKIND_FOREIGN_TABLE;
807 elog(ERROR, "unrecognized drop object type: %d",
808 (int) drop->removeType);
809 relkind = 0; /* keep compiler quiet */
813 /* Lock and validate each relation; build a list of object addresses */
814 objects = new_object_addresses();
816 foreach(cell, drop->objects)
818 RangeVar *rel = makeRangeVarFromNameList((List *) lfirst(cell));
821 struct DropRelationCallbackState state;
824 * These next few steps are a great deal like relation_openrv, but we
825 * don't bother building a relcache entry since we don't need it.
827 * Check for shared-cache-inval messages before trying to access the
828 * relation. This is needed to cover the case where the name
829 * identifies a rel that has been dropped and recreated since the
830 * start of our transaction: if we don't flush the old syscache entry,
831 * then we'll latch onto that entry and suffer an error later.
833 AcceptInvalidationMessages();
835 /* Look up the appropriate relation using namespace search. */
836 state.relkind = relkind;
837 state.heapOid = InvalidOid;
838 state.concurrent = drop->concurrent;
839 relOid = RangeVarGetRelidExtended(rel, lockmode, true,
841 RangeVarCallbackForDropRelation,
845 if (!OidIsValid(relOid))
847 DropErrorMsgNonExistent(rel->relname, relkind, drop->missing_ok);
851 /* OK, we're ready to delete this one */
852 obj.classId = RelationRelationId;
853 obj.objectId = relOid;
856 add_exact_object_address(&obj, objects);
859 performMultipleDeletions(objects, drop->behavior, flags);
861 free_object_addresses(objects);
865 * Before acquiring a table lock, check whether we have sufficient rights.
866 * In the case of DROP INDEX, also try to lock the table before the index.
869 RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid, Oid oldRelOid,
873 struct DropRelationCallbackState *state;
875 Form_pg_class classform;
876 LOCKMODE heap_lockmode;
878 state = (struct DropRelationCallbackState *) arg;
879 relkind = state->relkind;
880 heap_lockmode = state->concurrent ?
881 ShareUpdateExclusiveLock : AccessExclusiveLock;
884 * If we previously locked some other index's heap, and the name we're
885 * looking up no longer refers to that relation, release the now-useless
888 if (relOid != oldRelOid && OidIsValid(state->heapOid))
890 UnlockRelationOid(state->heapOid, heap_lockmode);
891 state->heapOid = InvalidOid;
894 /* Didn't find a relation, so no need for locking or permission checks. */
895 if (!OidIsValid(relOid))
898 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
899 if (!HeapTupleIsValid(tuple))
900 return; /* concurrently dropped, so nothing to do */
901 classform = (Form_pg_class) GETSTRUCT(tuple);
903 if (classform->relkind != relkind)
904 DropErrorMsgWrongType(rel->relname, classform->relkind, relkind);
906 /* Allow DROP to either table owner or schema owner */
907 if (!pg_class_ownercheck(relOid, GetUserId()) &&
908 !pg_namespace_ownercheck(classform->relnamespace, GetUserId()))
909 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
912 if (!allowSystemTableMods && IsSystemClass(classform))
914 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
915 errmsg("permission denied: \"%s\" is a system catalog",
918 ReleaseSysCache(tuple);
921 * In DROP INDEX, attempt to acquire lock on the parent table before
922 * locking the index. index_drop() will need this anyway, and since
923 * regular queries lock tables before their indexes, we risk deadlock if
924 * we do it the other way around. No error if we don't find a pg_index
925 * entry, though --- the relation may have been dropped.
927 if (relkind == RELKIND_INDEX && relOid != oldRelOid)
929 state->heapOid = IndexGetRelation(relOid, true);
930 if (OidIsValid(state->heapOid))
931 LockRelationOid(state->heapOid, heap_lockmode);
937 * Executes a TRUNCATE command.
939 * This is a multi-relation truncate. We first open and grab exclusive
940 * lock on all relations involved, checking permissions and otherwise
941 * verifying that the relation is OK for truncation. In CASCADE mode,
942 * relations having FK references to the targeted relations are automatically
943 * added to the group; in RESTRICT mode, we check that all FK references are
944 * internal to the group that's being truncated. Finally all the relations
945 * are truncated and reindexed.
948 ExecuteTruncate(TruncateStmt *stmt)
952 List *seq_relids = NIL;
954 ResultRelInfo *resultRelInfos;
955 ResultRelInfo *resultRelInfo;
956 SubTransactionId mySubid;
960 * Open, exclusive-lock, and check all the explicitly-specified relations
962 foreach(cell, stmt->relations)
964 RangeVar *rv = lfirst(cell);
966 bool recurse = interpretInhOption(rv->inhOpt);
969 rel = heap_openrv(rv, AccessExclusiveLock);
970 myrelid = RelationGetRelid(rel);
971 /* don't throw error for "TRUNCATE foo, foo" */
972 if (list_member_oid(relids, myrelid))
974 heap_close(rel, AccessExclusiveLock);
977 truncate_check_rel(rel);
978 rels = lappend(rels, rel);
979 relids = lappend_oid(relids, myrelid);
986 children = find_all_inheritors(myrelid, AccessExclusiveLock, NULL);
988 foreach(child, children)
990 Oid childrelid = lfirst_oid(child);
992 if (list_member_oid(relids, childrelid))
995 /* find_all_inheritors already got lock */
996 rel = heap_open(childrelid, NoLock);
997 truncate_check_rel(rel);
998 rels = lappend(rels, rel);
999 relids = lappend_oid(relids, childrelid);
1005 * In CASCADE mode, suck in all referencing relations as well. This
1006 * requires multiple iterations to find indirectly-dependent relations. At
1007 * each phase, we need to exclusive-lock new rels before looking for their
1008 * dependencies, else we might miss something. Also, we check each rel as
1009 * soon as we open it, to avoid a faux pas such as holding lock for a long
1010 * time on a rel we have no permissions for.
1012 if (stmt->behavior == DROP_CASCADE)
1018 newrelids = heap_truncate_find_FKs(relids);
1019 if (newrelids == NIL)
1020 break; /* nothing else to add */
1022 foreach(cell, newrelids)
1024 Oid relid = lfirst_oid(cell);
1027 rel = heap_open(relid, AccessExclusiveLock);
1029 (errmsg("truncate cascades to table \"%s\"",
1030 RelationGetRelationName(rel))));
1031 truncate_check_rel(rel);
1032 rels = lappend(rels, rel);
1033 relids = lappend_oid(relids, relid);
1039 * Check foreign key references. In CASCADE mode, this should be
1040 * unnecessary since we just pulled in all the references; but as a
1041 * cross-check, do it anyway if in an Assert-enabled build.
1043 #ifdef USE_ASSERT_CHECKING
1044 heap_truncate_check_FKs(rels, false);
1046 if (stmt->behavior == DROP_RESTRICT)
1047 heap_truncate_check_FKs(rels, false);
1051 * If we are asked to restart sequences, find all the sequences, lock them
1052 * (we need AccessExclusiveLock for ResetSequence), and check permissions.
1053 * We want to do this early since it's pointless to do all the truncation
1054 * work only to fail on sequence permissions.
1056 if (stmt->restart_seqs)
1060 Relation rel = (Relation) lfirst(cell);
1061 List *seqlist = getOwnedSequences(RelationGetRelid(rel));
1064 foreach(seqcell, seqlist)
1066 Oid seq_relid = lfirst_oid(seqcell);
1069 seq_rel = relation_open(seq_relid, AccessExclusiveLock);
1071 /* This check must match AlterSequence! */
1072 if (!pg_class_ownercheck(seq_relid, GetUserId()))
1073 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1074 RelationGetRelationName(seq_rel));
1076 seq_relids = lappend_oid(seq_relids, seq_relid);
1078 relation_close(seq_rel, NoLock);
1083 /* Prepare to catch AFTER triggers. */
1084 AfterTriggerBeginQuery();
1087 * To fire triggers, we'll need an EState as well as a ResultRelInfo for
1088 * each relation. We don't need to call ExecOpenIndices, though.
1090 estate = CreateExecutorState();
1091 resultRelInfos = (ResultRelInfo *)
1092 palloc(list_length(rels) * sizeof(ResultRelInfo));
1093 resultRelInfo = resultRelInfos;
1096 Relation rel = (Relation) lfirst(cell);
1098 InitResultRelInfo(resultRelInfo,
1100 0, /* dummy rangetable index */
1104 estate->es_result_relations = resultRelInfos;
1105 estate->es_num_result_relations = list_length(rels);
1108 * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
1109 * truncating (this is because one of them might throw an error). Also, if
1110 * we were to allow them to prevent statement execution, that would need
1111 * to be handled here.
1113 resultRelInfo = resultRelInfos;
1116 estate->es_result_relation_info = resultRelInfo;
1117 ExecBSTruncateTriggers(estate, resultRelInfo);
1122 * OK, truncate each table.
1124 mySubid = GetCurrentSubTransactionId();
1128 Relation rel = (Relation) lfirst(cell);
1131 * Normally, we need a transaction-safe truncation here. However, if
1132 * the table was either created in the current (sub)transaction or has
1133 * a new relfilenode in the current (sub)transaction, then we can just
1134 * truncate it in-place, because a rollback would cause the whole
1135 * table or the current physical file to be thrown away anyway.
1137 if (rel->rd_createSubid == mySubid ||
1138 rel->rd_newRelfilenodeSubid == mySubid)
1140 /* Immediate, non-rollbackable truncation is OK */
1141 heap_truncate_one_rel(rel);
1147 MultiXactId minmulti;
1150 * This effectively deletes all rows in the table, and may be done
1151 * in a serializable transaction. In that case we must record a
1152 * rw-conflict in to this transaction from each transaction
1153 * holding a predicate lock on the table.
1155 CheckTableForSerializableConflictIn(rel);
1157 minmulti = GetOldestMultiXactId();
1160 * Need the full transaction-safe pushups.
1162 * Create a new empty storage file for the relation, and assign it
1163 * as the relfilenode value. The old storage file is scheduled for
1164 * deletion at commit.
1166 RelationSetNewRelfilenode(rel, RecentXmin, minmulti);
1167 if (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED)
1168 heap_create_init_fork(rel);
1170 heap_relid = RelationGetRelid(rel);
1171 toast_relid = rel->rd_rel->reltoastrelid;
1174 * The same for the toast table, if any.
1176 if (OidIsValid(toast_relid))
1178 rel = relation_open(toast_relid, AccessExclusiveLock);
1179 RelationSetNewRelfilenode(rel, RecentXmin, minmulti);
1180 if (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED)
1181 heap_create_init_fork(rel);
1182 heap_close(rel, NoLock);
1186 * Reconstruct the indexes to match, and we're done.
1188 reindex_relation(heap_relid, REINDEX_REL_PROCESS_TOAST);
1193 * Restart owned sequences if we were asked to.
1195 foreach(cell, seq_relids)
1197 Oid seq_relid = lfirst_oid(cell);
1199 ResetSequence(seq_relid);
1203 * Process all AFTER STATEMENT TRUNCATE triggers.
1205 resultRelInfo = resultRelInfos;
1208 estate->es_result_relation_info = resultRelInfo;
1209 ExecASTruncateTriggers(estate, resultRelInfo);
1213 /* Handle queued AFTER triggers */
1214 AfterTriggerEndQuery(estate);
1216 /* We can clean up the EState now */
1217 FreeExecutorState(estate);
1219 /* And close the rels (can't do this while EState still holds refs) */
1222 Relation rel = (Relation) lfirst(cell);
1224 heap_close(rel, NoLock);
1229 * Check that a given rel is safe to truncate. Subroutine for ExecuteTruncate
1232 truncate_check_rel(Relation rel)
1234 AclResult aclresult;
1236 /* Only allow truncate on regular tables */
1237 if (rel->rd_rel->relkind != RELKIND_RELATION)
1239 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1240 errmsg("\"%s\" is not a table",
1241 RelationGetRelationName(rel))));
1243 /* Permissions checks */
1244 aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
1246 if (aclresult != ACLCHECK_OK)
1247 aclcheck_error(aclresult, ACL_KIND_CLASS,
1248 RelationGetRelationName(rel));
1250 if (!allowSystemTableMods && IsSystemRelation(rel))
1252 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1253 errmsg("permission denied: \"%s\" is a system catalog",
1254 RelationGetRelationName(rel))));
1257 * Don't allow truncate on temp tables of other backends ... their local
1258 * buffer manager is not going to cope.
1260 if (RELATION_IS_OTHER_TEMP(rel))
1262 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1263 errmsg("cannot truncate temporary tables of other sessions")));
1266 * Also check for active uses of the relation in the current transaction,
1267 * including open scans and pending AFTER trigger events.
1269 CheckTableNotInUse(rel, "TRUNCATE");
1274 * returns the name corresponding to a typstorage/attstorage enum value
1277 storage_name(char c)
1296 * Returns new schema given initial schema and superclasses.
1299 * 'schema' is the column/attribute definition for the table. (It's a list
1300 * of ColumnDef's.) It is destructively changed.
1301 * 'supers' is a list of names (as RangeVar nodes) of parent relations.
1302 * 'relpersistence' is a persistence type of the table.
1305 * 'supOids' receives a list of the OIDs of the parent relations.
1306 * 'supconstr' receives a list of constraints belonging to the parents,
1307 * updated as necessary to be valid for the child.
1308 * 'supOidCount' is set to the number of parents that have OID columns.
1311 * Completed schema list.
1314 * The order in which the attributes are inherited is very important.
1315 * Intuitively, the inherited attributes should come first. If a table
1316 * inherits from multiple parents, the order of those attributes are
1317 * according to the order of the parents specified in CREATE TABLE.
1319 * Here's an example:
1321 * create table person (name text, age int4, location point);
1322 * create table emp (salary int4, manager text) inherits(person);
1323 * create table student (gpa float8) inherits (person);
1324 * create table stud_emp (percent int4) inherits (emp, student);
1326 * The order of the attributes of stud_emp is:
1328 * person {1:name, 2:age, 3:location}
1330 * {6:gpa} student emp {4:salary, 5:manager}
1332 * stud_emp {7:percent}
1334 * If the same attribute name appears multiple times, then it appears
1335 * in the result table in the proper location for its first appearance.
1337 * Constraints (including NOT NULL constraints) for the child table
1338 * are the union of all relevant constraints, from both the child schema
1339 * and parent tables.
1341 * The default value for a child column is defined as:
1342 * (1) If the child schema specifies a default, that value is used.
1343 * (2) If neither the child nor any parent specifies a default, then
1344 * the column will not have a default.
1345 * (3) If conflicting defaults are inherited from different parents
1346 * (and not overridden by the child), an error is raised.
1347 * (4) Otherwise the inherited default is used.
1348 * Rule (3) is new in Postgres 7.1; in earlier releases you got a
1349 * rather arbitrary choice of which parent default to use.
1353 MergeAttributes(List *schema, List *supers, char relpersistence,
1354 List **supOids, List **supconstr, int *supOidCount)
1357 List *inhSchema = NIL;
1358 List *parentOids = NIL;
1359 List *constraints = NIL;
1360 int parentsWithOids = 0;
1361 bool have_bogus_defaults = false;
1363 static Node bogus_marker = {0}; /* marks conflicting defaults */
1366 * Check for and reject tables with too many columns. We perform this
1367 * check relatively early for two reasons: (a) we don't run the risk of
1368 * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
1369 * okay if we're processing <= 1600 columns, but could take minutes to
1370 * execute if the user attempts to create a table with hundreds of
1371 * thousands of columns.
1373 * Note that we also need to check that any we do not exceed this figure
1374 * after including columns from inherited relations.
1376 if (list_length(schema) > MaxHeapAttributeNumber)
1378 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1379 errmsg("tables can have at most %d columns",
1380 MaxHeapAttributeNumber)));
1383 * Check for duplicate names in the explicit list of attributes.
1385 * Although we might consider merging such entries in the same way that we
1386 * handle name conflicts for inherited attributes, it seems to make more
1387 * sense to assume such conflicts are errors.
1389 foreach(entry, schema)
1391 ColumnDef *coldef = lfirst(entry);
1392 ListCell *rest = lnext(entry);
1393 ListCell *prev = entry;
1395 if (coldef->typeName == NULL)
1398 * Typed table column option that does not belong to a column from
1399 * the type. This works because the columns from the type come
1400 * first in the list.
1403 (errcode(ERRCODE_UNDEFINED_COLUMN),
1404 errmsg("column \"%s\" does not exist",
1407 while (rest != NULL)
1409 ColumnDef *restdef = lfirst(rest);
1410 ListCell *next = lnext(rest); /* need to save it in case we
1413 if (strcmp(coldef->colname, restdef->colname) == 0)
1415 if (coldef->is_from_type)
1418 * merge the column options into the column from the type
1420 coldef->is_not_null = restdef->is_not_null;
1421 coldef->raw_default = restdef->raw_default;
1422 coldef->cooked_default = restdef->cooked_default;
1423 coldef->constraints = restdef->constraints;
1424 coldef->is_from_type = false;
1425 list_delete_cell(schema, rest, prev);
1429 (errcode(ERRCODE_DUPLICATE_COLUMN),
1430 errmsg("column \"%s\" specified more than once",
1439 * Scan the parents left-to-right, and merge their attributes to form a
1440 * list of inherited attributes (inhSchema). Also check to see if we need
1441 * to inherit an OID column.
1444 foreach(entry, supers)
1446 RangeVar *parent = (RangeVar *) lfirst(entry);
1448 TupleDesc tupleDesc;
1449 TupleConstr *constr;
1450 AttrNumber *newattno;
1451 AttrNumber parent_attno;
1454 * A self-exclusive lock is needed here. If two backends attempt to
1455 * add children to the same parent simultaneously, and that parent has
1456 * no pre-existing children, then both will attempt to update the
1457 * parent's relhassubclass field, leading to a "tuple concurrently
1458 * updated" error. Also, this interlocks against a concurrent ANALYZE
1459 * on the parent table, which might otherwise be attempting to clear
1460 * the parent's relhassubclass field, if its previous children were
1463 relation = heap_openrv(parent, ShareUpdateExclusiveLock);
1465 if (relation->rd_rel->relkind != RELKIND_RELATION)
1467 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1468 errmsg("inherited relation \"%s\" is not a table",
1470 /* Permanent rels cannot inherit from temporary ones */
1471 if (relpersistence != RELPERSISTENCE_TEMP &&
1472 relation->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
1474 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1475 errmsg("cannot inherit from temporary relation \"%s\"",
1478 /* If existing rel is temp, it must belong to this session */
1479 if (relation->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
1480 !relation->rd_islocaltemp)
1482 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1483 errmsg("cannot inherit from temporary relation of another session")));
1486 * We should have an UNDER permission flag for this, but for now,
1487 * demand that creator of a child table own the parent.
1489 if (!pg_class_ownercheck(RelationGetRelid(relation), GetUserId()))
1490 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1491 RelationGetRelationName(relation));
1494 * Reject duplications in the list of parents.
1496 if (list_member_oid(parentOids, RelationGetRelid(relation)))
1498 (errcode(ERRCODE_DUPLICATE_TABLE),
1499 errmsg("relation \"%s\" would be inherited from more than once",
1502 parentOids = lappend_oid(parentOids, RelationGetRelid(relation));
1504 if (relation->rd_rel->relhasoids)
1507 tupleDesc = RelationGetDescr(relation);
1508 constr = tupleDesc->constr;
1511 * newattno[] will contain the child-table attribute numbers for the
1512 * attributes of this parent table. (They are not the same for
1513 * parents after the first one, nor if we have dropped columns.)
1515 newattno = (AttrNumber *)
1516 palloc0(tupleDesc->natts * sizeof(AttrNumber));
1518 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1521 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
1522 char *attributeName = NameStr(attribute->attname);
1527 * Ignore dropped columns in the parent.
1529 if (attribute->attisdropped)
1530 continue; /* leave newattno entry as zero */
1533 * Does it conflict with some previously inherited column?
1535 exist_attno = findAttrByName(attributeName, inhSchema);
1536 if (exist_attno > 0)
1543 * Yes, try to merge the two column definitions. They must
1544 * have the same type, typmod, and collation.
1547 (errmsg("merging multiple inherited definitions of column \"%s\"",
1549 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1550 typenameTypeIdAndMod(NULL, def->typeName, &defTypeId, &deftypmod);
1551 if (defTypeId != attribute->atttypid ||
1552 deftypmod != attribute->atttypmod)
1554 (errcode(ERRCODE_DATATYPE_MISMATCH),
1555 errmsg("inherited column \"%s\" has a type conflict",
1557 errdetail("%s versus %s",
1558 TypeNameToString(def->typeName),
1559 format_type_be(attribute->atttypid))));
1560 defCollId = GetColumnDefCollation(NULL, def, defTypeId);
1561 if (defCollId != attribute->attcollation)
1563 (errcode(ERRCODE_COLLATION_MISMATCH),
1564 errmsg("inherited column \"%s\" has a collation conflict",
1566 errdetail("\"%s\" versus \"%s\"",
1567 get_collation_name(defCollId),
1568 get_collation_name(attribute->attcollation))));
1570 /* Copy storage parameter */
1571 if (def->storage == 0)
1572 def->storage = attribute->attstorage;
1573 else if (def->storage != attribute->attstorage)
1575 (errcode(ERRCODE_DATATYPE_MISMATCH),
1576 errmsg("inherited column \"%s\" has a storage parameter conflict",
1578 errdetail("%s versus %s",
1579 storage_name(def->storage),
1580 storage_name(attribute->attstorage))));
1583 /* Merge of NOT NULL constraints = OR 'em together */
1584 def->is_not_null |= attribute->attnotnull;
1585 /* Default and other constraints are handled below */
1586 newattno[parent_attno - 1] = exist_attno;
1591 * No, create a new inherited column
1593 def = makeNode(ColumnDef);
1594 def->colname = pstrdup(attributeName);
1595 def->typeName = makeTypeNameFromOid(attribute->atttypid,
1596 attribute->atttypmod);
1598 def->is_local = false;
1599 def->is_not_null = attribute->attnotnull;
1600 def->is_from_type = false;
1601 def->storage = attribute->attstorage;
1602 def->raw_default = NULL;
1603 def->cooked_default = NULL;
1604 def->collClause = NULL;
1605 def->collOid = attribute->attcollation;
1606 def->constraints = NIL;
1607 inhSchema = lappend(inhSchema, def);
1608 newattno[parent_attno - 1] = ++child_attno;
1612 * Copy default if any
1614 if (attribute->atthasdef)
1616 Node *this_default = NULL;
1617 AttrDefault *attrdef;
1620 /* Find default in constraint structure */
1621 Assert(constr != NULL);
1622 attrdef = constr->defval;
1623 for (i = 0; i < constr->num_defval; i++)
1625 if (attrdef[i].adnum == parent_attno)
1627 this_default = stringToNode(attrdef[i].adbin);
1631 Assert(this_default != NULL);
1634 * If default expr could contain any vars, we'd need to fix
1635 * 'em, but it can't; so default is ready to apply to child.
1637 * If we already had a default from some prior parent, check
1638 * to see if they are the same. If so, no problem; if not,
1639 * mark the column as having a bogus default. Below, we will
1640 * complain if the bogus default isn't overridden by the child
1643 Assert(def->raw_default == NULL);
1644 if (def->cooked_default == NULL)
1645 def->cooked_default = this_default;
1646 else if (!equal(def->cooked_default, this_default))
1648 def->cooked_default = &bogus_marker;
1649 have_bogus_defaults = true;
1655 * Now copy the CHECK constraints of this parent, adjusting attnos
1656 * using the completed newattno[] map. Identically named constraints
1657 * are merged if possible, else we throw error.
1659 if (constr && constr->num_check > 0)
1661 ConstrCheck *check = constr->check;
1664 for (i = 0; i < constr->num_check; i++)
1666 char *name = check[i].ccname;
1668 bool found_whole_row;
1670 /* ignore if the constraint is non-inheritable */
1671 if (check[i].ccnoinherit)
1674 /* Adjust Vars to match new table's column numbering */
1675 expr = map_variable_attnos(stringToNode(check[i].ccbin),
1677 newattno, tupleDesc->natts,
1681 * For the moment we have to reject whole-row variables. We
1682 * could convert them, if we knew the new table's rowtype OID,
1683 * but that hasn't been assigned yet.
1685 if (found_whole_row)
1687 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1688 errmsg("cannot convert whole-row table reference"),
1689 errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
1691 RelationGetRelationName(relation))));
1693 /* check for duplicate */
1694 if (!MergeCheckConstraint(constraints, name, expr))
1696 /* nope, this is a new one */
1697 CookedConstraint *cooked;
1699 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1700 cooked->contype = CONSTR_CHECK;
1701 cooked->name = pstrdup(name);
1702 cooked->attnum = 0; /* not used for constraints */
1703 cooked->expr = expr;
1704 cooked->skip_validation = false;
1705 cooked->is_local = false;
1706 cooked->inhcount = 1;
1707 cooked->is_no_inherit = false;
1708 constraints = lappend(constraints, cooked);
1716 * Close the parent rel, but keep our AccessShareLock on it until xact
1717 * commit. That will prevent someone else from deleting or ALTERing
1718 * the parent before the child is committed.
1720 heap_close(relation, NoLock);
1724 * If we had no inherited attributes, the result schema is just the
1725 * explicitly declared columns. Otherwise, we need to merge the declared
1726 * columns into the inherited schema list.
1728 if (inhSchema != NIL)
1730 foreach(entry, schema)
1732 ColumnDef *newdef = lfirst(entry);
1733 char *attributeName = newdef->colname;
1737 * Does it conflict with some previously inherited column?
1739 exist_attno = findAttrByName(attributeName, inhSchema);
1740 if (exist_attno > 0)
1751 * Yes, try to merge the two column definitions. They must
1752 * have the same type, typmod, and collation.
1755 (errmsg("merging column \"%s\" with inherited definition",
1757 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1758 typenameTypeIdAndMod(NULL, def->typeName, &defTypeId, &deftypmod);
1759 typenameTypeIdAndMod(NULL, newdef->typeName, &newTypeId, &newtypmod);
1760 if (defTypeId != newTypeId || deftypmod != newtypmod)
1762 (errcode(ERRCODE_DATATYPE_MISMATCH),
1763 errmsg("column \"%s\" has a type conflict",
1765 errdetail("%s versus %s",
1766 TypeNameToString(def->typeName),
1767 TypeNameToString(newdef->typeName))));
1768 defcollid = GetColumnDefCollation(NULL, def, defTypeId);
1769 newcollid = GetColumnDefCollation(NULL, newdef, newTypeId);
1770 if (defcollid != newcollid)
1772 (errcode(ERRCODE_COLLATION_MISMATCH),
1773 errmsg("column \"%s\" has a collation conflict",
1775 errdetail("\"%s\" versus \"%s\"",
1776 get_collation_name(defcollid),
1777 get_collation_name(newcollid))));
1779 /* Copy storage parameter */
1780 if (def->storage == 0)
1781 def->storage = newdef->storage;
1782 else if (newdef->storage != 0 && def->storage != newdef->storage)
1784 (errcode(ERRCODE_DATATYPE_MISMATCH),
1785 errmsg("column \"%s\" has a storage parameter conflict",
1787 errdetail("%s versus %s",
1788 storage_name(def->storage),
1789 storage_name(newdef->storage))));
1791 /* Mark the column as locally defined */
1792 def->is_local = true;
1793 /* Merge of NOT NULL constraints = OR 'em together */
1794 def->is_not_null |= newdef->is_not_null;
1795 /* If new def has a default, override previous default */
1796 if (newdef->raw_default != NULL)
1798 def->raw_default = newdef->raw_default;
1799 def->cooked_default = newdef->cooked_default;
1805 * No, attach new column to result schema
1807 inhSchema = lappend(inhSchema, newdef);
1814 * Check that we haven't exceeded the legal # of columns after merging
1815 * in inherited columns.
1817 if (list_length(schema) > MaxHeapAttributeNumber)
1819 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1820 errmsg("tables can have at most %d columns",
1821 MaxHeapAttributeNumber)));
1825 * If we found any conflicting parent default values, check to make sure
1826 * they were overridden by the child.
1828 if (have_bogus_defaults)
1830 foreach(entry, schema)
1832 ColumnDef *def = lfirst(entry);
1834 if (def->cooked_default == &bogus_marker)
1836 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
1837 errmsg("column \"%s\" inherits conflicting default values",
1839 errhint("To resolve the conflict, specify a default explicitly.")));
1843 *supOids = parentOids;
1844 *supconstr = constraints;
1845 *supOidCount = parentsWithOids;
1851 * MergeCheckConstraint
1852 * Try to merge an inherited CHECK constraint with previous ones
1854 * If we inherit identically-named constraints from multiple parents, we must
1855 * merge them, or throw an error if they don't have identical definitions.
1857 * constraints is a list of CookedConstraint structs for previous constraints.
1859 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
1860 * got a so-far-unique name, or throws error if conflict.
1863 MergeCheckConstraint(List *constraints, char *name, Node *expr)
1867 foreach(lc, constraints)
1869 CookedConstraint *ccon = (CookedConstraint *) lfirst(lc);
1871 Assert(ccon->contype == CONSTR_CHECK);
1873 /* Non-matching names never conflict */
1874 if (strcmp(ccon->name, name) != 0)
1877 if (equal(expr, ccon->expr))
1885 (errcode(ERRCODE_DUPLICATE_OBJECT),
1886 errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
1895 * StoreCatalogInheritance
1896 * Updates the system catalogs with proper inheritance information.
1898 * supers is a list of the OIDs of the new relation's direct ancestors.
1901 StoreCatalogInheritance(Oid relationId, List *supers)
1910 AssertArg(OidIsValid(relationId));
1916 * Store INHERITS information in pg_inherits using direct ancestors only.
1917 * Also enter dependencies on the direct ancestors, and make sure they are
1918 * marked with relhassubclass = true.
1920 * (Once upon a time, both direct and indirect ancestors were found here
1921 * and then entered into pg_ipl. Since that catalog doesn't exist
1922 * anymore, there's no need to look for indirect ancestors.)
1924 relation = heap_open(InheritsRelationId, RowExclusiveLock);
1927 foreach(entry, supers)
1929 Oid parentOid = lfirst_oid(entry);
1931 StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation);
1935 heap_close(relation, RowExclusiveLock);
1939 * Make catalog entries showing relationId as being an inheritance child
1940 * of parentOid. inhRelation is the already-opened pg_inherits catalog.
1943 StoreCatalogInheritance1(Oid relationId, Oid parentOid,
1944 int16 seqNumber, Relation inhRelation)
1946 TupleDesc desc = RelationGetDescr(inhRelation);
1947 Datum values[Natts_pg_inherits];
1948 bool nulls[Natts_pg_inherits];
1949 ObjectAddress childobject,
1954 * Make the pg_inherits entry
1956 values[Anum_pg_inherits_inhrelid - 1] = ObjectIdGetDatum(relationId);
1957 values[Anum_pg_inherits_inhparent - 1] = ObjectIdGetDatum(parentOid);
1958 values[Anum_pg_inherits_inhseqno - 1] = Int16GetDatum(seqNumber);
1960 memset(nulls, 0, sizeof(nulls));
1962 tuple = heap_form_tuple(desc, values, nulls);
1964 simple_heap_insert(inhRelation, tuple);
1966 CatalogUpdateIndexes(inhRelation, tuple);
1968 heap_freetuple(tuple);
1971 * Store a dependency too
1973 parentobject.classId = RelationRelationId;
1974 parentobject.objectId = parentOid;
1975 parentobject.objectSubId = 0;
1976 childobject.classId = RelationRelationId;
1977 childobject.objectId = relationId;
1978 childobject.objectSubId = 0;
1980 recordDependencyOn(&childobject, &parentobject, DEPENDENCY_NORMAL);
1983 * Post creation hook of this inheritance. Since object_access_hook
1984 * doesn't take multiple object identifiers, we relay oid of parent
1985 * relation using auxiliary_id argument.
1987 InvokeObjectPostAlterHookArg(InheritsRelationId,
1992 * Mark the parent as having subclasses.
1994 SetRelationHasSubclass(parentOid, true);
1998 * Look for an existing schema entry with the given name.
2000 * Returns the index (starting with 1) if attribute already exists in schema,
2004 findAttrByName(const char *attributeName, List *schema)
2011 ColumnDef *def = lfirst(s);
2013 if (strcmp(attributeName, def->colname) == 0)
2023 * SetRelationHasSubclass
2024 * Set the value of the relation's relhassubclass field in pg_class.
2026 * NOTE: caller must be holding an appropriate lock on the relation.
2027 * ShareUpdateExclusiveLock is sufficient.
2029 * NOTE: an important side-effect of this operation is that an SI invalidation
2030 * message is sent out to all backends --- including me --- causing plans
2031 * referencing the relation to be rebuilt with the new list of children.
2032 * This must happen even if we find that no change is needed in the pg_class
2036 SetRelationHasSubclass(Oid relationId, bool relhassubclass)
2038 Relation relationRelation;
2040 Form_pg_class classtuple;
2043 * Fetch a modifiable copy of the tuple, modify it, update pg_class.
2045 relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
2046 tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
2047 if (!HeapTupleIsValid(tuple))
2048 elog(ERROR, "cache lookup failed for relation %u", relationId);
2049 classtuple = (Form_pg_class) GETSTRUCT(tuple);
2051 if (classtuple->relhassubclass != relhassubclass)
2053 classtuple->relhassubclass = relhassubclass;
2054 simple_heap_update(relationRelation, &tuple->t_self, tuple);
2056 /* keep the catalog indexes up to date */
2057 CatalogUpdateIndexes(relationRelation, tuple);
2061 /* no need to change tuple, but force relcache rebuild anyway */
2062 CacheInvalidateRelcacheByTuple(tuple);
2065 heap_freetuple(tuple);
2066 heap_close(relationRelation, RowExclusiveLock);
2070 * renameatt_check - basic sanity checks before attribute rename
2073 renameatt_check(Oid myrelid, Form_pg_class classform, bool recursing)
2075 char relkind = classform->relkind;
2077 if (classform->reloftype && !recursing)
2079 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2080 errmsg("cannot rename column of typed table")));
2083 * Renaming the columns of sequences or toast tables doesn't actually
2084 * break anything from the system's point of view, since internal
2085 * references are by attnum. But it doesn't seem right to allow users to
2086 * change names that are hardcoded into the system, hence the following
2089 if (relkind != RELKIND_RELATION &&
2090 relkind != RELKIND_VIEW &&
2091 relkind != RELKIND_MATVIEW &&
2092 relkind != RELKIND_COMPOSITE_TYPE &&
2093 relkind != RELKIND_INDEX &&
2094 relkind != RELKIND_FOREIGN_TABLE)
2096 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2097 errmsg("\"%s\" is not a table, view, materialized view, composite type, index, or foreign table",
2098 NameStr(classform->relname))));
2101 * permissions checking. only the owner of a class can change its schema.
2103 if (!pg_class_ownercheck(myrelid, GetUserId()))
2104 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
2105 NameStr(classform->relname));
2106 if (!allowSystemTableMods && IsSystemClass(classform))
2108 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2109 errmsg("permission denied: \"%s\" is a system catalog",
2110 NameStr(classform->relname))));
2114 * renameatt_internal - workhorse for renameatt
2117 renameatt_internal(Oid myrelid,
2118 const char *oldattname,
2119 const char *newattname,
2122 int expected_parents,
2123 DropBehavior behavior)
2125 Relation targetrelation;
2126 Relation attrelation;
2128 Form_pg_attribute attform;
2132 * Grab an exclusive lock on the target table, which we will NOT release
2133 * until end of transaction.
2135 targetrelation = relation_open(myrelid, AccessExclusiveLock);
2136 renameatt_check(myrelid, RelationGetForm(targetrelation), recursing);
2139 * if the 'recurse' flag is set then we are supposed to rename this
2140 * attribute in all classes that inherit from 'relname' (as well as in
2143 * any permissions or problems with duplicate attributes will cause the
2144 * whole transaction to abort, which is what we want -- all or nothing.
2154 * we need the number of parents for each child so that the recursive
2155 * calls to renameatt() can determine whether there are any parents
2156 * outside the inheritance hierarchy being processed.
2158 child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
2162 * find_all_inheritors does the recursive search of the inheritance
2163 * hierarchy, so all we have to do is process all of the relids in the
2164 * list that it returns.
2166 forboth(lo, child_oids, li, child_numparents)
2168 Oid childrelid = lfirst_oid(lo);
2169 int numparents = lfirst_int(li);
2171 if (childrelid == myrelid)
2173 /* note we need not recurse again */
2174 renameatt_internal(childrelid, oldattname, newattname, false, true, numparents, behavior);
2180 * If we are told not to recurse, there had better not be any child
2181 * tables; else the rename would put them out of step.
2183 * expected_parents will only be 0 if we are not already recursing.
2185 if (expected_parents == 0 &&
2186 find_inheritance_children(myrelid, NoLock) != NIL)
2188 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2189 errmsg("inherited column \"%s\" must be renamed in child tables too",
2193 /* rename attributes in typed tables of composite type */
2194 if (targetrelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
2199 child_oids = find_typed_table_dependencies(targetrelation->rd_rel->reltype,
2200 RelationGetRelationName(targetrelation),
2203 foreach(lo, child_oids)
2204 renameatt_internal(lfirst_oid(lo), oldattname, newattname, true, true, 0, behavior);
2207 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
2209 atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
2210 if (!HeapTupleIsValid(atttup))
2212 (errcode(ERRCODE_UNDEFINED_COLUMN),
2213 errmsg("column \"%s\" does not exist",
2215 attform = (Form_pg_attribute) GETSTRUCT(atttup);
2217 attnum = attform->attnum;
2220 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2221 errmsg("cannot rename system column \"%s\"",
2225 * if the attribute is inherited, forbid the renaming. if this is a
2226 * top-level call to renameatt(), then expected_parents will be 0, so the
2227 * effect of this code will be to prohibit the renaming if the attribute
2228 * is inherited at all. if this is a recursive call to renameatt(),
2229 * expected_parents will be the number of parents the current relation has
2230 * within the inheritance hierarchy being processed, so we'll prohibit the
2231 * renaming only if there are additional parents from elsewhere.
2233 if (attform->attinhcount > expected_parents)
2235 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2236 errmsg("cannot rename inherited column \"%s\"",
2239 /* new name should not already exist */
2240 check_for_column_name_collision(targetrelation, newattname);
2242 /* apply the update */
2243 namestrcpy(&(attform->attname), newattname);
2245 simple_heap_update(attrelation, &atttup->t_self, atttup);
2247 /* keep system catalog indexes current */
2248 CatalogUpdateIndexes(attrelation, atttup);
2250 InvokeObjectPostAlterHook(RelationRelationId, myrelid, attnum);
2252 heap_freetuple(atttup);
2254 heap_close(attrelation, RowExclusiveLock);
2256 relation_close(targetrelation, NoLock); /* close rel but keep lock */
2260 * Perform permissions and integrity checks before acquiring a relation lock.
2263 RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid,
2269 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
2270 if (!HeapTupleIsValid(tuple))
2271 return; /* concurrently dropped */
2272 form = (Form_pg_class) GETSTRUCT(tuple);
2273 renameatt_check(relid, form, false);
2274 ReleaseSysCache(tuple);
2278 * renameatt - changes the name of a attribute in a relation
2281 renameatt(RenameStmt *stmt)
2285 /* lock level taken here should match renameatt_internal */
2286 relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
2287 stmt->missing_ok, false,
2288 RangeVarCallbackForRenameAttribute,
2291 if (!OidIsValid(relid))
2294 (errmsg("relation \"%s\" does not exist, skipping",
2295 stmt->relation->relname)));
2299 renameatt_internal(relid,
2300 stmt->subname, /* old att name */
2301 stmt->newname, /* new att name */
2302 interpretInhOption(stmt->relation->inhOpt), /* recursive? */
2303 false, /* recursing? */
2304 0, /* expected inhcount */
2307 /* This is an ALTER TABLE command so it's about the relid */
2313 * same logic as renameatt_internal
2316 rename_constraint_internal(Oid myrelid,
2318 const char *oldconname,
2319 const char *newconname,
2322 int expected_parents)
2324 Relation targetrelation = NULL;
2327 Form_pg_constraint con;
2329 AssertArg(!myrelid || !mytypid);
2333 constraintOid = get_domain_constraint_oid(mytypid, oldconname, false);
2337 targetrelation = relation_open(myrelid, AccessExclusiveLock);
2340 * don't tell it whether we're recursing; we allow changing typed
2343 renameatt_check(myrelid, RelationGetForm(targetrelation), false);
2345 constraintOid = get_relation_constraint_oid(myrelid, oldconname, false);
2348 tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
2349 if (!HeapTupleIsValid(tuple))
2350 elog(ERROR, "cache lookup failed for constraint %u",
2352 con = (Form_pg_constraint) GETSTRUCT(tuple);
2354 if (myrelid && con->contype == CONSTRAINT_CHECK && !con->connoinherit)
2363 child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
2366 forboth(lo, child_oids, li, child_numparents)
2368 Oid childrelid = lfirst_oid(lo);
2369 int numparents = lfirst_int(li);
2371 if (childrelid == myrelid)
2374 rename_constraint_internal(childrelid, InvalidOid, oldconname, newconname, false, true, numparents);
2379 if (expected_parents == 0 &&
2380 find_inheritance_children(myrelid, NoLock) != NIL)
2382 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2383 errmsg("inherited constraint \"%s\" must be renamed in child tables too",
2387 if (con->coninhcount > expected_parents)
2389 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2390 errmsg("cannot rename inherited constraint \"%s\"",
2395 && (con->contype == CONSTRAINT_PRIMARY
2396 || con->contype == CONSTRAINT_UNIQUE
2397 || con->contype == CONSTRAINT_EXCLUSION))
2398 /* rename the index; this renames the constraint as well */
2399 RenameRelationInternal(con->conindid, newconname, false);
2401 RenameConstraintById(constraintOid, newconname);
2403 ReleaseSysCache(tuple);
2406 relation_close(targetrelation, NoLock); /* close rel but keep lock */
2408 return constraintOid;
2412 RenameConstraint(RenameStmt *stmt)
2414 Oid relid = InvalidOid;
2415 Oid typid = InvalidOid;
2417 if (stmt->relationType == OBJECT_DOMAIN)
2422 typid = typenameTypeId(NULL, makeTypeNameFromNameList(stmt->object));
2423 rel = heap_open(TypeRelationId, RowExclusiveLock);
2424 tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2425 if (!HeapTupleIsValid(tup))
2426 elog(ERROR, "cache lookup failed for type %u", typid);
2427 checkDomainOwner(tup);
2428 ReleaseSysCache(tup);
2429 heap_close(rel, NoLock);
2433 /* lock level taken here should match rename_constraint_internal */
2434 relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
2436 RangeVarCallbackForRenameAttribute,
2441 rename_constraint_internal(relid, typid,
2444 stmt->relation ? interpretInhOption(stmt->relation->inhOpt) : false, /* recursive? */
2445 false, /* recursing? */
2446 0 /* expected inhcount */ );
2451 * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW/FOREIGN TABLE RENAME
2454 RenameRelation(RenameStmt *stmt)
2459 * Grab an exclusive lock on the target table, index, sequence or view,
2460 * which we will NOT release until end of transaction.
2462 * Lock level used here should match RenameRelationInternal, to avoid lock
2465 relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
2466 stmt->missing_ok, false,
2467 RangeVarCallbackForAlterRelation,
2470 if (!OidIsValid(relid))
2473 (errmsg("relation \"%s\" does not exist, skipping",
2474 stmt->relation->relname)));
2479 RenameRelationInternal(relid, stmt->newname, false);
2485 * RenameRelationInternal - change the name of a relation
2487 * XXX - When renaming sequences, we don't bother to modify the
2488 * sequence name that is stored within the sequence itself
2489 * (this would cause problems with MVCC). In the future,
2490 * the sequence name should probably be removed from the
2491 * sequence, AFAIK there's no need for it to be there.
2494 RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal)
2496 Relation targetrelation;
2497 Relation relrelation; /* for RELATION relation */
2499 Form_pg_class relform;
2503 * Grab an exclusive lock on the target table, index, sequence or view,
2504 * which we will NOT release until end of transaction.
2506 targetrelation = relation_open(myrelid, AccessExclusiveLock);
2507 namespaceId = RelationGetNamespace(targetrelation);
2510 * Find relation's pg_class tuple, and make sure newrelname isn't in use.
2512 relrelation = heap_open(RelationRelationId, RowExclusiveLock);
2514 reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
2515 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
2516 elog(ERROR, "cache lookup failed for relation %u", myrelid);
2517 relform = (Form_pg_class) GETSTRUCT(reltup);
2519 if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
2521 (errcode(ERRCODE_DUPLICATE_TABLE),
2522 errmsg("relation \"%s\" already exists",
2526 * Update pg_class tuple with new relname. (Scribbling on reltup is OK
2527 * because it's a copy...)
2529 namestrcpy(&(relform->relname), newrelname);
2531 simple_heap_update(relrelation, &reltup->t_self, reltup);
2533 /* keep the system catalog indexes current */
2534 CatalogUpdateIndexes(relrelation, reltup);
2536 InvokeObjectPostAlterHookArg(RelationRelationId, myrelid, 0,
2537 InvalidOid, is_internal);
2539 heap_freetuple(reltup);
2540 heap_close(relrelation, RowExclusiveLock);
2543 * Also rename the associated type, if any.
2545 if (OidIsValid(targetrelation->rd_rel->reltype))
2546 RenameTypeInternal(targetrelation->rd_rel->reltype,
2547 newrelname, namespaceId);
2550 * Also rename the associated constraint, if any.
2552 if (targetrelation->rd_rel->relkind == RELKIND_INDEX)
2554 Oid constraintId = get_index_constraint(myrelid);
2556 if (OidIsValid(constraintId))
2557 RenameConstraintById(constraintId, newrelname);
2561 * Close rel, but keep exclusive lock!
2563 relation_close(targetrelation, NoLock);
2567 * Disallow ALTER TABLE (and similar commands) when the current backend has
2568 * any open reference to the target table besides the one just acquired by
2569 * the calling command; this implies there's an open cursor or active plan.
2570 * We need this check because our lock doesn't protect us against stomping
2571 * on our own foot, only other people's feet!
2573 * For ALTER TABLE, the only case known to cause serious trouble is ALTER
2574 * COLUMN TYPE, and some changes are obviously pretty benign, so this could
2575 * possibly be relaxed to only error out for certain types of alterations.
2576 * But the use-case for allowing any of these things is not obvious, so we
2577 * won't work hard at it for now.
2579 * We also reject these commands if there are any pending AFTER trigger events
2580 * for the rel. This is certainly necessary for the rewriting variants of
2581 * ALTER TABLE, because they don't preserve tuple TIDs and so the pending
2582 * events would try to fetch the wrong tuples. It might be overly cautious
2583 * in other cases, but again it seems better to err on the side of paranoia.
2585 * REINDEX calls this with "rel" referencing the index to be rebuilt; here
2586 * we are worried about active indexscans on the index. The trigger-event
2587 * check can be skipped, since we are doing no damage to the parent table.
2589 * The statement name (eg, "ALTER TABLE") is passed for use in error messages.
2592 CheckTableNotInUse(Relation rel, const char *stmt)
2594 int expected_refcnt;
2596 expected_refcnt = rel->rd_isnailed ? 2 : 1;
2597 if (rel->rd_refcnt != expected_refcnt)
2599 (errcode(ERRCODE_OBJECT_IN_USE),
2600 /* translator: first %s is a SQL command, eg ALTER TABLE */
2601 errmsg("cannot %s \"%s\" because "
2602 "it is being used by active queries in this session",
2603 stmt, RelationGetRelationName(rel))));
2605 if (rel->rd_rel->relkind != RELKIND_INDEX &&
2606 AfterTriggerPendingOnRel(RelationGetRelid(rel)))
2608 (errcode(ERRCODE_OBJECT_IN_USE),
2609 /* translator: first %s is a SQL command, eg ALTER TABLE */
2610 errmsg("cannot %s \"%s\" because "
2611 "it has pending trigger events",
2612 stmt, RelationGetRelationName(rel))));
2616 * AlterTableLookupRelation
2617 * Look up, and lock, the OID for the relation named by an alter table
2621 AlterTableLookupRelation(AlterTableStmt *stmt, LOCKMODE lockmode)
2623 return RangeVarGetRelidExtended(stmt->relation, lockmode, stmt->missing_ok, false,
2624 RangeVarCallbackForAlterRelation,
2630 * Execute ALTER TABLE, which can be a list of subcommands
2632 * ALTER TABLE is performed in three phases:
2633 * 1. Examine subcommands and perform pre-transformation checking.
2634 * 2. Update system catalogs.
2635 * 3. Scan table(s) to check new constraints, and optionally recopy
2636 * the data into new table(s).
2637 * Phase 3 is not performed unless one or more of the subcommands requires
2638 * it. The intention of this design is to allow multiple independent
2639 * updates of the table schema to be performed with only one pass over the
2642 * ATPrepCmd performs phase 1. A "work queue" entry is created for
2643 * each table to be affected (there may be multiple affected tables if the
2644 * commands traverse a table inheritance hierarchy). Also we do preliminary
2645 * validation of the subcommands, including parse transformation of those
2646 * expressions that need to be evaluated with respect to the old table
2649 * ATRewriteCatalogs performs phase 2 for each affected table. (Note that
2650 * phases 2 and 3 normally do no explicit recursion, since phase 1 already
2651 * did it --- although some subcommands have to recurse in phase 2 instead.)
2652 * Certain subcommands need to be performed before others to avoid
2653 * unnecessary conflicts; for example, DROP COLUMN should come before
2654 * ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
2655 * lists, one for each logical "pass" of phase 2.
2657 * ATRewriteTables performs phase 3 for those tables that need it.
2659 * Thanks to the magic of MVCC, an error anywhere along the way rolls back
2660 * the whole operation; we don't have to do anything special to clean up.
2662 * The caller must lock the relation, with an appropriate lock level
2663 * for the subcommands requested. Any subcommand that needs to rewrite
2664 * tuples in the table forces the whole command to be executed with
2665 * AccessExclusiveLock (actually, that is currently required always, but
2666 * we hope to relax it at some point). We pass the lock level down
2667 * so that we can apply it recursively to inherited tables. Note that the
2668 * lock level we want as we recurse might well be higher than required for
2669 * that specific subcommand. So we pass down the overall lock requirement,
2670 * rather than reassess it at lower levels.
2673 AlterTable(Oid relid, LOCKMODE lockmode, AlterTableStmt *stmt)
2677 /* Caller is required to provide an adequate lock. */
2678 rel = relation_open(relid, NoLock);
2680 CheckTableNotInUse(rel, "ALTER TABLE");
2682 ATController(rel, stmt->cmds, interpretInhOption(stmt->relation->inhOpt),
2687 * AlterTableInternal
2689 * ALTER TABLE with target specified by OID
2691 * We do not reject if the relation is already open, because it's quite
2692 * likely that one or more layers of caller have it open. That means it
2693 * is unsafe to use this entry point for alterations that could break
2694 * existing query plans. On the assumption it's not used for such, we
2695 * don't have to reject pending AFTER triggers, either.
2698 AlterTableInternal(Oid relid, List *cmds, bool recurse)
2701 LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
2703 rel = relation_open(relid, lockmode);
2705 ATController(rel, cmds, recurse, lockmode);
2709 * AlterTableGetLockLevel
2711 * Sets the overall lock level required for the supplied list of subcommands.
2712 * Policy for doing this set according to needs of AlterTable(), see
2713 * comments there for overall explanation.
2715 * Function is called before and after parsing, so it must give same
2716 * answer each time it is called. Some subcommands are transformed
2717 * into other subcommand types, so the transform must never be made to a
2718 * lower lock level than previously assigned. All transforms are noted below.
2720 * Since this is called before we lock the table we cannot use table metadata
2721 * to influence the type of lock we acquire.
2723 * There should be no lockmodes hardcoded into the subcommand functions. All
2724 * lockmode decisions for ALTER TABLE are made here only. The one exception is
2725 * ALTER TABLE RENAME which is treated as a different statement type T_RenameStmt
2726 * and does not travel through this section of code and cannot be combined with
2727 * any of the subcommands given here.
2730 AlterTableGetLockLevel(List *cmds)
2733 * Late in 9.1 dev cycle a number of issues were uncovered with access to
2734 * catalog relations, leading to the decision to re-enforce all DDL at
2735 * AccessExclusiveLock level by default.
2737 * The issues are that there is a pervasive assumption in the code that
2738 * the catalogs will not be read unless an AccessExclusiveLock is held. If
2739 * that rule is relaxed, we must protect against a number of potential
2740 * effects - infrequent, but proven possible with test cases where
2741 * multiple DDL operations occur in a stream against frequently accessed
2744 * 1. Catalog tables are read using SnapshotNow, which has a race bug that
2745 * allows a scan to return no valid rows even when one is present in the
2746 * case of a commit of a concurrent update of the catalog table.
2747 * SnapshotNow also ignores transactions in progress, so takes the latest
2748 * committed version without waiting for the latest changes.
2750 * 2. Relcache needs to be internally consistent, so unless we lock the
2751 * definition during reads we have no way to guarantee that.
2753 * 3. Catcache access isn't coordinated at all so refreshes can occur at
2756 #ifdef REDUCED_ALTER_TABLE_LOCK_LEVELS
2758 LOCKMODE lockmode = ShareUpdateExclusiveLock;
2762 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2763 LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
2765 switch (cmd->subtype)
2768 * Need AccessExclusiveLock for these subcommands because they
2769 * affect or potentially affect both read and write
2772 * New subcommand types should be added here by default.
2774 case AT_AddColumn: /* may rewrite heap, in some cases and visible
2776 case AT_DropColumn: /* change visible to SELECT */
2777 case AT_AddColumnToView: /* CREATE VIEW */
2778 case AT_AlterColumnType: /* must rewrite heap */
2779 case AT_DropConstraint: /* as DROP INDEX */
2780 case AT_AddOids: /* must rewrite heap */
2781 case AT_DropOids: /* calls AT_DropColumn */
2782 case AT_EnableAlwaysRule: /* may change SELECT rules */
2783 case AT_EnableReplicaRule: /* may change SELECT rules */
2784 case AT_EnableRule: /* may change SELECT rules */
2785 case AT_DisableRule: /* may change SELECT rules */
2786 case AT_ChangeOwner: /* change visible to SELECT */
2787 case AT_SetTableSpace: /* must rewrite heap */
2788 case AT_DropNotNull: /* may change some SQL plans */
2790 case AT_GenericOptions:
2791 case AT_AlterColumnGenericOptions:
2792 cmd_lockmode = AccessExclusiveLock;
2796 * These subcommands affect write operations only.
2798 case AT_ColumnDefault:
2799 case AT_ProcessedConstraint: /* becomes AT_AddConstraint */
2800 case AT_AddConstraintRecurse: /* becomes AT_AddConstraint */
2801 case AT_ReAddConstraint: /* becomes AT_AddConstraint */
2803 case AT_EnableAlwaysTrig:
2804 case AT_EnableReplicaTrig:
2805 case AT_EnableTrigAll:
2806 case AT_EnableTrigUser:
2807 case AT_DisableTrig:
2808 case AT_DisableTrigAll:
2809 case AT_DisableTrigUser:
2810 case AT_AddIndex: /* from ADD CONSTRAINT */
2811 case AT_AddIndexConstraint:
2812 cmd_lockmode = ShareRowExclusiveLock;
2815 case AT_AddConstraint:
2816 if (IsA(cmd->def, Constraint))
2818 Constraint *con = (Constraint *) cmd->def;
2820 switch (con->contype)
2822 case CONSTR_EXCLUSION:
2823 case CONSTR_PRIMARY:
2827 * Cases essentially the same as CREATE INDEX. We
2828 * could reduce the lock strength to ShareLock if
2829 * we can work out how to allow concurrent catalog
2832 cmd_lockmode = ShareRowExclusiveLock;
2834 case CONSTR_FOREIGN:
2837 * We add triggers to both tables when we add a
2838 * Foreign Key, so the lock level must be at least
2839 * as strong as CREATE TRIGGER.
2841 cmd_lockmode = ShareRowExclusiveLock;
2845 cmd_lockmode = ShareRowExclusiveLock;
2851 * These subcommands affect inheritance behaviour. Queries
2852 * started before us will continue to see the old inheritance
2853 * behaviour, while queries started after we commit will see
2854 * new behaviour. No need to prevent reads or writes to the
2855 * subtable while we hook it up though.
2858 case AT_DropInherit:
2859 cmd_lockmode = ShareUpdateExclusiveLock;
2863 * These subcommands affect implicit row type conversion. They
2864 * have affects similar to CREATE/DROP CAST on queries. We
2865 * don't provide for invalidating parse trees as a result of
2866 * such changes. Do avoid concurrent pg_class updates,
2871 cmd_lockmode = ShareUpdateExclusiveLock;
2874 * These subcommands affect general strategies for performance
2875 * and maintenance, though don't change the semantic results
2876 * from normal data reads and writes. Delaying an ALTER TABLE
2877 * behind currently active writes only delays the point where
2878 * the new strategy begins to take effect, so there is no
2879 * benefit in waiting. In this case the minimum restriction
2880 * applies: we don't currently allow concurrent catalog
2883 case AT_SetStatistics:
2885 case AT_DropCluster:
2886 case AT_SetRelOptions:
2887 case AT_ResetRelOptions:
2888 case AT_ReplaceRelOptions:
2890 case AT_ResetOptions:
2892 case AT_AlterConstraint:
2893 case AT_ValidateConstraint:
2894 cmd_lockmode = ShareUpdateExclusiveLock;
2898 elog(ERROR, "unrecognized alter table type: %d",
2899 (int) cmd->subtype);
2904 * Take the greatest lockmode from any subcommand
2906 if (cmd_lockmode > lockmode)
2907 lockmode = cmd_lockmode;
2910 LOCKMODE lockmode = AccessExclusiveLock;
2917 ATController(Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
2922 /* Phase 1: preliminary examination of commands, create work queue */
2925 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2927 ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode);
2930 /* Close the relation, but keep lock until commit */
2931 relation_close(rel, NoLock);
2933 /* Phase 2: update system catalogs */
2934 ATRewriteCatalogs(&wqueue, lockmode);
2936 /* Phase 3: scan/rewrite tables as needed */
2937 ATRewriteTables(&wqueue, lockmode);
2943 * Traffic cop for ALTER TABLE Phase 1 operations, including simple
2944 * recursion and permission checks.
2946 * Caller must have acquired appropriate lock type on relation already.
2947 * This lock should be held until commit.
2950 ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
2951 bool recurse, bool recursing, LOCKMODE lockmode)
2953 AlteredTableInfo *tab;
2954 int pass = AT_PASS_UNSET;
2956 /* Find or create work queue entry for this table */
2957 tab = ATGetQueueEntry(wqueue, rel);
2960 * Copy the original subcommand for each table. This avoids conflicts
2961 * when different child tables need to make different parse
2962 * transformations (for example, the same column may have different column
2963 * numbers in different children).
2965 cmd = copyObject(cmd);
2968 * Do permissions checking, recursion to child tables if needed, and any
2969 * additional phase-1 processing needed.
2971 switch (cmd->subtype)
2973 case AT_AddColumn: /* ADD COLUMN */
2974 ATSimplePermissions(rel,
2975 ATT_TABLE | ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
2976 ATPrepAddColumn(wqueue, rel, recurse, recursing, cmd, lockmode);
2977 /* Recursion occurs during execution phase */
2978 pass = AT_PASS_ADD_COL;
2980 case AT_AddColumnToView: /* add column via CREATE OR REPLACE
2982 ATSimplePermissions(rel, ATT_VIEW);
2983 ATPrepAddColumn(wqueue, rel, recurse, recursing, cmd, lockmode);
2984 /* Recursion occurs during execution phase */
2985 pass = AT_PASS_ADD_COL;
2987 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
2990 * We allow defaults on views so that INSERT into a view can have
2991 * default-ish behavior. This works because the rewriter
2992 * substitutes default values into INSERTs before it expands
2995 ATSimplePermissions(rel, ATT_TABLE | ATT_VIEW | ATT_FOREIGN_TABLE);
2996 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
2997 /* No command-specific prep needed */
2998 pass = cmd->def ? AT_PASS_ADD_CONSTR : AT_PASS_DROP;
3000 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
3001 ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
3002 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
3003 /* No command-specific prep needed */
3004 pass = AT_PASS_DROP;
3006 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
3007 ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
3008 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
3009 /* No command-specific prep needed */
3010 pass = AT_PASS_ADD_CONSTR;
3012 case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
3013 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
3014 /* Performs own permission checks */
3015 ATPrepSetStatistics(rel, cmd->name, cmd->def, lockmode);
3016 pass = AT_PASS_MISC;
3018 case AT_SetOptions: /* ALTER COLUMN SET ( options ) */
3019 case AT_ResetOptions: /* ALTER COLUMN RESET ( options ) */
3020 ATSimplePermissions(rel, ATT_TABLE | ATT_MATVIEW | ATT_INDEX | ATT_FOREIGN_TABLE);
3021 /* This command never recurses */
3022 pass = AT_PASS_MISC;
3024 case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
3025 ATSimplePermissions(rel, ATT_TABLE | ATT_MATVIEW);
3026 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
3027 /* No command-specific prep needed */
3028 pass = AT_PASS_MISC;
3030 case AT_DropColumn: /* DROP COLUMN */
3031 ATSimplePermissions(rel,
3032 ATT_TABLE | ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
3033 ATPrepDropColumn(wqueue, rel, recurse, recursing, cmd, lockmode);
3034 /* Recursion occurs during execution phase */
3035 pass = AT_PASS_DROP;
3037 case AT_AddIndex: /* ADD INDEX */
3038 ATSimplePermissions(rel, ATT_TABLE | ATT_MATVIEW);
3039 /* This command never recurses */
3040 /* No command-specific prep needed */
3041 pass = AT_PASS_ADD_INDEX;
3043 case AT_AddConstraint: /* ADD CONSTRAINT */
3044 ATSimplePermissions(rel, ATT_TABLE);
3045 /* Recursion occurs during execution phase */
3046 /* No command-specific prep needed except saving recurse flag */
3048 cmd->subtype = AT_AddConstraintRecurse;
3049 pass = AT_PASS_ADD_CONSTR;
3051 case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
3052 ATSimplePermissions(rel, ATT_TABLE);
3053 /* This command never recurses */
3054 /* No command-specific prep needed */
3055 pass = AT_PASS_ADD_CONSTR;
3057 case AT_DropConstraint: /* DROP CONSTRAINT */
3058 ATSimplePermissions(rel, ATT_TABLE);
3059 /* Recursion occurs during execution phase */
3060 /* No command-specific prep needed except saving recurse flag */
3062 cmd->subtype = AT_DropConstraintRecurse;
3063 pass = AT_PASS_DROP;
3065 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
3066 ATSimplePermissions(rel,
3067 ATT_TABLE | ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
3068 /* Performs own recursion */
3069 ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd, lockmode);
3070 pass = AT_PASS_ALTER_TYPE;
3072 case AT_AlterColumnGenericOptions:
3073 ATSimplePermissions(rel, ATT_FOREIGN_TABLE);
3074 /* This command never recurses */
3075 /* No command-specific prep needed */
3076 pass = AT_PASS_MISC;
3078 case AT_ChangeOwner: /* ALTER OWNER */
3079 /* This command never recurses */
3080 /* No command-specific prep needed */
3081 pass = AT_PASS_MISC;
3083 case AT_ClusterOn: /* CLUSTER ON */
3084 case AT_DropCluster: /* SET WITHOUT CLUSTER */
3085 ATSimplePermissions(rel, ATT_TABLE | ATT_MATVIEW);
3086 /* These commands never recurse */
3087 /* No command-specific prep needed */
3088 pass = AT_PASS_MISC;
3090 case AT_AddOids: /* SET WITH OIDS */
3091 ATSimplePermissions(rel, ATT_TABLE);
3092 if (!rel->rd_rel->relhasoids || recursing)
3093 ATPrepAddOids(wqueue, rel, recurse, cmd, lockmode);
3094 /* Recursion occurs during execution phase */
3095 pass = AT_PASS_ADD_COL;
3097 case AT_DropOids: /* SET WITHOUT OIDS */
3098 ATSimplePermissions(rel, ATT_TABLE);
3099 /* Performs own recursion */
3100 if (rel->rd_rel->relhasoids)
3102 AlterTableCmd *dropCmd = makeNode(AlterTableCmd);
3104 dropCmd->subtype = AT_DropColumn;
3105 dropCmd->name = pstrdup("oid");
3106 dropCmd->behavior = cmd->behavior;
3107 ATPrepCmd(wqueue, rel, dropCmd, recurse, false, lockmode);
3109 pass = AT_PASS_DROP;
3111 case AT_SetTableSpace: /* SET TABLESPACE */
3112 ATSimplePermissions(rel, ATT_TABLE | ATT_MATVIEW | ATT_INDEX);
3113 /* This command never recurses */
3114 ATPrepSetTableSpace(tab, rel, cmd->name, lockmode);
3115 pass = AT_PASS_MISC; /* doesn't actually matter */
3117 case AT_SetRelOptions: /* SET (...) */
3118 case AT_ResetRelOptions: /* RESET (...) */
3119 case AT_ReplaceRelOptions: /* reset them all, then set just these */
3120 ATSimplePermissions(rel, ATT_TABLE | ATT_VIEW | ATT_MATVIEW | ATT_INDEX);
3121 /* This command never recurses */
3122 /* No command-specific prep needed */
3123 pass = AT_PASS_MISC;
3125 case AT_AddInherit: /* INHERIT */
3126 ATSimplePermissions(rel, ATT_TABLE);
3127 /* This command never recurses */
3128 ATPrepAddInherit(rel);
3129 pass = AT_PASS_MISC;
3131 case AT_AlterConstraint: /* ALTER CONSTRAINT */
3132 ATSimplePermissions(rel, ATT_TABLE);
3133 pass = AT_PASS_MISC;
3135 case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
3136 ATSimplePermissions(rel, ATT_TABLE);
3137 /* Recursion occurs during execution phase */
3138 /* No command-specific prep needed except saving recurse flag */
3140 cmd->subtype = AT_ValidateConstraintRecurse;
3141 pass = AT_PASS_MISC;
3143 case AT_EnableTrig: /* ENABLE TRIGGER variants */
3144 case AT_EnableAlwaysTrig:
3145 case AT_EnableReplicaTrig:
3146 case AT_EnableTrigAll:
3147 case AT_EnableTrigUser:
3148 case AT_DisableTrig: /* DISABLE TRIGGER variants */
3149 case AT_DisableTrigAll:
3150 case AT_DisableTrigUser:
3151 case AT_EnableRule: /* ENABLE/DISABLE RULE variants */
3152 case AT_EnableAlwaysRule:
3153 case AT_EnableReplicaRule:
3154 case AT_DisableRule:
3155 case AT_DropInherit: /* NO INHERIT */
3156 case AT_AddOf: /* OF */
3157 case AT_DropOf: /* NOT OF */
3158 ATSimplePermissions(rel, ATT_TABLE);
3159 /* These commands never recurse */
3160 /* No command-specific prep needed */
3161 pass = AT_PASS_MISC;
3163 case AT_GenericOptions:
3164 ATSimplePermissions(rel, ATT_FOREIGN_TABLE);
3165 /* No command-specific prep needed */
3166 pass = AT_PASS_MISC;
3169 elog(ERROR, "unrecognized alter table type: %d",
3170 (int) cmd->subtype);
3171 pass = AT_PASS_UNSET; /* keep compiler quiet */
3174 Assert(pass > AT_PASS_UNSET);
3176 /* Add the subcommand to the appropriate list for phase 2 */
3177 tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
3183 * Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
3184 * dispatched in a "safe" execution order (designed to avoid unnecessary
3188 ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode)
3194 * We process all the tables "in parallel", one pass at a time. This is
3195 * needed because we may have to propagate work from one table to another
3196 * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
3197 * re-adding of the foreign key constraint to the other table). Work can
3198 * only be propagated into later passes, however.
3200 for (pass = 0; pass < AT_NUM_PASSES; pass++)
3202 /* Go through each table that needs to be processed */
3203 foreach(ltab, *wqueue)
3205 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
3206 List *subcmds = tab->subcmds[pass];
3214 * Appropriate lock was obtained by phase 1, needn't get it again
3216 rel = relation_open(tab->relid, NoLock);
3218 foreach(lcmd, subcmds)
3219 ATExecCmd(wqueue, tab, rel, (AlterTableCmd *) lfirst(lcmd), lockmode);
3222 * After the ALTER TYPE pass, do cleanup work (this is not done in
3223 * ATExecAlterColumnType since it should be done only once if
3224 * multiple columns of a table are altered).
3226 if (pass == AT_PASS_ALTER_TYPE)
3227 ATPostAlterTypeCleanup(wqueue, tab, lockmode);
3229 relation_close(rel, NoLock);
3233 /* Check to see if a toast table must be added. */
3234 foreach(ltab, *wqueue)
3236 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
3238 if (tab->relkind == RELKIND_RELATION ||
3239 tab->relkind == RELKIND_MATVIEW)
3240 AlterTableCreateToastTable(tab->relid, (Datum) 0);
3245 * ATExecCmd: dispatch a subcommand to appropriate execution routine
3248 ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
3249 AlterTableCmd *cmd, LOCKMODE lockmode)
3251 switch (cmd->subtype)
3253 case AT_AddColumn: /* ADD COLUMN */
3254 case AT_AddColumnToView: /* add column via CREATE OR REPLACE
3256 ATExecAddColumn(wqueue, tab, rel, (ColumnDef *) cmd->def,
3257 false, false, false, lockmode);
3259 case AT_AddColumnRecurse:
3260 ATExecAddColumn(wqueue, tab, rel, (ColumnDef *) cmd->def,
3261 false, true, false, lockmode);
3263 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
3264 ATExecColumnDefault(rel, cmd->name, cmd->def, lockmode);
3266 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
3267 ATExecDropNotNull(rel, cmd->name, lockmode);
3269 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
3270 ATExecSetNotNull(tab, rel, cmd->name, lockmode);
3272 case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
3273 ATExecSetStatistics(rel, cmd->name, cmd->def, lockmode);
3275 case AT_SetOptions: /* ALTER COLUMN SET ( options ) */
3276 ATExecSetOptions(rel, cmd->name, cmd->def, false, lockmode);
3278 case AT_ResetOptions: /* ALTER COLUMN RESET ( options ) */
3279 ATExecSetOptions(rel, cmd->name, cmd->def, true, lockmode);
3281 case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
3282 ATExecSetStorage(rel, cmd->name, cmd->def, lockmode);
3284 case AT_DropColumn: /* DROP COLUMN */
3285 ATExecDropColumn(wqueue, rel, cmd->name,
3286 cmd->behavior, false, false, cmd->missing_ok, lockmode);
3288 case AT_DropColumnRecurse: /* DROP COLUMN with recursion */
3289 ATExecDropColumn(wqueue, rel, cmd->name,
3290 cmd->behavior, true, false, cmd->missing_ok, lockmode);
3292 case AT_AddIndex: /* ADD INDEX */
3293 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false, lockmode);
3295 case AT_ReAddIndex: /* ADD INDEX */
3296 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true, lockmode);
3298 case AT_AddConstraint: /* ADD CONSTRAINT */
3299 ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
3300 false, false, lockmode);
3302 case AT_AddConstraintRecurse: /* ADD CONSTRAINT with recursion */
3303 ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
3304 true, false, lockmode);
3306 case AT_ReAddConstraint: /* Re-add pre-existing check
3308 ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
3309 false, true, lockmode);
3311 case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
3312 ATExecAddIndexConstraint(tab, rel, (IndexStmt *) cmd->def, lockmode);
3314 case AT_AlterConstraint: /* ALTER CONSTRAINT */
3315 ATExecAlterConstraint(rel, cmd, false, false, lockmode);
3317 case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
3318 ATExecValidateConstraint(rel, cmd->name, false, false, lockmode);
3320 case AT_ValidateConstraintRecurse: /* VALIDATE CONSTRAINT with
3322 ATExecValidateConstraint(rel, cmd->name, true, false, lockmode);
3324 case AT_DropConstraint: /* DROP CONSTRAINT */
3325 ATExecDropConstraint(rel, cmd->name, cmd->behavior,
3327 cmd->missing_ok, lockmode);
3329 case AT_DropConstraintRecurse: /* DROP CONSTRAINT with recursion */
3330 ATExecDropConstraint(rel, cmd->name, cmd->behavior,
3332 cmd->missing_ok, lockmode);
3334 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
3335 ATExecAlterColumnType(tab, rel, cmd, lockmode);
3337 case AT_AlterColumnGenericOptions: /* ALTER COLUMN OPTIONS */
3338 ATExecAlterColumnGenericOptions(rel, cmd->name, (List *) cmd->def, lockmode);
3340 case AT_ChangeOwner: /* ALTER OWNER */
3341 ATExecChangeOwner(RelationGetRelid(rel),
3342 get_role_oid(cmd->name, false),
3345 case AT_ClusterOn: /* CLUSTER ON */
3346 ATExecClusterOn(rel, cmd->name, lockmode);
3348 case AT_DropCluster: /* SET WITHOUT CLUSTER */
3349 ATExecDropCluster(rel, lockmode);
3351 case AT_AddOids: /* SET WITH OIDS */
3352 /* Use the ADD COLUMN code, unless prep decided to do nothing */
3353 if (cmd->def != NULL)
3354 ATExecAddColumn(wqueue, tab, rel, (ColumnDef *) cmd->def,
3355 true, false, false, lockmode);
3357 case AT_AddOidsRecurse: /* SET WITH OIDS */
3358 /* Use the ADD COLUMN code, unless prep decided to do nothing */
3359 if (cmd->def != NULL)
3360 ATExecAddColumn(wqueue, tab, rel, (ColumnDef *) cmd->def,
3361 true, true, false, lockmode);
3363 case AT_DropOids: /* SET WITHOUT OIDS */
3366 * Nothing to do here; we'll have generated a DropColumn
3367 * subcommand to do the real work
3370 case AT_SetTableSpace: /* SET TABLESPACE */
3373 * Nothing to do here; Phase 3 does the work
3376 case AT_SetRelOptions: /* SET (...) */
3377 case AT_ResetRelOptions: /* RESET (...) */
3378 case AT_ReplaceRelOptions: /* replace entire option list */
3379 ATExecSetRelOptions(rel, (List *) cmd->def, cmd->subtype, lockmode);
3381 case AT_EnableTrig: /* ENABLE TRIGGER name */
3382 ATExecEnableDisableTrigger(rel, cmd->name,
3383 TRIGGER_FIRES_ON_ORIGIN, false, lockmode);
3385 case AT_EnableAlwaysTrig: /* ENABLE ALWAYS TRIGGER name */
3386 ATExecEnableDisableTrigger(rel, cmd->name,
3387 TRIGGER_FIRES_ALWAYS, false, lockmode);
3389 case AT_EnableReplicaTrig: /* ENABLE REPLICA TRIGGER name */
3390 ATExecEnableDisableTrigger(rel, cmd->name,
3391 TRIGGER_FIRES_ON_REPLICA, false, lockmode);
3393 case AT_DisableTrig: /* DISABLE TRIGGER name */
3394 ATExecEnableDisableTrigger(rel, cmd->name,
3395 TRIGGER_DISABLED, false, lockmode);
3397 case AT_EnableTrigAll: /* ENABLE TRIGGER ALL */
3398 ATExecEnableDisableTrigger(rel, NULL,
3399 TRIGGER_FIRES_ON_ORIGIN, false, lockmode);
3401 case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
3402 ATExecEnableDisableTrigger(rel, NULL,
3403 TRIGGER_DISABLED, false, lockmode);
3405 case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
3406 ATExecEnableDisableTrigger(rel, NULL,
3407 TRIGGER_FIRES_ON_ORIGIN, true, lockmode);
3409 case AT_DisableTrigUser: /* DISABLE TRIGGER USER */
3410 ATExecEnableDisableTrigger(rel, NULL,
3411 TRIGGER_DISABLED, true, lockmode);
3414 case AT_EnableRule: /* ENABLE RULE name */
3415 ATExecEnableDisableRule(rel, cmd->name,
3416 RULE_FIRES_ON_ORIGIN, lockmode);
3418 case AT_EnableAlwaysRule: /* ENABLE ALWAYS RULE name */
3419 ATExecEnableDisableRule(rel, cmd->name,
3420 RULE_FIRES_ALWAYS, lockmode);
3422 case AT_EnableReplicaRule: /* ENABLE REPLICA RULE name */
3423 ATExecEnableDisableRule(rel, cmd->name,
3424 RULE_FIRES_ON_REPLICA, lockmode);
3426 case AT_DisableRule: /* DISABLE RULE name */
3427 ATExecEnableDisableRule(rel, cmd->name,
3428 RULE_DISABLED, lockmode);
3432 ATExecAddInherit(rel, (RangeVar *) cmd->def, lockmode);
3434 case AT_DropInherit:
3435 ATExecDropInherit(rel, (RangeVar *) cmd->def, lockmode);
3438 ATExecAddOf(rel, (TypeName *) cmd->def, lockmode);
3441 ATExecDropOf(rel, lockmode);
3443 case AT_GenericOptions:
3444 ATExecGenericOptions(rel, (List *) cmd->def);
3447 elog(ERROR, "unrecognized alter table type: %d",
3448 (int) cmd->subtype);
3453 * Bump the command counter to ensure the next subcommand in the sequence
3454 * can see the changes so far
3456 CommandCounterIncrement();
3460 * ATRewriteTables: ALTER TABLE phase 3
3463 ATRewriteTables(List **wqueue, LOCKMODE lockmode)
3467 /* Go through each table that needs to be checked or rewritten */
3468 foreach(ltab, *wqueue)
3470 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
3472 /* Foreign tables have no storage. */
3473 if (tab->relkind == RELKIND_FOREIGN_TABLE)
3477 * If we change column data types or add/remove OIDs, the operation
3478 * has to be propagated to tables that use this table's rowtype as a
3479 * column type. tab->newvals will also be non-NULL in the case where
3480 * we're adding a column with a default. We choose to forbid that
3481 * case as well, since composite types might eventually support
3484 * (Eventually we'll probably need to check for composite type
3485 * dependencies even when we're just scanning the table without a
3486 * rewrite, but at the moment a composite type does not enforce any
3487 * constraints, so it's not necessary/appropriate to enforce them just
3490 if (tab->newvals != NIL || tab->rewrite)
3494 rel = heap_open(tab->relid, NoLock);
3495 find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
3496 heap_close(rel, NoLock);
3500 * We only need to rewrite the table if at least one column needs to
3501 * be recomputed, or we are adding/removing the OID column.
3505 /* Build a temporary relation and copy data */
3510 OldHeap = heap_open(tab->relid, NoLock);
3513 * We don't support rewriting of system catalogs; there are too
3514 * many corner cases and too little benefit. In particular this
3515 * is certainly not going to work for mapped catalogs.
3517 if (IsSystemRelation(OldHeap))
3519 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3520 errmsg("cannot rewrite system relation \"%s\"",
3521 RelationGetRelationName(OldHeap))));
3524 * Don't allow rewrite on temp tables of other backends ... their
3525 * local buffer manager is not going to cope.
3527 if (RELATION_IS_OTHER_TEMP(OldHeap))
3529 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3530 errmsg("cannot rewrite temporary tables of other sessions")));
3533 * Select destination tablespace (same as original unless user
3534 * requested a change)
3536 if (tab->newTableSpace)
3537 NewTableSpace = tab->newTableSpace;
3539 NewTableSpace = OldHeap->rd_rel->reltablespace;
3541 heap_close(OldHeap, NoLock);
3543 /* Create transient table that will receive the modified data */
3544 OIDNewHeap = make_new_heap(tab->relid, NewTableSpace);
3547 * Copy the heap data into the new table with the desired
3548 * modifications, and test the current data within the table
3549 * against new constraints generated by ALTER TABLE commands.
3551 ATRewriteTable(tab, OIDNewHeap, lockmode);
3554 * Swap the physical files of the old and new heaps, then rebuild
3555 * indexes and discard the old heap. We can use RecentXmin for
3556 * the table's new relfrozenxid because we rewrote all the tuples
3557 * in ATRewriteTable, so no older Xid remains in the table. Also,
3558 * we never try to swap toast tables by content, since we have no
3559 * interest in letting this code work on system catalogs.
3561 finish_heap_swap(tab->relid, OIDNewHeap,
3563 !OidIsValid(tab->newTableSpace),
3565 ReadNextMultiXactId());
3570 * Test the current data within the table against new constraints
3571 * generated by ALTER TABLE commands, but don't rebuild data.
3573 if (tab->constraints != NIL || tab->new_notnull)
3574 ATRewriteTable(tab, InvalidOid, lockmode);
3577 * If we had SET TABLESPACE but no reason to reconstruct tuples,
3578 * just do a block-by-block copy.
3580 if (tab->newTableSpace)
3581 ATExecSetTableSpace(tab->relid, tab->newTableSpace, lockmode);
3586 * Foreign key constraints are checked in a final pass, since (a) it's
3587 * generally best to examine each one separately, and (b) it's at least
3588 * theoretically possible that we have changed both relations of the
3589 * foreign key, and we'd better have finished both rewrites before we try
3590 * to read the tables.
3592 foreach(ltab, *wqueue)
3594 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
3595 Relation rel = NULL;
3598 foreach(lcon, tab->constraints)
3600 NewConstraint *con = lfirst(lcon);
3602 if (con->contype == CONSTR_FOREIGN)
3604 Constraint *fkconstraint = (Constraint *) con->qual;
3609 /* Long since locked, no need for another */
3610 rel = heap_open(tab->relid, NoLock);
3613 refrel = heap_open(con->refrelid, RowShareLock);
3615 validateForeignKeyConstraint(fkconstraint->conname, rel, refrel,
3620 * No need to mark the constraint row as validated, we did
3621 * that when we inserted the row earlier.
3624 heap_close(refrel, NoLock);
3629 heap_close(rel, NoLock);
3634 * ATRewriteTable: scan or rewrite one table
3636 * OIDNewHeap is InvalidOid if we don't need to rewrite
3639 ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap, LOCKMODE lockmode)
3643 TupleDesc oldTupDesc;
3644 TupleDesc newTupDesc;
3645 bool needscan = false;
3646 List *notnull_attrs;
3651 BulkInsertState bistate;
3655 * Open the relation(s). We have surely already locked the existing
3658 oldrel = heap_open(tab->relid, NoLock);
3659 oldTupDesc = tab->oldDesc;
3660 newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
3662 if (OidIsValid(OIDNewHeap))
3663 newrel = heap_open(OIDNewHeap, lockmode);
3668 * Prepare a BulkInsertState and options for heap_insert. Because we're
3669 * building a new heap, we can skip WAL-logging and fsync it to disk at
3670 * the end instead (unless WAL-logging is required for archiving or
3671 * streaming replication). The FSM is empty too, so don't bother using it.
3675 mycid = GetCurrentCommandId(true);
3676 bistate = GetBulkInsertState();
3678 hi_options = HEAP_INSERT_SKIP_FSM;
3679 if (!XLogIsNeeded())
3680 hi_options |= HEAP_INSERT_SKIP_WAL;
3684 /* keep compiler quiet about using these uninitialized */
3691 * Generate the constraint and default execution states
3694 estate = CreateExecutorState();
3696 /* Build the needed expression execution states */
3697 foreach(l, tab->constraints)
3699 NewConstraint *con = lfirst(l);
3701 switch (con->contype)
3705 con->qualstate = (List *)
3706 ExecPrepareExpr((Expr *) con->qual, estate);
3708 case CONSTR_FOREIGN:
3709 /* Nothing to do here */
3712 elog(ERROR, "unrecognized constraint type: %d",
3713 (int) con->contype);
3717 foreach(l, tab->newvals)
3719 NewColumnValue *ex = lfirst(l);
3721 /* expr already planned */
3722 ex->exprstate = ExecInitExpr((Expr *) ex->expr, NULL);
3725 notnull_attrs = NIL;
3726 if (newrel || tab->new_notnull)
3729 * If we are rebuilding the tuples OR if we added any new NOT NULL
3730 * constraints, check all not-null constraints. This is a bit of
3731 * overkill but it minimizes risk of bugs, and heap_attisnull is a
3732 * pretty cheap test anyway.
3734 for (i = 0; i < newTupDesc->natts; i++)
3736 if (newTupDesc->attrs[i]->attnotnull &&
3737 !newTupDesc->attrs[i]->attisdropped)
3738 notnull_attrs = lappend_int(notnull_attrs, i);
3744 if (newrel || needscan)
3746 ExprContext *econtext;
3749 TupleTableSlot *oldslot;
3750 TupleTableSlot *newslot;
3753 MemoryContext oldCxt;
3754 List *dropped_attrs = NIL;
3759 (errmsg("rewriting table \"%s\"",
3760 RelationGetRelationName(oldrel))));
3763 (errmsg("verifying table \"%s\"",
3764 RelationGetRelationName(oldrel))));
3769 * All predicate locks on the tuples or pages are about to be made
3770 * invalid, because we move tuples around. Promote them to
3773 TransferPredicateLocksToHeapRelation(oldrel);
3776 econtext = GetPerTupleExprContext(estate);
3779 * Make tuple slots for old and new tuples. Note that even when the
3780 * tuples are the same, the tupDescs might not be (consider ADD COLUMN
3781 * without a default).
3783 oldslot = MakeSingleTupleTableSlot(oldTupDesc);
3784 newslot = MakeSingleTupleTableSlot(newTupDesc);
3786 /* Preallocate values/isnull arrays */
3787 i = Max(newTupDesc->natts, oldTupDesc->natts);
3788 values = (Datum *) palloc(i * sizeof(Datum));
3789 isnull = (bool *) palloc(i * sizeof(bool));
3790 memset(values, 0, i * sizeof(Datum));
3791 memset(isnull, true, i * sizeof(bool));
3794 * Any attributes that are dropped according to the new tuple
3795 * descriptor can be set to NULL. We precompute the list of dropped
3796 * attributes to avoid needing to do so in the per-tuple loop.
3798 for (i = 0; i < newTupDesc->natts; i++)
3800 if (newTupDesc->attrs[i]->attisdropped)
3801 dropped_attrs = lappend_int(dropped_attrs, i);
3805 * Scan through the rows, generating a new row if needed and then
3806 * checking all the constraints.
3808 scan = heap_beginscan(oldrel, SnapshotNow, 0, NULL);
3811 * Switch to per-tuple memory context and reset it for each tuple
3812 * produced, so we don't leak memory.
3814 oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
3816 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
3820 Oid tupOid = InvalidOid;
3822 /* Extract data from old tuple */
3823 heap_deform_tuple(tuple, oldTupDesc, values, isnull);
3824 if (oldTupDesc->tdhasoid)
3825 tupOid = HeapTupleGetOid(tuple);
3827 /* Set dropped attributes to null in new tuple */
3828 foreach(lc, dropped_attrs)
3829 isnull[lfirst_int(lc)] = true;
3832 * Process supplied expressions to replace selected columns.
3833 * Expression inputs come from the old tuple.
3835 ExecStoreTuple(tuple, oldslot, InvalidBuffer, false);
3836 econtext->ecxt_scantuple = oldslot;
3838 foreach(l, tab->newvals)
3840 NewColumnValue *ex = lfirst(l);
3842 values[ex->attnum - 1] = ExecEvalExpr(ex->exprstate,
3844 &isnull[ex->attnum - 1],
3849 * Form the new tuple. Note that we don't explicitly pfree it,
3850 * since the per-tuple memory context will be reset shortly.
3852 tuple = heap_form_tuple(newTupDesc, values, isnull);
3854 /* Preserve OID, if any */
3855 if (newTupDesc->tdhasoid)
3856 HeapTupleSetOid(tuple, tupOid);
3859 /* Now check any constraints on the possibly-changed tuple */
3860 ExecStoreTuple(tuple, newslot, InvalidBuffer, false);
3861 econtext->ecxt_scantuple = newslot;
3863 foreach(l, notnull_attrs)
3865 int attn = lfirst_int(l);
3867 if (heap_attisnull(tuple, attn + 1))
3869 (errcode(ERRCODE_NOT_NULL_VIOLATION),
3870 errmsg("column \"%s\" contains null values",
3871 NameStr(newTupDesc->attrs[attn]->attname)),
3872 errtablecol(oldrel, attn + 1)));
3875 foreach(l, tab->constraints)
3877 NewConstraint *con = lfirst(l);
3879 switch (con->contype)
3882 if (!ExecQual(con->qualstate, econtext, true))
3884 (errcode(ERRCODE_CHECK_VIOLATION),
3885 errmsg("check constraint \"%s\" is violated by some row",
3887 errtableconstraint(oldrel, con->name)));
3889 case CONSTR_FOREIGN:
3890 /* Nothing to do here */
3893 elog(ERROR, "unrecognized constraint type: %d",
3894 (int) con->contype);
3898 /* Write the tuple out to the new relation */
3900 heap_insert(newrel, tuple, mycid, hi_options, bistate);
3902 ResetExprContext(econtext);
3904 CHECK_FOR_INTERRUPTS();
3907 MemoryContextSwitchTo(oldCxt);
3910 ExecDropSingleTupleTableSlot(oldslot);
3911 ExecDropSingleTupleTableSlot(newslot);
3914 FreeExecutorState(estate);
3916 heap_close(oldrel, NoLock);
3919 FreeBulkInsertState(bistate);
3921 /* If we skipped writing WAL, then we need to sync the heap. */
3922 if (hi_options & HEAP_INSERT_SKIP_WAL)
3925 heap_close(newrel, NoLock);
3930 * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
3932 static AlteredTableInfo *
3933 ATGetQueueEntry(List **wqueue, Relation rel)
3935 Oid relid = RelationGetRelid(rel);
3936 AlteredTableInfo *tab;
3939 foreach(ltab, *wqueue)
3941 tab = (AlteredTableInfo *) lfirst(ltab);
3942 if (tab->relid == relid)
3947 * Not there, so add it. Note that we make a copy of the relation's
3948 * existing descriptor before anything interesting can happen to it.
3950 tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
3952 tab->relkind = rel->rd_rel->relkind;
3953 tab->oldDesc = CreateTupleDescCopy(RelationGetDescr(rel));
3955 *wqueue = lappend(*wqueue, tab);
3961 * ATSimplePermissions
3963 * - Ensure that it is a relation (or possibly a view)
3964 * - Ensure this user is the owner
3965 * - Ensure that it is not a system table
3968 ATSimplePermissions(Relation rel, int allowed_targets)
3972 switch (rel->rd_rel->relkind)
3974 case RELKIND_RELATION:
3975 actual_target = ATT_TABLE;
3978 actual_target = ATT_VIEW;
3980 case RELKIND_MATVIEW:
3981 actual_target = ATT_MATVIEW;
3984 actual_target = ATT_INDEX;
3986 case RELKIND_COMPOSITE_TYPE:
3987 actual_target = ATT_COMPOSITE_TYPE;
3989 case RELKIND_FOREIGN_TABLE:
3990 actual_target = ATT_FOREIGN_TABLE;
3997 /* Wrong target type? */
3998 if ((actual_target & allowed_targets) == 0)
3999 ATWrongRelkindError(rel, allowed_targets);
4001 /* Permissions checks */
4002 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
4003 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
4004 RelationGetRelationName(rel));
4006 if (!allowSystemTableMods && IsSystemRelation(rel))
4008 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4009 errmsg("permission denied: \"%s\" is a system catalog",
4010 RelationGetRelationName(rel))));
4014 * ATWrongRelkindError
4016 * Throw an error when a relation has been determined to be of the wrong
4020 ATWrongRelkindError(Relation rel, int allowed_targets)
4024 switch (allowed_targets)
4027 msg = _("\"%s\" is not a table");
4029 case ATT_TABLE | ATT_VIEW:
4030 msg = _("\"%s\" is not a table or view");
4032 case ATT_TABLE | ATT_VIEW | ATT_MATVIEW | ATT_INDEX:
4033 msg = _("\"%s\" is not a table, view, materialized view, or index");
4035 case ATT_TABLE | ATT_MATVIEW:
4036 msg = _("\"%s\" is not a table or materialized view");
4038 case ATT_TABLE | ATT_MATVIEW | ATT_INDEX:
4039 msg = _("\"%s\" is not a table, materialized view, or index");
4041 case ATT_TABLE | ATT_FOREIGN_TABLE:
4042 msg = _("\"%s\" is not a table or foreign table");
4044 case ATT_TABLE | ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE:
4045 msg = _("\"%s\" is not a table, composite type, or foreign table");
4047 case ATT_TABLE | ATT_MATVIEW | ATT_INDEX | ATT_FOREIGN_TABLE:
4048 msg = _("\"%s\" is not a table, materialized view, composite type, or foreign table");
4051 msg = _("\"%s\" is not a view");
4053 case ATT_FOREIGN_TABLE:
4054 msg = _("\"%s\" is not a foreign table");
4057 /* shouldn't get here, add all necessary cases above */
4058 msg = _("\"%s\" is of the wrong type");
4063 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4064 errmsg(msg, RelationGetRelationName(rel))));
4070 * Simple table recursion sufficient for most ALTER TABLE operations.
4071 * All direct and indirect children are processed in an unspecified order.
4072 * Note that if a child inherits from the original table via multiple
4073 * inheritance paths, it will be visited just once.
4076 ATSimpleRecursion(List **wqueue, Relation rel,
4077 AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode)
4080 * Propagate to children if desired. Non-table relations never have
4081 * children, so no need to search in that case.
4083 if (recurse && rel->rd_rel->relkind == RELKIND_RELATION)
4085 Oid relid = RelationGetRelid(rel);
4089 children = find_all_inheritors(relid, lockmode, NULL);
4092 * find_all_inheritors does the recursive search of the inheritance
4093 * hierarchy, so all we have to do is process all of the relids in the
4094 * list that it returns.
4096 foreach(child, children)
4098 Oid childrelid = lfirst_oid(child);
4101 if (childrelid == relid)
4103 /* find_all_inheritors already got lock */
4104 childrel = relation_open(childrelid, NoLock);
4105 CheckTableNotInUse(childrel, "ALTER TABLE");
4106 ATPrepCmd(wqueue, childrel, cmd, false, true, lockmode);
4107 relation_close(childrel, NoLock);
4113 * ATTypedTableRecursion
4115 * Propagate ALTER TYPE operations to the typed tables of that type.
4116 * Also check the RESTRICT/CASCADE behavior. Given CASCADE, also permit
4117 * recursion to inheritance children of the typed tables.
4120 ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
4126 Assert(rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
4128 children = find_typed_table_dependencies(rel->rd_rel->reltype,
4129 RelationGetRelationName(rel),
4132 foreach(child, children)
4134 Oid childrelid = lfirst_oid(child);
4137 childrel = relation_open(childrelid, lockmode);
4138 CheckTableNotInUse(childrel, "ALTER TABLE");
4139 ATPrepCmd(wqueue, childrel, cmd, true, true, lockmode);
4140 relation_close(childrel, NoLock);
4146 * find_composite_type_dependencies
4148 * Check to see if a composite type is being used as a column in some
4149 * other table (possibly nested several levels deep in composite types!).
4150 * Eventually, we'd like to propagate the check or rewrite operation
4151 * into other such tables, but for now, just error out if we find any.
4153 * Caller should provide either a table name or a type name (not both) to
4154 * report in the error message, if any.
4156 * We assume that functions and views depending on the type are not reasons
4157 * to reject the ALTER. (How safe is this really?)
4160 find_composite_type_dependencies(Oid typeOid, Relation origRelation,
4161 const char *origTypeName)
4165 SysScanDesc depScan;
4170 * We scan pg_depend to find those things that depend on the rowtype. (We
4171 * assume we can ignore refobjsubid for a rowtype.)
4173 depRel = heap_open(DependRelationId, AccessShareLock);
4175 ScanKeyInit(&key[0],
4176 Anum_pg_depend_refclassid,
4177 BTEqualStrategyNumber, F_OIDEQ,
4178 ObjectIdGetDatum(TypeRelationId));
4179 ScanKeyInit(&key[1],
4180 Anum_pg_depend_refobjid,
4181 BTEqualStrategyNumber, F_OIDEQ,
4182 ObjectIdGetDatum(typeOid));
4184 depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
4185 SnapshotNow, 2, key);
4187 while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
4189 Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
4191 Form_pg_attribute att;
4193 /* Ignore dependees that aren't user columns of relations */
4194 /* (we assume system columns are never of rowtypes) */
4195 if (pg_depend->classid != RelationRelationId ||
4196 pg_depend->objsubid <= 0)
4199 rel = relation_open(pg_depend->objid, AccessShareLock);
4200 att = rel->rd_att->attrs[pg_depend->objsubid - 1];
4202 if (rel->rd_rel->relkind == RELKIND_RELATION ||
4203 rel->rd_rel->relkind == RELKIND_MATVIEW)
4207 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4208 errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
4210 RelationGetRelationName(rel),
4211 NameStr(att->attname))));
4212 else if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
4214 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4215 errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
4216 RelationGetRelationName(origRelation),
4217 RelationGetRelationName(rel),
4218 NameStr(att->attname))));
4219 else if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
4221 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4222 errmsg("cannot alter foreign table \"%s\" because column \"%s.%s\" uses its row type",
4223 RelationGetRelationName(origRelation),
4224 RelationGetRelationName(rel),
4225 NameStr(att->attname))));
4228 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4229 errmsg("cannot alter table \"%s\" because column \"%s.%s\" uses its row type",
4230 RelationGetRelationName(origRelation),
4231 RelationGetRelationName(rel),
4232 NameStr(att->attname))));
4234 else if (OidIsValid(rel->rd_rel->reltype))
4237 * A view or composite type itself isn't a problem, but we must
4238 * recursively check for indirect dependencies via its rowtype.
4240 find_composite_type_dependencies(rel->rd_rel->reltype,
4241 origRelation, origTypeName);
4244 relation_close(rel, AccessShareLock);
4247 systable_endscan(depScan);
4249 relation_close(depRel, AccessShareLock);
4252 * If there's an array type for the rowtype, must check for uses of it,
4255 arrayOid = get_array_type(typeOid);
4256 if (OidIsValid(arrayOid))
4257 find_composite_type_dependencies(arrayOid, origRelation, origTypeName);
4262 * find_typed_table_dependencies
4264 * Check to see if a composite type is being used as the type of a
4265 * typed table. Abort if any are found and behavior is RESTRICT.
4266 * Else return the list of tables.
4269 find_typed_table_dependencies(Oid typeOid, const char *typeName, DropBehavior behavior)
4277 classRel = heap_open(RelationRelationId, AccessShareLock);
4279 ScanKeyInit(&key[0],
4280 Anum_pg_class_reloftype,
4281 BTEqualStrategyNumber, F_OIDEQ,
4282 ObjectIdGetDatum(typeOid));
4284 scan = heap_beginscan(classRel, SnapshotNow, 1, key);
4286 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
4288 if (behavior == DROP_RESTRICT)
4290 (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
4291 errmsg("cannot alter type \"%s\" because it is the type of a typed table",
4293 errhint("Use ALTER ... CASCADE to alter the typed tables too.")));
4295 result = lappend_oid(result, HeapTupleGetOid(tuple));
4299 heap_close(classRel, AccessShareLock);
4308 * Check whether a type is suitable for CREATE TABLE OF/ALTER TABLE OF. If it
4309 * isn't suitable, throw an error. Currently, we require that the type
4310 * originated with CREATE TYPE AS. We could support any row type, but doing so
4311 * would require handling a number of extra corner cases in the DDL commands.
4314 check_of_type(HeapTuple typetuple)
4316 Form_pg_type typ = (Form_pg_type) GETSTRUCT(typetuple);
4317 bool typeOk = false;
4319 if (typ->typtype == TYPTYPE_COMPOSITE)
4321 Relation typeRelation;
4323 Assert(OidIsValid(typ->typrelid));
4324 typeRelation = relation_open(typ->typrelid, AccessShareLock);
4325 typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
4328 * Close the parent rel, but keep our AccessShareLock on it until xact
4329 * commit. That will prevent someone else from deleting or ALTERing
4330 * the type before the typed table creation/conversion commits.
4332 relation_close(typeRelation, NoLock);
4336 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4337 errmsg("type %s is not a composite type",
4338 format_type_be(HeapTupleGetOid(typetuple)))));
4343 * ALTER TABLE ADD COLUMN
4345 * Adds an additional attribute to a relation making the assumption that
4346 * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
4347 * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
4350 * ADD COLUMN cannot use the normal ALTER TABLE recursion mechanism, because we
4351 * have to decide at runtime whether to recurse or not depending on whether we
4352 * actually add a column or merely merge with an existing column. (We can't
4353 * check this in a static pre-pass because it won't handle multiple inheritance
4354 * situations correctly.)
4357 ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
4358 AlterTableCmd *cmd, LOCKMODE lockmode)
4360 if (rel->rd_rel->reloftype && !recursing)
4362 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4363 errmsg("cannot add column to typed table")));
4365 if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
4366 ATTypedTableRecursion(wqueue, rel, cmd, lockmode);
4369 cmd->subtype = AT_AddColumnRecurse;
4373 ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel,
4374 ColumnDef *colDef, bool isOid,
4375 bool recurse, bool recursing, LOCKMODE lockmode)
4377 Oid myrelid = RelationGetRelid(rel);
4381 FormData_pg_attribute attribute;
4384 HeapTuple typeTuple;
4392 AclResult aclresult;
4394 /* At top level, permission check was done in ATPrepCmd, else do it */
4396 ATSimplePermissions(rel, ATT_TABLE);
4398 attrdesc = heap_open(AttributeRelationId, RowExclusiveLock);
4401 * Are we adding the column to a recursion child? If so, check whether to
4402 * merge with an existing definition for the column. If we do merge, we
4403 * must not recurse. Children will already have the column, and recursing
4404 * into them would mess up attinhcount.
4406 if (colDef->inhcount > 0)
4410 /* Does child already have a column by this name? */
4411 tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
4412 if (HeapTupleIsValid(tuple))
4414 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
4419 /* Child column must match on type, typmod, and collation */
4420 typenameTypeIdAndMod(NULL, colDef->typeName, &ctypeId, &ctypmod);
4421 if (ctypeId != childatt->atttypid ||
4422 ctypmod != childatt->atttypmod)
4424 (errcode(ERRCODE_DATATYPE_MISMATCH),
4425 errmsg("child table \"%s\" has different type for column \"%s\"",
4426 RelationGetRelationName(rel), colDef->colname)));
4427 ccollid = GetColumnDefCollation(NULL, colDef, ctypeId);
4428 if (ccollid != childatt->attcollation)
4430 (errcode(ERRCODE_COLLATION_MISMATCH),
4431 errmsg("child table \"%s\" has different collation for column \"%s\"",
4432 RelationGetRelationName(rel), colDef->colname),
4433 errdetail("\"%s\" versus \"%s\"",
4434 get_collation_name(ccollid),
4435 get_collation_name(childatt->attcollation))));
4437 /* If it's OID, child column must actually be OID */
4438 if (isOid && childatt->attnum != ObjectIdAttributeNumber)
4440 (errcode(ERRCODE_DATATYPE_MISMATCH),
4441 errmsg("child table \"%s\" has a conflicting \"%s\" column",
4442 RelationGetRelationName(rel), colDef->colname)));
4444 /* Bump the existing child att's inhcount */
4445 childatt->attinhcount++;
4446 simple_heap_update(attrdesc, &tuple->t_self, tuple);
4447 CatalogUpdateIndexes(attrdesc, tuple);
4449 heap_freetuple(tuple);
4451 /* Inform the user about the merge */
4453 (errmsg("merging definition of column \"%s\" for child \"%s\"",
4454 colDef->colname, RelationGetRelationName(rel))));
4456 heap_close(attrdesc, RowExclusiveLock);
4461 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
4463 reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
4464 if (!HeapTupleIsValid(reltup))
4465 elog(ERROR, "cache lookup failed for relation %u", myrelid);
4466 relkind = ((Form_pg_class) GETSTRUCT(reltup))->relkind;
4468 /* new name should not already exist */
4469 check_for_column_name_collision(rel, colDef->colname);
4471 /* Determine the new attribute's number */
4473 newattnum = ObjectIdAttributeNumber;
4476 newattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts + 1;
4477 if (newattnum > MaxHeapAttributeNumber)
4479 (errcode(ERRCODE_TOO_MANY_COLUMNS),
4480 errmsg("tables can have at most %d columns",
4481 MaxHeapAttributeNumber)));
4484 typeTuple = typenameType(NULL, colDef->typeName, &typmod);
4485 tform = (Form_pg_type) GETSTRUCT(typeTuple);
4486 typeOid = HeapTupleGetOid(typeTuple);
4488 aclresult = pg_type_aclcheck(typeOid, GetUserId(), ACL_USAGE);
4489 if (aclresult != ACLCHECK_OK)
4490 aclcheck_error_type(aclresult, typeOid);
4492 collOid = GetColumnDefCollation(NULL, colDef, typeOid);
4494 /* make sure datatype is legal for a column */
4495 CheckAttributeType(colDef->colname, typeOid, collOid,
4496 list_make1_oid(rel->rd_rel->reltype),
4499 /* construct new attribute's pg_attribute entry */
4500 attribute.attrelid = myrelid;
4501 namestrcpy(&(attribute.attname), colDef->colname);
4502 attribute.atttypid = typeOid;
4503 attribute.attstattarget = (newattnum > 0) ? -1 : 0;
4504 attribute.attlen = tform->typlen;
4505 attribute.attcacheoff = -1;
4506 attribute.atttypmod = typmod;
4507 attribute.attnum = newattnum;
4508 attribute.attbyval = tform->typbyval;
4509 attribute.attndims = list_length(colDef->typeName->arrayBounds);
4510 attribute.attstorage = tform->typstorage;
4511 attribute.attalign = tform->typalign;
4512 attribute.attnotnull = colDef->is_not_null;
4513 attribute.atthasdef = false;
4514 attribute.attisdropped = false;
4515 attribute.attislocal = colDef->is_local;
4516 attribute.attinhcount = colDef->inhcount;
4517 attribute.attcollation = collOid;
4518 /* attribute.attacl is handled by InsertPgAttributeTuple */
4520 ReleaseSysCache(typeTuple);
4522 InsertPgAttributeTuple(attrdesc, &attribute, NULL);
4524 heap_close(attrdesc, RowExclusiveLock);
4527 * Update pg_class tuple as appropriate
4530 ((Form_pg_class) GETSTRUCT(reltup))->relhasoids = true;
4532 ((Form_pg_class) GETSTRUCT(reltup))->relnatts = newattnum;
4534 simple_heap_update(pgclass, &reltup->t_self, reltup);
4536 /* keep catalog indexes current */
4537 CatalogUpdateIndexes(pgclass, reltup);
4539 heap_freetuple(reltup);
4541 /* Post creation hook for new attribute */
4542 InvokeObjectPostCreateHook(RelationRelationId, myrelid, newattnum);
4544 heap_close(pgclass, RowExclusiveLock);
4546 /* Make the attribute's catalog entry visible */
4547 CommandCounterIncrement();
4550 * Store the DEFAULT, if any, in the catalogs
4552 if (colDef->raw_default)
4554 RawColumnDefault *rawEnt;
4556 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
4557 rawEnt->attnum = attribute.attnum;
4558 rawEnt->raw_default = copyObject(colDef->raw_default);
4561 * This function is intended for CREATE TABLE, so it processes a
4562 * _list_ of defaults, but we just do one.
4564 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
4565 false, true, false);
4567 /* Make the additional catalog changes visible */
4568 CommandCounterIncrement();
4572 * Tell Phase 3 to fill in the default expression, if there is one.
4574 * If there is no default, Phase 3 doesn't have to do anything, because
4575 * that effectively means that the default is NULL. The heap tuple access
4576 * routines always check for attnum > # of attributes in tuple, and return
4577 * NULL if so, so without any modification of the tuple data we will get
4578 * the effect of NULL values in the new column.
4580 * An exception occurs when the new column is of a domain type: the domain
4581 * might have a NOT NULL constraint, or a check constraint that indirectly
4582 * rejects nulls. If there are any domain constraints then we construct
4583 * an explicit NULL default value that will be passed through
4584 * CoerceToDomain processing. (This is a tad inefficient, since it causes
4585 * rewriting the table which we really don't have to do, but the present
4586 * design of domain processing doesn't offer any simple way of checking
4587 * the constraints more directly.)
4589 * Note: we use build_column_default, and not just the cooked default
4590 * returned by AddRelationNewConstraints, so that the right thing happens
4591 * when a datatype's default applies.
4593 * We skip this step completely for views and foreign tables. For a view,
4594 * we can only get here from CREATE OR REPLACE VIEW, which historically
4595 * doesn't set up defaults, not even for domain-typed columns. And in any
4596 * case we mustn't invoke Phase 3 on a view or foreign table, since they
4599 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE
4600 && relkind != RELKIND_FOREIGN_TABLE && attribute.attnum > 0)
4602 defval = (Expr *) build_column_default(rel, attribute.attnum);
4604 if (!defval && GetDomainConstraints(typeOid) != NIL)
4610 baseTypeMod = typmod;
4611 baseTypeId = getBaseTypeAndTypmod(typeOid, &baseTypeMod);
4612 baseTypeColl = get_typcollation(baseTypeId);
4613 defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod, baseTypeColl);
4614 defval = (Expr *) coerce_to_target_type(NULL,
4619 COERCION_ASSIGNMENT,
4620 COERCE_IMPLICIT_CAST,
4622 if (defval == NULL) /* should not happen */
4623 elog(ERROR, "failed to coerce base type to domain");
4628 NewColumnValue *newval;
4630 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
4631 newval->attnum = attribute.attnum;
4632 newval->expr = expression_planner(defval);
4634 tab->newvals = lappend(tab->newvals, newval);
4635 tab->rewrite = true;
4639 * If the new column is NOT NULL, tell Phase 3 it needs to test that.
4640 * (Note we don't do this for an OID column. OID will be marked not
4641 * null, but since it's filled specially, there's no need to test
4644 tab->new_notnull |= colDef->is_not_null;
4648 * If we are adding an OID column, we have to tell Phase 3 to rewrite the
4649 * table to fix that.
4652 tab->rewrite = true;
4655 * Add needed dependency entries for the new column.
4657 add_column_datatype_dependency(myrelid, newattnum, attribute.atttypid);
4658 add_column_collation_dependency(myrelid, newattnum, attribute.attcollation);
4661 * Propagate to children as appropriate. Unlike most other ALTER
4662 * routines, we have to do this one level of recursion at a time; we can't
4663 * use find_all_inheritors to do it in one pass.
4665 children = find_inheritance_children(RelationGetRelid(rel), lockmode);
4668 * If we are told not to recurse, there had better not be any child
4669 * tables; else the addition would put them out of step.
4671 if (children && !recurse)
4673 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4674 errmsg("column must be added to child tables too")));
4676 /* Children should see column as singly inherited */
4679 colDef = copyObject(colDef);
4680 colDef->inhcount = 1;
4681 colDef->is_local = false;
4684 foreach(child, children)
4686 Oid childrelid = lfirst_oid(child);
4688 AlteredTableInfo *childtab;
4690 /* find_inheritance_children already got lock */
4691 childrel = heap_open(childrelid, NoLock);
4692 CheckTableNotInUse(childrel, "ALTER TABLE");
4694 /* Find or create work queue entry for this table */
4695 childtab = ATGetQueueEntry(wqueue, childrel);
4697 /* Recurse to child */
4698 ATExecAddColumn(wqueue, childtab, childrel,
4699 colDef, isOid, recurse, true, lockmode);
4701 heap_close(childrel, NoLock);
4706 * If a new or renamed column will collide with the name of an existing
4707 * column, error out.
4710 check_for_column_name_collision(Relation rel, const char *colname)
4716 * this test is deliberately not attisdropped-aware, since if one tries to
4717 * add a column matching a dropped column name, it's gonna fail anyway.
4719 attTuple = SearchSysCache2(ATTNAME,
4720 ObjectIdGetDatum(RelationGetRelid(rel)),
4721 PointerGetDatum(colname));
4722 if (!HeapTupleIsValid(attTuple))
4725 attnum = ((Form_pg_attribute) GETSTRUCT(attTuple))->attnum;
4726 ReleaseSysCache(attTuple);
4729 * We throw a different error message for conflicts with system column
4730 * names, since they are normally not shown and the user might otherwise
4731 * be confused about the reason for the conflict.
4735 (errcode(ERRCODE_DUPLICATE_COLUMN),
4736 errmsg("column name \"%s\" conflicts with a system column name",
4740 (errcode(ERRCODE_DUPLICATE_COLUMN),
4741 errmsg("column \"%s\" of relation \"%s\" already exists",
4742 colname, RelationGetRelationName(rel))));
4746 * Install a column's dependency on its datatype.
4749 add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
4751 ObjectAddress myself,
4754 myself.classId = RelationRelationId;
4755 myself.objectId = relid;
4756 myself.objectSubId = attnum;
4757 referenced.classId = TypeRelationId;
4758 referenced.objectId = typid;
4759 referenced.objectSubId = 0;
4760 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
4764 * Install a column's dependency on its collation.
4767 add_column_collation_dependency(Oid relid, int32 attnum, Oid collid)
4769 ObjectAddress myself,
4772 /* We know the default collation is pinned, so don't bother recording it */
4773 if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
4775 myself.classId = RelationRelationId;
4776 myself.objectId = relid;
4777 myself.objectSubId = attnum;
4778 referenced.classId = CollationRelationId;
4779 referenced.objectId = collid;
4780 referenced.objectSubId = 0;
4781 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
4786 * ALTER TABLE SET WITH OIDS
4788 * Basically this is an ADD COLUMN for the special OID column. We have
4789 * to cons up a ColumnDef node because the ADD COLUMN code needs one.
4792 ATPrepAddOids(List **wqueue, Relation rel, bool recurse, AlterTableCmd *cmd, LOCKMODE lockmode)
4794 /* If we're recursing to a child table, the ColumnDef is already set up */
4795 if (cmd->def == NULL)
4797 ColumnDef *cdef = makeNode(ColumnDef);
4799 cdef->colname = pstrdup("oid");
4800 cdef->typeName = makeTypeNameFromOid(OIDOID, -1);
4802 cdef->is_local = true;
4803 cdef->is_not_null = true;
4805 cmd->def = (Node *) cdef;
4807 ATPrepAddColumn(wqueue, rel, recurse, false, cmd, lockmode);
4810 cmd->subtype = AT_AddOidsRecurse;
4814 * ALTER TABLE ALTER COLUMN DROP NOT NULL
4817 ATExecDropNotNull(Relation rel, const char *colName, LOCKMODE lockmode)
4823 ListCell *indexoidscan;
4826 * lookup the attribute
4828 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
4830 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4832 if (!HeapTupleIsValid(tuple))
4834 (errcode(ERRCODE_UNDEFINED_COLUMN),
4835 errmsg("column \"%s\" of relation \"%s\" does not exist",
4836 colName, RelationGetRelationName(rel))));
4838 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
4840 /* Prevent them from altering a system attribute */
4843 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4844 errmsg("cannot alter system column \"%s\"",
4848 * Check that the attribute is not in a primary key
4850 * Note: we'll throw error even if the pkey index is not valid.
4853 /* Loop over all indexes on the relation */
4854 indexoidlist = RelationGetIndexList(rel);
4856 foreach(indexoidscan, indexoidlist)
4858 Oid indexoid = lfirst_oid(indexoidscan);
4859 HeapTuple indexTuple;
4860 Form_pg_index indexStruct;
4863 indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
4864 if (!HeapTupleIsValid(indexTuple))
4865 elog(ERROR, "cache lookup failed for index %u", indexoid);
4866 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4868 /* If the index is not a primary key, skip the check */
4869 if (indexStruct->indisprimary)
4872 * Loop over each attribute in the primary key and see if it
4873 * matches the to-be-altered attribute
4875 for (i = 0; i < indexStruct->indnatts; i++)
4877 if (indexStruct->indkey.values[i] == attnum)
4879 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4880 errmsg("column \"%s\" is in a primary key",
4885 ReleaseSysCache(indexTuple);
4888 list_free(indexoidlist);
4891 * Okay, actually perform the catalog change ... if needed
4893 if (((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
4895 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = FALSE;
4897 simple_heap_update(attr_rel, &tuple->t_self, tuple);
4899 /* keep the system catalog indexes current */
4900 CatalogUpdateIndexes(attr_rel, tuple);
4903 InvokeObjectPostAlterHook(RelationRelationId,
4904 RelationGetRelid(rel), attnum);
4906 heap_close(attr_rel, RowExclusiveLock);
4910 * ALTER TABLE ALTER COLUMN SET NOT NULL
4913 ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
4914 const char *colName, LOCKMODE lockmode)
4921 * lookup the attribute
4923 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
4925 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4927 if (!HeapTupleIsValid(tuple))
4929 (errcode(ERRCODE_UNDEFINED_COLUMN),
4930 errmsg("column \"%s\" of relation \"%s\" does not exist",
4931 colName, RelationGetRelationName(rel))));
4933 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
4935 /* Prevent them from altering a system attribute */
4938 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4939 errmsg("cannot alter system column \"%s\"",
4943 * Okay, actually perform the catalog change ... if needed
4945 if (!((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
4947 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = TRUE;
4949 simple_heap_update(attr_rel, &tuple->t_self, tuple);
4951 /* keep the system catalog indexes current */
4952 CatalogUpdateIndexes(attr_rel, tuple);
4954 /* Tell Phase 3 it needs to test the constraint */
4955 tab->new_notnull = true;
4958 InvokeObjectPostAlterHook(RelationRelationId,
4959 RelationGetRelid(rel), attnum);
4961 heap_close(attr_rel, RowExclusiveLock);
4965 * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
4968 ATExecColumnDefault(Relation rel, const char *colName,
4969 Node *newDefault, LOCKMODE lockmode)
4974 * get the number of the attribute
4976 attnum = get_attnum(RelationGetRelid(rel), colName);
4977 if (attnum == InvalidAttrNumber)
4979 (errcode(ERRCODE_UNDEFINED_COLUMN),
4980 errmsg("column \"%s\" of relation \"%s\" does not exist",
4981 colName, RelationGetRelationName(rel))));
4983 /* Prevent them from altering a system attribute */
4986 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4987 errmsg("cannot alter system column \"%s\"",
4991 * Remove any old default for the column. We use RESTRICT here for
4992 * safety, but at present we do not expect anything to depend on the
4995 * We treat removing the existing default as an internal operation when it
4996 * is preparatory to adding a new default, but as a user-initiated
4997 * operation when the user asked for a drop.
4999 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false,
5000 newDefault == NULL ? false : true);
5005 RawColumnDefault *rawEnt;
5007 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
5008 rawEnt->attnum = attnum;
5009 rawEnt->raw_default = newDefault;
5012 * This function is intended for CREATE TABLE, so it processes a
5013 * _list_ of defaults, but we just do one.
5015 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
5016 false, true, false);
5021 * ALTER TABLE ALTER COLUMN SET STATISTICS
5024 ATPrepSetStatistics(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
5027 * We do our own permission checking because (a) we want to allow SET
5028 * STATISTICS on indexes (for expressional index columns), and (b) we want
5029 * to allow SET STATISTICS on system catalogs without requiring
5030 * allowSystemTableMods to be turned on.
5032 if (rel->rd_rel->relkind != RELKIND_RELATION &&
5033 rel->rd_rel->relkind != RELKIND_MATVIEW &&
5034 rel->rd_rel->relkind != RELKIND_INDEX &&
5035 rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
5037 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5038 errmsg("\"%s\" is not a table, materialized view, index, or foreign table",
5039 RelationGetRelationName(rel))));
5041 /* Permissions checks */
5042 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
5043 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
5044 RelationGetRelationName(rel));
5048 ATExecSetStatistics(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
5051 Relation attrelation;
5053 Form_pg_attribute attrtuple;
5055 Assert(IsA(newValue, Integer));
5056 newtarget = intVal(newValue);
5059 * Limit target to a sane range
5064 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5065 errmsg("statistics target %d is too low",
5068 else if (newtarget > 10000)
5072 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5073 errmsg("lowering statistics target to %d",
5077 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
5079 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5081 if (!HeapTupleIsValid(tuple))
5083 (errcode(ERRCODE_UNDEFINED_COLUMN),
5084 errmsg("column \"%s\" of relation \"%s\" does not exist",
5085 colName, RelationGetRelationName(rel))));
5086 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
5088 if (attrtuple->attnum <= 0)
5090 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5091 errmsg("cannot alter system column \"%s\"",
5094 attrtuple->attstattarget = newtarget;
5096 simple_heap_update(attrelation, &tuple->t_self, tuple);
5098 /* keep system catalog indexes current */
5099 CatalogUpdateIndexes(attrelation, tuple);
5101 InvokeObjectPostAlterHook(RelationRelationId,
5102 RelationGetRelid(rel),
5104 heap_freetuple(tuple);
5106 heap_close(attrelation, RowExclusiveLock);
5110 ATExecSetOptions(Relation rel, const char *colName, Node *options,
5111 bool isReset, LOCKMODE lockmode)
5113 Relation attrelation;
5116 Form_pg_attribute attrtuple;
5120 Datum repl_val[Natts_pg_attribute];
5121 bool repl_null[Natts_pg_attribute];
5122 bool repl_repl[Natts_pg_attribute];
5124 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
5126 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
5128 if (!HeapTupleIsValid(tuple))
5130 (errcode(ERRCODE_UNDEFINED_COLUMN),
5131 errmsg("column \"%s\" of relation \"%s\" does not exist",
5132 colName, RelationGetRelationName(rel))));
5133 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
5135 if (attrtuple->attnum <= 0)
5137 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5138 errmsg("cannot alter system column \"%s\"",
5141 /* Generate new proposed attoptions (text array) */
5142 Assert(IsA(options, List));
5143 datum = SysCacheGetAttr(ATTNAME, tuple, Anum_pg_attribute_attoptions,
5145 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
5146 (List *) options, NULL, NULL, false,
5148 /* Validate new options */
5149 (void) attribute_reloptions(newOptions, true);
5151 /* Build new tuple. */
5152 memset(repl_null, false, sizeof(repl_null));
5153 memset(repl_repl, false, sizeof(repl_repl));
5154 if (newOptions != (Datum) 0)
5155 repl_val[Anum_pg_attribute_attoptions - 1] = newOptions;
5157 repl_null[Anum_pg_attribute_attoptions - 1] = true;
5158 repl_repl[Anum_pg_attribute_attoptions - 1] = true;
5159 newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrelation),
5160 repl_val, repl_null, repl_repl);
5162 /* Update system catalog. */
5163 simple_heap_update(attrelation, &newtuple->t_self, newtuple);
5164 CatalogUpdateIndexes(attrelation, newtuple);
5166 InvokeObjectPostAlterHook(RelationRelationId,
5167 RelationGetRelid(rel),
5169 heap_freetuple(newtuple);
5171 ReleaseSysCache(tuple);
5173 heap_close(attrelation, RowExclusiveLock);
5177 * ALTER TABLE ALTER COLUMN SET STORAGE
5180 ATExecSetStorage(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
5184 Relation attrelation;
5186 Form_pg_attribute attrtuple;
5188 Assert(IsA(newValue, String));
5189 storagemode = strVal(newValue);
5191 if (pg_strcasecmp(storagemode, "plain") == 0)
5193 else if (pg_strcasecmp(storagemode, "external") == 0)
5195 else if (pg_strcasecmp(storagemode, "extended") == 0)
5197 else if (pg_strcasecmp(storagemode, "main") == 0)
5202 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5203 errmsg("invalid storage type \"%s\"",
5205 newstorage = 0; /* keep compiler quiet */
5208 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
5210 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5212 if (!HeapTupleIsValid(tuple))
5214 (errcode(ERRCODE_UNDEFINED_COLUMN),
5215 errmsg("column \"%s\" of relation \"%s\" does not exist",
5216 colName, RelationGetRelationName(rel))));
5217 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
5219 if (attrtuple->attnum <= 0)
5221 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5222 errmsg("cannot alter system column \"%s\"",
5226 * safety check: do not allow toasted storage modes unless column datatype
5229 if (newstorage == 'p' || TypeIsToastable(attrtuple->atttypid))
5230 attrtuple->attstorage = newstorage;
5233 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5234 errmsg("column data type %s can only have storage PLAIN",
5235 format_type_be(attrtuple->atttypid))));
5237 simple_heap_update(attrelation, &tuple->t_self, tuple);
5239 /* keep system catalog indexes current */
5240 CatalogUpdateIndexes(attrelation, tuple);
5242 InvokeObjectPostAlterHook(RelationRelationId,
5243 RelationGetRelid(rel),
5246 heap_freetuple(tuple);
5248 heap_close(attrelation, RowExclusiveLock);
5253 * ALTER TABLE DROP COLUMN
5255 * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
5256 * because we have to decide at runtime whether to recurse or not depending
5257 * on whether attinhcount goes to zero or not. (We can't check this in a
5258 * static pre-pass because it won't handle multiple inheritance situations
5262 ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
5263 AlterTableCmd *cmd, LOCKMODE lockmode)
5265 if (rel->rd_rel->reloftype && !recursing)
5267 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5268 errmsg("cannot drop column from typed table")));
5270 if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
5271 ATTypedTableRecursion(wqueue, rel, cmd, lockmode);
5274 cmd->subtype = AT_DropColumnRecurse;
5278 ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
5279 DropBehavior behavior,
5280 bool recurse, bool recursing,
5281 bool missing_ok, LOCKMODE lockmode)
5284 Form_pg_attribute targetatt;
5287 ObjectAddress object;
5289 /* At top level, permission check was done in ATPrepCmd, else do it */
5291 ATSimplePermissions(rel, ATT_TABLE);
5294 * get the number of the attribute
5296 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
5297 if (!HeapTupleIsValid(tuple))
5302 (errcode(ERRCODE_UNDEFINED_COLUMN),
5303 errmsg("column \"%s\" of relation \"%s\" does not exist",
5304 colName, RelationGetRelationName(rel))));
5309 (errmsg("column \"%s\" of relation \"%s\" does not exist, skipping",
5310 colName, RelationGetRelationName(rel))));
5314 targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
5316 attnum = targetatt->attnum;
5318 /* Can't drop a system attribute, except OID */
5319 if (attnum <= 0 && attnum != ObjectIdAttributeNumber)
5321 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5322 errmsg("cannot drop system column \"%s\"",
5325 /* Don't drop inherited columns */
5326 if (targetatt->attinhcount > 0 && !recursing)
5328 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5329 errmsg("cannot drop inherited column \"%s\"",
5332 ReleaseSysCache(tuple);
5335 * Propagate to children as appropriate. Unlike most other ALTER
5336 * routines, we have to do this one level of recursion at a time; we can't
5337 * use find_all_inheritors to do it in one pass.
5339 children = find_inheritance_children(RelationGetRelid(rel), lockmode);
5346 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
5347 foreach(child, children)
5349 Oid childrelid = lfirst_oid(child);
5351 Form_pg_attribute childatt;
5353 /* find_inheritance_children already got lock */
5354 childrel = heap_open(childrelid, NoLock);
5355 CheckTableNotInUse(childrel, "ALTER TABLE");
5357 tuple = SearchSysCacheCopyAttName(childrelid, colName);
5358 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
5359 elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
5360 colName, childrelid);
5361 childatt = (Form_pg_attribute) GETSTRUCT(tuple);
5363 if (childatt->attinhcount <= 0) /* shouldn't happen */
5364 elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
5365 childrelid, colName);
5370 * If the child column has other definition sources, just
5371 * decrement its inheritance count; if not, recurse to delete
5374 if (childatt->attinhcount == 1 && !childatt->attislocal)
5376 /* Time to delete this child column, too */
5377 ATExecDropColumn(wqueue, childrel, colName,
5378 behavior, true, true,
5383 /* Child column must survive my deletion */
5384 childatt->attinhcount--;
5386 simple_heap_update(attr_rel, &tuple->t_self, tuple);
5388 /* keep the system catalog indexes current */
5389 CatalogUpdateIndexes(attr_rel, tuple);
5391 /* Make update visible */
5392 CommandCounterIncrement();
5398 * If we were told to drop ONLY in this table (no recursion),
5399 * we need to mark the inheritors' attributes as locally
5400 * defined rather than inherited.
5402 childatt->attinhcount--;
5403 childatt->attislocal = true;
5405 simple_heap_update(attr_rel, &tuple->t_self, tuple);
5407 /* keep the system catalog indexes current */
5408 CatalogUpdateIndexes(attr_rel, tuple);
5410 /* Make update visible */
5411 CommandCounterIncrement();
5414 heap_freetuple(tuple);
5416 heap_close(childrel, NoLock);
5418 heap_close(attr_rel, RowExclusiveLock);
5422 * Perform the actual column deletion
5424 object.classId = RelationRelationId;
5425 object.objectId = RelationGetRelid(rel);
5426 object.objectSubId = attnum;
5428 performDeletion(&object, behavior, 0);
5431 * If we dropped the OID column, must adjust pg_class.relhasoids and tell
5432 * Phase 3 to physically get rid of the column. We formerly left the
5433 * column in place physically, but this caused subtle problems. See
5434 * http://archives.postgresql.org/pgsql-hackers/2009-02/msg00363.php
5436 if (attnum == ObjectIdAttributeNumber)
5439 Form_pg_class tuple_class;
5440 AlteredTableInfo *tab;
5442 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
5444 tuple = SearchSysCacheCopy1(RELOID,
5445 ObjectIdGetDatum(RelationGetRelid(rel)));
5446 if (!HeapTupleIsValid(tuple))
5447 elog(ERROR, "cache lookup failed for relation %u",
5448 RelationGetRelid(rel));
5449 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
5451 tuple_class->relhasoids = false;
5452 simple_heap_update(class_rel, &tuple->t_self, tuple);
5454 /* Keep the catalog indexes up to date */
5455 CatalogUpdateIndexes(class_rel, tuple);
5457 heap_close(class_rel, RowExclusiveLock);
5459 /* Find or create work queue entry for this table */
5460 tab = ATGetQueueEntry(wqueue, rel);
5462 /* Tell Phase 3 to physically remove the OID column */
5463 tab->rewrite = true;
5468 * ALTER TABLE ADD INDEX
5470 * There is no such command in the grammar, but parse_utilcmd.c converts
5471 * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands. This lets
5472 * us schedule creation of the index at the appropriate time during ALTER.
5475 ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
5476 IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
5483 Assert(IsA(stmt, IndexStmt));
5484 Assert(!stmt->concurrent);
5486 /* suppress schema rights check when rebuilding existing index */
5487 check_rights = !is_rebuild;
5488 /* skip index build if phase 3 will do it or we're reusing an old one */
5489 skip_build = tab->rewrite || OidIsValid(stmt->oldNode);
5490 /* suppress notices when rebuilding existing index */
5493 /* The IndexStmt has already been through transformIndexStmt */
5495 new_index = DefineIndex(stmt,
5496 InvalidOid, /* no predefined OID */
5497 true, /* is_alter_table */
5503 * If TryReuseIndex() stashed a relfilenode for us, we used it for the new
5504 * index instead of building from scratch. The DROP of the old edition of
5505 * this index will have scheduled the storage for deletion at commit, so
5506 * cancel that pending deletion.
5508 if (OidIsValid(stmt->oldNode))
5510 Relation irel = index_open(new_index, NoLock);
5512 RelationPreserveStorage(irel->rd_node, true);
5513 index_close(irel, NoLock);
5518 * ALTER TABLE ADD CONSTRAINT USING INDEX
5521 ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
5522 IndexStmt *stmt, LOCKMODE lockmode)
5524 Oid index_oid = stmt->indexOid;
5527 IndexInfo *indexInfo;
5528 char *constraintName;
5529 char constraintType;
5531 Assert(IsA(stmt, IndexStmt));
5532 Assert(OidIsValid(index_oid));
5533 Assert(stmt->isconstraint);
5535 indexRel = index_open(index_oid, AccessShareLock);
5537 indexName = pstrdup(RelationGetRelationName(indexRel));
5539 indexInfo = BuildIndexInfo(indexRel);
5541 /* this should have been checked at parse time */
5542 if (!indexInfo->ii_Unique)
5543 elog(ERROR, "index \"%s\" is not unique", indexName);
5546 * Determine name to assign to constraint. We require a constraint to
5547 * have the same name as the underlying index; therefore, use the index's
5548 * existing name as the default constraint name, and if the user
5549 * explicitly gives some other name for the constraint, rename the index
5552 constraintName = stmt->idxname;
5553 if (constraintName == NULL)
5554 constraintName = indexName;
5555 else if (strcmp(constraintName, indexName) != 0)
5558 (errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index \"%s\" to \"%s\"",
5559 indexName, constraintName)));
5560 RenameRelationInternal(index_oid, constraintName, false);
5563 /* Extra checks needed if making primary key */
5565 index_check_primary_key(rel, indexInfo, true);
5567 /* Note we currently don't support EXCLUSION constraints here */
5569 constraintType = CONSTRAINT_PRIMARY;
5571 constraintType = CONSTRAINT_UNIQUE;
5573 /* Create the catalog entries for the constraint */
5574 index_constraint_create(rel,
5582 true, /* update pg_index */
5583 true, /* remove old dependencies */
5584 allowSystemTableMods,
5585 false); /* is_internal */
5587 index_close(indexRel, NoLock);
5591 * ALTER TABLE ADD CONSTRAINT
5594 ATExecAddConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
5595 Constraint *newConstraint, bool recurse, bool is_readd,
5598 Assert(IsA(newConstraint, Constraint));
5601 * Currently, we only expect to see CONSTR_CHECK and CONSTR_FOREIGN nodes
5602 * arriving here (see the preprocessing done in parse_utilcmd.c). Use a
5603 * switch anyway to make it easier to add more code later.
5605 switch (newConstraint->contype)
5608 ATAddCheckConstraint(wqueue, tab, rel,
5609 newConstraint, recurse, false, is_readd,
5613 case CONSTR_FOREIGN:
5616 * Note that we currently never recurse for FK constraints, so the
5617 * "recurse" flag is silently ignored.
5619 * Assign or validate constraint name
5621 if (newConstraint->conname)
5623 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
5624 RelationGetRelid(rel),
5625 RelationGetNamespace(rel),
5626 newConstraint->conname))
5628 (errcode(ERRCODE_DUPLICATE_OBJECT),
5629 errmsg("constraint \"%s\" for relation \"%s\" already exists",
5630 newConstraint->conname,
5631 RelationGetRelationName(rel))));
5634 newConstraint->conname =
5635 ChooseConstraintName(RelationGetRelationName(rel),
5636 strVal(linitial(newConstraint->fk_attrs)),
5638 RelationGetNamespace(rel),
5641 ATAddForeignKeyConstraint(tab, rel, newConstraint, lockmode);
5645 elog(ERROR, "unrecognized constraint type: %d",
5646 (int) newConstraint->contype);
5651 * Add a check constraint to a single table and its children
5653 * Subroutine for ATExecAddConstraint.
5655 * We must recurse to child tables during execution, rather than using
5656 * ALTER TABLE's normal prep-time recursion. The reason is that all the
5657 * constraints *must* be given the same name, else they won't be seen as
5658 * related later. If the user didn't explicitly specify a name, then
5659 * AddRelationNewConstraints would normally assign different names to the
5660 * child constraints. To fix that, we must capture the name assigned at
5661 * the parent table and pass that down.
5663 * When re-adding a previously existing constraint (during ALTER COLUMN TYPE),
5664 * we don't need to recurse here, because recursion will be carried out at a
5665 * higher level; the constraint name issue doesn't apply because the names
5666 * have already been assigned and are just being re-used. We need a separate
5667 * "is_readd" flag for that; just setting recurse=false would result in an
5668 * error if there are child tables.
5671 ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
5672 Constraint *constr, bool recurse, bool recursing,
5673 bool is_readd, LOCKMODE lockmode)
5680 /* At top level, permission check was done in ATPrepCmd, else do it */
5682 ATSimplePermissions(rel, ATT_TABLE);
5685 * Call AddRelationNewConstraints to do the work, making sure it works on
5686 * a copy of the Constraint so transformExpr can't modify the original. It
5687 * returns a list of cooked constraints.
5689 * If the constraint ends up getting merged with a pre-existing one, it's
5690 * omitted from the returned list, which is what we want: we do not need
5691 * to do any validation work. That can only happen at child tables,
5692 * though, since we disallow merging at the top level.
5694 newcons = AddRelationNewConstraints(rel, NIL,
5695 list_make1(copyObject(constr)),
5696 recursing, /* allow_merge */
5697 !recursing, /* is_local */
5698 is_readd); /* is_internal */
5700 /* Add each to-be-validated constraint to Phase 3's queue */
5701 foreach(lcon, newcons)
5703 CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
5705 if (!ccon->skip_validation)
5707 NewConstraint *newcon;
5709 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
5710 newcon->name = ccon->name;
5711 newcon->contype = ccon->contype;
5712 /* ExecQual wants implicit-AND format */
5713 newcon->qual = (Node *) make_ands_implicit((Expr *) ccon->expr);
5715 tab->constraints = lappend(tab->constraints, newcon);
5718 /* Save the actually assigned name if it was defaulted */
5719 if (constr->conname == NULL)
5720 constr->conname = ccon->name;
5723 /* At this point we must have a locked-down name to use */
5724 Assert(constr->conname != NULL);
5726 /* Advance command counter in case same table is visited multiple times */
5727 CommandCounterIncrement();
5730 * If the constraint got merged with an existing constraint, we're done.
5731 * We mustn't recurse to child tables in this case, because they've
5732 * already got the constraint, and visiting them again would lead to an
5733 * incorrect value for coninhcount.
5739 * If adding a NO INHERIT constraint, no need to find our children.
5740 * Likewise, in a re-add operation, we don't need to recurse (that will be
5741 * handled at higher levels).
5743 if (constr->is_no_inherit || is_readd)
5747 * Propagate to children as appropriate. Unlike most other ALTER
5748 * routines, we have to do this one level of recursion at a time; we can't
5749 * use find_all_inheritors to do it in one pass.
5751 children = find_inheritance_children(RelationGetRelid(rel), lockmode);
5754 * Check if ONLY was specified with ALTER TABLE. If so, allow the
5755 * contraint creation only if there are no children currently. Error out
5758 if (!recurse && children != NIL)
5760 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5761 errmsg("constraint must be added to child tables too")));
5763 foreach(child, children)
5765 Oid childrelid = lfirst_oid(child);
5767 AlteredTableInfo *childtab;
5769 /* find_inheritance_children already got lock */
5770 childrel = heap_open(childrelid, NoLock);
5771 CheckTableNotInUse(childrel, "ALTER TABLE");
5773 /* Find or create work queue entry for this table */
5774 childtab = ATGetQueueEntry(wqueue, childrel);
5776 /* Recurse to child */
5777 ATAddCheckConstraint(wqueue, childtab, childrel,
5778 constr, recurse, true, is_readd, lockmode);
5780 heap_close(childrel, NoLock);
5785 * Add a foreign-key constraint to a single table
5787 * Subroutine for ATExecAddConstraint. Must already hold exclusive
5788 * lock on the rel, and have done appropriate validity checks for it.
5789 * We do permissions checks here, however.
5792 ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
5793 Constraint *fkconstraint, LOCKMODE lockmode)
5796 int16 pkattnum[INDEX_MAX_KEYS];
5797 int16 fkattnum[INDEX_MAX_KEYS];
5798 Oid pktypoid[INDEX_MAX_KEYS];
5799 Oid fktypoid[INDEX_MAX_KEYS];
5800 Oid opclasses[INDEX_MAX_KEYS];
5801 Oid pfeqoperators[INDEX_MAX_KEYS];
5802 Oid ppeqoperators[INDEX_MAX_KEYS];
5803 Oid ffeqoperators[INDEX_MAX_KEYS];
5810 ListCell *old_pfeqop_item = list_head(fkconstraint->old_conpfeqop);
5813 * Grab an exclusive lock on the pk table, so that someone doesn't delete
5814 * rows out from under us. (Although a lesser lock would do for that
5815 * purpose, we'll need exclusive lock anyway to add triggers to the pk
5816 * table; trying to start with a lesser lock will just create a risk of
5819 pkrel = heap_openrv(fkconstraint->pktable, AccessExclusiveLock);
5822 * Validity checks (permission checks wait till we have the column
5825 if (pkrel->rd_rel->relkind != RELKIND_RELATION)
5827 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5828 errmsg("referenced relation \"%s\" is not a table",
5829 RelationGetRelationName(pkrel))));
5831 if (!allowSystemTableMods && IsSystemRelation(pkrel))
5833 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5834 errmsg("permission denied: \"%s\" is a system catalog",
5835 RelationGetRelationName(pkrel))));
5838 * References from permanent or unlogged tables to temp tables, and from
5839 * permanent tables to unlogged tables, are disallowed because the
5840 * referenced data can vanish out from under us. References from temp
5841 * tables to any other table type are also disallowed, because other
5842 * backends might need to run the RI triggers on the perm table, but they
5843 * can't reliably see tuples in the local buffers of other backends.
5845 switch (rel->rd_rel->relpersistence)
5847 case RELPERSISTENCE_PERMANENT:
5848 if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT)
5850 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5851 errmsg("constraints on permanent tables may reference only permanent tables")));
5853 case RELPERSISTENCE_UNLOGGED:
5854 if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT
5855 && pkrel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED)
5857 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5858 errmsg("constraints on unlogged tables may reference only permanent or unlogged tables")));
5860 case RELPERSISTENCE_TEMP:
5861 if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
5863 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5864 errmsg("constraints on temporary tables may reference only temporary tables")));
5865 if (!pkrel->rd_islocaltemp || !rel->rd_islocaltemp)
5867 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5868 errmsg("constraints on temporary tables must involve temporary tables of this session")));
5873 * Look up the referencing attributes to make sure they exist, and record
5874 * their attnums and type OIDs.
5876 MemSet(pkattnum, 0, sizeof(pkattnum));
5877 MemSet(fkattnum, 0, sizeof(fkattnum));
5878 MemSet(pktypoid, 0, sizeof(pktypoid));
5879 MemSet(fktypoid, 0, sizeof(fktypoid));
5880 MemSet(opclasses, 0, sizeof(opclasses));
5881 MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
5882 MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
5883 MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
5885 numfks = transformColumnNameList(RelationGetRelid(rel),
5886 fkconstraint->fk_attrs,
5887 fkattnum, fktypoid);
5890 * If the attribute list for the referenced table was omitted, lookup the
5891 * definition of the primary key and use it. Otherwise, validate the
5892 * supplied attribute list. In either case, discover the index OID and
5893 * index opclasses, and the attnums and type OIDs of the attributes.
5895 if (fkconstraint->pk_attrs == NIL)
5897 numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
5898 &fkconstraint->pk_attrs,
5904 numpks = transformColumnNameList(RelationGetRelid(pkrel),
5905 fkconstraint->pk_attrs,
5906 pkattnum, pktypoid);
5907 /* Look for an index matching the column list */
5908 indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
5913 * Now we can check permissions.
5915 checkFkeyPermissions(pkrel, pkattnum, numpks);
5916 checkFkeyPermissions(rel, fkattnum, numfks);
5919 * Look up the equality operators to use in the constraint.
5921 * Note that we have to be careful about the difference between the actual
5922 * PK column type and the opclass' declared input type, which might be
5923 * only binary-compatible with it. The declared opcintype is the right
5924 * thing to probe pg_amop with.
5926 if (numfks != numpks)
5928 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
5929 errmsg("number of referencing and referenced columns for foreign key disagree")));
5932 * On the strength of a previous constraint, we might avoid scanning
5933 * tables to validate this one. See below.
5935 old_check_ok = (fkconstraint->old_conpfeqop != NIL);
5936 Assert(!old_check_ok || numfks == list_length(fkconstraint->old_conpfeqop));
5938 for (i = 0; i < numpks; i++)
5940 Oid pktype = pktypoid[i];
5941 Oid fktype = fktypoid[i];
5944 Form_pg_opclass cla_tup;
5954 /* We need several fields out of the pg_opclass entry */
5955 cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclasses[i]));
5956 if (!HeapTupleIsValid(cla_ht))
5957 elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
5958 cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
5959 amid = cla_tup->opcmethod;
5960 opfamily = cla_tup->opcfamily;
5961 opcintype = cla_tup->opcintype;
5962 ReleaseSysCache(cla_ht);
5965 * Check it's a btree; currently this can never fail since no other
5966 * index AMs support unique indexes. If we ever did have other types
5967 * of unique indexes, we'd need a way to determine which operator
5968 * strategy number is equality. (Is it reasonable to insist that
5969 * every such index AM use btree's number for equality?)
5971 if (amid != BTREE_AM_OID)
5972 elog(ERROR, "only b-tree indexes are supported for foreign keys");
5973 eqstrategy = BTEqualStrategyNumber;
5976 * There had better be a primary equality operator for the index.
5977 * We'll use it for PK = PK comparisons.
5979 ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
5982 if (!OidIsValid(ppeqop))
5983 elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
5984 eqstrategy, opcintype, opcintype, opfamily);
5987 * Are there equality operators that take exactly the FK type? Assume
5988 * we should look through any domain here.
5990 fktyped = getBaseType(fktype);
5992 pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
5994 if (OidIsValid(pfeqop))
5996 pfeqop_right = fktyped;
5997 ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
6002 /* keep compiler quiet */
6003 pfeqop_right = InvalidOid;
6004 ffeqop = InvalidOid;
6007 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
6010 * Otherwise, look for an implicit cast from the FK type to the
6011 * opcintype, and if found, use the primary equality operator.
6012 * This is a bit tricky because opcintype might be a polymorphic
6013 * type such as ANYARRAY or ANYENUM; so what we have to test is
6014 * whether the two actual column types can be concurrently cast to
6015 * that type. (Otherwise, we'd fail to reject combinations such
6016 * as int[] and point[].)
6018 Oid input_typeids[2];
6019 Oid target_typeids[2];
6021 input_typeids[0] = pktype;
6022 input_typeids[1] = fktype;
6023 target_typeids[0] = opcintype;
6024 target_typeids[1] = opcintype;
6025 if (can_coerce_type(2, input_typeids, target_typeids,
6028 pfeqop = ffeqop = ppeqop;
6029 pfeqop_right = opcintype;
6033 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
6035 (errcode(ERRCODE_DATATYPE_MISMATCH),
6036 errmsg("foreign key constraint \"%s\" "
6037 "cannot be implemented",
6038 fkconstraint->conname),
6039 errdetail("Key columns \"%s\" and \"%s\" "
6040 "are of incompatible types: %s and %s.",
6041 strVal(list_nth(fkconstraint->fk_attrs, i)),
6042 strVal(list_nth(fkconstraint->pk_attrs, i)),
6043 format_type_be(fktype),
6044 format_type_be(pktype))));
6049 * When a pfeqop changes, revalidate the constraint. We could
6050 * permit intra-opfamily changes, but that adds subtle complexity
6051 * without any concrete benefit for core types. We need not
6052 * assess ppeqop or ffeqop, which RI_Initial_Check() does not use.
6054 old_check_ok = (pfeqop == lfirst_oid(old_pfeqop_item));
6055 old_pfeqop_item = lnext(old_pfeqop_item);
6061 CoercionPathType old_pathtype;
6062 CoercionPathType new_pathtype;
6067 * Identify coercion pathways from each of the old and new FK-side
6068 * column types to the right (foreign) operand type of the pfeqop.
6069 * We may assume that pg_constraint.conkey is not changing.
6071 old_fktype = tab->oldDesc->attrs[fkattnum[i] - 1]->atttypid;
6072 new_fktype = fktype;
6073 old_pathtype = findFkeyCast(pfeqop_right, old_fktype,
6075 new_pathtype = findFkeyCast(pfeqop_right, new_fktype,
6079 * Upon a change to the cast from the FK column to its pfeqop
6080 * operand, revalidate the constraint. For this evaluation, a
6081 * binary coercion cast is equivalent to no cast at all. While
6082 * type implementors should design implicit casts with an eye
6083 * toward consistency of operations like equality, we cannot
6084 * assume here that they have done so.
6086 * A function with a polymorphic argument could change behavior
6087 * arbitrarily in response to get_fn_expr_argtype(). Therefore,
6088 * when the cast destination is polymorphic, we only avoid
6089 * revalidation if the input type has not changed at all. Given
6090 * just the core data types and operator classes, this requirement
6091 * prevents no would-be optimizations.
6093 * If the cast converts from a base type to a domain thereon, then
6094 * that domain type must be the opcintype of the unique index.
6095 * Necessarily, the primary key column must then be of the domain
6096 * type. Since the constraint was previously valid, all values on
6097 * the foreign side necessarily exist on the primary side and in
6098 * turn conform to the domain. Consequently, we need not treat
6099 * domains specially here.
6101 * Since we require that all collations share the same notion of
6102 * equality (which they do, because texteq reduces to bitwise
6103 * equality), we don't compare collation here.
6105 * We need not directly consider the PK type. It's necessarily
6106 * binary coercible to the opcintype of the unique index column,
6107 * and ri_triggers.c will only deal with PK datums in terms of
6108 * that opcintype. Changing the opcintype also changes pfeqop.
6110 old_check_ok = (new_pathtype == old_pathtype &&
6111 new_castfunc == old_castfunc &&
6112 (!IsPolymorphicType(pfeqop_right) ||
6113 new_fktype == old_fktype));
6117 pfeqoperators[i] = pfeqop;
6118 ppeqoperators[i] = ppeqop;
6119 ffeqoperators[i] = ffeqop;
6123 * Record the FK constraint in pg_constraint.
6125 constrOid = CreateConstraintEntry(fkconstraint->conname,
6126 RelationGetNamespace(rel),
6128 fkconstraint->deferrable,
6129 fkconstraint->initdeferred,
6130 fkconstraint->initially_valid,
6131 RelationGetRelid(rel),
6134 InvalidOid, /* not a domain
6137 RelationGetRelid(pkrel),
6143 fkconstraint->fk_upd_action,
6144 fkconstraint->fk_del_action,
6145 fkconstraint->fk_matchtype,
6146 NULL, /* no exclusion constraint */
6147 NULL, /* no check constraint */
6152 true, /* isnoinherit */
6153 false); /* is_internal */
6156 * Create the triggers that will enforce the constraint.
6158 createForeignKeyTriggers(rel, fkconstraint, constrOid, indexOid);
6161 * Tell Phase 3 to check that the constraint is satisfied by existing
6162 * rows. We can skip this during table creation, when requested explicitly
6163 * by specifying NOT VALID in an ADD FOREIGN KEY command, and when we're
6164 * recreating a constraint following a SET DATA TYPE operation that did
6165 * not impugn its validity.
6167 if (!old_check_ok && !fkconstraint->skip_validation)
6169 NewConstraint *newcon;
6171 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
6172 newcon->name = fkconstraint->conname;
6173 newcon->contype = CONSTR_FOREIGN;
6174 newcon->refrelid = RelationGetRelid(pkrel);
6175 newcon->refindid = indexOid;
6176 newcon->conid = constrOid;
6177 newcon->qual = (Node *) fkconstraint;
6179 tab->constraints = lappend(tab->constraints, newcon);
6183 * Close pk table, but keep lock until we've committed.
6185 heap_close(pkrel, NoLock);
6189 * ALTER TABLE ALTER CONSTRAINT
6191 * Update the attributes of a constraint.
6193 * Currently only works for Foreign Key constraints.
6194 * Foreign keys do not inherit, so we purposely ignore the
6195 * recursion bit here, but we keep the API the same for when
6196 * other constraint types are supported.
6199 ATExecAlterConstraint(Relation rel, AlterTableCmd *cmd,
6200 bool recurse, bool recursing, LOCKMODE lockmode)
6206 Form_pg_constraint currcon = NULL;
6207 Constraint *cmdcon = NULL;
6210 Assert(IsA(cmd->def, Constraint));
6211 cmdcon = (Constraint *) cmd->def;
6213 conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
6216 * Find and check the target constraint
6219 Anum_pg_constraint_conrelid,
6220 BTEqualStrategyNumber, F_OIDEQ,
6221 ObjectIdGetDatum(RelationGetRelid(rel)));
6222 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
6223 true, SnapshotNow, 1, &key);
6225 while (HeapTupleIsValid(contuple = systable_getnext(scan)))
6227 currcon = (Form_pg_constraint) GETSTRUCT(contuple);
6228 if (strcmp(NameStr(currcon->conname), cmdcon->conname) == 0)
6237 (errcode(ERRCODE_UNDEFINED_OBJECT),
6238 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
6239 cmdcon->conname, RelationGetRelationName(rel))));
6241 if (currcon->contype != CONSTRAINT_FOREIGN)
6243 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6244 errmsg("constraint \"%s\" of relation \"%s\" is not a foreign key constraint",
6245 cmdcon->conname, RelationGetRelationName(rel))));
6247 if (currcon->condeferrable != cmdcon->deferrable ||
6248 currcon->condeferred != cmdcon->initdeferred)
6250 HeapTuple copyTuple;
6252 Form_pg_constraint copy_con;
6253 Form_pg_trigger copy_tg;
6259 * Now update the catalog, while we have the door open.
6261 copyTuple = heap_copytuple(contuple);
6262 copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
6263 copy_con->condeferrable = cmdcon->deferrable;
6264 copy_con->condeferred = cmdcon->initdeferred;
6265 simple_heap_update(conrel, ©Tuple->t_self, copyTuple);
6266 CatalogUpdateIndexes(conrel, copyTuple);
6268 InvokeObjectPostAlterHook(ConstraintRelationId,
6269 HeapTupleGetOid(contuple), 0);
6271 heap_freetuple(copyTuple);
6274 * Now we need to update the multiple entries in pg_trigger
6275 * that implement the constraint.
6277 tgrel = heap_open(TriggerRelationId, RowExclusiveLock);
6280 Anum_pg_trigger_tgconstraint,
6281 BTEqualStrategyNumber, F_OIDEQ,
6282 ObjectIdGetDatum(HeapTupleGetOid(contuple)));
6284 tgscan = systable_beginscan(tgrel, TriggerConstraintIndexId, true,
6285 SnapshotNow, 1, &tgkey);
6287 while (HeapTupleIsValid(tgtuple = systable_getnext(tgscan)))
6289 copyTuple = heap_copytuple(tgtuple);
6290 copy_tg = (Form_pg_trigger) GETSTRUCT(copyTuple);
6291 copy_tg->tgdeferrable = cmdcon->deferrable;
6292 copy_tg->tginitdeferred = cmdcon->initdeferred;
6293 simple_heap_update(tgrel, ©Tuple->t_self, copyTuple);
6294 CatalogUpdateIndexes(tgrel, copyTuple);
6296 InvokeObjectPostAlterHook(TriggerRelationId,
6297 HeapTupleGetOid(tgtuple), 0);
6299 heap_freetuple(copyTuple);
6302 systable_endscan(tgscan);
6304 heap_close(tgrel, RowExclusiveLock);
6307 * Invalidate relcache so that others see the new attributes.
6309 CacheInvalidateRelcache(rel);
6312 systable_endscan(scan);
6314 heap_close(conrel, RowExclusiveLock);
6318 * ALTER TABLE VALIDATE CONSTRAINT
6320 * XXX The reason we handle recursion here rather than at Phase 1 is because
6321 * there's no good way to skip recursing when handling foreign keys: there is
6322 * no need to lock children in that case, yet we wouldn't be able to avoid
6323 * doing so at that level.
6326 ATExecValidateConstraint(Relation rel, char *constrName, bool recurse,
6327 bool recursing, LOCKMODE lockmode)
6333 Form_pg_constraint con = NULL;
6336 conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
6339 * Find and check the target constraint
6342 Anum_pg_constraint_conrelid,
6343 BTEqualStrategyNumber, F_OIDEQ,
6344 ObjectIdGetDatum(RelationGetRelid(rel)));
6345 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
6346 true, SnapshotNow, 1, &key);
6348 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
6350 con = (Form_pg_constraint) GETSTRUCT(tuple);
6351 if (strcmp(NameStr(con->conname), constrName) == 0)
6360 (errcode(ERRCODE_UNDEFINED_OBJECT),
6361 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
6362 constrName, RelationGetRelationName(rel))));
6364 if (con->contype != CONSTRAINT_FOREIGN &&
6365 con->contype != CONSTRAINT_CHECK)
6367 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6368 errmsg("constraint \"%s\" of relation \"%s\" is not a foreign key or check constraint",
6369 constrName, RelationGetRelationName(rel))));
6371 if (!con->convalidated)
6373 HeapTuple copyTuple;
6374 Form_pg_constraint copy_con;
6376 if (con->contype == CONSTRAINT_FOREIGN)
6378 Oid conid = HeapTupleGetOid(tuple);
6382 * Triggers are already in place on both tables, so a concurrent
6383 * write that alters the result here is not possible. Normally we
6384 * can run a query here to do the validation, which would only
6385 * require AccessShareLock. In some cases, it is possible that we
6386 * might need to fire triggers to perform the check, so we take a
6387 * lock at RowShareLock level just in case.
6389 refrel = heap_open(con->confrelid, RowShareLock);
6391 validateForeignKeyConstraint(constrName, rel, refrel,
6394 heap_close(refrel, NoLock);
6397 * Foreign keys do not inherit, so we purposely ignore the
6398 * recursion bit here
6401 else if (con->contype == CONSTRAINT_CHECK)
6403 List *children = NIL;
6407 * If we're recursing, the parent has already done this, so skip
6411 children = find_all_inheritors(RelationGetRelid(rel),
6415 * For CHECK constraints, we must ensure that we only mark the
6416 * constraint as validated on the parent if it's already validated
6419 * We recurse before validating on the parent, to reduce risk of
6422 foreach(child, children)
6424 Oid childoid = lfirst_oid(child);
6427 if (childoid == RelationGetRelid(rel))
6431 * If we are told not to recurse, there had better not be any
6432 * child tables; else the addition would put them out of step.
6436 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6437 errmsg("constraint must be validated on child tables too")));
6439 /* find_all_inheritors already got lock */
6440 childrel = heap_open(childoid, NoLock);
6442 ATExecValidateConstraint(childrel, constrName, false,
6444 heap_close(childrel, NoLock);
6447 validateCheckConstraint(rel, tuple);
6450 * Invalidate relcache so that others see the new validated
6453 CacheInvalidateRelcache(rel);
6457 * Now update the catalog, while we have the door open.
6459 copyTuple = heap_copytuple(tuple);
6460 copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
6461 copy_con->convalidated = true;
6462 simple_heap_update(conrel, ©Tuple->t_self, copyTuple);
6463 CatalogUpdateIndexes(conrel, copyTuple);
6465 InvokeObjectPostAlterHook(ConstraintRelationId,
6466 HeapTupleGetOid(tuple), 0);
6468 heap_freetuple(copyTuple);
6471 systable_endscan(scan);
6473 heap_close(conrel, RowExclusiveLock);
6478 * transformColumnNameList - transform list of column names
6480 * Lookup each name and return its attnum and type OID
6483 transformColumnNameList(Oid relId, List *colList,
6484 int16 *attnums, Oid *atttypids)
6492 char *attname = strVal(lfirst(l));
6495 atttuple = SearchSysCacheAttName(relId, attname);
6496 if (!HeapTupleIsValid(atttuple))
6498 (errcode(ERRCODE_UNDEFINED_COLUMN),
6499 errmsg("column \"%s\" referenced in foreign key constraint does not exist",
6501 if (attnum >= INDEX_MAX_KEYS)
6503 (errcode(ERRCODE_TOO_MANY_COLUMNS),
6504 errmsg("cannot have more than %d keys in a foreign key",
6506 attnums[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->attnum;
6507 atttypids[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->atttypid;
6508 ReleaseSysCache(atttuple);
6516 * transformFkeyGetPrimaryKey -
6518 * Look up the names, attnums, and types of the primary key attributes
6519 * for the pkrel. Also return the index OID and index opclasses of the
6520 * index supporting the primary key.
6522 * All parameters except pkrel are output parameters. Also, the function
6523 * return value is the number of attributes in the primary key.
6525 * Used when the column list in the REFERENCES specification is omitted.
6528 transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
6530 int16 *attnums, Oid *atttypids,
6534 ListCell *indexoidscan;
6535 HeapTuple indexTuple = NULL;
6536 Form_pg_index indexStruct = NULL;
6537 Datum indclassDatum;
6539 oidvector *indclass;
6543 * Get the list of index OIDs for the table from the relcache, and look up
6544 * each one in the pg_index syscache until we find one marked primary key
6545 * (hopefully there isn't more than one such). Insist it's valid, too.
6547 *indexOid = InvalidOid;
6549 indexoidlist = RelationGetIndexList(pkrel);
6551 foreach(indexoidscan, indexoidlist)
6553 Oid indexoid = lfirst_oid(indexoidscan);
6555 indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
6556 if (!HeapTupleIsValid(indexTuple))
6557 elog(ERROR, "cache lookup failed for index %u", indexoid);
6558 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
6559 if (indexStruct->indisprimary && IndexIsValid(indexStruct))
6562 * Refuse to use a deferrable primary key. This is per SQL spec,
6563 * and there would be a lot of interesting semantic problems if we
6564 * tried to allow it.
6566 if (!indexStruct->indimmediate)
6568 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6569 errmsg("cannot use a deferrable primary key for referenced table \"%s\"",
6570 RelationGetRelationName(pkrel))));
6572 *indexOid = indexoid;
6575 ReleaseSysCache(indexTuple);
6578 list_free(indexoidlist);
6581 * Check that we found it
6583 if (!OidIsValid(*indexOid))
6585 (errcode(ERRCODE_UNDEFINED_OBJECT),
6586 errmsg("there is no primary key for referenced table \"%s\"",
6587 RelationGetRelationName(pkrel))));
6589 /* Must get indclass the hard way */
6590 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
6591 Anum_pg_index_indclass, &isnull);
6593 indclass = (oidvector *) DatumGetPointer(indclassDatum);
6596 * Now build the list of PK attributes from the indkey definition (we
6597 * assume a primary key cannot have expressional elements)
6600 for (i = 0; i < indexStruct->indnatts; i++)
6602 int pkattno = indexStruct->indkey.values[i];
6604 attnums[i] = pkattno;
6605 atttypids[i] = attnumTypeId(pkrel, pkattno);
6606 opclasses[i] = indclass->values[i];
6607 *attnamelist = lappend(*attnamelist,
6608 makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
6611 ReleaseSysCache(indexTuple);
6617 * transformFkeyCheckAttrs -
6619 * Make sure that the attributes of a referenced table belong to a unique
6620 * (or primary key) constraint. Return the OID of the index supporting
6621 * the constraint, as well as the opclasses associated with the index
6625 transformFkeyCheckAttrs(Relation pkrel,
6626 int numattrs, int16 *attnums,
6627 Oid *opclasses) /* output parameter */
6629 Oid indexoid = InvalidOid;
6631 bool found_deferrable = false;
6633 ListCell *indexoidscan;
6636 * Get the list of index OIDs for the table from the relcache, and look up
6637 * each one in the pg_index syscache, and match unique indexes to the list
6638 * of attnums we are given.
6640 indexoidlist = RelationGetIndexList(pkrel);
6642 foreach(indexoidscan, indexoidlist)
6644 HeapTuple indexTuple;
6645 Form_pg_index indexStruct;
6649 indexoid = lfirst_oid(indexoidscan);
6650 indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
6651 if (!HeapTupleIsValid(indexTuple))
6652 elog(ERROR, "cache lookup failed for index %u", indexoid);
6653 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
6656 * Must have the right number of columns; must be unique and not a
6657 * partial index; forget it if there are any expressions, too. Invalid
6658 * indexes are out as well.
6660 if (indexStruct->indnatts == numattrs &&
6661 indexStruct->indisunique &&
6662 IndexIsValid(indexStruct) &&
6663 heap_attisnull(indexTuple, Anum_pg_index_indpred) &&
6664 heap_attisnull(indexTuple, Anum_pg_index_indexprs))
6666 /* Must get indclass the hard way */
6667 Datum indclassDatum;
6669 oidvector *indclass;
6671 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
6672 Anum_pg_index_indclass, &isnull);
6674 indclass = (oidvector *) DatumGetPointer(indclassDatum);
6677 * The given attnum list may match the index columns in any order.
6678 * Check that each list is a subset of the other.
6680 for (i = 0; i < numattrs; i++)
6683 for (j = 0; j < numattrs; j++)
6685 if (attnums[i] == indexStruct->indkey.values[j])
6696 for (i = 0; i < numattrs; i++)
6699 for (j = 0; j < numattrs; j++)
6701 if (attnums[j] == indexStruct->indkey.values[i])
6703 opclasses[j] = indclass->values[i];
6714 * Refuse to use a deferrable unique/primary key. This is per SQL
6715 * spec, and there would be a lot of interesting semantic problems
6716 * if we tried to allow it.
6718 if (found && !indexStruct->indimmediate)
6721 * Remember that we found an otherwise matching index, so that
6722 * we can generate a more appropriate error message.
6724 found_deferrable = true;
6728 ReleaseSysCache(indexTuple);
6735 if (found_deferrable)
6737 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6738 errmsg("cannot use a deferrable unique constraint for referenced table \"%s\"",
6739 RelationGetRelationName(pkrel))));
6742 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
6743 errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
6744 RelationGetRelationName(pkrel))));
6747 list_free(indexoidlist);
6755 * Wrapper around find_coercion_pathway() for ATAddForeignKeyConstraint().
6756 * Caller has equal regard for binary coercibility and for an exact match.
6758 static CoercionPathType
6759 findFkeyCast(Oid targetTypeId, Oid sourceTypeId, Oid *funcid)
6761 CoercionPathType ret;
6763 if (targetTypeId == sourceTypeId)
6765 ret = COERCION_PATH_RELABELTYPE;
6766 *funcid = InvalidOid;
6770 ret = find_coercion_pathway(targetTypeId, sourceTypeId,
6771 COERCION_IMPLICIT, funcid);
6772 if (ret == COERCION_PATH_NONE)
6773 /* A previously-relied-upon cast is now gone. */
6774 elog(ERROR, "could not find cast from %u to %u",
6775 sourceTypeId, targetTypeId);
6781 /* Permissions checks for ADD FOREIGN KEY */
6783 checkFkeyPermissions(Relation rel, int16 *attnums, int natts)
6785 Oid roleid = GetUserId();
6786 AclResult aclresult;
6789 /* Okay if we have relation-level REFERENCES permission */
6790 aclresult = pg_class_aclcheck(RelationGetRelid(rel), roleid,
6792 if (aclresult == ACLCHECK_OK)
6794 /* Else we must have REFERENCES on each column */
6795 for (i = 0; i < natts; i++)
6797 aclresult = pg_attribute_aclcheck(RelationGetRelid(rel), attnums[i],
6798 roleid, ACL_REFERENCES);
6799 if (aclresult != ACLCHECK_OK)
6800 aclcheck_error(aclresult, ACL_KIND_CLASS,
6801 RelationGetRelationName(rel));
6806 * Scan the existing rows in a table to verify they meet a proposed
6809 * The caller must have opened and locked the relation appropriately.
6812 validateCheckConstraint(Relation rel, HeapTuple constrtup)
6822 ExprContext *econtext;
6823 MemoryContext oldcxt;
6824 TupleTableSlot *slot;
6825 Form_pg_constraint constrForm;
6828 constrForm = (Form_pg_constraint) GETSTRUCT(constrtup);
6830 estate = CreateExecutorState();
6833 * XXX this tuple doesn't really come from a syscache, but this doesn't
6834 * matter to SysCacheGetAttr, because it only wants to be able to fetch
6837 val = SysCacheGetAttr(CONSTROID, constrtup, Anum_pg_constraint_conbin,
6840 elog(ERROR, "null conbin for constraint %u",
6841 HeapTupleGetOid(constrtup));
6842 conbin = TextDatumGetCString(val);
6843 origexpr = (Expr *) stringToNode(conbin);
6844 exprstate = (List *)
6845 ExecPrepareExpr((Expr *) make_ands_implicit(origexpr), estate);
6847 econtext = GetPerTupleExprContext(estate);
6848 tupdesc = RelationGetDescr(rel);
6849 slot = MakeSingleTupleTableSlot(tupdesc);
6850 econtext->ecxt_scantuple = slot;
6852 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
6855 * Switch to per-tuple memory context and reset it for each tuple
6856 * produced, so we don't leak memory.
6858 oldcxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
6860 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
6862 ExecStoreTuple(tuple, slot, InvalidBuffer, false);
6864 if (!ExecQual(exprstate, econtext, true))
6866 (errcode(ERRCODE_CHECK_VIOLATION),
6867 errmsg("check constraint \"%s\" is violated by some row",
6868 NameStr(constrForm->conname)),
6869 errtableconstraint(rel, NameStr(constrForm->conname))));
6871 ResetExprContext(econtext);
6874 MemoryContextSwitchTo(oldcxt);
6876 ExecDropSingleTupleTableSlot(slot);
6877 FreeExecutorState(estate);
6881 * Scan the existing rows in a table to verify they meet a proposed FK
6884 * Caller must have opened and locked both relations appropriately.
6887 validateForeignKeyConstraint(char *conname,
6898 (errmsg("validating foreign key constraint \"%s\"", conname)));
6901 * Build a trigger call structure; we'll need it either way.
6903 MemSet(&trig, 0, sizeof(trig));
6904 trig.tgoid = InvalidOid;
6905 trig.tgname = conname;
6906 trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
6907 trig.tgisinternal = TRUE;
6908 trig.tgconstrrelid = RelationGetRelid(pkrel);
6909 trig.tgconstrindid = pkindOid;
6910 trig.tgconstraint = constraintOid;
6911 trig.tgdeferrable = FALSE;
6912 trig.tginitdeferred = FALSE;
6913 /* we needn't fill in tgargs or tgqual */
6916 * See if we can do it with a single LEFT JOIN query. A FALSE result
6917 * indicates we must proceed with the fire-the-trigger method.
6919 if (RI_Initial_Check(&trig, rel, pkrel))
6923 * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
6924 * if that tuple had just been inserted. If any of those fail, it should
6925 * ereport(ERROR) and that's that.
6927 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
6929 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
6931 FunctionCallInfoData fcinfo;
6932 TriggerData trigdata;
6935 * Make a call to the trigger function
6937 * No parameters are passed, but we do set a context
6939 MemSet(&fcinfo, 0, sizeof(fcinfo));
6942 * We assume RI_FKey_check_ins won't look at flinfo...
6944 trigdata.type = T_TriggerData;
6945 trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
6946 trigdata.tg_relation = rel;
6947 trigdata.tg_trigtuple = tuple;
6948 trigdata.tg_newtuple = NULL;
6949 trigdata.tg_trigger = &trig;
6950 trigdata.tg_trigtuplebuf = scan->rs_cbuf;
6951 trigdata.tg_newtuplebuf = InvalidBuffer;
6953 fcinfo.context = (Node *) &trigdata;
6955 RI_FKey_check_ins(&fcinfo);
6962 CreateFKCheckTrigger(RangeVar *myRel, Constraint *fkconstraint,
6963 Oid constraintOid, Oid indexOid, bool on_insert)
6965 CreateTrigStmt *fk_trigger;
6968 * Note: for a self-referential FK (referencing and referenced tables are
6969 * the same), it is important that the ON UPDATE action fires before the
6970 * CHECK action, since both triggers will fire on the same row during an
6971 * UPDATE event; otherwise the CHECK trigger will be checking a non-final
6972 * state of the row. Triggers fire in name order, so we ensure this by
6973 * using names like "RI_ConstraintTrigger_a_NNNN" for the action triggers
6974 * and "RI_ConstraintTrigger_c_NNNN" for the check triggers.
6976 fk_trigger = makeNode(CreateTrigStmt);
6977 fk_trigger->trigname = "RI_ConstraintTrigger_c";
6978 fk_trigger->relation = myRel;
6979 fk_trigger->row = true;
6980 fk_trigger->timing = TRIGGER_TYPE_AFTER;
6982 /* Either ON INSERT or ON UPDATE */
6985 fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
6986 fk_trigger->events = TRIGGER_TYPE_INSERT;
6990 fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
6991 fk_trigger->events = TRIGGER_TYPE_UPDATE;
6994 fk_trigger->columns = NIL;
6995 fk_trigger->whenClause = NULL;
6996 fk_trigger->isconstraint = true;
6997 fk_trigger->deferrable = fkconstraint->deferrable;
6998 fk_trigger->initdeferred = fkconstraint->initdeferred;
6999 fk_trigger->constrrel = fkconstraint->pktable;
7000 fk_trigger->args = NIL;
7002 (void) CreateTrigger(fk_trigger, NULL, constraintOid, indexOid, true);
7004 /* Make changes-so-far visible */
7005 CommandCounterIncrement();
7009 * Create the triggers that implement an FK constraint.
7012 createForeignKeyTriggers(Relation rel, Constraint *fkconstraint,
7013 Oid constraintOid, Oid indexOid)
7016 CreateTrigStmt *fk_trigger;
7019 * Reconstruct a RangeVar for my relation (not passed in, unfortunately).
7021 myRel = makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
7022 pstrdup(RelationGetRelationName(rel)),
7025 /* Make changes-so-far visible */
7026 CommandCounterIncrement();
7029 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
7030 * DELETE action on the referenced table.
7032 fk_trigger = makeNode(CreateTrigStmt);
7033 fk_trigger->trigname = "RI_ConstraintTrigger_a";
7034 fk_trigger->relation = fkconstraint->pktable;
7035 fk_trigger->row = true;
7036 fk_trigger->timing = TRIGGER_TYPE_AFTER;
7037 fk_trigger->events = TRIGGER_TYPE_DELETE;
7038 fk_trigger->columns = NIL;
7039 fk_trigger->whenClause = NULL;
7040 fk_trigger->isconstraint = true;
7041 fk_trigger->constrrel = myRel;
7042 switch (fkconstraint->fk_del_action)
7044 case FKCONSTR_ACTION_NOACTION:
7045 fk_trigger->deferrable = fkconstraint->deferrable;
7046 fk_trigger->initdeferred = fkconstraint->initdeferred;
7047 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
7049 case FKCONSTR_ACTION_RESTRICT:
7050 fk_trigger->deferrable = false;
7051 fk_trigger->initdeferred = false;
7052 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
7054 case FKCONSTR_ACTION_CASCADE:
7055 fk_trigger->deferrable = false;
7056 fk_trigger->initdeferred = false;
7057 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
7059 case FKCONSTR_ACTION_SETNULL:
7060 fk_trigger->deferrable = false;
7061 fk_trigger->initdeferred = false;
7062 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
7064 case FKCONSTR_ACTION_SETDEFAULT:
7065 fk_trigger->deferrable = false;
7066 fk_trigger->initdeferred = false;
7067 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
7070 elog(ERROR, "unrecognized FK action type: %d",
7071 (int) fkconstraint->fk_del_action);
7074 fk_trigger->args = NIL;
7076 (void) CreateTrigger(fk_trigger, NULL, constraintOid, indexOid, true);
7078 /* Make changes-so-far visible */
7079 CommandCounterIncrement();
7082 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
7083 * UPDATE action on the referenced table.
7085 fk_trigger = makeNode(CreateTrigStmt);
7086 fk_trigger->trigname = "RI_ConstraintTrigger_a";
7087 fk_trigger->relation = fkconstraint->pktable;
7088 fk_trigger->row = true;
7089 fk_trigger->timing = TRIGGER_TYPE_AFTER;
7090 fk_trigger->events = TRIGGER_TYPE_UPDATE;
7091 fk_trigger->columns = NIL;
7092 fk_trigger->whenClause = NULL;
7093 fk_trigger->isconstraint = true;
7094 fk_trigger->constrrel = myRel;
7095 switch (fkconstraint->fk_upd_action)
7097 case FKCONSTR_ACTION_NOACTION:
7098 fk_trigger->deferrable = fkconstraint->deferrable;
7099 fk_trigger->initdeferred = fkconstraint->initdeferred;
7100 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
7102 case FKCONSTR_ACTION_RESTRICT:
7103 fk_trigger->deferrable = false;
7104 fk_trigger->initdeferred = false;
7105 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
7107 case FKCONSTR_ACTION_CASCADE:
7108 fk_trigger->deferrable = false;
7109 fk_trigger->initdeferred = false;
7110 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
7112 case FKCONSTR_ACTION_SETNULL:
7113 fk_trigger->deferrable = false;
7114 fk_trigger->initdeferred = false;
7115 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
7117 case FKCONSTR_ACTION_SETDEFAULT:
7118 fk_trigger->deferrable = false;
7119 fk_trigger->initdeferred = false;
7120 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
7123 elog(ERROR, "unrecognized FK action type: %d",
7124 (int) fkconstraint->fk_upd_action);
7127 fk_trigger->args = NIL;
7129 (void) CreateTrigger(fk_trigger, NULL, constraintOid, indexOid, true);
7131 /* Make changes-so-far visible */
7132 CommandCounterIncrement();
7135 * Build and execute CREATE CONSTRAINT TRIGGER statements for the CHECK
7136 * action for both INSERTs and UPDATEs on the referencing table.
7138 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, indexOid, true);
7139 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, indexOid, false);
7143 * ALTER TABLE DROP CONSTRAINT
7145 * Like DROP COLUMN, we can't use the normal ALTER TABLE recursion mechanism.
7148 ATExecDropConstraint(Relation rel, const char *constrName,
7149 DropBehavior behavior,
7150 bool recurse, bool recursing,
7151 bool missing_ok, LOCKMODE lockmode)
7156 Form_pg_constraint con;
7161 bool is_no_inherit_constraint = false;
7163 /* At top level, permission check was done in ATPrepCmd, else do it */
7165 ATSimplePermissions(rel, ATT_TABLE);
7167 conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
7170 * Find and drop the target constraint
7173 Anum_pg_constraint_conrelid,
7174 BTEqualStrategyNumber, F_OIDEQ,
7175 ObjectIdGetDatum(RelationGetRelid(rel)));
7176 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
7177 true, SnapshotNow, 1, &key);
7179 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
7181 ObjectAddress conobj;
7183 con = (Form_pg_constraint) GETSTRUCT(tuple);
7185 if (strcmp(NameStr(con->conname), constrName) != 0)
7188 /* Don't drop inherited constraints */
7189 if (con->coninhcount > 0 && !recursing)
7191 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7192 errmsg("cannot drop inherited constraint \"%s\" of relation \"%s\"",
7193 constrName, RelationGetRelationName(rel))));
7195 is_no_inherit_constraint = con->connoinherit;
7198 * Perform the actual constraint deletion
7200 conobj.classId = ConstraintRelationId;
7201 conobj.objectId = HeapTupleGetOid(tuple);
7202 conobj.objectSubId = 0;
7204 performDeletion(&conobj, behavior, 0);
7208 /* constraint found and dropped -- no need to keep looping */
7212 systable_endscan(scan);
7219 (errcode(ERRCODE_UNDEFINED_OBJECT),
7220 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
7221 constrName, RelationGetRelationName(rel))));
7226 (errmsg("constraint \"%s\" of relation \"%s\" does not exist, skipping",
7227 constrName, RelationGetRelationName(rel))));
7228 heap_close(conrel, RowExclusiveLock);
7234 * Propagate to children as appropriate. Unlike most other ALTER
7235 * routines, we have to do this one level of recursion at a time; we can't
7236 * use find_all_inheritors to do it in one pass.
7238 if (!is_no_inherit_constraint)
7239 children = find_inheritance_children(RelationGetRelid(rel), lockmode);
7243 foreach(child, children)
7245 Oid childrelid = lfirst_oid(child);
7247 HeapTuple copy_tuple;
7249 /* find_inheritance_children already got lock */
7250 childrel = heap_open(childrelid, NoLock);
7251 CheckTableNotInUse(childrel, "ALTER TABLE");
7254 Anum_pg_constraint_conrelid,
7255 BTEqualStrategyNumber, F_OIDEQ,
7256 ObjectIdGetDatum(childrelid));
7257 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
7258 true, SnapshotNow, 1, &key);
7260 /* scan for matching tuple - there should only be one */
7261 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
7263 con = (Form_pg_constraint) GETSTRUCT(tuple);
7265 /* Right now only CHECK constraints can be inherited */
7266 if (con->contype != CONSTRAINT_CHECK)
7269 if (strcmp(NameStr(con->conname), constrName) == 0)
7273 if (!HeapTupleIsValid(tuple))
7275 (errcode(ERRCODE_UNDEFINED_OBJECT),
7276 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
7278 RelationGetRelationName(childrel))));
7280 copy_tuple = heap_copytuple(tuple);
7282 systable_endscan(scan);
7284 con = (Form_pg_constraint) GETSTRUCT(copy_tuple);
7286 if (con->coninhcount <= 0) /* shouldn't happen */
7287 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
7288 childrelid, constrName);
7293 * If the child constraint has other definition sources, just
7294 * decrement its inheritance count; if not, recurse to delete it.
7296 if (con->coninhcount == 1 && !con->conislocal)
7298 /* Time to delete this child constraint, too */
7299 ATExecDropConstraint(childrel, constrName, behavior,
7305 /* Child constraint must survive my deletion */
7307 simple_heap_update(conrel, ©_tuple->t_self, copy_tuple);
7308 CatalogUpdateIndexes(conrel, copy_tuple);
7310 /* Make update visible */
7311 CommandCounterIncrement();
7317 * If we were told to drop ONLY in this table (no recursion), we
7318 * need to mark the inheritors' constraints as locally defined
7319 * rather than inherited.
7322 con->conislocal = true;
7324 simple_heap_update(conrel, ©_tuple->t_self, copy_tuple);
7325 CatalogUpdateIndexes(conrel, copy_tuple);
7327 /* Make update visible */
7328 CommandCounterIncrement();
7331 heap_freetuple(copy_tuple);
7333 heap_close(childrel, NoLock);
7336 heap_close(conrel, RowExclusiveLock);
7343 ATPrepAlterColumnType(List **wqueue,
7344 AlteredTableInfo *tab, Relation rel,
7345 bool recurse, bool recursing,
7346 AlterTableCmd *cmd, LOCKMODE lockmode)
7348 char *colName = cmd->name;
7349 ColumnDef *def = (ColumnDef *) cmd->def;
7350 TypeName *typeName = def->typeName;
7351 Node *transform = def->raw_default;
7353 Form_pg_attribute attTup;
7358 NewColumnValue *newval;
7359 ParseState *pstate = make_parsestate(NULL);
7360 AclResult aclresult;
7362 if (rel->rd_rel->reloftype && !recursing)
7364 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7365 errmsg("cannot alter column type of typed table")));
7367 /* lookup the attribute so we can check inheritance status */
7368 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
7369 if (!HeapTupleIsValid(tuple))
7371 (errcode(ERRCODE_UNDEFINED_COLUMN),
7372 errmsg("column \"%s\" of relation \"%s\" does not exist",
7373 colName, RelationGetRelationName(rel))));
7374 attTup = (Form_pg_attribute) GETSTRUCT(tuple);
7375 attnum = attTup->attnum;
7377 /* Can't alter a system attribute */
7380 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7381 errmsg("cannot alter system column \"%s\"",
7384 /* Don't alter inherited columns */
7385 if (attTup->attinhcount > 0 && !recursing)
7387 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7388 errmsg("cannot alter inherited column \"%s\"",
7391 /* Look up the target type */
7392 typenameTypeIdAndMod(NULL, typeName, &targettype, &targettypmod);
7394 aclresult = pg_type_aclcheck(targettype, GetUserId(), ACL_USAGE);
7395 if (aclresult != ACLCHECK_OK)
7396 aclcheck_error_type(aclresult, targettype);
7398 /* And the collation */
7399 targetcollid = GetColumnDefCollation(NULL, def, targettype);
7401 /* make sure datatype is legal for a column */
7402 CheckAttributeType(colName, targettype, targetcollid,
7403 list_make1_oid(rel->rd_rel->reltype),
7406 if (tab->relkind == RELKIND_RELATION)
7409 * Set up an expression to transform the old data value to the new
7410 * type. If a USING option was given, transform and use that
7411 * expression, else just take the old value and try to coerce it. We
7412 * do this first so that type incompatibility can be detected before
7413 * we waste effort, and because we need the expression to be parsed
7414 * against the original table row type.
7420 /* Expression must be able to access vars of old table */
7421 rte = addRangeTableEntryForRelation(pstate,
7426 addRTEtoQuery(pstate, rte, false, true, true);
7428 transform = transformExpr(pstate, transform,
7429 EXPR_KIND_ALTER_COL_TRANSFORM);
7431 /* It can't return a set */
7432 if (expression_returns_set(transform))
7434 (errcode(ERRCODE_DATATYPE_MISMATCH),
7435 errmsg("transform expression must not return a set")));
7439 transform = (Node *) makeVar(1, attnum,
7440 attTup->atttypid, attTup->atttypmod,
7441 attTup->attcollation,
7445 transform = coerce_to_target_type(pstate,
7446 transform, exprType(transform),
7447 targettype, targettypmod,
7448 COERCION_ASSIGNMENT,
7449 COERCE_IMPLICIT_CAST,
7451 if (transform == NULL)
7453 (errcode(ERRCODE_DATATYPE_MISMATCH),
7454 errmsg("column \"%s\" cannot be cast automatically to type %s",
7455 colName, format_type_be(targettype)),
7456 errhint("Specify a USING expression to perform the conversion.")));
7458 /* Fix collations after all else */
7459 assign_expr_collations(pstate, transform);
7461 /* Plan the expr now so we can accurately assess the need to rewrite. */
7462 transform = (Node *) expression_planner((Expr *) transform);
7465 * Add a work queue item to make ATRewriteTable update the column
7468 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
7469 newval->attnum = attnum;
7470 newval->expr = (Expr *) transform;
7472 tab->newvals = lappend(tab->newvals, newval);
7473 if (ATColumnChangeRequiresRewrite(transform, attnum))
7474 tab->rewrite = true;
7478 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7479 errmsg("\"%s\" is not a table",
7480 RelationGetRelationName(rel))));
7482 if (tab->relkind == RELKIND_COMPOSITE_TYPE ||
7483 tab->relkind == RELKIND_FOREIGN_TABLE)
7486 * For composite types, do this check now. Tables will check it later
7487 * when the table is being rewritten.
7489 find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
7492 ReleaseSysCache(tuple);
7495 * The recursion case is handled by ATSimpleRecursion. However, if we are
7496 * told not to recurse, there had better not be any child tables; else the
7497 * alter would put them out of step.
7500 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
7501 else if (!recursing &&
7502 find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL)
7504 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7505 errmsg("type of inherited column \"%s\" must be changed in child tables too",
7508 if (tab->relkind == RELKIND_COMPOSITE_TYPE)
7509 ATTypedTableRecursion(wqueue, rel, cmd, lockmode);
7513 * When the data type of a column is changed, a rewrite might not be required
7514 * if the new type is sufficiently identical to the old one, and the USING
7515 * clause isn't trying to insert some other value. It's safe to skip the
7516 * rewrite if the old type is binary coercible to the new type, or if the
7517 * new type is an unconstrained domain over the old type. In the case of a
7518 * constrained domain, we could get by with scanning the table and checking
7519 * the constraint rather than actually rewriting it, but we don't currently
7523 ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno)
7525 Assert(expr != NULL);
7529 /* only one varno, so no need to check that */
7530 if (IsA(expr, Var) &&((Var *) expr)->varattno == varattno)
7532 else if (IsA(expr, RelabelType))
7533 expr = (Node *) ((RelabelType *) expr)->arg;
7534 else if (IsA(expr, CoerceToDomain))
7536 CoerceToDomain *d = (CoerceToDomain *) expr;
7538 if (GetDomainConstraints(d->resulttype) != NIL)
7540 expr = (Node *) d->arg;
7548 ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
7549 AlterTableCmd *cmd, LOCKMODE lockmode)
7551 char *colName = cmd->name;
7552 ColumnDef *def = (ColumnDef *) cmd->def;
7553 TypeName *typeName = def->typeName;
7555 Form_pg_attribute attTup;
7557 HeapTuple typeTuple;
7563 Relation attrelation;
7569 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
7571 /* Look up the target column */
7572 heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
7573 if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
7575 (errcode(ERRCODE_UNDEFINED_COLUMN),
7576 errmsg("column \"%s\" of relation \"%s\" does not exist",
7577 colName, RelationGetRelationName(rel))));
7578 attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
7579 attnum = attTup->attnum;
7581 /* Check for multiple ALTER TYPE on same column --- can't cope */
7582 if (attTup->atttypid != tab->oldDesc->attrs[attnum - 1]->atttypid ||
7583 attTup->atttypmod != tab->oldDesc->attrs[attnum - 1]->atttypmod)
7585 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7586 errmsg("cannot alter type of column \"%s\" twice",
7589 /* Look up the target type (should not fail, since prep found it) */
7590 typeTuple = typenameType(NULL, typeName, &targettypmod);
7591 tform = (Form_pg_type) GETSTRUCT(typeTuple);
7592 targettype = HeapTupleGetOid(typeTuple);
7593 /* And the collation */
7594 targetcollid = GetColumnDefCollation(NULL, def, targettype);
7597 * If there is a default expression for the column, get it and ensure we
7598 * can coerce it to the new datatype. (We must do this before changing
7599 * the column type, because build_column_default itself will try to
7600 * coerce, and will not issue the error message we want if it fails.)
7602 * We remove any implicit coercion steps at the top level of the old
7603 * default expression; this has been agreed to satisfy the principle of
7604 * least surprise. (The conversion to the new column type should act like
7605 * it started from what the user sees as the stored expression, and the
7606 * implicit coercions aren't going to be shown.)
7608 if (attTup->atthasdef)
7610 defaultexpr = build_column_default(rel, attnum);
7611 Assert(defaultexpr);
7612 defaultexpr = strip_implicit_coercions(defaultexpr);
7613 defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
7614 defaultexpr, exprType(defaultexpr),
7615 targettype, targettypmod,
7616 COERCION_ASSIGNMENT,
7617 COERCE_IMPLICIT_CAST,
7619 if (defaultexpr == NULL)
7621 (errcode(ERRCODE_DATATYPE_MISMATCH),
7622 errmsg("default for column \"%s\" cannot be cast automatically to type %s",
7623 colName, format_type_be(targettype))));
7629 * Find everything that depends on the column (constraints, indexes, etc),
7630 * and record enough information to let us recreate the objects.
7632 * The actual recreation does not happen here, but only after we have
7633 * performed all the individual ALTER TYPE operations. We have to save
7634 * the info before executing ALTER TYPE, though, else the deparser will
7637 * There could be multiple entries for the same object, so we must check
7638 * to ensure we process each one only once. Note: we assume that an index
7639 * that implements a constraint will not show a direct dependency on the
7642 depRel = heap_open(DependRelationId, RowExclusiveLock);
7644 ScanKeyInit(&key[0],
7645 Anum_pg_depend_refclassid,
7646 BTEqualStrategyNumber, F_OIDEQ,
7647 ObjectIdGetDatum(RelationRelationId));
7648 ScanKeyInit(&key[1],
7649 Anum_pg_depend_refobjid,
7650 BTEqualStrategyNumber, F_OIDEQ,
7651 ObjectIdGetDatum(RelationGetRelid(rel)));
7652 ScanKeyInit(&key[2],
7653 Anum_pg_depend_refobjsubid,
7654 BTEqualStrategyNumber, F_INT4EQ,
7655 Int32GetDatum((int32) attnum));
7657 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
7658 SnapshotNow, 3, key);
7660 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
7662 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
7663 ObjectAddress foundObject;
7665 /* We don't expect any PIN dependencies on columns */
7666 if (foundDep->deptype == DEPENDENCY_PIN)
7667 elog(ERROR, "cannot alter type of a pinned column");
7669 foundObject.classId = foundDep->classid;
7670 foundObject.objectId = foundDep->objid;
7671 foundObject.objectSubId = foundDep->objsubid;
7673 switch (getObjectClass(&foundObject))
7677 char relKind = get_rel_relkind(foundObject.objectId);
7679 if (relKind == RELKIND_INDEX)
7681 Assert(foundObject.objectSubId == 0);
7682 if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
7684 tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
7685 foundObject.objectId);
7686 tab->changedIndexDefs = lappend(tab->changedIndexDefs,
7687 pg_get_indexdef_string(foundObject.objectId));
7690 else if (relKind == RELKIND_SEQUENCE)
7693 * This must be a SERIAL column's sequence. We need
7694 * not do anything to it.
7696 Assert(foundObject.objectSubId == 0);
7700 /* Not expecting any other direct dependencies... */
7701 elog(ERROR, "unexpected object depending on column: %s",
7702 getObjectDescription(&foundObject));
7707 case OCLASS_CONSTRAINT:
7708 Assert(foundObject.objectSubId == 0);
7709 if (!list_member_oid(tab->changedConstraintOids,
7710 foundObject.objectId))
7712 char *defstring = pg_get_constraintdef_string(foundObject.objectId);
7715 * Put NORMAL dependencies at the front of the list and
7716 * AUTO dependencies at the back. This makes sure that
7717 * foreign-key constraints depending on this column will
7718 * be dropped before unique or primary-key constraints of
7719 * the column; which we must have because the FK
7720 * constraints depend on the indexes belonging to the
7721 * unique constraints.
7723 if (foundDep->deptype == DEPENDENCY_NORMAL)
7725 tab->changedConstraintOids =
7726 lcons_oid(foundObject.objectId,
7727 tab->changedConstraintOids);
7728 tab->changedConstraintDefs =
7730 tab->changedConstraintDefs);
7734 tab->changedConstraintOids =
7735 lappend_oid(tab->changedConstraintOids,
7736 foundObject.objectId);
7737 tab->changedConstraintDefs =
7738 lappend(tab->changedConstraintDefs,
7744 case OCLASS_REWRITE:
7745 /* XXX someday see if we can cope with revising views */
7747 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7748 errmsg("cannot alter type of a column used by a view or rule"),
7749 errdetail("%s depends on column \"%s\"",
7750 getObjectDescription(&foundObject),
7754 case OCLASS_TRIGGER:
7757 * A trigger can depend on a column because the column is
7758 * specified as an update target, or because the column is
7759 * used in the trigger's WHEN condition. The first case would
7760 * not require any extra work, but the second case would
7761 * require updating the WHEN expression, which will take a
7762 * significant amount of new code. Since we can't easily tell
7763 * which case applies, we punt for both. FIXME someday.
7766 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7767 errmsg("cannot alter type of a column used in a trigger definition"),
7768 errdetail("%s depends on column \"%s\"",
7769 getObjectDescription(&foundObject),
7773 case OCLASS_DEFAULT:
7776 * Ignore the column's default expression, since we will fix
7779 Assert(defaultexpr);
7785 case OCLASS_COLLATION:
7786 case OCLASS_CONVERSION:
7787 case OCLASS_LANGUAGE:
7788 case OCLASS_LARGEOBJECT:
7789 case OCLASS_OPERATOR:
7790 case OCLASS_OPCLASS:
7791 case OCLASS_OPFAMILY:
7795 case OCLASS_TSPARSER:
7797 case OCLASS_TSTEMPLATE:
7798 case OCLASS_TSCONFIG:
7800 case OCLASS_DATABASE:
7801 case OCLASS_TBLSPACE:
7803 case OCLASS_FOREIGN_SERVER:
7804 case OCLASS_USER_MAPPING:
7806 case OCLASS_EXTENSION:
7809 * We don't expect any of these sorts of objects to depend on
7812 elog(ERROR, "unexpected object depending on column: %s",
7813 getObjectDescription(&foundObject));
7817 elog(ERROR, "unrecognized object class: %u",
7818 foundObject.classId);
7822 systable_endscan(scan);
7825 * Now scan for dependencies of this column on other things. The only
7826 * thing we should find is the dependency on the column datatype, which we
7827 * want to remove, and possibly a collation dependency.
7829 ScanKeyInit(&key[0],
7830 Anum_pg_depend_classid,
7831 BTEqualStrategyNumber, F_OIDEQ,
7832 ObjectIdGetDatum(RelationRelationId));
7833 ScanKeyInit(&key[1],
7834 Anum_pg_depend_objid,
7835 BTEqualStrategyNumber, F_OIDEQ,
7836 ObjectIdGetDatum(RelationGetRelid(rel)));
7837 ScanKeyInit(&key[2],
7838 Anum_pg_depend_objsubid,
7839 BTEqualStrategyNumber, F_INT4EQ,
7840 Int32GetDatum((int32) attnum));
7842 scan = systable_beginscan(depRel, DependDependerIndexId, true,
7843 SnapshotNow, 3, key);
7845 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
7847 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
7849 if (foundDep->deptype != DEPENDENCY_NORMAL)
7850 elog(ERROR, "found unexpected dependency type '%c'",
7852 if (!(foundDep->refclassid == TypeRelationId &&
7853 foundDep->refobjid == attTup->atttypid) &&
7854 !(foundDep->refclassid == CollationRelationId &&
7855 foundDep->refobjid == attTup->attcollation))
7856 elog(ERROR, "found unexpected dependency for column");
7858 simple_heap_delete(depRel, &depTup->t_self);
7861 systable_endscan(scan);
7863 heap_close(depRel, RowExclusiveLock);
7866 * Here we go --- change the recorded column type and collation. (Note
7867 * heapTup is a copy of the syscache entry, so okay to scribble on.)
7869 attTup->atttypid = targettype;
7870 attTup->atttypmod = targettypmod;
7871 attTup->attcollation = targetcollid;
7872 attTup->attndims = list_length(typeName->arrayBounds);
7873 attTup->attlen = tform->typlen;
7874 attTup->attbyval = tform->typbyval;
7875 attTup->attalign = tform->typalign;
7876 attTup->attstorage = tform->typstorage;
7878 ReleaseSysCache(typeTuple);
7880 simple_heap_update(attrelation, &heapTup->t_self, heapTup);
7882 /* keep system catalog indexes current */
7883 CatalogUpdateIndexes(attrelation, heapTup);
7885 heap_close(attrelation, RowExclusiveLock);
7887 /* Install dependencies on new datatype and collation */
7888 add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
7889 add_column_collation_dependency(RelationGetRelid(rel), attnum, targetcollid);
7892 * Drop any pg_statistic entry for the column, since it's now wrong type
7894 RemoveStatistics(RelationGetRelid(rel), attnum);
7896 InvokeObjectPostAlterHook(RelationRelationId,
7897 RelationGetRelid(rel), attnum);
7900 * Update the default, if present, by brute force --- remove and re-add
7901 * the default. Probably unsafe to take shortcuts, since the new version
7902 * may well have additional dependencies. (It's okay to do this now,
7903 * rather than after other ALTER TYPE commands, since the default won't
7904 * depend on other column types.)
7908 /* Must make new row visible since it will be updated again */
7909 CommandCounterIncrement();
7912 * We use RESTRICT here for safety, but at present we do not expect
7913 * anything to depend on the default.
7915 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true,
7918 StoreAttrDefault(rel, attnum, defaultexpr, true);
7922 heap_freetuple(heapTup);
7926 ATExecAlterColumnGenericOptions(Relation rel,
7927 const char *colName,
7933 ForeignServer *server;
7934 ForeignDataWrapper *fdw;
7938 Datum repl_val[Natts_pg_attribute];
7939 bool repl_null[Natts_pg_attribute];
7940 bool repl_repl[Natts_pg_attribute];
7942 Form_pg_foreign_table fttableform;
7943 Form_pg_attribute atttableform;
7948 /* First, determine FDW validator associated to the foreign table. */
7949 ftrel = heap_open(ForeignTableRelationId, AccessShareLock);
7950 tuple = SearchSysCache1(FOREIGNTABLEREL, rel->rd_id);
7951 if (!HeapTupleIsValid(tuple))
7953 (errcode(ERRCODE_UNDEFINED_OBJECT),
7954 errmsg("foreign table \"%s\" does not exist",
7955 RelationGetRelationName(rel))));
7956 fttableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
7957 server = GetForeignServer(fttableform->ftserver);
7958 fdw = GetForeignDataWrapper(server->fdwid);
7960 heap_close(ftrel, AccessShareLock);
7961 ReleaseSysCache(tuple);
7963 attrel = heap_open(AttributeRelationId, RowExclusiveLock);
7964 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
7965 if (!HeapTupleIsValid(tuple))
7967 (errcode(ERRCODE_UNDEFINED_COLUMN),
7968 errmsg("column \"%s\" of relation \"%s\" does not exist",
7969 colName, RelationGetRelationName(rel))));
7971 /* Prevent them from altering a system attribute */
7972 atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
7973 if (atttableform->attnum <= 0)
7975 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7976 errmsg("cannot alter system column \"%s\"", colName)));
7979 /* Initialize buffers for new tuple values */
7980 memset(repl_val, 0, sizeof(repl_val));
7981 memset(repl_null, false, sizeof(repl_null));
7982 memset(repl_repl, false, sizeof(repl_repl));
7984 /* Extract the current options */
7985 datum = SysCacheGetAttr(ATTNAME,
7987 Anum_pg_attribute_attfdwoptions,
7990 datum = PointerGetDatum(NULL);
7992 /* Transform the options */
7993 datum = transformGenericOptions(AttributeRelationId,
7998 if (PointerIsValid(DatumGetPointer(datum)))
7999 repl_val[Anum_pg_attribute_attfdwoptions - 1] = datum;
8001 repl_null[Anum_pg_attribute_attfdwoptions - 1] = true;
8003 repl_repl[Anum_pg_attribute_attfdwoptions - 1] = true;
8005 /* Everything looks good - update the tuple */
8007 newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrel),
8008 repl_val, repl_null, repl_repl);
8010 simple_heap_update(attrel, &newtuple->t_self, newtuple);
8011 CatalogUpdateIndexes(attrel, newtuple);
8013 InvokeObjectPostAlterHook(RelationRelationId,
8014 RelationGetRelid(rel),
8015 atttableform->attnum);
8017 ReleaseSysCache(tuple);
8019 heap_close(attrel, RowExclusiveLock);
8021 heap_freetuple(newtuple);
8025 * Cleanup after we've finished all the ALTER TYPE operations for a
8026 * particular relation. We have to drop and recreate all the indexes
8027 * and constraints that depend on the altered columns.
8030 ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)
8037 * Re-parse the index and constraint definitions, and attach them to the
8038 * appropriate work queue entries. We do this before dropping because in
8039 * the case of a FOREIGN KEY constraint, we might not yet have exclusive
8040 * lock on the table the constraint is attached to, and we need to get
8041 * that before dropping. It's safe because the parser won't actually look
8042 * at the catalogs to detect the existing entry.
8044 forboth(oid_item, tab->changedConstraintOids,
8045 def_item, tab->changedConstraintDefs)
8046 ATPostAlterTypeParse(lfirst_oid(oid_item), (char *) lfirst(def_item),
8047 wqueue, lockmode, tab->rewrite);
8048 forboth(oid_item, tab->changedIndexOids,
8049 def_item, tab->changedIndexDefs)
8050 ATPostAlterTypeParse(lfirst_oid(oid_item), (char *) lfirst(def_item),
8051 wqueue, lockmode, tab->rewrite);
8054 * Now we can drop the existing constraints and indexes --- constraints
8055 * first, since some of them might depend on the indexes. In fact, we
8056 * have to delete FOREIGN KEY constraints before UNIQUE constraints, but
8057 * we already ordered the constraint list to ensure that would happen. It
8058 * should be okay to use DROP_RESTRICT here, since nothing else should be
8059 * depending on these objects.
8061 foreach(oid_item, tab->changedConstraintOids)
8063 obj.classId = ConstraintRelationId;
8064 obj.objectId = lfirst_oid(oid_item);
8065 obj.objectSubId = 0;
8066 performDeletion(&obj, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
8069 foreach(oid_item, tab->changedIndexOids)
8071 obj.classId = RelationRelationId;
8072 obj.objectId = lfirst_oid(oid_item);
8073 obj.objectSubId = 0;
8074 performDeletion(&obj, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
8078 * The objects will get recreated during subsequent passes over the work
8084 ATPostAlterTypeParse(Oid oldId, char *cmd,
8085 List **wqueue, LOCKMODE lockmode, bool rewrite)
8087 List *raw_parsetree_list;
8088 List *querytree_list;
8089 ListCell *list_item;
8092 * We expect that we will get only ALTER TABLE and CREATE INDEX
8093 * statements. Hence, there is no need to pass them through
8094 * parse_analyze() or the rewriter, but instead we need to pass them
8095 * through parse_utilcmd.c to make them ready for execution.
8097 raw_parsetree_list = raw_parser(cmd);
8098 querytree_list = NIL;
8099 foreach(list_item, raw_parsetree_list)
8101 Node *stmt = (Node *) lfirst(list_item);
8103 if (IsA(stmt, IndexStmt))
8104 querytree_list = lappend(querytree_list,
8105 transformIndexStmt((IndexStmt *) stmt,
8107 else if (IsA(stmt, AlterTableStmt))
8108 querytree_list = list_concat(querytree_list,
8109 transformAlterTableStmt((AlterTableStmt *) stmt,
8112 querytree_list = lappend(querytree_list, stmt);
8116 * Attach each generated command to the proper place in the work queue.
8117 * Note this could result in creation of entirely new work-queue entries.
8119 * Also note that we have to tweak the command subtypes, because it turns
8120 * out that re-creation of indexes and constraints has to act a bit
8121 * differently from initial creation.
8123 foreach(list_item, querytree_list)
8125 Node *stm = (Node *) lfirst(list_item);
8127 AlteredTableInfo *tab;
8129 switch (nodeTag(stm))
8133 IndexStmt *stmt = (IndexStmt *) stm;
8134 AlterTableCmd *newcmd;
8137 TryReuseIndex(oldId, stmt);
8139 rel = relation_openrv(stmt->relation, lockmode);
8140 tab = ATGetQueueEntry(wqueue, rel);
8141 newcmd = makeNode(AlterTableCmd);
8142 newcmd->subtype = AT_ReAddIndex;
8143 newcmd->def = (Node *) stmt;
8144 tab->subcmds[AT_PASS_OLD_INDEX] =
8145 lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
8146 relation_close(rel, NoLock);
8149 case T_AlterTableStmt:
8151 AlterTableStmt *stmt = (AlterTableStmt *) stm;
8154 rel = relation_openrv(stmt->relation, lockmode);
8155 tab = ATGetQueueEntry(wqueue, rel);
8156 foreach(lcmd, stmt->cmds)
8158 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
8161 switch (cmd->subtype)
8164 Assert(IsA(cmd->def, IndexStmt));
8166 TryReuseIndex(get_constraint_index(oldId),
8167 (IndexStmt *) cmd->def);
8168 cmd->subtype = AT_ReAddIndex;
8169 tab->subcmds[AT_PASS_OLD_INDEX] =
8170 lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
8172 case AT_AddConstraint:
8173 Assert(IsA(cmd->def, Constraint));
8174 con = (Constraint *) cmd->def;
8175 /* rewriting neither side of a FK */
8176 if (con->contype == CONSTR_FOREIGN &&
8177 !rewrite && !tab->rewrite)
8178 TryReuseForeignKey(oldId, con);
8179 cmd->subtype = AT_ReAddConstraint;
8180 tab->subcmds[AT_PASS_OLD_CONSTR] =
8181 lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
8184 elog(ERROR, "unexpected statement type: %d",
8185 (int) cmd->subtype);
8188 relation_close(rel, NoLock);
8192 elog(ERROR, "unexpected statement type: %d",
8193 (int) nodeTag(stm));
8199 * Subroutine for ATPostAlterTypeParse(). Calls out to CheckIndexCompatible()
8200 * for the real analysis, then mutates the IndexStmt based on that verdict.
8203 TryReuseIndex(Oid oldId, IndexStmt *stmt)
8205 if (CheckIndexCompatible(oldId,
8209 stmt->excludeOpNames))
8211 Relation irel = index_open(oldId, NoLock);
8213 stmt->oldNode = irel->rd_node.relNode;
8214 index_close(irel, NoLock);
8219 * Subroutine for ATPostAlterTypeParse().
8221 * Stash the old P-F equality operator into the Constraint node, for possible
8222 * use by ATAddForeignKeyConstraint() in determining whether revalidation of
8223 * this constraint can be skipped.
8226 TryReuseForeignKey(Oid oldId, Constraint *con)
8236 Assert(con->contype == CONSTR_FOREIGN);
8237 Assert(con->old_conpfeqop == NIL); /* already prepared this node */
8239 tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(oldId));
8240 if (!HeapTupleIsValid(tup)) /* should not happen */
8241 elog(ERROR, "cache lookup failed for constraint %u", oldId);
8243 adatum = SysCacheGetAttr(CONSTROID, tup,
8244 Anum_pg_constraint_conpfeqop, &isNull);
8246 elog(ERROR, "null conpfeqop for constraint %u", oldId);
8247 arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
8248 numkeys = ARR_DIMS(arr)[0];
8249 /* test follows the one in ri_FetchConstraintInfo() */
8250 if (ARR_NDIM(arr) != 1 ||
8252 ARR_ELEMTYPE(arr) != OIDOID)
8253 elog(ERROR, "conpfeqop is not a 1-D Oid array");
8254 rawarr = (Oid *) ARR_DATA_PTR(arr);
8256 /* stash a List of the operator Oids in our Constraint node */
8257 for (i = 0; i < numkeys; i++)
8258 con->old_conpfeqop = lcons_oid(rawarr[i], con->old_conpfeqop);
8260 ReleaseSysCache(tup);
8266 * recursing is true if we are recursing from a table to its indexes,
8267 * sequences, or toast table. We don't allow the ownership of those things to
8268 * be changed separately from the parent table. Also, we can skip permission
8269 * checks (this is necessary not just an optimization, else we'd fail to
8270 * handle toast tables properly).
8272 * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
8273 * free-standing composite type.
8276 ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
8278 Relation target_rel;
8281 Form_pg_class tuple_class;
8284 * Get exclusive lock till end of transaction on the target table. Use
8285 * relation_open so that we can work on indexes and sequences.
8287 target_rel = relation_open(relationOid, lockmode);
8289 /* Get its pg_class tuple, too */
8290 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
8292 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
8293 if (!HeapTupleIsValid(tuple))
8294 elog(ERROR, "cache lookup failed for relation %u", relationOid);
8295 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
8297 /* Can we change the ownership of this tuple? */
8298 switch (tuple_class->relkind)
8300 case RELKIND_RELATION:
8302 case RELKIND_MATVIEW:
8303 case RELKIND_FOREIGN_TABLE:
8304 /* ok to change owner */
8310 * Because ALTER INDEX OWNER used to be allowed, and in fact
8311 * is generated by old versions of pg_dump, we give a warning
8312 * and do nothing rather than erroring out. Also, to avoid
8313 * unnecessary chatter while restoring those old dumps, say
8314 * nothing at all if the command would be a no-op anyway.
8316 if (tuple_class->relowner != newOwnerId)
8318 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8319 errmsg("cannot change owner of index \"%s\"",
8320 NameStr(tuple_class->relname)),
8321 errhint("Change the ownership of the index's table, instead.")));
8322 /* quick hack to exit via the no-op path */
8323 newOwnerId = tuple_class->relowner;
8326 case RELKIND_SEQUENCE:
8328 tuple_class->relowner != newOwnerId)
8330 /* if it's an owned sequence, disallow changing it by itself */
8334 if (sequenceIsOwned(relationOid, &tableId, &colId))
8336 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8337 errmsg("cannot change owner of sequence \"%s\"",
8338 NameStr(tuple_class->relname)),
8339 errdetail("Sequence \"%s\" is linked to table \"%s\".",
8340 NameStr(tuple_class->relname),
8341 get_rel_name(tableId))));
8344 case RELKIND_COMPOSITE_TYPE:
8348 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8349 errmsg("\"%s\" is a composite type",
8350 NameStr(tuple_class->relname)),
8351 errhint("Use ALTER TYPE instead.")));
8353 case RELKIND_TOASTVALUE:
8359 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8360 errmsg("\"%s\" is not a table, view, sequence, or foreign table",
8361 NameStr(tuple_class->relname))));
8365 * If the new owner is the same as the existing owner, consider the
8366 * command to have succeeded. This is for dump restoration purposes.
8368 if (tuple_class->relowner != newOwnerId)
8370 Datum repl_val[Natts_pg_class];
8371 bool repl_null[Natts_pg_class];
8372 bool repl_repl[Natts_pg_class];
8378 /* skip permission checks when recursing to index or toast table */
8381 /* Superusers can always do it */
8384 Oid namespaceOid = tuple_class->relnamespace;
8385 AclResult aclresult;
8387 /* Otherwise, must be owner of the existing object */
8388 if (!pg_class_ownercheck(relationOid, GetUserId()))
8389 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
8390 RelationGetRelationName(target_rel));
8392 /* Must be able to become new owner */
8393 check_is_member_of_role(GetUserId(), newOwnerId);
8395 /* New owner must have CREATE privilege on namespace */
8396 aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
8398 if (aclresult != ACLCHECK_OK)
8399 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
8400 get_namespace_name(namespaceOid));
8404 memset(repl_null, false, sizeof(repl_null));
8405 memset(repl_repl, false, sizeof(repl_repl));
8407 repl_repl[Anum_pg_class_relowner - 1] = true;
8408 repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
8411 * Determine the modified ACL for the new owner. This is only
8412 * necessary when the ACL is non-null.
8414 aclDatum = SysCacheGetAttr(RELOID, tuple,
8415 Anum_pg_class_relacl,
8419 newAcl = aclnewowner(DatumGetAclP(aclDatum),
8420 tuple_class->relowner, newOwnerId);
8421 repl_repl[Anum_pg_class_relacl - 1] = true;
8422 repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
8425 newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
8427 simple_heap_update(class_rel, &newtuple->t_self, newtuple);
8428 CatalogUpdateIndexes(class_rel, newtuple);
8430 heap_freetuple(newtuple);
8433 * We must similarly update any per-column ACLs to reflect the new
8434 * owner; for neatness reasons that's split out as a subroutine.
8436 change_owner_fix_column_acls(relationOid,
8437 tuple_class->relowner,
8441 * Update owner dependency reference, if any. A composite type has
8442 * none, because it's tracked for the pg_type entry instead of here;
8443 * indexes and TOAST tables don't have their own entries either.
8445 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
8446 tuple_class->relkind != RELKIND_INDEX &&
8447 tuple_class->relkind != RELKIND_TOASTVALUE)
8448 changeDependencyOnOwner(RelationRelationId, relationOid,
8452 * Also change the ownership of the table's row type, if it has one
8454 if (tuple_class->relkind != RELKIND_INDEX)
8455 AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId,
8456 tuple_class->relkind == RELKIND_COMPOSITE_TYPE);
8459 * If we are operating on a table or materialized view, also change
8460 * the ownership of any indexes and sequences that belong to the
8461 * relation, as well as its toast table (if it has one).
8463 if (tuple_class->relkind == RELKIND_RELATION ||
8464 tuple_class->relkind == RELKIND_MATVIEW ||
8465 tuple_class->relkind == RELKIND_TOASTVALUE)
8467 List *index_oid_list;
8470 /* Find all the indexes belonging to this relation */
8471 index_oid_list = RelationGetIndexList(target_rel);
8473 /* For each index, recursively change its ownership */
8474 foreach(i, index_oid_list)
8475 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
8477 list_free(index_oid_list);
8480 if (tuple_class->relkind == RELKIND_RELATION ||
8481 tuple_class->relkind == RELKIND_MATVIEW)
8483 /* If it has a toast table, recurse to change its ownership */
8484 if (tuple_class->reltoastrelid != InvalidOid)
8485 ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
8488 /* If it has dependent sequences, recurse to change them too */
8489 change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
8493 InvokeObjectPostAlterHook(RelationRelationId, relationOid, 0);
8495 ReleaseSysCache(tuple);
8496 heap_close(class_rel, RowExclusiveLock);
8497 relation_close(target_rel, NoLock);
8501 * change_owner_fix_column_acls
8503 * Helper function for ATExecChangeOwner. Scan the columns of the table
8504 * and fix any non-null column ACLs to reflect the new owner.
8507 change_owner_fix_column_acls(Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
8509 Relation attRelation;
8512 HeapTuple attributeTuple;
8514 attRelation = heap_open(AttributeRelationId, RowExclusiveLock);
8515 ScanKeyInit(&key[0],
8516 Anum_pg_attribute_attrelid,
8517 BTEqualStrategyNumber, F_OIDEQ,
8518 ObjectIdGetDatum(relationOid));
8519 scan = systable_beginscan(attRelation, AttributeRelidNumIndexId,
8520 true, SnapshotNow, 1, key);
8521 while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
8523 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
8524 Datum repl_val[Natts_pg_attribute];
8525 bool repl_null[Natts_pg_attribute];
8526 bool repl_repl[Natts_pg_attribute];
8532 /* Ignore dropped columns */
8533 if (att->attisdropped)
8536 aclDatum = heap_getattr(attributeTuple,
8537 Anum_pg_attribute_attacl,
8538 RelationGetDescr(attRelation),
8540 /* Null ACLs do not require changes */
8544 memset(repl_null, false, sizeof(repl_null));
8545 memset(repl_repl, false, sizeof(repl_repl));
8547 newAcl = aclnewowner(DatumGetAclP(aclDatum),
8548 oldOwnerId, newOwnerId);
8549 repl_repl[Anum_pg_attribute_attacl - 1] = true;
8550 repl_val[Anum_pg_attribute_attacl - 1] = PointerGetDatum(newAcl);
8552 newtuple = heap_modify_tuple(attributeTuple,
8553 RelationGetDescr(attRelation),
8554 repl_val, repl_null, repl_repl);
8556 simple_heap_update(attRelation, &newtuple->t_self, newtuple);
8557 CatalogUpdateIndexes(attRelation, newtuple);
8559 heap_freetuple(newtuple);
8561 systable_endscan(scan);
8562 heap_close(attRelation, RowExclusiveLock);
8566 * change_owner_recurse_to_sequences
8568 * Helper function for ATExecChangeOwner. Examines pg_depend searching
8569 * for sequences that are dependent on serial columns, and changes their
8573 change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
8581 * SERIAL sequences are those having an auto dependency on one of the
8582 * table's columns (we don't care *which* column, exactly).
8584 depRel = heap_open(DependRelationId, AccessShareLock);
8586 ScanKeyInit(&key[0],
8587 Anum_pg_depend_refclassid,
8588 BTEqualStrategyNumber, F_OIDEQ,
8589 ObjectIdGetDatum(RelationRelationId));
8590 ScanKeyInit(&key[1],
8591 Anum_pg_depend_refobjid,
8592 BTEqualStrategyNumber, F_OIDEQ,
8593 ObjectIdGetDatum(relationOid));
8594 /* we leave refobjsubid unspecified */
8596 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
8597 SnapshotNow, 2, key);
8599 while (HeapTupleIsValid(tup = systable_getnext(scan)))
8601 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
8604 /* skip dependencies other than auto dependencies on columns */
8605 if (depForm->refobjsubid == 0 ||
8606 depForm->classid != RelationRelationId ||
8607 depForm->objsubid != 0 ||
8608 depForm->deptype != DEPENDENCY_AUTO)
8611 /* Use relation_open just in case it's an index */
8612 seqRel = relation_open(depForm->objid, lockmode);
8614 /* skip non-sequence relations */
8615 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
8617 /* No need to keep the lock */
8618 relation_close(seqRel, lockmode);
8622 /* We don't need to close the sequence while we alter it. */
8623 ATExecChangeOwner(depForm->objid, newOwnerId, true, lockmode);
8625 /* Now we can close it. Keep the lock till end of transaction. */
8626 relation_close(seqRel, NoLock);
8629 systable_endscan(scan);
8631 relation_close(depRel, AccessShareLock);
8635 * ALTER TABLE CLUSTER ON
8637 * The only thing we have to do is to change the indisclustered bits.
8640 ATExecClusterOn(Relation rel, const char *indexName, LOCKMODE lockmode)
8644 indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
8646 if (!OidIsValid(indexOid))
8648 (errcode(ERRCODE_UNDEFINED_OBJECT),
8649 errmsg("index \"%s\" for table \"%s\" does not exist",
8650 indexName, RelationGetRelationName(rel))));
8652 /* Check index is valid to cluster on */
8653 check_index_is_clusterable(rel, indexOid, false, lockmode);
8655 /* And do the work */
8656 mark_index_clustered(rel, indexOid, false);
8660 * ALTER TABLE SET WITHOUT CLUSTER
8662 * We have to find any indexes on the table that have indisclustered bit
8663 * set and turn it off.
8666 ATExecDropCluster(Relation rel, LOCKMODE lockmode)
8668 mark_index_clustered(rel, InvalidOid, false);
8672 * ALTER TABLE SET TABLESPACE
8675 ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, char *tablespacename, LOCKMODE lockmode)
8678 AclResult aclresult;
8680 /* Check that the tablespace exists */
8681 tablespaceId = get_tablespace_oid(tablespacename, false);
8683 /* Check its permissions */
8684 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(), ACL_CREATE);
8685 if (aclresult != ACLCHECK_OK)
8686 aclcheck_error(aclresult, ACL_KIND_TABLESPACE, tablespacename);
8688 /* Save info for Phase 3 to do the real work */
8689 if (OidIsValid(tab->newTableSpace))
8691 (errcode(ERRCODE_SYNTAX_ERROR),
8692 errmsg("cannot have multiple SET TABLESPACE subcommands")));
8693 tab->newTableSpace = tablespaceId;
8697 * Set, reset, or replace reloptions.
8700 ATExecSetRelOptions(Relation rel, List *defList, AlterTableType operation,
8710 Datum repl_val[Natts_pg_class];
8711 bool repl_null[Natts_pg_class];
8712 bool repl_repl[Natts_pg_class];
8713 static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
8715 if (defList == NIL && operation != AT_ReplaceRelOptions)
8716 return; /* nothing to do */
8718 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
8720 /* Fetch heap tuple */
8721 relid = RelationGetRelid(rel);
8722 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
8723 if (!HeapTupleIsValid(tuple))
8724 elog(ERROR, "cache lookup failed for relation %u", relid);
8726 if (operation == AT_ReplaceRelOptions)
8729 * If we're supposed to replace the reloptions list, we just pretend
8730 * there were none before.
8737 /* Get the old reloptions */
8738 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
8742 /* Generate new proposed reloptions (text array) */
8743 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
8744 defList, NULL, validnsps, false,
8745 operation == AT_ResetRelOptions);
8748 switch (rel->rd_rel->relkind)
8750 case RELKIND_RELATION:
8751 case RELKIND_TOASTVALUE:
8753 case RELKIND_MATVIEW:
8754 (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
8757 (void) index_reloptions(rel->rd_am->amoptions, newOptions, true);
8761 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8762 errmsg("\"%s\" is not a table, view, materialized view, index, or TOAST table",
8763 RelationGetRelationName(rel))));
8768 * All we need do here is update the pg_class row; the new options will be
8769 * propagated into relcaches during post-commit cache inval.
8771 memset(repl_val, 0, sizeof(repl_val));
8772 memset(repl_null, false, sizeof(repl_null));
8773 memset(repl_repl, false, sizeof(repl_repl));
8775 if (newOptions != (Datum) 0)
8776 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
8778 repl_null[Anum_pg_class_reloptions - 1] = true;
8780 repl_repl[Anum_pg_class_reloptions - 1] = true;
8782 newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
8783 repl_val, repl_null, repl_repl);
8785 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
8787 CatalogUpdateIndexes(pgclass, newtuple);
8789 InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
8791 heap_freetuple(newtuple);
8793 ReleaseSysCache(tuple);
8795 /* repeat the whole exercise for the toast table, if there's one */
8796 if (OidIsValid(rel->rd_rel->reltoastrelid))
8799 Oid toastid = rel->rd_rel->reltoastrelid;
8801 toastrel = heap_open(toastid, lockmode);
8803 /* Fetch heap tuple */
8804 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(toastid));
8805 if (!HeapTupleIsValid(tuple))
8806 elog(ERROR, "cache lookup failed for relation %u", toastid);
8808 if (operation == AT_ReplaceRelOptions)
8811 * If we're supposed to replace the reloptions list, we just
8812 * pretend there were none before.
8819 /* Get the old reloptions */
8820 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
8824 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
8825 defList, "toast", validnsps, false,
8826 operation == AT_ResetRelOptions);
8828 (void) heap_reloptions(RELKIND_TOASTVALUE, newOptions, true);
8830 memset(repl_val, 0, sizeof(repl_val));
8831 memset(repl_null, false, sizeof(repl_null));
8832 memset(repl_repl, false, sizeof(repl_repl));
8834 if (newOptions != (Datum) 0)
8835 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
8837 repl_null[Anum_pg_class_reloptions - 1] = true;
8839 repl_repl[Anum_pg_class_reloptions - 1] = true;
8841 newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
8842 repl_val, repl_null, repl_repl);
8844 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
8846 CatalogUpdateIndexes(pgclass, newtuple);
8848 InvokeObjectPostAlterHookArg(RelationRelationId,
8849 RelationGetRelid(toastrel), 0,
8852 heap_freetuple(newtuple);
8854 ReleaseSysCache(tuple);
8856 heap_close(toastrel, NoLock);
8859 heap_close(pgclass, RowExclusiveLock);
8863 * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
8864 * rewriting to be done, so we just want to copy the data as fast as possible.
8867 ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode)
8874 RelFileNode newrnode;
8875 SMgrRelation dstrel;
8878 Form_pg_class rd_rel;
8882 * Need lock here in case we are recursing to toast table or index
8884 rel = relation_open(tableOid, lockmode);
8887 * No work if no change in tablespace.
8889 oldTableSpace = rel->rd_rel->reltablespace;
8890 if (newTableSpace == oldTableSpace ||
8891 (newTableSpace == MyDatabaseTableSpace && oldTableSpace == 0))
8893 InvokeObjectPostAlterHook(RelationRelationId,
8894 RelationGetRelid(rel), 0);
8896 relation_close(rel, NoLock);
8901 * We cannot support moving mapped relations into different tablespaces.
8902 * (In particular this eliminates all shared catalogs.)
8904 if (RelationIsMapped(rel))
8906 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8907 errmsg("cannot move system relation \"%s\"",
8908 RelationGetRelationName(rel))));
8910 /* Can't move a non-shared relation into pg_global */
8911 if (newTableSpace == GLOBALTABLESPACE_OID)
8913 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
8914 errmsg("only shared relations can be placed in pg_global tablespace")));
8917 * Don't allow moving temp tables of other backends ... their local buffer
8918 * manager is not going to cope.
8920 if (RELATION_IS_OTHER_TEMP(rel))
8922 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8923 errmsg("cannot move temporary tables of other sessions")));
8925 reltoastrelid = rel->rd_rel->reltoastrelid;
8926 reltoastidxid = rel->rd_rel->reltoastidxid;
8928 /* Get a modifiable copy of the relation's pg_class row */
8929 pg_class = heap_open(RelationRelationId, RowExclusiveLock);
8931 tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(tableOid));
8932 if (!HeapTupleIsValid(tuple))
8933 elog(ERROR, "cache lookup failed for relation %u", tableOid);
8934 rd_rel = (Form_pg_class) GETSTRUCT(tuple);
8937 * Since we copy the file directly without looking at the shared buffers,
8938 * we'd better first flush out any pages of the source relation that are
8939 * in shared buffers. We assume no new changes will be made while we are
8940 * holding exclusive lock on the rel.
8942 FlushRelationBuffers(rel);
8945 * Relfilenodes are not unique across tablespaces, so we need to allocate
8946 * a new one in the new tablespace.
8948 newrelfilenode = GetNewRelFileNode(newTableSpace, NULL,
8949 rel->rd_rel->relpersistence);
8951 /* Open old and new relation */
8952 newrnode = rel->rd_node;
8953 newrnode.relNode = newrelfilenode;
8954 newrnode.spcNode = newTableSpace;
8955 dstrel = smgropen(newrnode, rel->rd_backend);
8957 RelationOpenSmgr(rel);
8960 * Create and copy all forks of the relation, and schedule unlinking of
8961 * old physical files.
8963 * NOTE: any conflict in relfilenode value will be caught in
8964 * RelationCreateStorage().
8966 RelationCreateStorage(newrnode, rel->rd_rel->relpersistence);
8968 /* copy main fork */
8969 copy_relation_data(rel->rd_smgr, dstrel, MAIN_FORKNUM,
8970 rel->rd_rel->relpersistence);
8972 /* copy those extra forks that exist */
8973 for (forkNum = MAIN_FORKNUM + 1; forkNum <= MAX_FORKNUM; forkNum++)
8975 if (smgrexists(rel->rd_smgr, forkNum))
8977 smgrcreate(dstrel, forkNum, false);
8978 copy_relation_data(rel->rd_smgr, dstrel, forkNum,
8979 rel->rd_rel->relpersistence);
8983 /* drop old relation, and close new one */
8984 RelationDropStorage(rel);
8987 /* update the pg_class row */
8988 rd_rel->reltablespace = (newTableSpace == MyDatabaseTableSpace) ? InvalidOid : newTableSpace;
8989 rd_rel->relfilenode = newrelfilenode;
8990 simple_heap_update(pg_class, &tuple->t_self, tuple);
8991 CatalogUpdateIndexes(pg_class, tuple);
8993 InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
8995 heap_freetuple(tuple);
8997 heap_close(pg_class, RowExclusiveLock);
8999 relation_close(rel, NoLock);
9001 /* Make sure the reltablespace change is visible */
9002 CommandCounterIncrement();
9004 /* Move associated toast relation and/or index, too */
9005 if (OidIsValid(reltoastrelid))
9006 ATExecSetTableSpace(reltoastrelid, newTableSpace, lockmode);
9007 if (OidIsValid(reltoastidxid))
9008 ATExecSetTableSpace(reltoastidxid, newTableSpace, lockmode);
9012 * Copy data, block by block
9015 copy_relation_data(SMgrRelation src, SMgrRelation dst,
9016 ForkNumber forkNum, char relpersistence)
9021 BlockNumber nblocks;
9025 * palloc the buffer so that it's MAXALIGN'd. If it were just a local
9026 * char[] array, the compiler might align it on any byte boundary, which
9027 * can seriously hurt transfer speed to and from the kernel; not to
9028 * mention possibly making log_newpage's accesses to the page header fail.
9030 buf = (char *) palloc(BLCKSZ);
9034 * We need to log the copied data in WAL iff WAL archiving/streaming is
9035 * enabled AND it's a permanent relation.
9037 use_wal = XLogIsNeeded() && relpersistence == RELPERSISTENCE_PERMANENT;
9039 nblocks = smgrnblocks(src, forkNum);
9041 for (blkno = 0; blkno < nblocks; blkno++)
9043 /* If we got a cancel signal during the copy of the data, quit */
9044 CHECK_FOR_INTERRUPTS();
9046 smgrread(src, forkNum, blkno, buf);
9048 if (!PageIsVerified(page, blkno))
9050 (errcode(ERRCODE_DATA_CORRUPTED),
9051 errmsg("invalid page in block %u of relation %s",
9053 relpathbackend(src->smgr_rnode.node,
9054 src->smgr_rnode.backend,
9059 log_newpage(&dst->smgr_rnode.node, forkNum, blkno, page);
9061 PageSetChecksumInplace(page, blkno);
9064 * Now write the page. We say isTemp = true even if it's not a temp
9065 * rel, because there's no need for smgr to schedule an fsync for this
9066 * write; we'll do it ourselves below.
9068 smgrextend(dst, forkNum, blkno, buf, true);
9074 * If the rel is WAL-logged, must fsync before commit. We use heap_sync
9075 * to ensure that the toast table gets fsync'd too. (For a temp or
9076 * unlogged rel we don't care since the data will be gone after a crash
9079 * It's obvious that we must do this when not WAL-logging the copy. It's
9080 * less obvious that we have to do it even if we did WAL-log the copied
9081 * pages. The reason is that since we're copying outside shared buffers, a
9082 * CHECKPOINT occurring during the copy has no way to flush the previously
9083 * written data to disk (indeed it won't know the new rel even exists). A
9084 * crash later on would replay WAL from the checkpoint, therefore it
9085 * wouldn't replay our earlier WAL entries. If we do not fsync those pages
9086 * here, they might still not be on disk when the crash occurs.
9088 if (relpersistence == RELPERSISTENCE_PERMANENT)
9089 smgrimmedsync(dst, forkNum);
9093 * ALTER TABLE ENABLE/DISABLE TRIGGER
9095 * We just pass this off to trigger.c.
9098 ATExecEnableDisableTrigger(Relation rel, char *trigname,
9099 char fires_when, bool skip_system, LOCKMODE lockmode)
9101 EnableDisableTrigger(rel, trigname, fires_when, skip_system);
9105 * ALTER TABLE ENABLE/DISABLE RULE
9107 * We just pass this off to rewriteDefine.c.
9110 ATExecEnableDisableRule(Relation rel, char *trigname,
9111 char fires_when, LOCKMODE lockmode)
9113 EnableDisableRule(rel, trigname, fires_when);
9117 * ALTER TABLE INHERIT
9119 * Add a parent to the child's parents. This verifies that all the columns and
9120 * check constraints of the parent appear in the child and that they have the
9121 * same data types and expressions.
9124 ATPrepAddInherit(Relation child_rel)
9126 if (child_rel->rd_rel->reloftype)
9128 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9129 errmsg("cannot change inheritance of typed table")));
9133 ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode)
9135 Relation parent_rel,
9139 HeapTuple inheritsTuple;
9144 * A self-exclusive lock is needed here. See the similar case in
9145 * MergeAttributes() for a full explanation.
9147 parent_rel = heap_openrv(parent, ShareUpdateExclusiveLock);
9150 * Must be owner of both parent and child -- child was checked by
9151 * ATSimplePermissions call in ATPrepCmd
9153 ATSimplePermissions(parent_rel, ATT_TABLE);
9155 /* Permanent rels cannot inherit from temporary ones */
9156 if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
9157 child_rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
9159 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9160 errmsg("cannot inherit from temporary relation \"%s\"",
9161 RelationGetRelationName(parent_rel))));
9163 /* If parent rel is temp, it must belong to this session */
9164 if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
9165 !parent_rel->rd_islocaltemp)
9167 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9168 errmsg("cannot inherit from temporary relation of another session")));
9170 /* Ditto for the child */
9171 if (child_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
9172 !child_rel->rd_islocaltemp)
9174 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9175 errmsg("cannot inherit to temporary relation of another session")));
9178 * Check for duplicates in the list of parents, and determine the highest
9179 * inhseqno already present; we'll use the next one for the new parent.
9180 * (Note: get RowExclusiveLock because we will write pg_inherits below.)
9182 * Note: we do not reject the case where the child already inherits from
9183 * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
9185 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
9187 Anum_pg_inherits_inhrelid,
9188 BTEqualStrategyNumber, F_OIDEQ,
9189 ObjectIdGetDatum(RelationGetRelid(child_rel)));
9190 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
9191 true, SnapshotNow, 1, &key);
9193 /* inhseqno sequences start at 1 */
9195 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
9197 Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
9199 if (inh->inhparent == RelationGetRelid(parent_rel))
9201 (errcode(ERRCODE_DUPLICATE_TABLE),
9202 errmsg("relation \"%s\" would be inherited from more than once",
9203 RelationGetRelationName(parent_rel))));
9204 if (inh->inhseqno > inhseqno)
9205 inhseqno = inh->inhseqno;
9207 systable_endscan(scan);
9210 * Prevent circularity by seeing if proposed parent inherits from child.
9211 * (In particular, this disallows making a rel inherit from itself.)
9213 * This is not completely bulletproof because of race conditions: in
9214 * multi-level inheritance trees, someone else could concurrently be
9215 * making another inheritance link that closes the loop but does not join
9216 * either of the rels we have locked. Preventing that seems to require
9217 * exclusive locks on the entire inheritance tree, which is a cure worse
9218 * than the disease. find_all_inheritors() will cope with circularity
9219 * anyway, so don't sweat it too much.
9221 * We use weakest lock we can on child's children, namely AccessShareLock.
9223 children = find_all_inheritors(RelationGetRelid(child_rel),
9224 AccessShareLock, NULL);
9226 if (list_member_oid(children, RelationGetRelid(parent_rel)))
9228 (errcode(ERRCODE_DUPLICATE_TABLE),
9229 errmsg("circular inheritance not allowed"),
9230 errdetail("\"%s\" is already a child of \"%s\".",
9232 RelationGetRelationName(child_rel))));
9234 /* If parent has OIDs then child must have OIDs */
9235 if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
9237 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9238 errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
9239 RelationGetRelationName(child_rel),
9240 RelationGetRelationName(parent_rel))));
9242 /* Match up the columns and bump attinhcount as needed */
9243 MergeAttributesIntoExisting(child_rel, parent_rel);
9245 /* Match up the constraints and bump coninhcount as needed */
9246 MergeConstraintsIntoExisting(child_rel, parent_rel);
9249 * OK, it looks valid. Make the catalog entries that show inheritance.
9251 StoreCatalogInheritance1(RelationGetRelid(child_rel),
9252 RelationGetRelid(parent_rel),
9256 /* Now we're done with pg_inherits */
9257 heap_close(catalogRelation, RowExclusiveLock);
9259 /* keep our lock on the parent relation until commit */
9260 heap_close(parent_rel, NoLock);
9264 * Obtain the source-text form of the constraint expression for a check
9265 * constraint, given its pg_constraint tuple
9268 decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
9270 Form_pg_constraint con;
9275 con = (Form_pg_constraint) GETSTRUCT(contup);
9276 attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
9278 elog(ERROR, "null conbin for constraint %u", HeapTupleGetOid(contup));
9280 expr = DirectFunctionCall2(pg_get_expr, attr,
9281 ObjectIdGetDatum(con->conrelid));
9282 return TextDatumGetCString(expr);
9286 * Determine whether two check constraints are functionally equivalent
9288 * The test we apply is to see whether they reverse-compile to the same
9289 * source string. This insulates us from issues like whether attributes
9290 * have the same physical column numbers in parent and child relations.
9293 constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
9295 Form_pg_constraint acon = (Form_pg_constraint) GETSTRUCT(a);
9296 Form_pg_constraint bcon = (Form_pg_constraint) GETSTRUCT(b);
9298 if (acon->condeferrable != bcon->condeferrable ||
9299 acon->condeferred != bcon->condeferred ||
9300 strcmp(decompile_conbin(a, tupleDesc),
9301 decompile_conbin(b, tupleDesc)) != 0)
9308 * Check columns in child table match up with columns in parent, and increment
9309 * their attinhcount.
9311 * Called by ATExecAddInherit
9313 * Currently all parent columns must be found in child. Missing columns are an
9314 * error. One day we might consider creating new columns like CREATE TABLE
9315 * does. However, that is widely unpopular --- in the common use case of
9316 * partitioned tables it's a foot-gun.
9318 * The data type must match exactly. If the parent column is NOT NULL then
9319 * the child must be as well. Defaults are not compared, however.
9322 MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel)
9325 AttrNumber parent_attno;
9327 TupleDesc tupleDesc;
9330 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
9332 tupleDesc = RelationGetDescr(parent_rel);
9333 parent_natts = tupleDesc->natts;
9335 for (parent_attno = 1; parent_attno <= parent_natts; parent_attno++)
9337 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
9338 char *attributeName = NameStr(attribute->attname);
9340 /* Ignore dropped columns in the parent. */
9341 if (attribute->attisdropped)
9344 /* Find same column in child (matching on column name). */
9345 tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel),
9347 if (HeapTupleIsValid(tuple))
9349 /* Check they are same type, typmod, and collation */
9350 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
9352 if (attribute->atttypid != childatt->atttypid ||
9353 attribute->atttypmod != childatt->atttypmod)
9355 (errcode(ERRCODE_DATATYPE_MISMATCH),
9356 errmsg("child table \"%s\" has different type for column \"%s\"",
9357 RelationGetRelationName(child_rel),
9360 if (attribute->attcollation != childatt->attcollation)
9362 (errcode(ERRCODE_COLLATION_MISMATCH),
9363 errmsg("child table \"%s\" has different collation for column \"%s\"",
9364 RelationGetRelationName(child_rel),
9368 * Check child doesn't discard NOT NULL property. (Other
9369 * constraints are checked elsewhere.)
9371 if (attribute->attnotnull && !childatt->attnotnull)
9373 (errcode(ERRCODE_DATATYPE_MISMATCH),
9374 errmsg("column \"%s\" in child table must be marked NOT NULL",
9378 * OK, bump the child column's inheritance count. (If we fail
9379 * later on, this change will just roll back.)
9381 childatt->attinhcount++;
9382 simple_heap_update(attrrel, &tuple->t_self, tuple);
9383 CatalogUpdateIndexes(attrrel, tuple);
9384 heap_freetuple(tuple);
9389 (errcode(ERRCODE_DATATYPE_MISMATCH),
9390 errmsg("child table is missing column \"%s\"",
9395 heap_close(attrrel, RowExclusiveLock);
9399 * Check constraints in child table match up with constraints in parent,
9400 * and increment their coninhcount.
9402 * Constraints that are marked ONLY in the parent are ignored.
9404 * Called by ATExecAddInherit
9406 * Currently all constraints in parent must be present in the child. One day we
9407 * may consider adding new constraints like CREATE TABLE does.
9409 * XXX This is O(N^2) which may be an issue with tables with hundreds of
9410 * constraints. As long as tables have more like 10 constraints it shouldn't be
9411 * a problem though. Even 100 constraints ought not be the end of the world.
9413 * XXX See MergeWithExistingConstraint too if you change this code.
9416 MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
9418 Relation catalog_relation;
9419 TupleDesc tuple_desc;
9420 SysScanDesc parent_scan;
9421 ScanKeyData parent_key;
9422 HeapTuple parent_tuple;
9424 catalog_relation = heap_open(ConstraintRelationId, RowExclusiveLock);
9425 tuple_desc = RelationGetDescr(catalog_relation);
9427 /* Outer loop scans through the parent's constraint definitions */
9428 ScanKeyInit(&parent_key,
9429 Anum_pg_constraint_conrelid,
9430 BTEqualStrategyNumber, F_OIDEQ,
9431 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
9432 parent_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
9433 true, SnapshotNow, 1, &parent_key);
9435 while (HeapTupleIsValid(parent_tuple = systable_getnext(parent_scan)))
9437 Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(parent_tuple);
9438 SysScanDesc child_scan;
9439 ScanKeyData child_key;
9440 HeapTuple child_tuple;
9443 if (parent_con->contype != CONSTRAINT_CHECK)
9446 /* if the parent's constraint is marked NO INHERIT, it's not inherited */
9447 if (parent_con->connoinherit)
9450 /* Search for a child constraint matching this one */
9451 ScanKeyInit(&child_key,
9452 Anum_pg_constraint_conrelid,
9453 BTEqualStrategyNumber, F_OIDEQ,
9454 ObjectIdGetDatum(RelationGetRelid(child_rel)));
9455 child_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
9456 true, SnapshotNow, 1, &child_key);
9458 while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
9460 Form_pg_constraint child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
9461 HeapTuple child_copy;
9463 if (child_con->contype != CONSTRAINT_CHECK)
9466 if (strcmp(NameStr(parent_con->conname),
9467 NameStr(child_con->conname)) != 0)
9470 if (!constraints_equivalent(parent_tuple, child_tuple, tuple_desc))
9472 (errcode(ERRCODE_DATATYPE_MISMATCH),
9473 errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
9474 RelationGetRelationName(child_rel),
9475 NameStr(parent_con->conname))));
9477 /* If the constraint is "no inherit" then cannot merge */
9478 if (child_con->connoinherit)
9480 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
9481 errmsg("constraint \"%s\" conflicts with non-inherited constraint on child table \"%s\"",
9482 NameStr(child_con->conname),
9483 RelationGetRelationName(child_rel))));
9486 * OK, bump the child constraint's inheritance count. (If we fail
9487 * later on, this change will just roll back.)
9489 child_copy = heap_copytuple(child_tuple);
9490 child_con = (Form_pg_constraint) GETSTRUCT(child_copy);
9491 child_con->coninhcount++;
9492 simple_heap_update(catalog_relation, &child_copy->t_self, child_copy);
9493 CatalogUpdateIndexes(catalog_relation, child_copy);
9494 heap_freetuple(child_copy);
9500 systable_endscan(child_scan);
9504 (errcode(ERRCODE_DATATYPE_MISMATCH),
9505 errmsg("child table is missing constraint \"%s\"",
9506 NameStr(parent_con->conname))));
9509 systable_endscan(parent_scan);
9510 heap_close(catalog_relation, RowExclusiveLock);
9514 * ALTER TABLE NO INHERIT
9516 * Drop a parent from the child's parents. This just adjusts the attinhcount
9517 * and attislocal of the columns and removes the pg_inherit and pg_depend
9520 * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
9521 * up attislocal stays true, which means if a child is ever removed from a
9522 * parent then its columns will never be automatically dropped which may
9523 * surprise. But at least we'll never surprise by dropping columns someone
9524 * isn't expecting to be dropped which would actually mean data loss.
9526 * coninhcount and conislocal for inherited constraints are adjusted in
9527 * exactly the same way.
9530 ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode)
9532 Relation parent_rel;
9533 Relation catalogRelation;
9536 HeapTuple inheritsTuple,
9543 * AccessShareLock on the parent is probably enough, seeing that DROP
9544 * TABLE doesn't lock parent tables at all. We need some lock since we'll
9545 * be inspecting the parent's schema.
9547 parent_rel = heap_openrv(parent, AccessShareLock);
9550 * We don't bother to check ownership of the parent table --- ownership of
9551 * the child is presumed enough rights.
9555 * Find and destroy the pg_inherits entry linking the two, or error out if
9558 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
9559 ScanKeyInit(&key[0],
9560 Anum_pg_inherits_inhrelid,
9561 BTEqualStrategyNumber, F_OIDEQ,
9562 ObjectIdGetDatum(RelationGetRelid(rel)));
9563 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
9564 true, SnapshotNow, 1, key);
9566 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
9570 inhparent = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
9571 if (inhparent == RelationGetRelid(parent_rel))
9573 simple_heap_delete(catalogRelation, &inheritsTuple->t_self);
9579 systable_endscan(scan);
9580 heap_close(catalogRelation, RowExclusiveLock);
9584 (errcode(ERRCODE_UNDEFINED_TABLE),
9585 errmsg("relation \"%s\" is not a parent of relation \"%s\"",
9586 RelationGetRelationName(parent_rel),
9587 RelationGetRelationName(rel))));
9590 * Search through child columns looking for ones matching parent rel
9592 catalogRelation = heap_open(AttributeRelationId, RowExclusiveLock);
9593 ScanKeyInit(&key[0],
9594 Anum_pg_attribute_attrelid,
9595 BTEqualStrategyNumber, F_OIDEQ,
9596 ObjectIdGetDatum(RelationGetRelid(rel)));
9597 scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
9598 true, SnapshotNow, 1, key);
9599 while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
9601 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
9603 /* Ignore if dropped or not inherited */
9604 if (att->attisdropped)
9606 if (att->attinhcount <= 0)
9609 if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
9610 NameStr(att->attname)))
9612 /* Decrement inhcount and possibly set islocal to true */
9613 HeapTuple copyTuple = heap_copytuple(attributeTuple);
9614 Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
9616 copy_att->attinhcount--;
9617 if (copy_att->attinhcount == 0)
9618 copy_att->attislocal = true;
9620 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
9621 CatalogUpdateIndexes(catalogRelation, copyTuple);
9622 heap_freetuple(copyTuple);
9625 systable_endscan(scan);
9626 heap_close(catalogRelation, RowExclusiveLock);
9629 * Likewise, find inherited check constraints and disinherit them. To do
9630 * this, we first need a list of the names of the parent's check
9631 * constraints. (We cheat a bit by only checking for name matches,
9632 * assuming that the expressions will match.)
9634 catalogRelation = heap_open(ConstraintRelationId, RowExclusiveLock);
9635 ScanKeyInit(&key[0],
9636 Anum_pg_constraint_conrelid,
9637 BTEqualStrategyNumber, F_OIDEQ,
9638 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
9639 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
9640 true, SnapshotNow, 1, key);
9644 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
9646 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
9648 if (con->contype == CONSTRAINT_CHECK)
9649 connames = lappend(connames, pstrdup(NameStr(con->conname)));
9652 systable_endscan(scan);
9654 /* Now scan the child's constraints */
9655 ScanKeyInit(&key[0],
9656 Anum_pg_constraint_conrelid,
9657 BTEqualStrategyNumber, F_OIDEQ,
9658 ObjectIdGetDatum(RelationGetRelid(rel)));
9659 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
9660 true, SnapshotNow, 1, key);
9662 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
9664 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
9668 if (con->contype != CONSTRAINT_CHECK)
9672 foreach(lc, connames)
9674 if (strcmp(NameStr(con->conname), (char *) lfirst(lc)) == 0)
9683 /* Decrement inhcount and possibly set islocal to true */
9684 HeapTuple copyTuple = heap_copytuple(constraintTuple);
9685 Form_pg_constraint copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
9687 if (copy_con->coninhcount <= 0) /* shouldn't happen */
9688 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
9689 RelationGetRelid(rel), NameStr(copy_con->conname));
9691 copy_con->coninhcount--;
9692 if (copy_con->coninhcount == 0)
9693 copy_con->conislocal = true;
9695 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
9696 CatalogUpdateIndexes(catalogRelation, copyTuple);
9697 heap_freetuple(copyTuple);
9701 systable_endscan(scan);
9702 heap_close(catalogRelation, RowExclusiveLock);
9704 drop_parent_dependency(RelationGetRelid(rel),
9706 RelationGetRelid(parent_rel));
9709 * Post alter hook of this inherits. Since object_access_hook doesn't take
9710 * multiple object identifiers, we relay oid of parent relation using
9711 * auxiliary_id argument.
9713 InvokeObjectPostAlterHookArg(InheritsRelationId,
9714 RelationGetRelid(rel), 0,
9715 RelationGetRelid(parent_rel), false);
9717 /* keep our lock on the parent relation until commit */
9718 heap_close(parent_rel, NoLock);
9722 * Drop the dependency created by StoreCatalogInheritance1 (CREATE TABLE
9723 * INHERITS/ALTER TABLE INHERIT -- refclassid will be RelationRelationId) or
9724 * heap_create_with_catalog (CREATE TABLE OF/ALTER TABLE OF -- refclassid will
9725 * be TypeRelationId). There's no convenient way to do this, so go trawling
9726 * through pg_depend.
9729 drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid)
9731 Relation catalogRelation;
9736 catalogRelation = heap_open(DependRelationId, RowExclusiveLock);
9738 ScanKeyInit(&key[0],
9739 Anum_pg_depend_classid,
9740 BTEqualStrategyNumber, F_OIDEQ,
9741 ObjectIdGetDatum(RelationRelationId));
9742 ScanKeyInit(&key[1],
9743 Anum_pg_depend_objid,
9744 BTEqualStrategyNumber, F_OIDEQ,
9745 ObjectIdGetDatum(relid));
9746 ScanKeyInit(&key[2],
9747 Anum_pg_depend_objsubid,
9748 BTEqualStrategyNumber, F_INT4EQ,
9751 scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
9752 SnapshotNow, 3, key);
9754 while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
9756 Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
9758 if (dep->refclassid == refclassid &&
9759 dep->refobjid == refobjid &&
9760 dep->refobjsubid == 0 &&
9761 dep->deptype == DEPENDENCY_NORMAL)
9762 simple_heap_delete(catalogRelation, &depTuple->t_self);
9765 systable_endscan(scan);
9766 heap_close(catalogRelation, RowExclusiveLock);
9772 * Attach a table to a composite type, as though it had been created with CREATE
9773 * TABLE OF. All attname, atttypid, atttypmod and attcollation must match. The
9774 * subject table must not have inheritance parents. These restrictions ensure
9775 * that you cannot create a configuration impossible with CREATE TABLE OF alone.
9778 ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode)
9780 Oid relid = RelationGetRelid(rel);
9783 Relation inheritsRelation,
9787 AttrNumber table_attno,
9789 TupleDesc typeTupleDesc,
9791 ObjectAddress tableobj,
9793 HeapTuple classtuple;
9795 /* Validate the type. */
9796 typetuple = typenameType(NULL, ofTypename, NULL);
9797 check_of_type(typetuple);
9798 typeid = HeapTupleGetOid(typetuple);
9800 /* Fail if the table has any inheritance parents. */
9801 inheritsRelation = heap_open(InheritsRelationId, AccessShareLock);
9803 Anum_pg_inherits_inhrelid,
9804 BTEqualStrategyNumber, F_OIDEQ,
9805 ObjectIdGetDatum(relid));
9806 scan = systable_beginscan(inheritsRelation, InheritsRelidSeqnoIndexId,
9807 true, SnapshotNow, 1, &key);
9808 if (HeapTupleIsValid(systable_getnext(scan)))
9810 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9811 errmsg("typed tables cannot inherit")));
9812 systable_endscan(scan);
9813 heap_close(inheritsRelation, AccessShareLock);
9816 * Check the tuple descriptors for compatibility. Unlike inheritance, we
9817 * require that the order also match. However, attnotnull need not match.
9818 * Also unlike inheritance, we do not require matching relhasoids.
9820 typeTupleDesc = lookup_rowtype_tupdesc(typeid, -1);
9821 tableTupleDesc = RelationGetDescr(rel);
9823 for (type_attno = 1; type_attno <= typeTupleDesc->natts; type_attno++)
9825 Form_pg_attribute type_attr,
9827 const char *type_attname,
9830 /* Get the next non-dropped type attribute. */
9831 type_attr = typeTupleDesc->attrs[type_attno - 1];
9832 if (type_attr->attisdropped)
9834 type_attname = NameStr(type_attr->attname);
9836 /* Get the next non-dropped table attribute. */
9839 if (table_attno > tableTupleDesc->natts)
9841 (errcode(ERRCODE_DATATYPE_MISMATCH),
9842 errmsg("table is missing column \"%s\"",
9844 table_attr = tableTupleDesc->attrs[table_attno++ - 1];
9845 } while (table_attr->attisdropped);
9846 table_attname = NameStr(table_attr->attname);
9849 if (strncmp(table_attname, type_attname, NAMEDATALEN) != 0)
9851 (errcode(ERRCODE_DATATYPE_MISMATCH),
9852 errmsg("table has column \"%s\" where type requires \"%s\"",
9853 table_attname, type_attname)));
9856 if (table_attr->atttypid != type_attr->atttypid ||
9857 table_attr->atttypmod != type_attr->atttypmod ||
9858 table_attr->attcollation != type_attr->attcollation)
9860 (errcode(ERRCODE_DATATYPE_MISMATCH),
9861 errmsg("table \"%s\" has different type for column \"%s\"",
9862 RelationGetRelationName(rel), type_attname)));
9864 DecrTupleDescRefCount(typeTupleDesc);
9866 /* Any remaining columns at the end of the table had better be dropped. */
9867 for (; table_attno <= tableTupleDesc->natts; table_attno++)
9869 Form_pg_attribute table_attr = tableTupleDesc->attrs[table_attno - 1];
9871 if (!table_attr->attisdropped)
9873 (errcode(ERRCODE_DATATYPE_MISMATCH),
9874 errmsg("table has extra column \"%s\"",
9875 NameStr(table_attr->attname))));
9878 /* If the table was already typed, drop the existing dependency. */
9879 if (rel->rd_rel->reloftype)
9880 drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype);
9882 /* Record a dependency on the new type. */
9883 tableobj.classId = RelationRelationId;
9884 tableobj.objectId = relid;
9885 tableobj.objectSubId = 0;
9886 typeobj.classId = TypeRelationId;
9887 typeobj.objectId = typeid;
9888 typeobj.objectSubId = 0;
9889 recordDependencyOn(&tableobj, &typeobj, DEPENDENCY_NORMAL);
9891 /* Update pg_class.reloftype */
9892 relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
9893 classtuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
9894 if (!HeapTupleIsValid(classtuple))
9895 elog(ERROR, "cache lookup failed for relation %u", relid);
9896 ((Form_pg_class) GETSTRUCT(classtuple))->reloftype = typeid;
9897 simple_heap_update(relationRelation, &classtuple->t_self, classtuple);
9898 CatalogUpdateIndexes(relationRelation, classtuple);
9900 InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
9902 heap_freetuple(classtuple);
9903 heap_close(relationRelation, RowExclusiveLock);
9905 ReleaseSysCache(typetuple);
9909 * ALTER TABLE NOT OF
9911 * Detach a typed table from its originating type. Just clear reloftype and
9912 * remove the dependency.
9915 ATExecDropOf(Relation rel, LOCKMODE lockmode)
9917 Oid relid = RelationGetRelid(rel);
9918 Relation relationRelation;
9921 if (!OidIsValid(rel->rd_rel->reloftype))
9923 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9924 errmsg("\"%s\" is not a typed table",
9925 RelationGetRelationName(rel))));
9928 * We don't bother to check ownership of the type --- ownership of the
9929 * table is presumed enough rights. No lock required on the type, either.
9932 drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype);
9934 /* Clear pg_class.reloftype */
9935 relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
9936 tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
9937 if (!HeapTupleIsValid(tuple))
9938 elog(ERROR, "cache lookup failed for relation %u", relid);
9939 ((Form_pg_class) GETSTRUCT(tuple))->reloftype = InvalidOid;
9940 simple_heap_update(relationRelation, &tuple->t_self, tuple);
9941 CatalogUpdateIndexes(relationRelation, tuple);
9943 InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
9945 heap_freetuple(tuple);
9946 heap_close(relationRelation, RowExclusiveLock);
9950 * ALTER FOREIGN TABLE <name> OPTIONS (...)
9953 ATExecGenericOptions(Relation rel, List *options)
9956 ForeignServer *server;
9957 ForeignDataWrapper *fdw;
9960 Datum repl_val[Natts_pg_foreign_table];
9961 bool repl_null[Natts_pg_foreign_table];
9962 bool repl_repl[Natts_pg_foreign_table];
9964 Form_pg_foreign_table tableform;
9969 ftrel = heap_open(ForeignTableRelationId, RowExclusiveLock);
9971 tuple = SearchSysCacheCopy1(FOREIGNTABLEREL, rel->rd_id);
9972 if (!HeapTupleIsValid(tuple))
9974 (errcode(ERRCODE_UNDEFINED_OBJECT),
9975 errmsg("foreign table \"%s\" does not exist",
9976 RelationGetRelationName(rel))));
9977 tableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
9978 server = GetForeignServer(tableform->ftserver);
9979 fdw = GetForeignDataWrapper(server->fdwid);
9981 memset(repl_val, 0, sizeof(repl_val));
9982 memset(repl_null, false, sizeof(repl_null));
9983 memset(repl_repl, false, sizeof(repl_repl));
9985 /* Extract the current options */
9986 datum = SysCacheGetAttr(FOREIGNTABLEREL,
9988 Anum_pg_foreign_table_ftoptions,
9991 datum = PointerGetDatum(NULL);
9993 /* Transform the options */
9994 datum = transformGenericOptions(ForeignTableRelationId,
9999 if (PointerIsValid(DatumGetPointer(datum)))
10000 repl_val[Anum_pg_foreign_table_ftoptions - 1] = datum;
10002 repl_null[Anum_pg_foreign_table_ftoptions - 1] = true;
10004 repl_repl[Anum_pg_foreign_table_ftoptions - 1] = true;
10006 /* Everything looks good - update the tuple */
10008 tuple = heap_modify_tuple(tuple, RelationGetDescr(ftrel),
10009 repl_val, repl_null, repl_repl);
10011 simple_heap_update(ftrel, &tuple->t_self, tuple);
10012 CatalogUpdateIndexes(ftrel, tuple);
10014 InvokeObjectPostAlterHook(ForeignTableRelationId,
10015 RelationGetRelid(rel), 0);
10017 heap_close(ftrel, RowExclusiveLock);
10019 heap_freetuple(tuple);
10023 * Execute ALTER TABLE SET SCHEMA
10026 AlterTableNamespace(AlterObjectSchemaStmt *stmt)
10033 ObjectAddresses *objsMoved;
10035 relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
10036 stmt->missing_ok, false,
10037 RangeVarCallbackForAlterRelation,
10040 if (!OidIsValid(relid))
10043 (errmsg("relation \"%s\" does not exist, skipping",
10044 stmt->relation->relname)));
10048 rel = relation_open(relid, NoLock);
10050 oldNspOid = RelationGetNamespace(rel);
10052 /* If it's an owned sequence, disallow moving it by itself. */
10053 if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
10058 if (sequenceIsOwned(relid, &tableId, &colId))
10060 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10061 errmsg("cannot move an owned sequence into another schema"),
10062 errdetail("Sequence \"%s\" is linked to table \"%s\".",
10063 RelationGetRelationName(rel),
10064 get_rel_name(tableId))));
10067 /* Get and lock schema OID and check its permissions. */
10068 newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
10069 nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
10071 /* common checks on switching namespaces */
10072 CheckSetNamespace(oldNspOid, nspOid, RelationRelationId, relid);
10074 objsMoved = new_object_addresses();
10075 AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
10076 free_object_addresses(objsMoved);
10078 /* close rel, but keep lock until commit */
10079 relation_close(rel, NoLock);
10085 * The guts of relocating a table or materialized view to another namespace:
10086 * besides moving the relation itself, its dependent objects are relocated to
10090 AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid,
10091 ObjectAddresses *objsMoved)
10095 Assert(objsMoved != NULL);
10097 /* OK, modify the pg_class row and pg_depend entry */
10098 classRel = heap_open(RelationRelationId, RowExclusiveLock);
10100 AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
10101 nspOid, true, objsMoved);
10103 /* Fix the table's row type too */
10104 AlterTypeNamespaceInternal(rel->rd_rel->reltype,
10105 nspOid, false, false, objsMoved);
10107 /* Fix other dependent stuff */
10108 if (rel->rd_rel->relkind == RELKIND_RELATION ||
10109 rel->rd_rel->relkind == RELKIND_MATVIEW)
10111 AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
10112 AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
10113 objsMoved, AccessExclusiveLock);
10114 AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
10118 heap_close(classRel, RowExclusiveLock);
10122 * The guts of relocating a relation to another namespace: fix the pg_class
10123 * entry, and the pg_depend entry if any. Caller must already have
10124 * opened and write-locked pg_class.
10127 AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
10128 Oid oldNspOid, Oid newNspOid,
10129 bool hasDependEntry,
10130 ObjectAddresses *objsMoved)
10132 HeapTuple classTup;
10133 Form_pg_class classForm;
10134 ObjectAddress thisobj;
10136 classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
10137 if (!HeapTupleIsValid(classTup))
10138 elog(ERROR, "cache lookup failed for relation %u", relOid);
10139 classForm = (Form_pg_class) GETSTRUCT(classTup);
10141 Assert(classForm->relnamespace == oldNspOid);
10143 thisobj.classId = RelationRelationId;
10144 thisobj.objectId = relOid;
10145 thisobj.objectSubId = 0;
10148 * Do nothing when there's nothing to do.
10150 if (!object_address_present(&thisobj, objsMoved))
10152 /* check for duplicate name (more friendly than unique-index failure) */
10153 if (get_relname_relid(NameStr(classForm->relname),
10154 newNspOid) != InvalidOid)
10156 (errcode(ERRCODE_DUPLICATE_TABLE),
10157 errmsg("relation \"%s\" already exists in schema \"%s\"",
10158 NameStr(classForm->relname),
10159 get_namespace_name(newNspOid))));
10161 /* classTup is a copy, so OK to scribble on */
10162 classForm->relnamespace = newNspOid;
10164 simple_heap_update(classRel, &classTup->t_self, classTup);
10165 CatalogUpdateIndexes(classRel, classTup);
10167 /* Update dependency on schema if caller said so */
10168 if (hasDependEntry &&
10169 changeDependencyFor(RelationRelationId,
10171 NamespaceRelationId,
10174 elog(ERROR, "failed to change schema dependency for relation \"%s\"",
10175 NameStr(classForm->relname));
10177 add_exact_object_address(&thisobj, objsMoved);
10179 InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
10182 heap_freetuple(classTup);
10186 * Move all indexes for the specified relation to another namespace.
10188 * Note: we assume adequate permission checking was done by the caller,
10189 * and that the caller has a suitable lock on the owning relation.
10192 AlterIndexNamespaces(Relation classRel, Relation rel,
10193 Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
10198 indexList = RelationGetIndexList(rel);
10200 foreach(l, indexList)
10202 Oid indexOid = lfirst_oid(l);
10203 ObjectAddress thisobj;
10205 thisobj.classId = RelationRelationId;
10206 thisobj.objectId = indexOid;
10207 thisobj.objectSubId = 0;
10210 * Note: currently, the index will not have its own dependency on the
10211 * namespace, so we don't need to do changeDependencyFor(). There's no
10212 * row type in pg_type, either.
10214 * XXX this objsMoved test may be pointless -- surely we have a single
10215 * dependency link from a relation to each index?
10217 if (!object_address_present(&thisobj, objsMoved))
10219 AlterRelationNamespaceInternal(classRel, indexOid,
10220 oldNspOid, newNspOid,
10222 add_exact_object_address(&thisobj, objsMoved);
10226 list_free(indexList);
10230 * Move all SERIAL-column sequences of the specified relation to another
10233 * Note: we assume adequate permission checking was done by the caller,
10234 * and that the caller has a suitable lock on the owning relation.
10237 AlterSeqNamespaces(Relation classRel, Relation rel,
10238 Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved,
10243 ScanKeyData key[2];
10247 * SERIAL sequences are those having an auto dependency on one of the
10248 * table's columns (we don't care *which* column, exactly).
10250 depRel = heap_open(DependRelationId, AccessShareLock);
10252 ScanKeyInit(&key[0],
10253 Anum_pg_depend_refclassid,
10254 BTEqualStrategyNumber, F_OIDEQ,
10255 ObjectIdGetDatum(RelationRelationId));
10256 ScanKeyInit(&key[1],
10257 Anum_pg_depend_refobjid,
10258 BTEqualStrategyNumber, F_OIDEQ,
10259 ObjectIdGetDatum(RelationGetRelid(rel)));
10260 /* we leave refobjsubid unspecified */
10262 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
10263 SnapshotNow, 2, key);
10265 while (HeapTupleIsValid(tup = systable_getnext(scan)))
10267 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
10270 /* skip dependencies other than auto dependencies on columns */
10271 if (depForm->refobjsubid == 0 ||
10272 depForm->classid != RelationRelationId ||
10273 depForm->objsubid != 0 ||
10274 depForm->deptype != DEPENDENCY_AUTO)
10277 /* Use relation_open just in case it's an index */
10278 seqRel = relation_open(depForm->objid, lockmode);
10280 /* skip non-sequence relations */
10281 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
10283 /* No need to keep the lock */
10284 relation_close(seqRel, lockmode);
10288 /* Fix the pg_class and pg_depend entries */
10289 AlterRelationNamespaceInternal(classRel, depForm->objid,
10290 oldNspOid, newNspOid,
10294 * Sequences have entries in pg_type. We need to be careful to move
10295 * them to the new namespace, too.
10297 AlterTypeNamespaceInternal(RelationGetForm(seqRel)->reltype,
10298 newNspOid, false, false, objsMoved);
10300 /* Now we can close it. Keep the lock till end of transaction. */
10301 relation_close(seqRel, NoLock);
10304 systable_endscan(scan);
10306 relation_close(depRel, AccessShareLock);
10311 * This code supports
10312 * CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
10314 * Because we only support this for TEMP tables, it's sufficient to remember
10315 * the state in a backend-local data structure.
10319 * Register a newly-created relation's ON COMMIT action.
10322 register_on_commit_action(Oid relid, OnCommitAction action)
10325 MemoryContext oldcxt;
10328 * We needn't bother registering the relation unless there is an ON COMMIT
10329 * action we need to take.
10331 if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
10334 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
10336 oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
10338 oc->oncommit = action;
10339 oc->creating_subid = GetCurrentSubTransactionId();
10340 oc->deleting_subid = InvalidSubTransactionId;
10342 on_commits = lcons(oc, on_commits);
10344 MemoryContextSwitchTo(oldcxt);
10348 * Unregister any ON COMMIT action when a relation is deleted.
10350 * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
10353 remove_on_commit_action(Oid relid)
10357 foreach(l, on_commits)
10359 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
10361 if (oc->relid == relid)
10363 oc->deleting_subid = GetCurrentSubTransactionId();
10370 * Perform ON COMMIT actions.
10372 * This is invoked just before actually committing, since it's possible
10373 * to encounter errors.
10376 PreCommit_on_commit_actions(void)
10379 List *oids_to_truncate = NIL;
10381 foreach(l, on_commits)
10383 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
10385 /* Ignore entry if already dropped in this xact */
10386 if (oc->deleting_subid != InvalidSubTransactionId)
10389 switch (oc->oncommit)
10391 case ONCOMMIT_NOOP:
10392 case ONCOMMIT_PRESERVE_ROWS:
10393 /* Do nothing (there shouldn't be such entries, actually) */
10395 case ONCOMMIT_DELETE_ROWS:
10398 * If this transaction hasn't accessed any temporary
10399 * relations, we can skip truncating ON COMMIT DELETE ROWS
10400 * tables, as they must still be empty.
10402 if (MyXactAccessedTempRel)
10403 oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
10405 case ONCOMMIT_DROP:
10407 ObjectAddress object;
10409 object.classId = RelationRelationId;
10410 object.objectId = oc->relid;
10411 object.objectSubId = 0;
10414 * Since this is an automatic drop, rather than one
10415 * directly initiated by the user, we pass the
10416 * PERFORM_DELETION_INTERNAL flag.
10418 performDeletion(&object,
10419 DROP_CASCADE, PERFORM_DELETION_INTERNAL);
10422 * Note that table deletion will call
10423 * remove_on_commit_action, so the entry should get marked
10426 Assert(oc->deleting_subid != InvalidSubTransactionId);
10431 if (oids_to_truncate != NIL)
10433 heap_truncate(oids_to_truncate);
10434 CommandCounterIncrement(); /* XXX needed? */
10439 * Post-commit or post-abort cleanup for ON COMMIT management.
10441 * All we do here is remove no-longer-needed OnCommitItem entries.
10443 * During commit, remove entries that were deleted during this transaction;
10444 * during abort, remove those created during this transaction.
10447 AtEOXact_on_commit_actions(bool isCommit)
10449 ListCell *cur_item;
10450 ListCell *prev_item;
10453 cur_item = list_head(on_commits);
10455 while (cur_item != NULL)
10457 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
10459 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
10460 oc->creating_subid != InvalidSubTransactionId)
10462 /* cur_item must be removed */
10463 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
10466 cur_item = lnext(prev_item);
10468 cur_item = list_head(on_commits);
10472 /* cur_item must be preserved */
10473 oc->creating_subid = InvalidSubTransactionId;
10474 oc->deleting_subid = InvalidSubTransactionId;
10475 prev_item = cur_item;
10476 cur_item = lnext(prev_item);
10482 * Post-subcommit or post-subabort cleanup for ON COMMIT management.
10484 * During subabort, we can immediately remove entries created during this
10485 * subtransaction. During subcommit, just relabel entries marked during
10486 * this subtransaction as being the parent's responsibility.
10489 AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
10490 SubTransactionId parentSubid)
10492 ListCell *cur_item;
10493 ListCell *prev_item;
10496 cur_item = list_head(on_commits);
10498 while (cur_item != NULL)
10500 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
10502 if (!isCommit && oc->creating_subid == mySubid)
10504 /* cur_item must be removed */
10505 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
10508 cur_item = lnext(prev_item);
10510 cur_item = list_head(on_commits);
10514 /* cur_item must be preserved */
10515 if (oc->creating_subid == mySubid)
10516 oc->creating_subid = parentSubid;
10517 if (oc->deleting_subid == mySubid)
10518 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
10519 prev_item = cur_item;
10520 cur_item = lnext(prev_item);
10526 * This is intended as a callback for RangeVarGetRelidExtended(). It allows
10527 * the relation to be locked only if (1) it's a plain table, materialized
10528 * view, or TOAST table and (2) the current user is the owner (or the
10529 * superuser). This meets the permission-checking needs of CLUSTER, REINDEX
10530 * TABLE, and REFRESH MATERIALIZED VIEW; we expose it here so that it can be
10534 RangeVarCallbackOwnsTable(const RangeVar *relation,
10535 Oid relId, Oid oldRelId, void *arg)
10539 /* Nothing to do if the relation was not found. */
10540 if (!OidIsValid(relId))
10544 * If the relation does exist, check whether it's an index. But note that
10545 * the relation might have been dropped between the time we did the name
10546 * lookup and now. In that case, there's nothing to do.
10548 relkind = get_rel_relkind(relId);
10551 if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
10552 relkind != RELKIND_MATVIEW)
10554 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10555 errmsg("\"%s\" is not a table or materialized view", relation->relname)));
10557 /* Check permissions */
10558 if (!pg_class_ownercheck(relId, GetUserId()))
10559 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS, relation->relname);
10563 * Common RangeVarGetRelid callback for rename, set schema, and alter table
10567 RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid,
10570 Node *stmt = (Node *) arg;
10571 ObjectType reltype;
10573 Form_pg_class classform;
10574 AclResult aclresult;
10577 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
10578 if (!HeapTupleIsValid(tuple))
10579 return; /* concurrently dropped */
10580 classform = (Form_pg_class) GETSTRUCT(tuple);
10581 relkind = classform->relkind;
10583 /* Must own relation. */
10584 if (!pg_class_ownercheck(relid, GetUserId()))
10585 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS, rv->relname);
10587 /* No system table modifications unless explicitly allowed. */
10588 if (!allowSystemTableMods && IsSystemClass(classform))
10590 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
10591 errmsg("permission denied: \"%s\" is a system catalog",
10595 * Extract the specified relation type from the statement parse tree.
10597 * Also, for ALTER .. RENAME, check permissions: the user must (still)
10598 * have CREATE rights on the containing namespace.
10600 if (IsA(stmt, RenameStmt))
10602 aclresult = pg_namespace_aclcheck(classform->relnamespace,
10603 GetUserId(), ACL_CREATE);
10604 if (aclresult != ACLCHECK_OK)
10605 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
10606 get_namespace_name(classform->relnamespace));
10607 reltype = ((RenameStmt *) stmt)->renameType;
10609 else if (IsA(stmt, AlterObjectSchemaStmt))
10610 reltype = ((AlterObjectSchemaStmt *) stmt)->objectType;
10612 else if (IsA(stmt, AlterTableStmt))
10613 reltype = ((AlterTableStmt *) stmt)->relkind;
10616 reltype = OBJECT_TABLE; /* placate compiler */
10617 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(stmt));
10621 * For compatibility with prior releases, we allow ALTER TABLE to be used
10622 * with most other types of relations (but not composite types). We allow
10623 * similar flexibility for ALTER INDEX in the case of RENAME, but not
10624 * otherwise. Otherwise, the user must select the correct form of the
10625 * command for the relation at issue.
10627 if (reltype == OBJECT_SEQUENCE && relkind != RELKIND_SEQUENCE)
10629 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10630 errmsg("\"%s\" is not a sequence", rv->relname)));
10632 if (reltype == OBJECT_VIEW && relkind != RELKIND_VIEW)
10634 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10635 errmsg("\"%s\" is not a view", rv->relname)));
10637 if (reltype == OBJECT_MATVIEW && relkind != RELKIND_MATVIEW)
10639 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10640 errmsg("\"%s\" is not a materialized view", rv->relname)));
10642 if (reltype == OBJECT_FOREIGN_TABLE && relkind != RELKIND_FOREIGN_TABLE)
10644 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10645 errmsg("\"%s\" is not a foreign table", rv->relname)));
10647 if (reltype == OBJECT_TYPE && relkind != RELKIND_COMPOSITE_TYPE)
10649 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10650 errmsg("\"%s\" is not a composite type", rv->relname)));
10652 if (reltype == OBJECT_INDEX && relkind != RELKIND_INDEX
10653 && !IsA(stmt, RenameStmt))
10655 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10656 errmsg("\"%s\" is not an index", rv->relname)));
10659 * Don't allow ALTER TABLE on composite types. We want people to use ALTER
10662 if (reltype != OBJECT_TYPE && relkind == RELKIND_COMPOSITE_TYPE)
10664 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10665 errmsg("\"%s\" is a composite type", rv->relname),
10666 errhint("Use ALTER TYPE instead.")));
10669 * Don't allow ALTER TABLE .. SET SCHEMA on relations that can't be moved
10670 * to a different schema, such as indexes and TOAST tables.
10672 if (IsA(stmt, AlterObjectSchemaStmt) &&
10673 relkind != RELKIND_RELATION &&
10674 relkind != RELKIND_VIEW &&
10675 relkind != RELKIND_MATVIEW &&
10676 relkind != RELKIND_SEQUENCE &&
10677 relkind != RELKIND_FOREIGN_TABLE)
10679 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10680 errmsg("\"%s\" is not a table, view, sequence, or foreign table",
10683 ReleaseSysCache(tuple);