1 /*-------------------------------------------------------------------------
4 * Commands for creating and altering table structures and settings
6 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/commands/tablecmds.c
13 *-------------------------------------------------------------------------
17 #include "access/genam.h"
18 #include "access/heapam.h"
19 #include "access/reloptions.h"
20 #include "access/relscan.h"
21 #include "access/sysattr.h"
22 #include "access/xact.h"
23 #include "catalog/catalog.h"
24 #include "catalog/dependency.h"
25 #include "catalog/heap.h"
26 #include "catalog/index.h"
27 #include "catalog/indexing.h"
28 #include "catalog/namespace.h"
29 #include "catalog/objectaccess.h"
30 #include "catalog/pg_collation.h"
31 #include "catalog/pg_constraint.h"
32 #include "catalog/pg_depend.h"
33 #include "catalog/pg_foreign_table.h"
34 #include "catalog/pg_inherits.h"
35 #include "catalog/pg_inherits_fn.h"
36 #include "catalog/pg_namespace.h"
37 #include "catalog/pg_opclass.h"
38 #include "catalog/pg_tablespace.h"
39 #include "catalog/pg_trigger.h"
40 #include "catalog/pg_type.h"
41 #include "catalog/pg_type_fn.h"
42 #include "catalog/storage.h"
43 #include "catalog/toasting.h"
44 #include "commands/cluster.h"
45 #include "commands/comment.h"
46 #include "commands/defrem.h"
47 #include "commands/sequence.h"
48 #include "commands/tablecmds.h"
49 #include "commands/tablespace.h"
50 #include "commands/trigger.h"
51 #include "commands/typecmds.h"
52 #include "executor/executor.h"
53 #include "foreign/foreign.h"
54 #include "miscadmin.h"
55 #include "nodes/makefuncs.h"
56 #include "nodes/nodeFuncs.h"
57 #include "nodes/parsenodes.h"
58 #include "optimizer/clauses.h"
59 #include "optimizer/planner.h"
60 #include "parser/parse_clause.h"
61 #include "parser/parse_coerce.h"
62 #include "parser/parse_collate.h"
63 #include "parser/parse_expr.h"
64 #include "parser/parse_oper.h"
65 #include "parser/parse_relation.h"
66 #include "parser/parse_type.h"
67 #include "parser/parse_utilcmd.h"
68 #include "parser/parser.h"
69 #include "rewrite/rewriteDefine.h"
70 #include "rewrite/rewriteHandler.h"
71 #include "storage/bufmgr.h"
72 #include "storage/lmgr.h"
73 #include "storage/lock.h"
74 #include "storage/predicate.h"
75 #include "storage/smgr.h"
76 #include "utils/acl.h"
77 #include "utils/builtins.h"
78 #include "utils/fmgroids.h"
79 #include "utils/inval.h"
80 #include "utils/lsyscache.h"
81 #include "utils/memutils.h"
82 #include "utils/relcache.h"
83 #include "utils/snapmgr.h"
84 #include "utils/syscache.h"
85 #include "utils/tqual.h"
86 #include "utils/typcache.h"
90 * ON COMMIT action list
92 typedef struct OnCommitItem
94 Oid relid; /* relid of relation */
95 OnCommitAction oncommit; /* what to do at end of xact */
98 * If this entry was created during the current transaction,
99 * creating_subid is the ID of the creating subxact; if created in a prior
100 * transaction, creating_subid is zero. If deleted during the current
101 * transaction, deleting_subid is the ID of the deleting subxact; if no
102 * deletion request is pending, deleting_subid is zero.
104 SubTransactionId creating_subid;
105 SubTransactionId deleting_subid;
108 static List *on_commits = NIL;
112 * State information for ALTER TABLE
114 * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
115 * structs, one for each table modified by the operation (the named table
116 * plus any child tables that are affected). We save lists of subcommands
117 * to apply to this table (possibly modified by parse transformation steps);
118 * these lists will be executed in Phase 2. If a Phase 3 step is needed,
119 * necessary information is stored in the constraints and newvals lists.
121 * Phase 2 is divided into multiple passes; subcommands are executed in
122 * a pass determined by subcommand type.
125 #define AT_PASS_DROP 0 /* DROP (all flavors) */
126 #define AT_PASS_ALTER_TYPE 1 /* ALTER COLUMN TYPE */
127 #define AT_PASS_OLD_INDEX 2 /* re-add existing indexes */
128 #define AT_PASS_OLD_CONSTR 3 /* re-add existing constraints */
129 #define AT_PASS_COL_ATTRS 4 /* set other column attributes */
130 /* We could support a RENAME COLUMN pass here, but not currently used */
131 #define AT_PASS_ADD_COL 5 /* ADD COLUMN */
132 #define AT_PASS_ADD_INDEX 6 /* ADD indexes */
133 #define AT_PASS_ADD_CONSTR 7 /* ADD constraints, defaults */
134 #define AT_PASS_MISC 8 /* other stuff */
135 #define AT_NUM_PASSES 9
137 typedef struct AlteredTableInfo
139 /* Information saved before any work commences: */
140 Oid relid; /* Relation to work on */
141 char relkind; /* Its relkind */
142 TupleDesc oldDesc; /* Pre-modification tuple descriptor */
143 /* Information saved by Phase 1 for Phase 2: */
144 List *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
145 /* Information saved by Phases 1/2 for Phase 3: */
146 List *constraints; /* List of NewConstraint */
147 List *newvals; /* List of NewColumnValue */
148 bool new_notnull; /* T if we added new NOT NULL constraints */
149 bool rewrite; /* T if a rewrite is forced */
150 Oid newTableSpace; /* new tablespace; 0 means no change */
151 /* Objects to rebuild after completing ALTER TYPE operations */
152 List *changedConstraintOids; /* OIDs of constraints to rebuild */
153 List *changedConstraintDefs; /* string definitions of same */
154 List *changedIndexOids; /* OIDs of indexes to rebuild */
155 List *changedIndexDefs; /* string definitions of same */
158 /* Struct describing one new constraint to check in Phase 3 scan */
159 /* Note: new NOT NULL constraints are handled elsewhere */
160 typedef struct NewConstraint
162 char *name; /* Constraint name, or NULL if none */
163 ConstrType contype; /* CHECK or FOREIGN */
164 Oid refrelid; /* PK rel, if FOREIGN */
165 Oid refindid; /* OID of PK's index, if FOREIGN */
166 Oid conid; /* OID of pg_constraint entry, if FOREIGN */
167 Node *qual; /* Check expr or CONSTR_FOREIGN Constraint */
168 List *qualstate; /* Execution state for CHECK */
172 * Struct describing one new column value that needs to be computed during
173 * Phase 3 copy (this could be either a new column with a non-null default, or
174 * a column that we're changing the type of). Columns without such an entry
175 * are just copied from the old table during ATRewriteTable. Note that the
176 * expr is an expression over *old* table values.
178 typedef struct NewColumnValue
180 AttrNumber attnum; /* which column */
181 Expr *expr; /* expression to compute */
182 ExprState *exprstate; /* execution state */
186 * Error-reporting support for RemoveRelations
188 struct dropmsgstrings
191 int nonexistent_code;
192 const char *nonexistent_msg;
193 const char *skipping_msg;
194 const char *nota_msg;
195 const char *drophint_msg;
198 static const struct dropmsgstrings dropmsgstringarray[] = {
200 ERRCODE_UNDEFINED_TABLE,
201 gettext_noop("table \"%s\" does not exist"),
202 gettext_noop("table \"%s\" does not exist, skipping"),
203 gettext_noop("\"%s\" is not a table"),
204 gettext_noop("Use DROP TABLE to remove a table.")},
206 ERRCODE_UNDEFINED_TABLE,
207 gettext_noop("sequence \"%s\" does not exist"),
208 gettext_noop("sequence \"%s\" does not exist, skipping"),
209 gettext_noop("\"%s\" is not a sequence"),
210 gettext_noop("Use DROP SEQUENCE to remove a sequence.")},
212 ERRCODE_UNDEFINED_TABLE,
213 gettext_noop("view \"%s\" does not exist"),
214 gettext_noop("view \"%s\" does not exist, skipping"),
215 gettext_noop("\"%s\" is not a view"),
216 gettext_noop("Use DROP VIEW to remove a view.")},
218 ERRCODE_UNDEFINED_OBJECT,
219 gettext_noop("index \"%s\" does not exist"),
220 gettext_noop("index \"%s\" does not exist, skipping"),
221 gettext_noop("\"%s\" is not an index"),
222 gettext_noop("Use DROP INDEX to remove an index.")},
223 {RELKIND_COMPOSITE_TYPE,
224 ERRCODE_UNDEFINED_OBJECT,
225 gettext_noop("type \"%s\" does not exist"),
226 gettext_noop("type \"%s\" does not exist, skipping"),
227 gettext_noop("\"%s\" is not a type"),
228 gettext_noop("Use DROP TYPE to remove a type.")},
229 {RELKIND_FOREIGN_TABLE,
230 ERRCODE_UNDEFINED_OBJECT,
231 gettext_noop("foreign table \"%s\" does not exist"),
232 gettext_noop("foreign table \"%s\" does not exist, skipping"),
233 gettext_noop("\"%s\" is not a foreign table"),
234 gettext_noop("Use DROP FOREIGN TABLE to remove a foreign table.")},
235 {'\0', 0, NULL, NULL, NULL, NULL}
238 /* Alter table target-type flags for ATSimplePermissions */
239 #define ATT_TABLE 0x0001
240 #define ATT_VIEW 0x0002
241 #define ATT_INDEX 0x0004
242 #define ATT_COMPOSITE_TYPE 0x0008
243 #define ATT_FOREIGN_TABLE 0x0010
245 static void truncate_check_rel(Relation rel);
246 static List *MergeAttributes(List *schema, List *supers, char relpersistence,
247 List **supOids, List **supconstr, int *supOidCount);
248 static bool MergeCheckConstraint(List *constraints, char *name, Node *expr);
249 static bool change_varattnos_walker(Node *node, const AttrNumber *newattno);
250 static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel);
251 static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
252 static void StoreCatalogInheritance(Oid relationId, List *supers);
253 static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
254 int16 seqNumber, Relation inhRelation);
255 static int findAttrByName(const char *attributeName, List *schema);
256 static void setRelhassubclassInRelation(Oid relationId, bool relhassubclass);
257 static void AlterIndexNamespaces(Relation classRel, Relation rel,
258 Oid oldNspOid, Oid newNspOid);
259 static void AlterSeqNamespaces(Relation classRel, Relation rel,
260 Oid oldNspOid, Oid newNspOid,
261 const char *newNspName, LOCKMODE lockmode);
262 static void ATExecValidateConstraint(Relation rel, char *constrName,
263 bool recurse, bool recursing, LOCKMODE lockmode);
264 static int transformColumnNameList(Oid relId, List *colList,
265 int16 *attnums, Oid *atttypids);
266 static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
268 int16 *attnums, Oid *atttypids,
270 static Oid transformFkeyCheckAttrs(Relation pkrel,
271 int numattrs, int16 *attnums,
273 static void checkFkeyPermissions(Relation rel, int16 *attnums, int natts);
274 static void validateCheckConstraint(Relation rel, HeapTuple constrtup);
275 static void validateForeignKeyConstraint(char *conname,
276 Relation rel, Relation pkrel,
277 Oid pkindOid, Oid constraintOid);
278 static void createForeignKeyTriggers(Relation rel, Constraint *fkconstraint,
279 Oid constraintOid, Oid indexOid);
280 static void ATController(Relation rel, List *cmds, bool recurse, LOCKMODE lockmode);
281 static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
282 bool recurse, bool recursing, LOCKMODE lockmode);
283 static void ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode);
284 static void ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
285 AlterTableCmd *cmd, LOCKMODE lockmode);
286 static void ATRewriteTables(List **wqueue, LOCKMODE lockmode);
287 static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap, LOCKMODE lockmode);
288 static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
289 static void ATSimplePermissions(Relation rel, int allowed_targets);
290 static void ATWrongRelkindError(Relation rel, int allowed_targets);
291 static void ATSimpleRecursion(List **wqueue, Relation rel,
292 AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode);
293 static void ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
295 static List *find_typed_table_dependencies(Oid typeOid, const char *typeName,
296 DropBehavior behavior);
297 static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
298 AlterTableCmd *cmd, LOCKMODE lockmode);
299 static void ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel,
300 ColumnDef *colDef, bool isOid,
301 bool recurse, bool recursing, LOCKMODE lockmode);
302 static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
303 static void add_column_collation_dependency(Oid relid, int32 attnum, Oid collid);
304 static void ATPrepAddOids(List **wqueue, Relation rel, bool recurse,
305 AlterTableCmd *cmd, LOCKMODE lockmode);
306 static void ATExecDropNotNull(Relation rel, const char *colName, LOCKMODE lockmode);
307 static void ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
308 const char *colName, LOCKMODE lockmode);
309 static void ATExecColumnDefault(Relation rel, const char *colName,
310 Node *newDefault, LOCKMODE lockmode);
311 static void ATPrepSetStatistics(Relation rel, const char *colName,
312 Node *newValue, LOCKMODE lockmode);
313 static void ATExecSetStatistics(Relation rel, const char *colName,
314 Node *newValue, LOCKMODE lockmode);
315 static void ATExecSetOptions(Relation rel, const char *colName,
316 Node *options, bool isReset, LOCKMODE lockmode);
317 static void ATExecSetStorage(Relation rel, const char *colName,
318 Node *newValue, LOCKMODE lockmode);
319 static void ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
320 AlterTableCmd *cmd, LOCKMODE lockmode);
321 static void ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
322 DropBehavior behavior,
323 bool recurse, bool recursing,
324 bool missing_ok, LOCKMODE lockmode);
325 static void ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
326 IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode);
327 static void ATExecAddConstraint(List **wqueue,
328 AlteredTableInfo *tab, Relation rel,
329 Constraint *newConstraint, bool recurse, LOCKMODE lockmode);
330 static void ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
331 IndexStmt *stmt, LOCKMODE lockmode);
332 static void ATAddCheckConstraint(List **wqueue,
333 AlteredTableInfo *tab, Relation rel,
335 bool recurse, bool recursing, LOCKMODE lockmode);
336 static void ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
337 Constraint *fkconstraint, LOCKMODE lockmode);
338 static void ATExecDropConstraint(Relation rel, const char *constrName,
339 DropBehavior behavior,
340 bool recurse, bool recursing,
341 bool missing_ok, LOCKMODE lockmode);
342 static void ATPrepAlterColumnType(List **wqueue,
343 AlteredTableInfo *tab, Relation rel,
344 bool recurse, bool recursing,
345 AlterTableCmd *cmd, LOCKMODE lockmode);
346 static bool ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno);
347 static void ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
348 AlterTableCmd *cmd, LOCKMODE lockmode);
349 static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode);
350 static void ATPostAlterTypeParse(char *cmd, List **wqueue, LOCKMODE lockmode);
351 static void change_owner_recurse_to_sequences(Oid relationOid,
352 Oid newOwnerId, LOCKMODE lockmode);
353 static void ATExecClusterOn(Relation rel, const char *indexName, LOCKMODE lockmode);
354 static void ATExecDropCluster(Relation rel, LOCKMODE lockmode);
355 static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
356 char *tablespacename, LOCKMODE lockmode);
357 static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode);
358 static void ATExecSetRelOptions(Relation rel, List *defList, bool isReset, LOCKMODE lockmode);
359 static void ATExecEnableDisableTrigger(Relation rel, char *trigname,
360 char fires_when, bool skip_system, LOCKMODE lockmode);
361 static void ATExecEnableDisableRule(Relation rel, char *rulename,
362 char fires_when, LOCKMODE lockmode);
363 static void ATPrepAddInherit(Relation child_rel);
364 static void ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode);
365 static void ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode);
366 static void drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid);
367 static void ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode);
368 static void ATExecDropOf(Relation rel, LOCKMODE lockmode);
369 static void ATExecGenericOptions(Relation rel, List *options);
371 static void copy_relation_data(SMgrRelation rel, SMgrRelation dst,
372 ForkNumber forkNum, char relpersistence);
373 static const char *storage_name(char c);
376 /* ----------------------------------------------------------------
378 * Creates a new relation.
380 * stmt carries parsetree information from an ordinary CREATE TABLE statement.
381 * The other arguments are used to extend the behavior for other cases:
382 * relkind: relkind to assign to the new relation
383 * ownerId: if not InvalidOid, use this as the new relation's owner.
385 * Note that permissions checks are done against current user regardless of
386 * ownerId. A nonzero ownerId is used when someone is creating a relation
387 * "on behalf of" someone else, so we still want to see that the current user
388 * has permissions to do it.
390 * If successful, returns the OID of the new relation.
391 * ----------------------------------------------------------------
394 DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId)
396 char relname[NAMEDATALEN];
398 List *schema = stmt->tableElts;
402 TupleDesc descriptor;
404 List *old_constraints;
408 List *cookedDefaults;
412 static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
416 * Truncate relname to appropriate length (probably a waste of time, as
417 * parser should have done this already).
419 StrNCpy(relname, stmt->relation->relname, NAMEDATALEN);
422 * Check consistency of arguments
424 if (stmt->oncommit != ONCOMMIT_NOOP
425 && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
427 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
428 errmsg("ON COMMIT can only be used on temporary tables")));
429 if (stmt->constraints != NIL && relkind == RELKIND_FOREIGN_TABLE)
431 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
432 errmsg("constraints on foreign tables are not supported")));
435 * Look up the namespace in which we are supposed to create the relation,
436 * and check we have permission to create there.
438 namespaceId = RangeVarGetAndCheckCreationNamespace(stmt->relation);
439 RangeVarAdjustRelationPersistence(stmt->relation, namespaceId);
442 * Security check: disallow creating temp tables from security-restricted
443 * code. This is needed because calling code might not expect untrusted
444 * tables to appear in pg_temp at the front of its search path.
446 if (stmt->relation->relpersistence == RELPERSISTENCE_TEMP
447 && InSecurityRestrictedOperation())
449 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
450 errmsg("cannot create temporary table within security-restricted operation")));
453 * Select tablespace to use. If not specified, use default tablespace
454 * (which may in turn default to database's default).
456 if (stmt->tablespacename)
458 tablespaceId = get_tablespace_oid(stmt->tablespacename, false);
462 tablespaceId = GetDefaultTablespace(stmt->relation->relpersistence);
463 /* note InvalidOid is OK in this case */
466 /* Check permissions except when using database's default */
467 if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
471 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
473 if (aclresult != ACLCHECK_OK)
474 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
475 get_tablespace_name(tablespaceId));
478 /* In all cases disallow placing user relations in pg_global */
479 if (tablespaceId == GLOBALTABLESPACE_OID)
481 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
482 errmsg("only shared relations can be placed in pg_global tablespace")));
484 /* Identify user ID that will own the table */
485 if (!OidIsValid(ownerId))
486 ownerId = GetUserId();
489 * Parse and validate reloptions, if any.
491 reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, validnsps,
494 (void) heap_reloptions(relkind, reloptions, true);
496 if (stmt->ofTypename)
497 ofTypeId = typenameTypeId(NULL, stmt->ofTypename);
499 ofTypeId = InvalidOid;
502 * Look up inheritance ancestors and generate relation schema, including
503 * inherited attributes.
505 schema = MergeAttributes(schema, stmt->inhRelations,
506 stmt->relation->relpersistence,
507 &inheritOids, &old_constraints, &parentOidCount);
510 * Create a tuple descriptor from the relation schema. Note that this
511 * deals with column names, types, and NOT NULL constraints, but not
512 * default values or CHECK constraints; we handle those below.
514 descriptor = BuildDescForRelation(schema);
516 localHasOids = interpretOidsOption(stmt->options);
517 descriptor->tdhasoid = (localHasOids || parentOidCount > 0);
520 * Find columns with default values and prepare for insertion of the
521 * defaults. Pre-cooked (that is, inherited) defaults go into a list of
522 * CookedConstraint structs that we'll pass to heap_create_with_catalog,
523 * while raw defaults go into a list of RawColumnDefault structs that will
524 * be processed by AddRelationNewConstraints. (We can't deal with raw
525 * expressions until we can do transformExpr.)
527 * We can set the atthasdef flags now in the tuple descriptor; this just
528 * saves StoreAttrDefault from having to do an immediate update of the
532 cookedDefaults = NIL;
535 foreach(listptr, schema)
537 ColumnDef *colDef = lfirst(listptr);
541 if (colDef->raw_default != NULL)
543 RawColumnDefault *rawEnt;
545 if (relkind == RELKIND_FOREIGN_TABLE)
547 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
548 errmsg("default values on foreign tables are not supported")));
550 Assert(colDef->cooked_default == NULL);
552 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
553 rawEnt->attnum = attnum;
554 rawEnt->raw_default = colDef->raw_default;
555 rawDefaults = lappend(rawDefaults, rawEnt);
556 descriptor->attrs[attnum - 1]->atthasdef = true;
558 else if (colDef->cooked_default != NULL)
560 CookedConstraint *cooked;
562 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
563 cooked->contype = CONSTR_DEFAULT;
565 cooked->attnum = attnum;
566 cooked->expr = colDef->cooked_default;
567 cooked->skip_validation = false;
568 cooked->is_local = true; /* not used for defaults */
569 cooked->inhcount = 0; /* ditto */
570 cookedDefaults = lappend(cookedDefaults, cooked);
571 descriptor->attrs[attnum - 1]->atthasdef = true;
576 * Create the relation. Inherited defaults and constraints are passed in
577 * for immediate handling --- since they don't need parsing, they can be
578 * stored immediately.
580 relationId = heap_create_with_catalog(relname,
588 list_concat(cookedDefaults,
591 stmt->relation->relpersistence,
599 allowSystemTableMods);
601 /* Store inheritance information for new rel. */
602 StoreCatalogInheritance(relationId, inheritOids);
605 * We must bump the command counter to make the newly-created relation
606 * tuple visible for opening.
608 CommandCounterIncrement();
611 * Open the new relation and acquire exclusive lock on it. This isn't
612 * really necessary for locking out other backends (since they can't see
613 * the new rel anyway until we commit), but it keeps the lock manager from
614 * complaining about deadlock risks.
616 rel = relation_open(relationId, AccessExclusiveLock);
619 * Now add any newly specified column default values and CHECK constraints
620 * to the new relation. These are passed to us in the form of raw
621 * parsetrees; we need to transform them to executable expression trees
622 * before they can be added. The most convenient way to do that is to
623 * apply the parser's transformExpr routine, but transformExpr doesn't
624 * work unless we have a pre-existing relation. So, the transformation has
625 * to be postponed to this final step of CREATE TABLE.
627 if (rawDefaults || stmt->constraints)
628 AddRelationNewConstraints(rel, rawDefaults, stmt->constraints,
632 * Clean up. We keep lock on new relation (although it shouldn't be
633 * visible to anyone else anyway, until commit).
635 relation_close(rel, NoLock);
641 * Emit the right error or warning message for a "DROP" command issued on a
642 * non-existent relation
645 DropErrorMsgNonExistent(const char *relname, char rightkind, bool missing_ok)
647 const struct dropmsgstrings *rentry;
649 for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
651 if (rentry->kind == rightkind)
656 (errcode(rentry->nonexistent_code),
657 errmsg(rentry->nonexistent_msg, relname)));
661 ereport(NOTICE, (errmsg(rentry->skipping_msg, relname)));
667 Assert(rentry->kind != '\0'); /* Should be impossible */
671 * Emit the right error message for a "DROP" command issued on a
672 * relation of the wrong type
675 DropErrorMsgWrongType(const char *relname, char wrongkind, char rightkind)
677 const struct dropmsgstrings *rentry;
678 const struct dropmsgstrings *wentry;
680 for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
681 if (rentry->kind == rightkind)
683 Assert(rentry->kind != '\0');
685 for (wentry = dropmsgstringarray; wentry->kind != '\0'; wentry++)
686 if (wentry->kind == wrongkind)
688 /* wrongkind could be something we don't have in our table... */
691 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
692 errmsg(rentry->nota_msg, relname),
693 (wentry->kind != '\0') ? errhint("%s", _(wentry->drophint_msg)) : 0));
698 * Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW,
702 RemoveRelations(DropStmt *drop)
704 ObjectAddresses *objects;
709 * First we identify all the relations, then we delete them in a single
710 * performMultipleDeletions() call. This is to avoid unwanted DROP
711 * RESTRICT errors if one of the relations depends on another.
714 /* Determine required relkind */
715 switch (drop->removeType)
718 relkind = RELKIND_RELATION;
722 relkind = RELKIND_INDEX;
725 case OBJECT_SEQUENCE:
726 relkind = RELKIND_SEQUENCE;
730 relkind = RELKIND_VIEW;
733 case OBJECT_FOREIGN_TABLE:
734 relkind = RELKIND_FOREIGN_TABLE;
738 elog(ERROR, "unrecognized drop object type: %d",
739 (int) drop->removeType);
740 relkind = 0; /* keep compiler quiet */
744 /* Lock and validate each relation; build a list of object addresses */
745 objects = new_object_addresses();
747 foreach(cell, drop->objects)
749 RangeVar *rel = makeRangeVarFromNameList((List *) lfirst(cell));
752 Form_pg_class classform;
756 * These next few steps are a great deal like relation_openrv, but we
757 * don't bother building a relcache entry since we don't need it.
759 * Check for shared-cache-inval messages before trying to access the
760 * relation. This is needed to cover the case where the name
761 * identifies a rel that has been dropped and recreated since the
762 * start of our transaction: if we don't flush the old syscache entry,
763 * then we'll latch onto that entry and suffer an error later.
765 AcceptInvalidationMessages();
767 /* Look up the appropriate relation using namespace search */
768 relOid = RangeVarGetRelid(rel, true);
771 if (!OidIsValid(relOid))
773 DropErrorMsgNonExistent(rel->relname, relkind, drop->missing_ok);
778 * In DROP INDEX, attempt to acquire lock on the parent table before
779 * locking the index. index_drop() will need this anyway, and since
780 * regular queries lock tables before their indexes, we risk deadlock
781 * if we do it the other way around. No error if we don't find a
782 * pg_index entry, though --- that most likely means it isn't an
783 * index, and we'll fail below.
785 if (relkind == RELKIND_INDEX)
787 tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(relOid));
788 if (HeapTupleIsValid(tuple))
790 Form_pg_index index = (Form_pg_index) GETSTRUCT(tuple);
792 LockRelationOid(index->indrelid, AccessExclusiveLock);
793 ReleaseSysCache(tuple);
797 /* Get the lock before trying to fetch the syscache entry */
798 LockRelationOid(relOid, AccessExclusiveLock);
800 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
801 if (!HeapTupleIsValid(tuple))
802 elog(ERROR, "cache lookup failed for relation %u", relOid);
803 classform = (Form_pg_class) GETSTRUCT(tuple);
805 if (classform->relkind != relkind)
806 DropErrorMsgWrongType(rel->relname, classform->relkind, relkind);
808 /* Allow DROP to either table owner or schema owner */
809 if (!pg_class_ownercheck(relOid, GetUserId()) &&
810 !pg_namespace_ownercheck(classform->relnamespace, GetUserId()))
811 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
814 if (!allowSystemTableMods && IsSystemClass(classform))
816 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
817 errmsg("permission denied: \"%s\" is a system catalog",
820 /* OK, we're ready to delete this one */
821 obj.classId = RelationRelationId;
822 obj.objectId = relOid;
825 add_exact_object_address(&obj, objects);
827 ReleaseSysCache(tuple);
830 performMultipleDeletions(objects, drop->behavior);
832 free_object_addresses(objects);
837 * Executes a TRUNCATE command.
839 * This is a multi-relation truncate. We first open and grab exclusive
840 * lock on all relations involved, checking permissions and otherwise
841 * verifying that the relation is OK for truncation. In CASCADE mode,
842 * relations having FK references to the targeted relations are automatically
843 * added to the group; in RESTRICT mode, we check that all FK references are
844 * internal to the group that's being truncated. Finally all the relations
845 * are truncated and reindexed.
848 ExecuteTruncate(TruncateStmt *stmt)
852 List *seq_relids = NIL;
854 ResultRelInfo *resultRelInfos;
855 ResultRelInfo *resultRelInfo;
856 SubTransactionId mySubid;
860 * Open, exclusive-lock, and check all the explicitly-specified relations
862 foreach(cell, stmt->relations)
864 RangeVar *rv = lfirst(cell);
866 bool recurse = interpretInhOption(rv->inhOpt);
869 rel = heap_openrv(rv, AccessExclusiveLock);
870 myrelid = RelationGetRelid(rel);
871 /* don't throw error for "TRUNCATE foo, foo" */
872 if (list_member_oid(relids, myrelid))
874 heap_close(rel, AccessExclusiveLock);
877 truncate_check_rel(rel);
878 rels = lappend(rels, rel);
879 relids = lappend_oid(relids, myrelid);
886 children = find_all_inheritors(myrelid, AccessExclusiveLock, NULL);
888 foreach(child, children)
890 Oid childrelid = lfirst_oid(child);
892 if (list_member_oid(relids, childrelid))
895 /* find_all_inheritors already got lock */
896 rel = heap_open(childrelid, NoLock);
897 truncate_check_rel(rel);
898 rels = lappend(rels, rel);
899 relids = lappend_oid(relids, childrelid);
905 * In CASCADE mode, suck in all referencing relations as well. This
906 * requires multiple iterations to find indirectly-dependent relations. At
907 * each phase, we need to exclusive-lock new rels before looking for their
908 * dependencies, else we might miss something. Also, we check each rel as
909 * soon as we open it, to avoid a faux pas such as holding lock for a long
910 * time on a rel we have no permissions for.
912 if (stmt->behavior == DROP_CASCADE)
918 newrelids = heap_truncate_find_FKs(relids);
919 if (newrelids == NIL)
920 break; /* nothing else to add */
922 foreach(cell, newrelids)
924 Oid relid = lfirst_oid(cell);
927 rel = heap_open(relid, AccessExclusiveLock);
929 (errmsg("truncate cascades to table \"%s\"",
930 RelationGetRelationName(rel))));
931 truncate_check_rel(rel);
932 rels = lappend(rels, rel);
933 relids = lappend_oid(relids, relid);
939 * Check foreign key references. In CASCADE mode, this should be
940 * unnecessary since we just pulled in all the references; but as a
941 * cross-check, do it anyway if in an Assert-enabled build.
943 #ifdef USE_ASSERT_CHECKING
944 heap_truncate_check_FKs(rels, false);
946 if (stmt->behavior == DROP_RESTRICT)
947 heap_truncate_check_FKs(rels, false);
951 * If we are asked to restart sequences, find all the sequences, lock them
952 * (we need AccessExclusiveLock for ResetSequence), and check permissions.
953 * We want to do this early since it's pointless to do all the truncation
954 * work only to fail on sequence permissions.
956 if (stmt->restart_seqs)
960 Relation rel = (Relation) lfirst(cell);
961 List *seqlist = getOwnedSequences(RelationGetRelid(rel));
964 foreach(seqcell, seqlist)
966 Oid seq_relid = lfirst_oid(seqcell);
969 seq_rel = relation_open(seq_relid, AccessExclusiveLock);
971 /* This check must match AlterSequence! */
972 if (!pg_class_ownercheck(seq_relid, GetUserId()))
973 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
974 RelationGetRelationName(seq_rel));
976 seq_relids = lappend_oid(seq_relids, seq_relid);
978 relation_close(seq_rel, NoLock);
983 /* Prepare to catch AFTER triggers. */
984 AfterTriggerBeginQuery();
987 * To fire triggers, we'll need an EState as well as a ResultRelInfo for
988 * each relation. We don't need to call ExecOpenIndices, though.
990 estate = CreateExecutorState();
991 resultRelInfos = (ResultRelInfo *)
992 palloc(list_length(rels) * sizeof(ResultRelInfo));
993 resultRelInfo = resultRelInfos;
996 Relation rel = (Relation) lfirst(cell);
998 InitResultRelInfo(resultRelInfo,
1000 0, /* dummy rangetable index */
1004 estate->es_result_relations = resultRelInfos;
1005 estate->es_num_result_relations = list_length(rels);
1008 * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
1009 * truncating (this is because one of them might throw an error). Also, if
1010 * we were to allow them to prevent statement execution, that would need
1011 * to be handled here.
1013 resultRelInfo = resultRelInfos;
1016 estate->es_result_relation_info = resultRelInfo;
1017 ExecBSTruncateTriggers(estate, resultRelInfo);
1022 * OK, truncate each table.
1024 mySubid = GetCurrentSubTransactionId();
1028 Relation rel = (Relation) lfirst(cell);
1031 * Normally, we need a transaction-safe truncation here. However, if
1032 * the table was either created in the current (sub)transaction or has
1033 * a new relfilenode in the current (sub)transaction, then we can just
1034 * truncate it in-place, because a rollback would cause the whole
1035 * table or the current physical file to be thrown away anyway.
1037 if (rel->rd_createSubid == mySubid ||
1038 rel->rd_newRelfilenodeSubid == mySubid)
1040 /* Immediate, non-rollbackable truncation is OK */
1041 heap_truncate_one_rel(rel);
1049 * This effectively deletes all rows in the table, and may be done
1050 * in a serializable transaction. In that case we must record a
1051 * rw-conflict in to this transaction from each transaction
1052 * holding a predicate lock on the table.
1054 CheckTableForSerializableConflictIn(rel);
1057 * Need the full transaction-safe pushups.
1059 * Create a new empty storage file for the relation, and assign it
1060 * as the relfilenode value. The old storage file is scheduled for
1061 * deletion at commit.
1063 RelationSetNewRelfilenode(rel, RecentXmin);
1065 heap_relid = RelationGetRelid(rel);
1066 toast_relid = rel->rd_rel->reltoastrelid;
1069 * The same for the toast table, if any.
1071 if (OidIsValid(toast_relid))
1073 rel = relation_open(toast_relid, AccessExclusiveLock);
1074 RelationSetNewRelfilenode(rel, RecentXmin);
1075 heap_close(rel, NoLock);
1079 * Reconstruct the indexes to match, and we're done.
1081 reindex_relation(heap_relid, REINDEX_REL_PROCESS_TOAST);
1086 * Restart owned sequences if we were asked to.
1088 foreach(cell, seq_relids)
1090 Oid seq_relid = lfirst_oid(cell);
1092 ResetSequence(seq_relid);
1096 * Process all AFTER STATEMENT TRUNCATE triggers.
1098 resultRelInfo = resultRelInfos;
1101 estate->es_result_relation_info = resultRelInfo;
1102 ExecASTruncateTriggers(estate, resultRelInfo);
1106 /* Handle queued AFTER triggers */
1107 AfterTriggerEndQuery(estate);
1109 /* We can clean up the EState now */
1110 FreeExecutorState(estate);
1112 /* And close the rels (can't do this while EState still holds refs) */
1115 Relation rel = (Relation) lfirst(cell);
1117 heap_close(rel, NoLock);
1122 * Check that a given rel is safe to truncate. Subroutine for ExecuteTruncate
1125 truncate_check_rel(Relation rel)
1127 AclResult aclresult;
1129 /* Only allow truncate on regular tables */
1130 if (rel->rd_rel->relkind != RELKIND_RELATION)
1132 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1133 errmsg("\"%s\" is not a table",
1134 RelationGetRelationName(rel))));
1136 /* Permissions checks */
1137 aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
1139 if (aclresult != ACLCHECK_OK)
1140 aclcheck_error(aclresult, ACL_KIND_CLASS,
1141 RelationGetRelationName(rel));
1143 if (!allowSystemTableMods && IsSystemRelation(rel))
1145 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1146 errmsg("permission denied: \"%s\" is a system catalog",
1147 RelationGetRelationName(rel))));
1150 * Don't allow truncate on temp tables of other backends ... their local
1151 * buffer manager is not going to cope.
1153 if (RELATION_IS_OTHER_TEMP(rel))
1155 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1156 errmsg("cannot truncate temporary tables of other sessions")));
1159 * Also check for active uses of the relation in the current transaction,
1160 * including open scans and pending AFTER trigger events.
1162 CheckTableNotInUse(rel, "TRUNCATE");
1167 * returns the name corresponding to a typstorage/attstorage enum value
1170 storage_name(char c)
1189 * Returns new schema given initial schema and superclasses.
1192 * 'schema' is the column/attribute definition for the table. (It's a list
1193 * of ColumnDef's.) It is destructively changed.
1194 * 'supers' is a list of names (as RangeVar nodes) of parent relations.
1195 * 'relpersistence' is a persistence type of the table.
1198 * 'supOids' receives a list of the OIDs of the parent relations.
1199 * 'supconstr' receives a list of constraints belonging to the parents,
1200 * updated as necessary to be valid for the child.
1201 * 'supOidCount' is set to the number of parents that have OID columns.
1204 * Completed schema list.
1207 * The order in which the attributes are inherited is very important.
1208 * Intuitively, the inherited attributes should come first. If a table
1209 * inherits from multiple parents, the order of those attributes are
1210 * according to the order of the parents specified in CREATE TABLE.
1212 * Here's an example:
1214 * create table person (name text, age int4, location point);
1215 * create table emp (salary int4, manager text) inherits(person);
1216 * create table student (gpa float8) inherits (person);
1217 * create table stud_emp (percent int4) inherits (emp, student);
1219 * The order of the attributes of stud_emp is:
1221 * person {1:name, 2:age, 3:location}
1223 * {6:gpa} student emp {4:salary, 5:manager}
1225 * stud_emp {7:percent}
1227 * If the same attribute name appears multiple times, then it appears
1228 * in the result table in the proper location for its first appearance.
1230 * Constraints (including NOT NULL constraints) for the child table
1231 * are the union of all relevant constraints, from both the child schema
1232 * and parent tables.
1234 * The default value for a child column is defined as:
1235 * (1) If the child schema specifies a default, that value is used.
1236 * (2) If neither the child nor any parent specifies a default, then
1237 * the column will not have a default.
1238 * (3) If conflicting defaults are inherited from different parents
1239 * (and not overridden by the child), an error is raised.
1240 * (4) Otherwise the inherited default is used.
1241 * Rule (3) is new in Postgres 7.1; in earlier releases you got a
1242 * rather arbitrary choice of which parent default to use.
1246 MergeAttributes(List *schema, List *supers, char relpersistence,
1247 List **supOids, List **supconstr, int *supOidCount)
1250 List *inhSchema = NIL;
1251 List *parentOids = NIL;
1252 List *constraints = NIL;
1253 int parentsWithOids = 0;
1254 bool have_bogus_defaults = false;
1256 static Node bogus_marker = {0}; /* marks conflicting defaults */
1259 * Check for and reject tables with too many columns. We perform this
1260 * check relatively early for two reasons: (a) we don't run the risk of
1261 * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
1262 * okay if we're processing <= 1600 columns, but could take minutes to
1263 * execute if the user attempts to create a table with hundreds of
1264 * thousands of columns.
1266 * Note that we also need to check that any we do not exceed this figure
1267 * after including columns from inherited relations.
1269 if (list_length(schema) > MaxHeapAttributeNumber)
1271 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1272 errmsg("tables can have at most %d columns",
1273 MaxHeapAttributeNumber)));
1276 * Check for duplicate names in the explicit list of attributes.
1278 * Although we might consider merging such entries in the same way that we
1279 * handle name conflicts for inherited attributes, it seems to make more
1280 * sense to assume such conflicts are errors.
1282 foreach(entry, schema)
1284 ColumnDef *coldef = lfirst(entry);
1285 ListCell *rest = lnext(entry);
1286 ListCell *prev = entry;
1288 if (coldef->typeName == NULL)
1291 * Typed table column option that does not belong to a column from
1292 * the type. This works because the columns from the type come
1293 * first in the list.
1296 (errcode(ERRCODE_UNDEFINED_COLUMN),
1297 errmsg("column \"%s\" does not exist",
1300 while (rest != NULL)
1302 ColumnDef *restdef = lfirst(rest);
1303 ListCell *next = lnext(rest); /* need to save it in case we
1306 if (strcmp(coldef->colname, restdef->colname) == 0)
1308 if (coldef->is_from_type)
1311 * merge the column options into the column from the type
1313 coldef->is_not_null = restdef->is_not_null;
1314 coldef->raw_default = restdef->raw_default;
1315 coldef->cooked_default = restdef->cooked_default;
1316 coldef->constraints = restdef->constraints;
1317 coldef->is_from_type = false;
1318 list_delete_cell(schema, rest, prev);
1322 (errcode(ERRCODE_DUPLICATE_COLUMN),
1323 errmsg("column \"%s\" specified more than once",
1332 * Scan the parents left-to-right, and merge their attributes to form a
1333 * list of inherited attributes (inhSchema). Also check to see if we need
1334 * to inherit an OID column.
1337 foreach(entry, supers)
1339 RangeVar *parent = (RangeVar *) lfirst(entry);
1341 TupleDesc tupleDesc;
1342 TupleConstr *constr;
1343 AttrNumber *newattno;
1344 AttrNumber parent_attno;
1347 * A self-exclusive lock is needed here. If two backends attempt to
1348 * add children to the same parent simultaneously, and that parent has
1349 * no pre-existing children, then both will attempt to update the
1350 * parent's relhassubclass field, leading to a "tuple concurrently
1353 relation = heap_openrv(parent, ShareUpdateExclusiveLock);
1355 if (relation->rd_rel->relkind != RELKIND_RELATION)
1357 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1358 errmsg("inherited relation \"%s\" is not a table",
1360 /* Permanent rels cannot inherit from temporary ones */
1361 if (relpersistence != RELPERSISTENCE_TEMP
1362 && RelationUsesTempNamespace(relation))
1364 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1365 errmsg("cannot inherit from temporary relation \"%s\"",
1369 * We should have an UNDER permission flag for this, but for now,
1370 * demand that creator of a child table own the parent.
1372 if (!pg_class_ownercheck(RelationGetRelid(relation), GetUserId()))
1373 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1374 RelationGetRelationName(relation));
1377 * Reject duplications in the list of parents.
1379 if (list_member_oid(parentOids, RelationGetRelid(relation)))
1381 (errcode(ERRCODE_DUPLICATE_TABLE),
1382 errmsg("relation \"%s\" would be inherited from more than once",
1385 parentOids = lappend_oid(parentOids, RelationGetRelid(relation));
1387 if (relation->rd_rel->relhasoids)
1390 tupleDesc = RelationGetDescr(relation);
1391 constr = tupleDesc->constr;
1394 * newattno[] will contain the child-table attribute numbers for the
1395 * attributes of this parent table. (They are not the same for
1396 * parents after the first one, nor if we have dropped columns.)
1398 newattno = (AttrNumber *)
1399 palloc(tupleDesc->natts * sizeof(AttrNumber));
1401 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1404 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
1405 char *attributeName = NameStr(attribute->attname);
1410 * Ignore dropped columns in the parent.
1412 if (attribute->attisdropped)
1415 * change_varattnos_of_a_node asserts that this is greater
1416 * than zero, so if anything tries to use it, we should find
1419 newattno[parent_attno - 1] = 0;
1424 * Does it conflict with some previously inherited column?
1426 exist_attno = findAttrByName(attributeName, inhSchema);
1427 if (exist_attno > 0)
1434 * Yes, try to merge the two column definitions. They must
1435 * have the same type, typmod, and collation.
1438 (errmsg("merging multiple inherited definitions of column \"%s\"",
1440 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1441 typenameTypeIdAndMod(NULL, def->typeName, &defTypeId, &deftypmod);
1442 if (defTypeId != attribute->atttypid ||
1443 deftypmod != attribute->atttypmod)
1445 (errcode(ERRCODE_DATATYPE_MISMATCH),
1446 errmsg("inherited column \"%s\" has a type conflict",
1448 errdetail("%s versus %s",
1449 TypeNameToString(def->typeName),
1450 format_type_be(attribute->atttypid))));
1451 defCollId = GetColumnDefCollation(NULL, def, defTypeId);
1452 if (defCollId != attribute->attcollation)
1454 (errcode(ERRCODE_COLLATION_MISMATCH),
1455 errmsg("inherited column \"%s\" has a collation conflict",
1457 errdetail("\"%s\" versus \"%s\"",
1458 get_collation_name(defCollId),
1459 get_collation_name(attribute->attcollation))));
1461 /* Copy storage parameter */
1462 if (def->storage == 0)
1463 def->storage = attribute->attstorage;
1464 else if (def->storage != attribute->attstorage)
1466 (errcode(ERRCODE_DATATYPE_MISMATCH),
1467 errmsg("inherited column \"%s\" has a storage parameter conflict",
1469 errdetail("%s versus %s",
1470 storage_name(def->storage),
1471 storage_name(attribute->attstorage))));
1474 /* Merge of NOT NULL constraints = OR 'em together */
1475 def->is_not_null |= attribute->attnotnull;
1476 /* Default and other constraints are handled below */
1477 newattno[parent_attno - 1] = exist_attno;
1482 * No, create a new inherited column
1484 def = makeNode(ColumnDef);
1485 def->colname = pstrdup(attributeName);
1486 def->typeName = makeTypeNameFromOid(attribute->atttypid,
1487 attribute->atttypmod);
1489 def->is_local = false;
1490 def->is_not_null = attribute->attnotnull;
1491 def->is_from_type = false;
1492 def->storage = attribute->attstorage;
1493 def->raw_default = NULL;
1494 def->cooked_default = NULL;
1495 def->collClause = NULL;
1496 def->collOid = attribute->attcollation;
1497 def->constraints = NIL;
1498 inhSchema = lappend(inhSchema, def);
1499 newattno[parent_attno - 1] = ++child_attno;
1503 * Copy default if any
1505 if (attribute->atthasdef)
1507 Node *this_default = NULL;
1508 AttrDefault *attrdef;
1511 /* Find default in constraint structure */
1512 Assert(constr != NULL);
1513 attrdef = constr->defval;
1514 for (i = 0; i < constr->num_defval; i++)
1516 if (attrdef[i].adnum == parent_attno)
1518 this_default = stringToNode(attrdef[i].adbin);
1522 Assert(this_default != NULL);
1525 * If default expr could contain any vars, we'd need to fix
1526 * 'em, but it can't; so default is ready to apply to child.
1528 * If we already had a default from some prior parent, check
1529 * to see if they are the same. If so, no problem; if not,
1530 * mark the column as having a bogus default. Below, we will
1531 * complain if the bogus default isn't overridden by the child
1534 Assert(def->raw_default == NULL);
1535 if (def->cooked_default == NULL)
1536 def->cooked_default = this_default;
1537 else if (!equal(def->cooked_default, this_default))
1539 def->cooked_default = &bogus_marker;
1540 have_bogus_defaults = true;
1546 * Now copy the CHECK constraints of this parent, adjusting attnos
1547 * using the completed newattno[] map. Identically named constraints
1548 * are merged if possible, else we throw error.
1550 if (constr && constr->num_check > 0)
1552 ConstrCheck *check = constr->check;
1555 for (i = 0; i < constr->num_check; i++)
1557 char *name = check[i].ccname;
1560 /* adjust varattnos of ccbin here */
1561 expr = stringToNode(check[i].ccbin);
1562 change_varattnos_of_a_node(expr, newattno);
1564 /* check for duplicate */
1565 if (!MergeCheckConstraint(constraints, name, expr))
1567 /* nope, this is a new one */
1568 CookedConstraint *cooked;
1570 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1571 cooked->contype = CONSTR_CHECK;
1572 cooked->name = pstrdup(name);
1573 cooked->attnum = 0; /* not used for constraints */
1574 cooked->expr = expr;
1575 cooked->skip_validation = false;
1576 cooked->is_local = false;
1577 cooked->inhcount = 1;
1578 constraints = lappend(constraints, cooked);
1586 * Close the parent rel, but keep our AccessShareLock on it until xact
1587 * commit. That will prevent someone else from deleting or ALTERing
1588 * the parent before the child is committed.
1590 heap_close(relation, NoLock);
1594 * If we had no inherited attributes, the result schema is just the
1595 * explicitly declared columns. Otherwise, we need to merge the declared
1596 * columns into the inherited schema list.
1598 if (inhSchema != NIL)
1600 foreach(entry, schema)
1602 ColumnDef *newdef = lfirst(entry);
1603 char *attributeName = newdef->colname;
1607 * Does it conflict with some previously inherited column?
1609 exist_attno = findAttrByName(attributeName, inhSchema);
1610 if (exist_attno > 0)
1621 * Yes, try to merge the two column definitions. They must
1622 * have the same type, typmod, and collation.
1625 (errmsg("merging column \"%s\" with inherited definition",
1627 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1628 typenameTypeIdAndMod(NULL, def->typeName, &defTypeId, &deftypmod);
1629 typenameTypeIdAndMod(NULL, newdef->typeName, &newTypeId, &newtypmod);
1630 if (defTypeId != newTypeId || deftypmod != newtypmod)
1632 (errcode(ERRCODE_DATATYPE_MISMATCH),
1633 errmsg("column \"%s\" has a type conflict",
1635 errdetail("%s versus %s",
1636 TypeNameToString(def->typeName),
1637 TypeNameToString(newdef->typeName))));
1638 defcollid = GetColumnDefCollation(NULL, def, defTypeId);
1639 newcollid = GetColumnDefCollation(NULL, newdef, newTypeId);
1640 if (defcollid != newcollid)
1642 (errcode(ERRCODE_COLLATION_MISMATCH),
1643 errmsg("column \"%s\" has a collation conflict",
1645 errdetail("\"%s\" versus \"%s\"",
1646 get_collation_name(defcollid),
1647 get_collation_name(newcollid))));
1649 /* Copy storage parameter */
1650 if (def->storage == 0)
1651 def->storage = newdef->storage;
1652 else if (newdef->storage != 0 && def->storage != newdef->storage)
1654 (errcode(ERRCODE_DATATYPE_MISMATCH),
1655 errmsg("column \"%s\" has a storage parameter conflict",
1657 errdetail("%s versus %s",
1658 storage_name(def->storage),
1659 storage_name(newdef->storage))));
1661 /* Mark the column as locally defined */
1662 def->is_local = true;
1663 /* Merge of NOT NULL constraints = OR 'em together */
1664 def->is_not_null |= newdef->is_not_null;
1665 /* If new def has a default, override previous default */
1666 if (newdef->raw_default != NULL)
1668 def->raw_default = newdef->raw_default;
1669 def->cooked_default = newdef->cooked_default;
1675 * No, attach new column to result schema
1677 inhSchema = lappend(inhSchema, newdef);
1684 * Check that we haven't exceeded the legal # of columns after merging
1685 * in inherited columns.
1687 if (list_length(schema) > MaxHeapAttributeNumber)
1689 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1690 errmsg("tables can have at most %d columns",
1691 MaxHeapAttributeNumber)));
1695 * If we found any conflicting parent default values, check to make sure
1696 * they were overridden by the child.
1698 if (have_bogus_defaults)
1700 foreach(entry, schema)
1702 ColumnDef *def = lfirst(entry);
1704 if (def->cooked_default == &bogus_marker)
1706 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
1707 errmsg("column \"%s\" inherits conflicting default values",
1709 errhint("To resolve the conflict, specify a default explicitly.")));
1713 *supOids = parentOids;
1714 *supconstr = constraints;
1715 *supOidCount = parentsWithOids;
1721 * MergeCheckConstraint
1722 * Try to merge an inherited CHECK constraint with previous ones
1724 * If we inherit identically-named constraints from multiple parents, we must
1725 * merge them, or throw an error if they don't have identical definitions.
1727 * constraints is a list of CookedConstraint structs for previous constraints.
1729 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
1730 * got a so-far-unique name, or throws error if conflict.
1733 MergeCheckConstraint(List *constraints, char *name, Node *expr)
1737 foreach(lc, constraints)
1739 CookedConstraint *ccon = (CookedConstraint *) lfirst(lc);
1741 Assert(ccon->contype == CONSTR_CHECK);
1743 /* Non-matching names never conflict */
1744 if (strcmp(ccon->name, name) != 0)
1747 if (equal(expr, ccon->expr))
1755 (errcode(ERRCODE_DUPLICATE_OBJECT),
1756 errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
1765 * Replace varattno values in an expression tree according to the given
1766 * map array, that is, varattno N is replaced by newattno[N-1]. It is
1767 * caller's responsibility to ensure that the array is long enough to
1768 * define values for all user varattnos present in the tree. System column
1769 * attnos remain unchanged.
1771 * Note that the passed node tree is modified in-place!
1774 change_varattnos_of_a_node(Node *node, const AttrNumber *newattno)
1776 /* no setup needed, so away we go */
1777 (void) change_varattnos_walker(node, newattno);
1781 change_varattnos_walker(Node *node, const AttrNumber *newattno)
1787 Var *var = (Var *) node;
1789 if (var->varlevelsup == 0 && var->varno == 1 &&
1793 * ??? the following may be a problem when the node is multiply
1794 * referenced though stringToNode() doesn't create such a node
1797 Assert(newattno[var->varattno - 1] > 0);
1798 var->varattno = var->varoattno = newattno[var->varattno - 1];
1802 return expression_tree_walker(node, change_varattnos_walker,
1807 * Generate a map for change_varattnos_of_a_node from old and new TupleDesc's,
1808 * matching according to column name.
1811 varattnos_map(TupleDesc olddesc, TupleDesc newdesc)
1817 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * olddesc->natts);
1818 for (i = 1; i <= olddesc->natts; i++)
1820 if (olddesc->attrs[i - 1]->attisdropped)
1821 continue; /* leave the entry as zero */
1823 for (j = 1; j <= newdesc->natts; j++)
1825 if (strcmp(NameStr(olddesc->attrs[i - 1]->attname),
1826 NameStr(newdesc->attrs[j - 1]->attname)) == 0)
1837 * Generate a map for change_varattnos_of_a_node from a TupleDesc and a list
1841 varattnos_map_schema(TupleDesc old, List *schema)
1846 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * old->natts);
1847 for (i = 1; i <= old->natts; i++)
1849 if (old->attrs[i - 1]->attisdropped)
1850 continue; /* leave the entry as zero */
1852 attmap[i - 1] = findAttrByName(NameStr(old->attrs[i - 1]->attname),
1860 * StoreCatalogInheritance
1861 * Updates the system catalogs with proper inheritance information.
1863 * supers is a list of the OIDs of the new relation's direct ancestors.
1866 StoreCatalogInheritance(Oid relationId, List *supers)
1875 AssertArg(OidIsValid(relationId));
1881 * Store INHERITS information in pg_inherits using direct ancestors only.
1882 * Also enter dependencies on the direct ancestors, and make sure they are
1883 * marked with relhassubclass = true.
1885 * (Once upon a time, both direct and indirect ancestors were found here
1886 * and then entered into pg_ipl. Since that catalog doesn't exist
1887 * anymore, there's no need to look for indirect ancestors.)
1889 relation = heap_open(InheritsRelationId, RowExclusiveLock);
1892 foreach(entry, supers)
1894 Oid parentOid = lfirst_oid(entry);
1896 StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation);
1900 heap_close(relation, RowExclusiveLock);
1904 * Make catalog entries showing relationId as being an inheritance child
1905 * of parentOid. inhRelation is the already-opened pg_inherits catalog.
1908 StoreCatalogInheritance1(Oid relationId, Oid parentOid,
1909 int16 seqNumber, Relation inhRelation)
1911 TupleDesc desc = RelationGetDescr(inhRelation);
1912 Datum values[Natts_pg_inherits];
1913 bool nulls[Natts_pg_inherits];
1914 ObjectAddress childobject,
1919 * Make the pg_inherits entry
1921 values[Anum_pg_inherits_inhrelid - 1] = ObjectIdGetDatum(relationId);
1922 values[Anum_pg_inherits_inhparent - 1] = ObjectIdGetDatum(parentOid);
1923 values[Anum_pg_inherits_inhseqno - 1] = Int16GetDatum(seqNumber);
1925 memset(nulls, 0, sizeof(nulls));
1927 tuple = heap_form_tuple(desc, values, nulls);
1929 simple_heap_insert(inhRelation, tuple);
1931 CatalogUpdateIndexes(inhRelation, tuple);
1933 heap_freetuple(tuple);
1936 * Store a dependency too
1938 parentobject.classId = RelationRelationId;
1939 parentobject.objectId = parentOid;
1940 parentobject.objectSubId = 0;
1941 childobject.classId = RelationRelationId;
1942 childobject.objectId = relationId;
1943 childobject.objectSubId = 0;
1945 recordDependencyOn(&childobject, &parentobject, DEPENDENCY_NORMAL);
1948 * Mark the parent as having subclasses.
1950 setRelhassubclassInRelation(parentOid, true);
1954 * Look for an existing schema entry with the given name.
1956 * Returns the index (starting with 1) if attribute already exists in schema,
1960 findAttrByName(const char *attributeName, List *schema)
1967 ColumnDef *def = lfirst(s);
1969 if (strcmp(attributeName, def->colname) == 0)
1978 * Update a relation's pg_class.relhassubclass entry to the given value
1981 setRelhassubclassInRelation(Oid relationId, bool relhassubclass)
1983 Relation relationRelation;
1985 Form_pg_class classtuple;
1988 * Fetch a modifiable copy of the tuple, modify it, update pg_class.
1990 * If the tuple already has the right relhassubclass setting, we don't
1991 * need to update it, but we still need to issue an SI inval message.
1993 relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
1994 tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
1995 if (!HeapTupleIsValid(tuple))
1996 elog(ERROR, "cache lookup failed for relation %u", relationId);
1997 classtuple = (Form_pg_class) GETSTRUCT(tuple);
1999 if (classtuple->relhassubclass != relhassubclass)
2001 classtuple->relhassubclass = relhassubclass;
2002 simple_heap_update(relationRelation, &tuple->t_self, tuple);
2004 /* keep the catalog indexes up to date */
2005 CatalogUpdateIndexes(relationRelation, tuple);
2009 /* no need to change tuple, but force relcache rebuild anyway */
2010 CacheInvalidateRelcacheByTuple(tuple);
2013 heap_freetuple(tuple);
2014 heap_close(relationRelation, RowExclusiveLock);
2019 * renameatt_internal - workhorse for renameatt
2022 renameatt_internal(Oid myrelid,
2023 const char *oldattname,
2024 const char *newattname,
2027 int expected_parents,
2028 DropBehavior behavior)
2030 Relation targetrelation;
2031 Relation attrelation;
2033 Form_pg_attribute attform;
2038 * Grab an exclusive lock on the target table, which we will NOT release
2039 * until end of transaction.
2041 targetrelation = relation_open(myrelid, AccessExclusiveLock);
2043 if (targetrelation->rd_rel->reloftype && !recursing)
2045 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2046 errmsg("cannot rename column of typed table")));
2049 * Renaming the columns of sequences or toast tables doesn't actually
2050 * break anything from the system's point of view, since internal
2051 * references are by attnum. But it doesn't seem right to allow users to
2052 * change names that are hardcoded into the system, hence the following
2055 relkind = RelationGetForm(targetrelation)->relkind;
2056 if (relkind != RELKIND_RELATION &&
2057 relkind != RELKIND_VIEW &&
2058 relkind != RELKIND_COMPOSITE_TYPE &&
2059 relkind != RELKIND_INDEX &&
2060 relkind != RELKIND_FOREIGN_TABLE)
2062 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2063 errmsg("\"%s\" is not a table, view, composite type, index or foreign table",
2064 RelationGetRelationName(targetrelation))));
2067 * permissions checking. only the owner of a class can change its schema.
2069 if (!pg_class_ownercheck(myrelid, GetUserId()))
2070 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
2071 RelationGetRelationName(targetrelation));
2072 if (!allowSystemTableMods && IsSystemRelation(targetrelation))
2074 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2075 errmsg("permission denied: \"%s\" is a system catalog",
2076 RelationGetRelationName(targetrelation))));
2079 * if the 'recurse' flag is set then we are supposed to rename this
2080 * attribute in all classes that inherit from 'relname' (as well as in
2083 * any permissions or problems with duplicate attributes will cause the
2084 * whole transaction to abort, which is what we want -- all or nothing.
2094 * we need the number of parents for each child so that the recursive
2095 * calls to renameatt() can determine whether there are any parents
2096 * outside the inheritance hierarchy being processed.
2098 child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
2102 * find_all_inheritors does the recursive search of the inheritance
2103 * hierarchy, so all we have to do is process all of the relids in the
2104 * list that it returns.
2106 forboth(lo, child_oids, li, child_numparents)
2108 Oid childrelid = lfirst_oid(lo);
2109 int numparents = lfirst_int(li);
2111 if (childrelid == myrelid)
2113 /* note we need not recurse again */
2114 renameatt_internal(childrelid, oldattname, newattname, false, true, numparents, behavior);
2120 * If we are told not to recurse, there had better not be any child
2121 * tables; else the rename would put them out of step.
2123 * expected_parents will only be 0 if we are not already recursing.
2125 if (expected_parents == 0 &&
2126 find_inheritance_children(myrelid, NoLock) != NIL)
2128 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2129 errmsg("inherited column \"%s\" must be renamed in child tables too",
2133 /* rename attributes in typed tables of composite type */
2134 if (targetrelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
2139 child_oids = find_typed_table_dependencies(targetrelation->rd_rel->reltype,
2140 RelationGetRelationName(targetrelation),
2143 foreach(lo, child_oids)
2144 renameatt_internal(lfirst_oid(lo), oldattname, newattname, true, true, 0, behavior);
2147 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
2149 atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
2150 if (!HeapTupleIsValid(atttup))
2152 (errcode(ERRCODE_UNDEFINED_COLUMN),
2153 errmsg("column \"%s\" does not exist",
2155 attform = (Form_pg_attribute) GETSTRUCT(atttup);
2157 attnum = attform->attnum;
2160 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2161 errmsg("cannot rename system column \"%s\"",
2165 * if the attribute is inherited, forbid the renaming. if this is a
2166 * top-level call to renameatt(), then expected_parents will be 0, so the
2167 * effect of this code will be to prohibit the renaming if the attribute
2168 * is inherited at all. if this is a recursive call to renameatt(),
2169 * expected_parents will be the number of parents the current relation has
2170 * within the inheritance hierarchy being processed, so we'll prohibit the
2171 * renaming only if there are additional parents from elsewhere.
2173 if (attform->attinhcount > expected_parents)
2175 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2176 errmsg("cannot rename inherited column \"%s\"",
2179 /* new name should not already exist */
2181 /* this test is deliberately not attisdropped-aware */
2182 if (SearchSysCacheExists2(ATTNAME,
2183 ObjectIdGetDatum(myrelid),
2184 PointerGetDatum(newattname)))
2186 (errcode(ERRCODE_DUPLICATE_COLUMN),
2187 errmsg("column \"%s\" of relation \"%s\" already exists",
2188 newattname, RelationGetRelationName(targetrelation))));
2190 /* apply the update */
2191 namestrcpy(&(attform->attname), newattname);
2193 simple_heap_update(attrelation, &atttup->t_self, atttup);
2195 /* keep system catalog indexes current */
2196 CatalogUpdateIndexes(attrelation, atttup);
2198 heap_freetuple(atttup);
2200 heap_close(attrelation, RowExclusiveLock);
2202 relation_close(targetrelation, NoLock); /* close rel but keep lock */
2207 * renameatt - changes the name of a attribute in a relation
2210 renameatt(Oid myrelid, RenameStmt *stmt)
2212 renameatt_internal(myrelid,
2213 stmt->subname, /* old att name */
2214 stmt->newname, /* new att name */
2215 interpretInhOption(stmt->relation->inhOpt), /* recursive? */
2216 false, /* recursing? */
2217 0, /* expected inhcount */
2223 * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW/FOREIGN TABLE RENAME
2225 * Caller has already done permissions checks.
2228 RenameRelation(Oid myrelid, const char *newrelname, ObjectType reltype)
2230 Relation targetrelation;
2235 * Grab an exclusive lock on the target table, index, sequence or view,
2236 * which we will NOT release until end of transaction.
2238 targetrelation = relation_open(myrelid, AccessExclusiveLock);
2240 namespaceId = RelationGetNamespace(targetrelation);
2241 relkind = targetrelation->rd_rel->relkind;
2244 * For compatibility with prior releases, we don't complain if ALTER TABLE
2245 * or ALTER INDEX is used to rename some other type of relation. But
2246 * ALTER SEQUENCE/VIEW/FOREIGN TABLE are only to be used with relations of
2249 if (reltype == OBJECT_SEQUENCE && relkind != RELKIND_SEQUENCE)
2251 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2252 errmsg("\"%s\" is not a sequence",
2253 RelationGetRelationName(targetrelation))));
2255 if (reltype == OBJECT_VIEW && relkind != RELKIND_VIEW)
2257 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2258 errmsg("\"%s\" is not a view",
2259 RelationGetRelationName(targetrelation))));
2261 if (reltype == OBJECT_FOREIGN_TABLE && relkind != RELKIND_FOREIGN_TABLE)
2263 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2264 errmsg("\"%s\" is not a foreign table",
2265 RelationGetRelationName(targetrelation))));
2268 * Don't allow ALTER TABLE on composite types. We want people to use ALTER
2271 if (relkind == RELKIND_COMPOSITE_TYPE)
2273 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2274 errmsg("\"%s\" is a composite type",
2275 RelationGetRelationName(targetrelation)),
2276 errhint("Use ALTER TYPE instead.")));
2279 RenameRelationInternal(myrelid, newrelname, namespaceId);
2282 * Close rel, but keep exclusive lock!
2284 relation_close(targetrelation, NoLock);
2288 * RenameRelationInternal - change the name of a relation
2290 * XXX - When renaming sequences, we don't bother to modify the
2291 * sequence name that is stored within the sequence itself
2292 * (this would cause problems with MVCC). In the future,
2293 * the sequence name should probably be removed from the
2294 * sequence, AFAIK there's no need for it to be there.
2297 RenameRelationInternal(Oid myrelid, const char *newrelname, Oid namespaceId)
2299 Relation targetrelation;
2300 Relation relrelation; /* for RELATION relation */
2302 Form_pg_class relform;
2305 * Grab an exclusive lock on the target table, index, sequence or view,
2306 * which we will NOT release until end of transaction.
2308 targetrelation = relation_open(myrelid, AccessExclusiveLock);
2311 * Find relation's pg_class tuple, and make sure newrelname isn't in use.
2313 relrelation = heap_open(RelationRelationId, RowExclusiveLock);
2315 reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
2316 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
2317 elog(ERROR, "cache lookup failed for relation %u", myrelid);
2318 relform = (Form_pg_class) GETSTRUCT(reltup);
2320 if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
2322 (errcode(ERRCODE_DUPLICATE_TABLE),
2323 errmsg("relation \"%s\" already exists",
2327 * Update pg_class tuple with new relname. (Scribbling on reltup is OK
2328 * because it's a copy...)
2330 namestrcpy(&(relform->relname), newrelname);
2332 simple_heap_update(relrelation, &reltup->t_self, reltup);
2334 /* keep the system catalog indexes current */
2335 CatalogUpdateIndexes(relrelation, reltup);
2337 heap_freetuple(reltup);
2338 heap_close(relrelation, RowExclusiveLock);
2341 * Also rename the associated type, if any.
2343 if (OidIsValid(targetrelation->rd_rel->reltype))
2344 RenameTypeInternal(targetrelation->rd_rel->reltype,
2345 newrelname, namespaceId);
2348 * Also rename the associated constraint, if any.
2350 if (targetrelation->rd_rel->relkind == RELKIND_INDEX)
2352 Oid constraintId = get_index_constraint(myrelid);
2354 if (OidIsValid(constraintId))
2355 RenameConstraintById(constraintId, newrelname);
2359 * Close rel, but keep exclusive lock!
2361 relation_close(targetrelation, NoLock);
2365 * Disallow ALTER TABLE (and similar commands) when the current backend has
2366 * any open reference to the target table besides the one just acquired by
2367 * the calling command; this implies there's an open cursor or active plan.
2368 * We need this check because our lock doesn't protect us against stomping
2369 * on our own foot, only other people's feet!
2371 * For ALTER TABLE, the only case known to cause serious trouble is ALTER
2372 * COLUMN TYPE, and some changes are obviously pretty benign, so this could
2373 * possibly be relaxed to only error out for certain types of alterations.
2374 * But the use-case for allowing any of these things is not obvious, so we
2375 * won't work hard at it for now.
2377 * We also reject these commands if there are any pending AFTER trigger events
2378 * for the rel. This is certainly necessary for the rewriting variants of
2379 * ALTER TABLE, because they don't preserve tuple TIDs and so the pending
2380 * events would try to fetch the wrong tuples. It might be overly cautious
2381 * in other cases, but again it seems better to err on the side of paranoia.
2383 * REINDEX calls this with "rel" referencing the index to be rebuilt; here
2384 * we are worried about active indexscans on the index. The trigger-event
2385 * check can be skipped, since we are doing no damage to the parent table.
2387 * The statement name (eg, "ALTER TABLE") is passed for use in error messages.
2390 CheckTableNotInUse(Relation rel, const char *stmt)
2392 int expected_refcnt;
2394 expected_refcnt = rel->rd_isnailed ? 2 : 1;
2395 if (rel->rd_refcnt != expected_refcnt)
2397 (errcode(ERRCODE_OBJECT_IN_USE),
2398 /* translator: first %s is a SQL command, eg ALTER TABLE */
2399 errmsg("cannot %s \"%s\" because "
2400 "it is being used by active queries in this session",
2401 stmt, RelationGetRelationName(rel))));
2403 if (rel->rd_rel->relkind != RELKIND_INDEX &&
2404 AfterTriggerPendingOnRel(RelationGetRelid(rel)))
2406 (errcode(ERRCODE_OBJECT_IN_USE),
2407 /* translator: first %s is a SQL command, eg ALTER TABLE */
2408 errmsg("cannot %s \"%s\" because "
2409 "it has pending trigger events",
2410 stmt, RelationGetRelationName(rel))));
2415 * Execute ALTER TABLE, which can be a list of subcommands
2417 * ALTER TABLE is performed in three phases:
2418 * 1. Examine subcommands and perform pre-transformation checking.
2419 * 2. Update system catalogs.
2420 * 3. Scan table(s) to check new constraints, and optionally recopy
2421 * the data into new table(s).
2422 * Phase 3 is not performed unless one or more of the subcommands requires
2423 * it. The intention of this design is to allow multiple independent
2424 * updates of the table schema to be performed with only one pass over the
2427 * ATPrepCmd performs phase 1. A "work queue" entry is created for
2428 * each table to be affected (there may be multiple affected tables if the
2429 * commands traverse a table inheritance hierarchy). Also we do preliminary
2430 * validation of the subcommands, including parse transformation of those
2431 * expressions that need to be evaluated with respect to the old table
2434 * ATRewriteCatalogs performs phase 2 for each affected table. (Note that
2435 * phases 2 and 3 normally do no explicit recursion, since phase 1 already
2436 * did it --- although some subcommands have to recurse in phase 2 instead.)
2437 * Certain subcommands need to be performed before others to avoid
2438 * unnecessary conflicts; for example, DROP COLUMN should come before
2439 * ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
2440 * lists, one for each logical "pass" of phase 2.
2442 * ATRewriteTables performs phase 3 for those tables that need it.
2444 * Thanks to the magic of MVCC, an error anywhere along the way rolls back
2445 * the whole operation; we don't have to do anything special to clean up.
2447 * We lock the table as the first action, with an appropriate lock level
2448 * for the subcommands requested. Any subcommand that needs to rewrite
2449 * tuples in the table forces the whole command to be executed with
2450 * AccessExclusiveLock. If all subcommands do not require rewrite table
2451 * then we may be able to use lower lock levels. We pass the lock level down
2452 * so that we can apply it recursively to inherited tables. Note that the
2453 * lock level we want as we recurse may well be higher than required for
2454 * that specific subcommand. So we pass down the overall lock requirement,
2455 * rather than reassess it at lower levels.
2458 AlterTable(AlterTableStmt *stmt)
2461 LOCKMODE lockmode = AlterTableGetLockLevel(stmt->cmds);
2464 * Acquire same level of lock as already acquired during parsing.
2466 rel = relation_openrv(stmt->relation, lockmode);
2468 CheckTableNotInUse(rel, "ALTER TABLE");
2470 /* Check relation type against type specified in the ALTER command */
2471 switch (stmt->relkind)
2476 * For mostly-historical reasons, we allow ALTER TABLE to apply to
2477 * almost all relation types.
2479 if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE
2480 || rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2482 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2483 errmsg("\"%s\" is not a table",
2484 RelationGetRelationName(rel))));
2488 if (rel->rd_rel->relkind != RELKIND_INDEX)
2490 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2491 errmsg("\"%s\" is not an index",
2492 RelationGetRelationName(rel))));
2495 case OBJECT_SEQUENCE:
2496 if (rel->rd_rel->relkind != RELKIND_SEQUENCE)
2498 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2499 errmsg("\"%s\" is not a sequence",
2500 RelationGetRelationName(rel))));
2504 if (rel->rd_rel->relkind != RELKIND_COMPOSITE_TYPE)
2506 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2507 errmsg("\"%s\" is not a composite type",
2508 RelationGetRelationName(rel))));
2512 if (rel->rd_rel->relkind != RELKIND_VIEW)
2514 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2515 errmsg("\"%s\" is not a view",
2516 RelationGetRelationName(rel))));
2519 case OBJECT_FOREIGN_TABLE:
2520 if (rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
2522 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2523 errmsg("\"%s\" is not a foreign table",
2524 RelationGetRelationName(rel))));
2528 elog(ERROR, "unrecognized object type: %d", (int) stmt->relkind);
2531 ATController(rel, stmt->cmds, interpretInhOption(stmt->relation->inhOpt),
2536 * AlterTableInternal
2538 * ALTER TABLE with target specified by OID
2540 * We do not reject if the relation is already open, because it's quite
2541 * likely that one or more layers of caller have it open. That means it
2542 * is unsafe to use this entry point for alterations that could break
2543 * existing query plans. On the assumption it's not used for such, we
2544 * don't have to reject pending AFTER triggers, either.
2547 AlterTableInternal(Oid relid, List *cmds, bool recurse)
2550 LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
2552 rel = relation_open(relid, lockmode);
2554 ATController(rel, cmds, recurse, lockmode);
2558 * AlterTableGetLockLevel
2560 * Sets the overall lock level required for the supplied list of subcommands.
2561 * Policy for doing this set according to needs of AlterTable(), see
2562 * comments there for overall explanation.
2564 * Function is called before and after parsing, so it must give same
2565 * answer each time it is called. Some subcommands are transformed
2566 * into other subcommand types, so the transform must never be made to a
2567 * lower lock level than previously assigned. All transforms are noted below.
2569 * Since this is called before we lock the table we cannot use table metadata
2570 * to influence the type of lock we acquire.
2572 * There should be no lockmodes hardcoded into the subcommand functions. All
2573 * lockmode decisions for ALTER TABLE are made here only. The one exception is
2574 * ALTER TABLE RENAME which is treated as a different statement type T_RenameStmt
2575 * and does not travel through this section of code and cannot be combined with
2576 * any of the subcommands given here.
2579 AlterTableGetLockLevel(List *cmds)
2582 * Late in 9.1 dev cycle a number of issues were uncovered with access
2583 * to catalog relations, leading to the decision to re-enforce all DDL
2584 * at AccessExclusiveLock level by default.
2586 * The issues are that there is a pervasive assumption in the code that
2587 * the catalogs will not be read unless an AccessExclusiveLock is held.
2588 * If that rule is relaxed, we must protect against a number of potential
2589 * effects - infrequent, but proven possible with test cases where
2590 * multiple DDL operations occur in a stream against frequently accessed
2593 * 1. Catalog tables are read using SnapshotNow, which has a race bug
2594 * that allows a scan to return no valid rows even when one is present
2595 * in the case of a commit of a concurrent update of the catalog table.
2596 * SnapshotNow also ignores transactions in progress, so takes the
2597 * latest committed version without waiting for the latest changes.
2599 * 2. Relcache needs to be internally consistent, so unless we lock the
2600 * definition during reads we have no way to guarantee that.
2602 * 3. Catcache access isn't coordinated at all so refreshes can occur at
2605 #ifdef REDUCED_ALTER_TABLE_LOCK_LEVELS
2607 LOCKMODE lockmode = ShareUpdateExclusiveLock;
2611 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2612 LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
2614 switch (cmd->subtype)
2617 * Need AccessExclusiveLock for these subcommands because they
2618 * affect or potentially affect both read and write
2621 * New subcommand types should be added here by default.
2623 case AT_AddColumn: /* may rewrite heap, in some cases and visible
2625 case AT_DropColumn: /* change visible to SELECT */
2626 case AT_AddColumnToView: /* CREATE VIEW */
2627 case AT_AlterColumnType: /* must rewrite heap */
2628 case AT_DropConstraint: /* as DROP INDEX */
2629 case AT_AddOids: /* must rewrite heap */
2630 case AT_DropOids: /* calls AT_DropColumn */
2631 case AT_EnableAlwaysRule: /* may change SELECT rules */
2632 case AT_EnableReplicaRule: /* may change SELECT rules */
2633 case AT_EnableRule: /* may change SELECT rules */
2634 case AT_DisableRule: /* may change SELECT rules */
2635 case AT_ChangeOwner: /* change visible to SELECT */
2636 case AT_SetTableSpace: /* must rewrite heap */
2637 case AT_DropNotNull: /* may change some SQL plans */
2639 case AT_GenericOptions:
2640 cmd_lockmode = AccessExclusiveLock;
2644 * These subcommands affect write operations only.
2646 case AT_ColumnDefault:
2647 case AT_ProcessedConstraint: /* becomes AT_AddConstraint */
2648 case AT_AddConstraintRecurse: /* becomes AT_AddConstraint */
2650 case AT_EnableAlwaysTrig:
2651 case AT_EnableReplicaTrig:
2652 case AT_EnableTrigAll:
2653 case AT_EnableTrigUser:
2654 case AT_DisableTrig:
2655 case AT_DisableTrigAll:
2656 case AT_DisableTrigUser:
2657 case AT_AddIndex: /* from ADD CONSTRAINT */
2658 case AT_AddIndexConstraint:
2659 cmd_lockmode = ShareRowExclusiveLock;
2662 case AT_AddConstraint:
2663 if (IsA(cmd->def, Constraint))
2665 Constraint *con = (Constraint *) cmd->def;
2667 switch (con->contype)
2669 case CONSTR_EXCLUSION:
2670 case CONSTR_PRIMARY:
2674 * Cases essentially the same as CREATE INDEX. We
2675 * could reduce the lock strength to ShareLock if
2676 * we can work out how to allow concurrent catalog
2679 cmd_lockmode = ShareRowExclusiveLock;
2681 case CONSTR_FOREIGN:
2684 * We add triggers to both tables when we add a
2685 * Foreign Key, so the lock level must be at least
2686 * as strong as CREATE TRIGGER.
2688 cmd_lockmode = ShareRowExclusiveLock;
2692 cmd_lockmode = ShareRowExclusiveLock;
2698 * These subcommands affect inheritance behaviour. Queries
2699 * started before us will continue to see the old inheritance
2700 * behaviour, while queries started after we commit will see
2701 * new behaviour. No need to prevent reads or writes to the
2702 * subtable while we hook it up though.
2705 case AT_DropInherit:
2706 cmd_lockmode = ShareUpdateExclusiveLock;
2710 * These subcommands affect implicit row type conversion. They
2711 * have affects similar to CREATE/DROP CAST on queries. We
2712 * don't provide for invalidating parse trees as a result of
2713 * such changes. Do avoid concurrent pg_class updates,
2718 cmd_lockmode = ShareUpdateExclusiveLock;
2721 * These subcommands affect general strategies for performance
2722 * and maintenance, though don't change the semantic results
2723 * from normal data reads and writes. Delaying an ALTER TABLE
2724 * behind currently active writes only delays the point where
2725 * the new strategy begins to take effect, so there is no
2726 * benefit in waiting. In this case the minimum restriction
2727 * applies: we don't currently allow concurrent catalog
2730 case AT_SetStatistics:
2732 case AT_DropCluster:
2733 case AT_SetRelOptions:
2734 case AT_ResetRelOptions:
2736 case AT_ResetOptions:
2738 case AT_ValidateConstraint:
2739 cmd_lockmode = ShareUpdateExclusiveLock;
2743 elog(ERROR, "unrecognized alter table type: %d",
2744 (int) cmd->subtype);
2749 * Take the greatest lockmode from any subcommand
2751 if (cmd_lockmode > lockmode)
2752 lockmode = cmd_lockmode;
2755 LOCKMODE lockmode = AccessExclusiveLock;
2762 ATController(Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
2767 /* Phase 1: preliminary examination of commands, create work queue */
2770 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2772 ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode);
2775 /* Close the relation, but keep lock until commit */
2776 relation_close(rel, NoLock);
2778 /* Phase 2: update system catalogs */
2779 ATRewriteCatalogs(&wqueue, lockmode);
2781 /* Phase 3: scan/rewrite tables as needed */
2782 ATRewriteTables(&wqueue, lockmode);
2788 * Traffic cop for ALTER TABLE Phase 1 operations, including simple
2789 * recursion and permission checks.
2791 * Caller must have acquired appropriate lock type on relation already.
2792 * This lock should be held until commit.
2795 ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
2796 bool recurse, bool recursing, LOCKMODE lockmode)
2798 AlteredTableInfo *tab;
2801 /* Find or create work queue entry for this table */
2802 tab = ATGetQueueEntry(wqueue, rel);
2805 * Copy the original subcommand for each table. This avoids conflicts
2806 * when different child tables need to make different parse
2807 * transformations (for example, the same column may have different column
2808 * numbers in different children).
2810 cmd = copyObject(cmd);
2813 * Do permissions checking, recursion to child tables if needed, and any
2814 * additional phase-1 processing needed.
2816 switch (cmd->subtype)
2818 case AT_AddColumn: /* ADD COLUMN */
2819 ATSimplePermissions(rel,
2820 ATT_TABLE | ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
2821 ATPrepAddColumn(wqueue, rel, recurse, recursing, cmd, lockmode);
2822 /* Recursion occurs during execution phase */
2823 pass = AT_PASS_ADD_COL;
2825 case AT_AddColumnToView: /* add column via CREATE OR REPLACE
2827 ATSimplePermissions(rel, ATT_VIEW);
2828 ATPrepAddColumn(wqueue, rel, recurse, recursing, cmd, lockmode);
2829 /* Recursion occurs during execution phase */
2830 pass = AT_PASS_ADD_COL;
2832 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
2835 * We allow defaults on views so that INSERT into a view can have
2836 * default-ish behavior. This works because the rewriter
2837 * substitutes default values into INSERTs before it expands
2840 ATSimplePermissions(rel, ATT_TABLE | ATT_VIEW);
2841 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
2842 /* No command-specific prep needed */
2843 pass = cmd->def ? AT_PASS_ADD_CONSTR : AT_PASS_DROP;
2845 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
2846 ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
2847 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
2848 /* No command-specific prep needed */
2849 pass = AT_PASS_DROP;
2851 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
2852 ATSimplePermissions(rel, ATT_TABLE | ATT_FOREIGN_TABLE);
2853 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
2854 /* No command-specific prep needed */
2855 pass = AT_PASS_ADD_CONSTR;
2857 case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
2858 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
2859 /* Performs own permission checks */
2860 ATPrepSetStatistics(rel, cmd->name, cmd->def, lockmode);
2861 pass = AT_PASS_MISC;
2863 case AT_SetOptions: /* ALTER COLUMN SET ( options ) */
2864 case AT_ResetOptions: /* ALTER COLUMN RESET ( options ) */
2865 ATSimplePermissions(rel, ATT_TABLE | ATT_INDEX);
2866 /* This command never recurses */
2867 pass = AT_PASS_MISC;
2869 case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
2870 ATSimplePermissions(rel, ATT_TABLE);
2871 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
2872 /* No command-specific prep needed */
2873 pass = AT_PASS_MISC;
2875 case AT_DropColumn: /* DROP COLUMN */
2876 ATSimplePermissions(rel,
2877 ATT_TABLE | ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
2878 ATPrepDropColumn(wqueue, rel, recurse, recursing, cmd, lockmode);
2879 /* Recursion occurs during execution phase */
2880 pass = AT_PASS_DROP;
2882 case AT_AddIndex: /* ADD INDEX */
2883 ATSimplePermissions(rel, ATT_TABLE);
2884 /* This command never recurses */
2885 /* No command-specific prep needed */
2886 pass = AT_PASS_ADD_INDEX;
2888 case AT_AddConstraint: /* ADD CONSTRAINT */
2889 ATSimplePermissions(rel, ATT_TABLE);
2890 /* Recursion occurs during execution phase */
2891 /* No command-specific prep needed except saving recurse flag */
2893 cmd->subtype = AT_AddConstraintRecurse;
2894 pass = AT_PASS_ADD_CONSTR;
2896 case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
2897 ATSimplePermissions(rel, ATT_TABLE);
2898 /* This command never recurses */
2899 /* No command-specific prep needed */
2900 pass = AT_PASS_ADD_CONSTR;
2902 case AT_DropConstraint: /* DROP CONSTRAINT */
2903 ATSimplePermissions(rel, ATT_TABLE);
2904 /* Recursion occurs during execution phase */
2905 /* No command-specific prep needed except saving recurse flag */
2907 cmd->subtype = AT_DropConstraintRecurse;
2908 pass = AT_PASS_DROP;
2910 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
2911 ATSimplePermissions(rel,
2912 ATT_TABLE | ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
2913 /* Performs own recursion */
2914 ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd, lockmode);
2915 pass = AT_PASS_ALTER_TYPE;
2917 case AT_ChangeOwner: /* ALTER OWNER */
2918 /* This command never recurses */
2919 /* No command-specific prep needed */
2920 pass = AT_PASS_MISC;
2922 case AT_ClusterOn: /* CLUSTER ON */
2923 case AT_DropCluster: /* SET WITHOUT CLUSTER */
2924 ATSimplePermissions(rel, ATT_TABLE);
2925 /* These commands never recurse */
2926 /* No command-specific prep needed */
2927 pass = AT_PASS_MISC;
2929 case AT_AddOids: /* SET WITH OIDS */
2930 ATSimplePermissions(rel, ATT_TABLE);
2931 if (!rel->rd_rel->relhasoids || recursing)
2932 ATPrepAddOids(wqueue, rel, recurse, cmd, lockmode);
2933 /* Recursion occurs during execution phase */
2934 pass = AT_PASS_ADD_COL;
2936 case AT_DropOids: /* SET WITHOUT OIDS */
2937 ATSimplePermissions(rel, ATT_TABLE);
2938 /* Performs own recursion */
2939 if (rel->rd_rel->relhasoids)
2941 AlterTableCmd *dropCmd = makeNode(AlterTableCmd);
2943 dropCmd->subtype = AT_DropColumn;
2944 dropCmd->name = pstrdup("oid");
2945 dropCmd->behavior = cmd->behavior;
2946 ATPrepCmd(wqueue, rel, dropCmd, recurse, false, lockmode);
2948 pass = AT_PASS_DROP;
2950 case AT_SetTableSpace: /* SET TABLESPACE */
2951 ATSimplePermissions(rel, ATT_TABLE | ATT_INDEX);
2952 /* This command never recurses */
2953 ATPrepSetTableSpace(tab, rel, cmd->name, lockmode);
2954 pass = AT_PASS_MISC; /* doesn't actually matter */
2956 case AT_SetRelOptions: /* SET (...) */
2957 case AT_ResetRelOptions: /* RESET (...) */
2958 ATSimplePermissions(rel, ATT_TABLE | ATT_INDEX);
2959 /* This command never recurses */
2960 /* No command-specific prep needed */
2961 pass = AT_PASS_MISC;
2963 case AT_AddInherit: /* INHERIT */
2964 ATSimplePermissions(rel, ATT_TABLE);
2965 /* This command never recurses */
2966 ATPrepAddInherit(rel);
2967 pass = AT_PASS_MISC;
2969 case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
2970 ATSimplePermissions(rel, ATT_TABLE);
2971 /* Recursion occurs during execution phase */
2972 /* No command-specific prep needed except saving recurse flag */
2974 cmd->subtype = AT_ValidateConstraintRecurse;
2975 pass = AT_PASS_MISC;
2977 case AT_EnableTrig: /* ENABLE TRIGGER variants */
2978 case AT_EnableAlwaysTrig:
2979 case AT_EnableReplicaTrig:
2980 case AT_EnableTrigAll:
2981 case AT_EnableTrigUser:
2982 case AT_DisableTrig: /* DISABLE TRIGGER variants */
2983 case AT_DisableTrigAll:
2984 case AT_DisableTrigUser:
2985 case AT_EnableRule: /* ENABLE/DISABLE RULE variants */
2986 case AT_EnableAlwaysRule:
2987 case AT_EnableReplicaRule:
2988 case AT_DisableRule:
2989 case AT_DropInherit: /* NO INHERIT */
2990 case AT_AddOf: /* OF */
2991 case AT_DropOf: /* NOT OF */
2992 ATSimplePermissions(rel, ATT_TABLE);
2993 /* These commands never recurse */
2994 /* No command-specific prep needed */
2995 pass = AT_PASS_MISC;
2997 case AT_GenericOptions:
2998 ATSimplePermissions(rel, ATT_FOREIGN_TABLE);
2999 /* No command-specific prep needed */
3000 pass = AT_PASS_MISC;
3003 elog(ERROR, "unrecognized alter table type: %d",
3004 (int) cmd->subtype);
3005 pass = 0; /* keep compiler quiet */
3009 /* Add the subcommand to the appropriate list for phase 2 */
3010 tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
3016 * Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
3017 * dispatched in a "safe" execution order (designed to avoid unnecessary
3021 ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode)
3027 * We process all the tables "in parallel", one pass at a time. This is
3028 * needed because we may have to propagate work from one table to another
3029 * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
3030 * re-adding of the foreign key constraint to the other table). Work can
3031 * only be propagated into later passes, however.
3033 for (pass = 0; pass < AT_NUM_PASSES; pass++)
3035 /* Go through each table that needs to be processed */
3036 foreach(ltab, *wqueue)
3038 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
3039 List *subcmds = tab->subcmds[pass];
3047 * Appropriate lock was obtained by phase 1, needn't get it again
3049 rel = relation_open(tab->relid, NoLock);
3051 foreach(lcmd, subcmds)
3052 ATExecCmd(wqueue, tab, rel, (AlterTableCmd *) lfirst(lcmd), lockmode);
3055 * After the ALTER TYPE pass, do cleanup work (this is not done in
3056 * ATExecAlterColumnType since it should be done only once if
3057 * multiple columns of a table are altered).
3059 if (pass == AT_PASS_ALTER_TYPE)
3060 ATPostAlterTypeCleanup(wqueue, tab, lockmode);
3062 relation_close(rel, NoLock);
3066 /* Check to see if a toast table must be added. */
3067 foreach(ltab, *wqueue)
3069 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
3071 if (tab->relkind == RELKIND_RELATION)
3072 AlterTableCreateToastTable(tab->relid, (Datum) 0);
3077 * ATExecCmd: dispatch a subcommand to appropriate execution routine
3080 ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
3081 AlterTableCmd *cmd, LOCKMODE lockmode)
3083 switch (cmd->subtype)
3085 case AT_AddColumn: /* ADD COLUMN */
3086 case AT_AddColumnToView: /* add column via CREATE OR REPLACE
3088 ATExecAddColumn(wqueue, tab, rel, (ColumnDef *) cmd->def,
3089 false, false, false, lockmode);
3091 case AT_AddColumnRecurse:
3092 ATExecAddColumn(wqueue, tab, rel, (ColumnDef *) cmd->def,
3093 false, true, false, lockmode);
3095 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
3096 ATExecColumnDefault(rel, cmd->name, cmd->def, lockmode);
3098 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
3099 ATExecDropNotNull(rel, cmd->name, lockmode);
3101 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
3102 ATExecSetNotNull(tab, rel, cmd->name, lockmode);
3104 case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
3105 ATExecSetStatistics(rel, cmd->name, cmd->def, lockmode);
3107 case AT_SetOptions: /* ALTER COLUMN SET ( options ) */
3108 ATExecSetOptions(rel, cmd->name, cmd->def, false, lockmode);
3110 case AT_ResetOptions: /* ALTER COLUMN RESET ( options ) */
3111 ATExecSetOptions(rel, cmd->name, cmd->def, true, lockmode);
3113 case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
3114 ATExecSetStorage(rel, cmd->name, cmd->def, lockmode);
3116 case AT_DropColumn: /* DROP COLUMN */
3117 ATExecDropColumn(wqueue, rel, cmd->name,
3118 cmd->behavior, false, false, cmd->missing_ok, lockmode);
3120 case AT_DropColumnRecurse: /* DROP COLUMN with recursion */
3121 ATExecDropColumn(wqueue, rel, cmd->name,
3122 cmd->behavior, true, false, cmd->missing_ok, lockmode);
3124 case AT_AddIndex: /* ADD INDEX */
3125 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false, lockmode);
3127 case AT_ReAddIndex: /* ADD INDEX */
3128 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true, lockmode);
3130 case AT_AddConstraint: /* ADD CONSTRAINT */
3131 ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
3134 case AT_AddConstraintRecurse: /* ADD CONSTRAINT with recursion */
3135 ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
3138 case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
3139 ATExecAddIndexConstraint(tab, rel, (IndexStmt *) cmd->def, lockmode);
3141 case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
3142 ATExecValidateConstraint(rel, cmd->name, false, false, lockmode);
3144 case AT_ValidateConstraintRecurse: /* VALIDATE CONSTRAINT with
3146 ATExecValidateConstraint(rel, cmd->name, true, false, lockmode);
3148 case AT_DropConstraint: /* DROP CONSTRAINT */
3149 ATExecDropConstraint(rel, cmd->name, cmd->behavior,
3151 cmd->missing_ok, lockmode);
3153 case AT_DropConstraintRecurse: /* DROP CONSTRAINT with recursion */
3154 ATExecDropConstraint(rel, cmd->name, cmd->behavior,
3156 cmd->missing_ok, lockmode);
3158 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
3159 ATExecAlterColumnType(tab, rel, cmd, lockmode);
3161 case AT_ChangeOwner: /* ALTER OWNER */
3162 ATExecChangeOwner(RelationGetRelid(rel),
3163 get_role_oid(cmd->name, false),
3166 case AT_ClusterOn: /* CLUSTER ON */
3167 ATExecClusterOn(rel, cmd->name, lockmode);
3169 case AT_DropCluster: /* SET WITHOUT CLUSTER */
3170 ATExecDropCluster(rel, lockmode);
3172 case AT_AddOids: /* SET WITH OIDS */
3173 /* Use the ADD COLUMN code, unless prep decided to do nothing */
3174 if (cmd->def != NULL)
3175 ATExecAddColumn(wqueue, tab, rel, (ColumnDef *) cmd->def,
3176 true, false, false, lockmode);
3178 case AT_AddOidsRecurse: /* SET WITH OIDS */
3179 /* Use the ADD COLUMN code, unless prep decided to do nothing */
3180 if (cmd->def != NULL)
3181 ATExecAddColumn(wqueue, tab, rel, (ColumnDef *) cmd->def,
3182 true, true, false, lockmode);
3184 case AT_DropOids: /* SET WITHOUT OIDS */
3187 * Nothing to do here; we'll have generated a DropColumn
3188 * subcommand to do the real work
3191 case AT_SetTableSpace: /* SET TABLESPACE */
3194 * Nothing to do here; Phase 3 does the work
3197 case AT_SetRelOptions: /* SET (...) */
3198 ATExecSetRelOptions(rel, (List *) cmd->def, false, lockmode);
3200 case AT_ResetRelOptions: /* RESET (...) */
3201 ATExecSetRelOptions(rel, (List *) cmd->def, true, lockmode);
3204 case AT_EnableTrig: /* ENABLE TRIGGER name */
3205 ATExecEnableDisableTrigger(rel, cmd->name,
3206 TRIGGER_FIRES_ON_ORIGIN, false, lockmode);
3208 case AT_EnableAlwaysTrig: /* ENABLE ALWAYS TRIGGER name */
3209 ATExecEnableDisableTrigger(rel, cmd->name,
3210 TRIGGER_FIRES_ALWAYS, false, lockmode);
3212 case AT_EnableReplicaTrig: /* ENABLE REPLICA TRIGGER name */
3213 ATExecEnableDisableTrigger(rel, cmd->name,
3214 TRIGGER_FIRES_ON_REPLICA, false, lockmode);
3216 case AT_DisableTrig: /* DISABLE TRIGGER name */
3217 ATExecEnableDisableTrigger(rel, cmd->name,
3218 TRIGGER_DISABLED, false, lockmode);
3220 case AT_EnableTrigAll: /* ENABLE TRIGGER ALL */
3221 ATExecEnableDisableTrigger(rel, NULL,
3222 TRIGGER_FIRES_ON_ORIGIN, false, lockmode);
3224 case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
3225 ATExecEnableDisableTrigger(rel, NULL,
3226 TRIGGER_DISABLED, false, lockmode);
3228 case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
3229 ATExecEnableDisableTrigger(rel, NULL,
3230 TRIGGER_FIRES_ON_ORIGIN, true, lockmode);
3232 case AT_DisableTrigUser: /* DISABLE TRIGGER USER */
3233 ATExecEnableDisableTrigger(rel, NULL,
3234 TRIGGER_DISABLED, true, lockmode);
3237 case AT_EnableRule: /* ENABLE RULE name */
3238 ATExecEnableDisableRule(rel, cmd->name,
3239 RULE_FIRES_ON_ORIGIN, lockmode);
3241 case AT_EnableAlwaysRule: /* ENABLE ALWAYS RULE name */
3242 ATExecEnableDisableRule(rel, cmd->name,
3243 RULE_FIRES_ALWAYS, lockmode);
3245 case AT_EnableReplicaRule: /* ENABLE REPLICA RULE name */
3246 ATExecEnableDisableRule(rel, cmd->name,
3247 RULE_FIRES_ON_REPLICA, lockmode);
3249 case AT_DisableRule: /* DISABLE RULE name */
3250 ATExecEnableDisableRule(rel, cmd->name,
3251 RULE_DISABLED, lockmode);
3255 ATExecAddInherit(rel, (RangeVar *) cmd->def, lockmode);
3257 case AT_DropInherit:
3258 ATExecDropInherit(rel, (RangeVar *) cmd->def, lockmode);
3261 ATExecAddOf(rel, (TypeName *) cmd->def, lockmode);
3264 ATExecDropOf(rel, lockmode);
3266 case AT_GenericOptions:
3267 ATExecGenericOptions(rel, (List *) cmd->def);
3270 elog(ERROR, "unrecognized alter table type: %d",
3271 (int) cmd->subtype);
3276 * Bump the command counter to ensure the next subcommand in the sequence
3277 * can see the changes so far
3279 CommandCounterIncrement();
3283 * ATRewriteTables: ALTER TABLE phase 3
3286 ATRewriteTables(List **wqueue, LOCKMODE lockmode)
3290 /* Go through each table that needs to be checked or rewritten */
3291 foreach(ltab, *wqueue)
3293 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
3295 /* Foreign tables have no storage. */
3296 if (tab->relkind == RELKIND_FOREIGN_TABLE)
3300 * If we change column data types or add/remove OIDs, the operation
3301 * has to be propagated to tables that use this table's rowtype as a
3302 * column type. tab->newvals will also be non-NULL in the case where
3303 * we're adding a column with a default. We choose to forbid that
3304 * case as well, since composite types might eventually support
3307 * (Eventually we'll probably need to check for composite type
3308 * dependencies even when we're just scanning the table without a
3309 * rewrite, but at the moment a composite type does not enforce any
3310 * constraints, so it's not necessary/appropriate to enforce them just
3313 if (tab->newvals != NIL || tab->rewrite)
3317 rel = heap_open(tab->relid, NoLock);
3318 find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
3319 heap_close(rel, NoLock);
3323 * We only need to rewrite the table if at least one column needs to
3324 * be recomputed, or we are adding/removing the OID column.
3328 /* Build a temporary relation and copy data */
3333 OldHeap = heap_open(tab->relid, NoLock);
3336 * We don't support rewriting of system catalogs; there are too
3337 * many corner cases and too little benefit. In particular this
3338 * is certainly not going to work for mapped catalogs.
3340 if (IsSystemRelation(OldHeap))
3342 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3343 errmsg("cannot rewrite system relation \"%s\"",
3344 RelationGetRelationName(OldHeap))));
3347 * Don't allow rewrite on temp tables of other backends ... their
3348 * local buffer manager is not going to cope.
3350 if (RELATION_IS_OTHER_TEMP(OldHeap))
3352 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3353 errmsg("cannot rewrite temporary tables of other sessions")));
3356 * Select destination tablespace (same as original unless user
3357 * requested a change)
3359 if (tab->newTableSpace)
3360 NewTableSpace = tab->newTableSpace;
3362 NewTableSpace = OldHeap->rd_rel->reltablespace;
3364 heap_close(OldHeap, NoLock);
3366 /* Create transient table that will receive the modified data */
3367 OIDNewHeap = make_new_heap(tab->relid, NewTableSpace);
3370 * Copy the heap data into the new table with the desired
3371 * modifications, and test the current data within the table
3372 * against new constraints generated by ALTER TABLE commands.
3374 ATRewriteTable(tab, OIDNewHeap, lockmode);
3377 * Swap the physical files of the old and new heaps, then rebuild
3378 * indexes and discard the old heap. We can use RecentXmin for
3379 * the table's new relfrozenxid because we rewrote all the tuples
3380 * in ATRewriteTable, so no older Xid remains in the table. Also,
3381 * we never try to swap toast tables by content, since we have no
3382 * interest in letting this code work on system catalogs.
3384 finish_heap_swap(tab->relid, OIDNewHeap,
3385 false, false, true, RecentXmin);
3390 * Test the current data within the table against new constraints
3391 * generated by ALTER TABLE commands, but don't rebuild data.
3393 if (tab->constraints != NIL || tab->new_notnull)
3394 ATRewriteTable(tab, InvalidOid, lockmode);
3397 * If we had SET TABLESPACE but no reason to reconstruct tuples,
3398 * just do a block-by-block copy.
3400 if (tab->newTableSpace)
3401 ATExecSetTableSpace(tab->relid, tab->newTableSpace, lockmode);
3406 * Foreign key constraints are checked in a final pass, since (a) it's
3407 * generally best to examine each one separately, and (b) it's at least
3408 * theoretically possible that we have changed both relations of the
3409 * foreign key, and we'd better have finished both rewrites before we try
3410 * to read the tables.
3412 foreach(ltab, *wqueue)
3414 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
3415 Relation rel = NULL;
3418 foreach(lcon, tab->constraints)
3420 NewConstraint *con = lfirst(lcon);
3422 if (con->contype == CONSTR_FOREIGN)
3424 Constraint *fkconstraint = (Constraint *) con->qual;
3428 /* Long since locked, no need for another */
3429 rel = heap_open(tab->relid, NoLock);
3432 * We're adding a trigger to both tables, so the lock level
3433 * here should sensibly reflect that.
3435 refrel = heap_open(con->refrelid, ShareRowExclusiveLock);
3437 validateForeignKeyConstraint(fkconstraint->conname, rel, refrel,
3442 * No need to mark the constraint row as validated, we did
3443 * that when we inserted the row earlier.
3446 heap_close(refrel, NoLock);
3451 heap_close(rel, NoLock);
3456 * ATRewriteTable: scan or rewrite one table
3458 * OIDNewHeap is InvalidOid if we don't need to rewrite
3461 ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap, LOCKMODE lockmode)
3465 TupleDesc oldTupDesc;
3466 TupleDesc newTupDesc;
3467 bool needscan = false;
3468 List *notnull_attrs;
3473 BulkInsertState bistate;
3477 * Open the relation(s). We have surely already locked the existing
3480 oldrel = heap_open(tab->relid, NoLock);
3481 oldTupDesc = tab->oldDesc;
3482 newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
3484 if (OidIsValid(OIDNewHeap))
3485 newrel = heap_open(OIDNewHeap, lockmode);
3490 * Prepare a BulkInsertState and options for heap_insert. Because we're
3491 * building a new heap, we can skip WAL-logging and fsync it to disk at
3492 * the end instead (unless WAL-logging is required for archiving or
3493 * streaming replication). The FSM is empty too, so don't bother using it.
3497 mycid = GetCurrentCommandId(true);
3498 bistate = GetBulkInsertState();
3500 hi_options = HEAP_INSERT_SKIP_FSM;
3501 if (!XLogIsNeeded())
3502 hi_options |= HEAP_INSERT_SKIP_WAL;
3506 /* keep compiler quiet about using these uninitialized */
3513 * Generate the constraint and default execution states
3516 estate = CreateExecutorState();
3518 /* Build the needed expression execution states */
3519 foreach(l, tab->constraints)
3521 NewConstraint *con = lfirst(l);
3523 switch (con->contype)
3527 con->qualstate = (List *)
3528 ExecPrepareExpr((Expr *) con->qual, estate);
3530 case CONSTR_FOREIGN:
3531 /* Nothing to do here */
3534 elog(ERROR, "unrecognized constraint type: %d",
3535 (int) con->contype);
3539 foreach(l, tab->newvals)
3541 NewColumnValue *ex = lfirst(l);
3543 /* expr already planned */
3544 ex->exprstate = ExecInitExpr((Expr *) ex->expr, NULL);
3547 notnull_attrs = NIL;
3548 if (newrel || tab->new_notnull)
3551 * If we are rebuilding the tuples OR if we added any new NOT NULL
3552 * constraints, check all not-null constraints. This is a bit of
3553 * overkill but it minimizes risk of bugs, and heap_attisnull is a
3554 * pretty cheap test anyway.
3556 for (i = 0; i < newTupDesc->natts; i++)
3558 if (newTupDesc->attrs[i]->attnotnull &&
3559 !newTupDesc->attrs[i]->attisdropped)
3560 notnull_attrs = lappend_int(notnull_attrs, i);
3566 if (newrel || needscan)
3568 ExprContext *econtext;
3571 TupleTableSlot *oldslot;
3572 TupleTableSlot *newslot;
3575 MemoryContext oldCxt;
3576 List *dropped_attrs = NIL;
3581 (errmsg("rewriting table \"%s\"",
3582 RelationGetRelationName(oldrel))));
3585 (errmsg("verifying table \"%s\"",
3586 RelationGetRelationName(oldrel))));
3591 * All predicate locks on the tuples or pages are about to be made
3592 * invalid, because we move tuples around. Promote them to
3595 TransferPredicateLocksToHeapRelation(oldrel);
3598 econtext = GetPerTupleExprContext(estate);
3601 * Make tuple slots for old and new tuples. Note that even when the
3602 * tuples are the same, the tupDescs might not be (consider ADD COLUMN
3603 * without a default).
3605 oldslot = MakeSingleTupleTableSlot(oldTupDesc);
3606 newslot = MakeSingleTupleTableSlot(newTupDesc);
3608 /* Preallocate values/isnull arrays */
3609 i = Max(newTupDesc->natts, oldTupDesc->natts);
3610 values = (Datum *) palloc(i * sizeof(Datum));
3611 isnull = (bool *) palloc(i * sizeof(bool));
3612 memset(values, 0, i * sizeof(Datum));
3613 memset(isnull, true, i * sizeof(bool));
3616 * Any attributes that are dropped according to the new tuple
3617 * descriptor can be set to NULL. We precompute the list of dropped
3618 * attributes to avoid needing to do so in the per-tuple loop.
3620 for (i = 0; i < newTupDesc->natts; i++)
3622 if (newTupDesc->attrs[i]->attisdropped)
3623 dropped_attrs = lappend_int(dropped_attrs, i);
3627 * Scan through the rows, generating a new row if needed and then
3628 * checking all the constraints.
3630 scan = heap_beginscan(oldrel, SnapshotNow, 0, NULL);
3633 * Switch to per-tuple memory context and reset it for each tuple
3634 * produced, so we don't leak memory.
3636 oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
3638 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
3642 Oid tupOid = InvalidOid;
3644 /* Extract data from old tuple */
3645 heap_deform_tuple(tuple, oldTupDesc, values, isnull);
3646 if (oldTupDesc->tdhasoid)
3647 tupOid = HeapTupleGetOid(tuple);
3649 /* Set dropped attributes to null in new tuple */
3650 foreach(lc, dropped_attrs)
3651 isnull[lfirst_int(lc)] = true;
3654 * Process supplied expressions to replace selected columns.
3655 * Expression inputs come from the old tuple.
3657 ExecStoreTuple(tuple, oldslot, InvalidBuffer, false);
3658 econtext->ecxt_scantuple = oldslot;
3660 foreach(l, tab->newvals)
3662 NewColumnValue *ex = lfirst(l);
3664 values[ex->attnum - 1] = ExecEvalExpr(ex->exprstate,
3666 &isnull[ex->attnum - 1],
3671 * Form the new tuple. Note that we don't explicitly pfree it,
3672 * since the per-tuple memory context will be reset shortly.
3674 tuple = heap_form_tuple(newTupDesc, values, isnull);
3676 /* Preserve OID, if any */
3677 if (newTupDesc->tdhasoid)
3678 HeapTupleSetOid(tuple, tupOid);
3681 /* Now check any constraints on the possibly-changed tuple */
3682 ExecStoreTuple(tuple, newslot, InvalidBuffer, false);
3683 econtext->ecxt_scantuple = newslot;
3685 foreach(l, notnull_attrs)
3687 int attn = lfirst_int(l);
3689 if (heap_attisnull(tuple, attn + 1))
3691 (errcode(ERRCODE_NOT_NULL_VIOLATION),
3692 errmsg("column \"%s\" contains null values",
3693 NameStr(newTupDesc->attrs[attn]->attname))));
3696 foreach(l, tab->constraints)
3698 NewConstraint *con = lfirst(l);
3700 switch (con->contype)
3703 if (!ExecQual(con->qualstate, econtext, true))
3705 (errcode(ERRCODE_CHECK_VIOLATION),
3706 errmsg("check constraint \"%s\" is violated by some row",
3709 case CONSTR_FOREIGN:
3710 /* Nothing to do here */
3713 elog(ERROR, "unrecognized constraint type: %d",
3714 (int) con->contype);
3718 /* Write the tuple out to the new relation */
3720 heap_insert(newrel, tuple, mycid, hi_options, bistate);
3722 ResetExprContext(econtext);
3724 CHECK_FOR_INTERRUPTS();
3727 MemoryContextSwitchTo(oldCxt);
3730 ExecDropSingleTupleTableSlot(oldslot);
3731 ExecDropSingleTupleTableSlot(newslot);
3734 FreeExecutorState(estate);
3736 heap_close(oldrel, NoLock);
3739 FreeBulkInsertState(bistate);
3741 /* If we skipped writing WAL, then we need to sync the heap. */
3742 if (hi_options & HEAP_INSERT_SKIP_WAL)
3745 heap_close(newrel, NoLock);
3750 * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
3752 static AlteredTableInfo *
3753 ATGetQueueEntry(List **wqueue, Relation rel)
3755 Oid relid = RelationGetRelid(rel);
3756 AlteredTableInfo *tab;
3759 foreach(ltab, *wqueue)
3761 tab = (AlteredTableInfo *) lfirst(ltab);
3762 if (tab->relid == relid)
3767 * Not there, so add it. Note that we make a copy of the relation's
3768 * existing descriptor before anything interesting can happen to it.
3770 tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
3772 tab->relkind = rel->rd_rel->relkind;
3773 tab->oldDesc = CreateTupleDescCopy(RelationGetDescr(rel));
3775 *wqueue = lappend(*wqueue, tab);
3781 * ATSimplePermissions
3783 * - Ensure that it is a relation (or possibly a view)
3784 * - Ensure this user is the owner
3785 * - Ensure that it is not a system table
3788 ATSimplePermissions(Relation rel, int allowed_targets)
3792 switch (rel->rd_rel->relkind)
3794 case RELKIND_RELATION:
3795 actual_target = ATT_TABLE;
3798 actual_target = ATT_VIEW;
3801 actual_target = ATT_INDEX;
3803 case RELKIND_COMPOSITE_TYPE:
3804 actual_target = ATT_COMPOSITE_TYPE;
3806 case RELKIND_FOREIGN_TABLE:
3807 actual_target = ATT_FOREIGN_TABLE;
3814 /* Wrong target type? */
3815 if ((actual_target & allowed_targets) == 0)
3816 ATWrongRelkindError(rel, allowed_targets);
3818 /* Permissions checks */
3819 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3820 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3821 RelationGetRelationName(rel));
3823 if (!allowSystemTableMods && IsSystemRelation(rel))
3825 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3826 errmsg("permission denied: \"%s\" is a system catalog",
3827 RelationGetRelationName(rel))));
3831 * ATWrongRelkindError
3833 * Throw an error when a relation has been determined to be of the wrong
3837 ATWrongRelkindError(Relation rel, int allowed_targets)
3841 switch (allowed_targets)
3844 msg = _("\"%s\" is not a table");
3846 case ATT_TABLE | ATT_INDEX:
3847 msg = _("\"%s\" is not a table or index");
3849 case ATT_TABLE | ATT_VIEW:
3850 msg = _("\"%s\" is not a table or view");
3852 case ATT_TABLE | ATT_FOREIGN_TABLE:
3853 msg = _("\"%s\" is not a table or foreign table");
3855 case ATT_TABLE | ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE:
3856 msg = _("\"%s\" is not a table, composite type, or foreign table");
3859 msg = _("\"%s\" is not a view");
3861 case ATT_FOREIGN_TABLE:
3862 msg = _("\"%s\" is not a foreign table");
3865 /* shouldn't get here, add all necessary cases above */
3866 msg = _("\"%s\" is of the wrong type");
3871 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3872 errmsg(msg, RelationGetRelationName(rel))));
3878 * Simple table recursion sufficient for most ALTER TABLE operations.
3879 * All direct and indirect children are processed in an unspecified order.
3880 * Note that if a child inherits from the original table via multiple
3881 * inheritance paths, it will be visited just once.
3884 ATSimpleRecursion(List **wqueue, Relation rel,
3885 AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode)
3888 * Propagate to children if desired. Non-table relations never have
3889 * children, so no need to search in that case.
3891 if (recurse && rel->rd_rel->relkind == RELKIND_RELATION)
3893 Oid relid = RelationGetRelid(rel);
3897 children = find_all_inheritors(relid, lockmode, NULL);
3900 * find_all_inheritors does the recursive search of the inheritance
3901 * hierarchy, so all we have to do is process all of the relids in the
3902 * list that it returns.
3904 foreach(child, children)
3906 Oid childrelid = lfirst_oid(child);
3909 if (childrelid == relid)
3911 /* find_all_inheritors already got lock */
3912 childrel = relation_open(childrelid, NoLock);
3913 CheckTableNotInUse(childrel, "ALTER TABLE");
3914 ATPrepCmd(wqueue, childrel, cmd, false, true, lockmode);
3915 relation_close(childrel, NoLock);
3921 * ATTypedTableRecursion
3923 * Propagate ALTER TYPE operations to the typed tables of that type.
3924 * Also check the RESTRICT/CASCADE behavior. Given CASCADE, also permit
3925 * recursion to inheritance children of the typed tables.
3928 ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
3934 Assert(rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
3936 children = find_typed_table_dependencies(rel->rd_rel->reltype,
3937 RelationGetRelationName(rel),
3940 foreach(child, children)
3942 Oid childrelid = lfirst_oid(child);
3945 childrel = relation_open(childrelid, lockmode);
3946 CheckTableNotInUse(childrel, "ALTER TABLE");
3947 ATPrepCmd(wqueue, childrel, cmd, true, true, lockmode);
3948 relation_close(childrel, NoLock);
3954 * find_composite_type_dependencies
3956 * Check to see if a composite type is being used as a column in some
3957 * other table (possibly nested several levels deep in composite types!).
3958 * Eventually, we'd like to propagate the check or rewrite operation
3959 * into other such tables, but for now, just error out if we find any.
3961 * Caller should provide either a table name or a type name (not both) to
3962 * report in the error message, if any.
3964 * We assume that functions and views depending on the type are not reasons
3965 * to reject the ALTER. (How safe is this really?)
3968 find_composite_type_dependencies(Oid typeOid, Relation origRelation,
3969 const char *origTypeName)
3973 SysScanDesc depScan;
3978 * We scan pg_depend to find those things that depend on the rowtype. (We
3979 * assume we can ignore refobjsubid for a rowtype.)
3981 depRel = heap_open(DependRelationId, AccessShareLock);
3983 ScanKeyInit(&key[0],
3984 Anum_pg_depend_refclassid,
3985 BTEqualStrategyNumber, F_OIDEQ,
3986 ObjectIdGetDatum(TypeRelationId));
3987 ScanKeyInit(&key[1],
3988 Anum_pg_depend_refobjid,
3989 BTEqualStrategyNumber, F_OIDEQ,
3990 ObjectIdGetDatum(typeOid));
3992 depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
3993 SnapshotNow, 2, key);
3995 while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
3997 Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
3999 Form_pg_attribute att;
4001 /* Ignore dependees that aren't user columns of relations */
4002 /* (we assume system columns are never of rowtypes) */
4003 if (pg_depend->classid != RelationRelationId ||
4004 pg_depend->objsubid <= 0)
4007 rel = relation_open(pg_depend->objid, AccessShareLock);
4008 att = rel->rd_att->attrs[pg_depend->objsubid - 1];
4010 if (rel->rd_rel->relkind == RELKIND_RELATION)
4014 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4015 errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
4017 RelationGetRelationName(rel),
4018 NameStr(att->attname))));
4019 else if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
4021 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4022 errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
4023 RelationGetRelationName(origRelation),
4024 RelationGetRelationName(rel),
4025 NameStr(att->attname))));
4026 else if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
4028 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4029 errmsg("cannot alter foreign table \"%s\" because column \"%s.%s\" uses its row type",
4030 RelationGetRelationName(origRelation),
4031 RelationGetRelationName(rel),
4032 NameStr(att->attname))));
4035 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4036 errmsg("cannot alter table \"%s\" because column \"%s.%s\" uses its row type",
4037 RelationGetRelationName(origRelation),
4038 RelationGetRelationName(rel),
4039 NameStr(att->attname))));
4041 else if (OidIsValid(rel->rd_rel->reltype))
4044 * A view or composite type itself isn't a problem, but we must
4045 * recursively check for indirect dependencies via its rowtype.
4047 find_composite_type_dependencies(rel->rd_rel->reltype,
4048 origRelation, origTypeName);
4051 relation_close(rel, AccessShareLock);
4054 systable_endscan(depScan);
4056 relation_close(depRel, AccessShareLock);
4059 * If there's an array type for the rowtype, must check for uses of it,
4062 arrayOid = get_array_type(typeOid);
4063 if (OidIsValid(arrayOid))
4064 find_composite_type_dependencies(arrayOid, origRelation, origTypeName);
4069 * find_typed_table_dependencies
4071 * Check to see if a composite type is being used as the type of a
4072 * typed table. Abort if any are found and behavior is RESTRICT.
4073 * Else return the list of tables.
4076 find_typed_table_dependencies(Oid typeOid, const char *typeName, DropBehavior behavior)
4084 classRel = heap_open(RelationRelationId, AccessShareLock);
4086 ScanKeyInit(&key[0],
4087 Anum_pg_class_reloftype,
4088 BTEqualStrategyNumber, F_OIDEQ,
4089 ObjectIdGetDatum(typeOid));
4091 scan = heap_beginscan(classRel, SnapshotNow, 1, key);
4093 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
4095 if (behavior == DROP_RESTRICT)
4097 (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
4098 errmsg("cannot alter type \"%s\" because it is the type of a typed table",
4100 errhint("Use ALTER ... CASCADE to alter the typed tables too.")));
4102 result = lappend_oid(result, HeapTupleGetOid(tuple));
4106 heap_close(classRel, AccessShareLock);
4115 * Check whether a type is suitable for CREATE TABLE OF/ALTER TABLE OF. If it
4116 * isn't suitable, throw an error. Currently, we require that the type
4117 * originated with CREATE TYPE AS. We could support any row type, but doing so
4118 * would require handling a number of extra corner cases in the DDL commands.
4121 check_of_type(HeapTuple typetuple)
4123 Form_pg_type typ = (Form_pg_type) GETSTRUCT(typetuple);
4124 bool typeOk = false;
4126 if (typ->typtype == TYPTYPE_COMPOSITE)
4128 Relation typeRelation;
4130 Assert(OidIsValid(typ->typrelid));
4131 typeRelation = relation_open(typ->typrelid, AccessShareLock);
4132 typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
4135 * Close the parent rel, but keep our AccessShareLock on it until xact
4136 * commit. That will prevent someone else from deleting or ALTERing
4137 * the type before the typed table creation/conversion commits.
4139 relation_close(typeRelation, NoLock);
4143 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4144 errmsg("type %s is not a composite type",
4145 format_type_be(HeapTupleGetOid(typetuple)))));
4150 * ALTER TABLE ADD COLUMN
4152 * Adds an additional attribute to a relation making the assumption that
4153 * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
4154 * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
4157 * ADD COLUMN cannot use the normal ALTER TABLE recursion mechanism, because we
4158 * have to decide at runtime whether to recurse or not depending on whether we
4159 * actually add a column or merely merge with an existing column. (We can't
4160 * check this in a static pre-pass because it won't handle multiple inheritance
4161 * situations correctly.)
4164 ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
4165 AlterTableCmd *cmd, LOCKMODE lockmode)
4167 if (rel->rd_rel->reloftype && !recursing)
4169 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4170 errmsg("cannot add column to typed table")));
4172 if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
4173 ATTypedTableRecursion(wqueue, rel, cmd, lockmode);
4176 cmd->subtype = AT_AddColumnRecurse;
4180 ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel,
4181 ColumnDef *colDef, bool isOid,
4182 bool recurse, bool recursing, LOCKMODE lockmode)
4184 Oid myrelid = RelationGetRelid(rel);
4188 FormData_pg_attribute attribute;
4191 HeapTuple typeTuple;
4200 /* At top level, permission check was done in ATPrepCmd, else do it */
4202 ATSimplePermissions(rel, ATT_TABLE);
4204 attrdesc = heap_open(AttributeRelationId, RowExclusiveLock);
4207 * Are we adding the column to a recursion child? If so, check whether to
4208 * merge with an existing definition for the column. If we do merge, we
4209 * must not recurse. Children will already have the column, and recursing
4210 * into them would mess up attinhcount.
4212 if (colDef->inhcount > 0)
4216 /* Does child already have a column by this name? */
4217 tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
4218 if (HeapTupleIsValid(tuple))
4220 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
4225 /* Child column must match on type, typmod, and collation */
4226 typenameTypeIdAndMod(NULL, colDef->typeName, &ctypeId, &ctypmod);
4227 if (ctypeId != childatt->atttypid ||
4228 ctypmod != childatt->atttypmod)
4230 (errcode(ERRCODE_DATATYPE_MISMATCH),
4231 errmsg("child table \"%s\" has different type for column \"%s\"",
4232 RelationGetRelationName(rel), colDef->colname)));
4233 ccollid = GetColumnDefCollation(NULL, colDef, ctypeId);
4234 if (ccollid != childatt->attcollation)
4236 (errcode(ERRCODE_COLLATION_MISMATCH),
4237 errmsg("child table \"%s\" has different collation for column \"%s\"",
4238 RelationGetRelationName(rel), colDef->colname),
4239 errdetail("\"%s\" versus \"%s\"",
4240 get_collation_name(ccollid),
4241 get_collation_name(childatt->attcollation))));
4243 /* If it's OID, child column must actually be OID */
4244 if (isOid && childatt->attnum != ObjectIdAttributeNumber)
4246 (errcode(ERRCODE_DATATYPE_MISMATCH),
4247 errmsg("child table \"%s\" has a conflicting \"%s\" column",
4248 RelationGetRelationName(rel), colDef->colname)));
4250 /* Bump the existing child att's inhcount */
4251 childatt->attinhcount++;
4252 simple_heap_update(attrdesc, &tuple->t_self, tuple);
4253 CatalogUpdateIndexes(attrdesc, tuple);
4255 heap_freetuple(tuple);
4257 /* Inform the user about the merge */
4259 (errmsg("merging definition of column \"%s\" for child \"%s\"",
4260 colDef->colname, RelationGetRelationName(rel))));
4262 heap_close(attrdesc, RowExclusiveLock);
4267 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
4269 reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
4270 if (!HeapTupleIsValid(reltup))
4271 elog(ERROR, "cache lookup failed for relation %u", myrelid);
4272 relkind = ((Form_pg_class) GETSTRUCT(reltup))->relkind;
4275 * this test is deliberately not attisdropped-aware, since if one tries to
4276 * add a column matching a dropped column name, it's gonna fail anyway.
4278 if (SearchSysCacheExists2(ATTNAME,
4279 ObjectIdGetDatum(myrelid),
4280 PointerGetDatum(colDef->colname)))
4282 (errcode(ERRCODE_DUPLICATE_COLUMN),
4283 errmsg("column \"%s\" of relation \"%s\" already exists",
4284 colDef->colname, RelationGetRelationName(rel))));
4286 /* Determine the new attribute's number */
4288 newattnum = ObjectIdAttributeNumber;
4291 newattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts + 1;
4292 if (newattnum > MaxHeapAttributeNumber)
4294 (errcode(ERRCODE_TOO_MANY_COLUMNS),
4295 errmsg("tables can have at most %d columns",
4296 MaxHeapAttributeNumber)));
4299 typeTuple = typenameType(NULL, colDef->typeName, &typmod);
4300 tform = (Form_pg_type) GETSTRUCT(typeTuple);
4301 typeOid = HeapTupleGetOid(typeTuple);
4302 collOid = GetColumnDefCollation(NULL, colDef, typeOid);
4304 /* make sure datatype is legal for a column */
4305 CheckAttributeType(colDef->colname, typeOid, collOid,
4306 list_make1_oid(rel->rd_rel->reltype),
4309 /* construct new attribute's pg_attribute entry */
4310 attribute.attrelid = myrelid;
4311 namestrcpy(&(attribute.attname), colDef->colname);
4312 attribute.atttypid = typeOid;
4313 attribute.attstattarget = (newattnum > 0) ? -1 : 0;
4314 attribute.attlen = tform->typlen;
4315 attribute.attcacheoff = -1;
4316 attribute.atttypmod = typmod;
4317 attribute.attnum = newattnum;
4318 attribute.attbyval = tform->typbyval;
4319 attribute.attndims = list_length(colDef->typeName->arrayBounds);
4320 attribute.attstorage = tform->typstorage;
4321 attribute.attalign = tform->typalign;
4322 attribute.attnotnull = colDef->is_not_null;
4323 attribute.atthasdef = false;
4324 attribute.attisdropped = false;
4325 attribute.attislocal = colDef->is_local;
4326 attribute.attinhcount = colDef->inhcount;
4327 attribute.attcollation = collOid;
4328 /* attribute.attacl is handled by InsertPgAttributeTuple */
4330 ReleaseSysCache(typeTuple);
4332 InsertPgAttributeTuple(attrdesc, &attribute, NULL);
4334 heap_close(attrdesc, RowExclusiveLock);
4337 * Update pg_class tuple as appropriate
4340 ((Form_pg_class) GETSTRUCT(reltup))->relhasoids = true;
4342 ((Form_pg_class) GETSTRUCT(reltup))->relnatts = newattnum;
4344 simple_heap_update(pgclass, &reltup->t_self, reltup);
4346 /* keep catalog indexes current */
4347 CatalogUpdateIndexes(pgclass, reltup);
4349 heap_freetuple(reltup);
4351 /* Post creation hook for new attribute */
4352 InvokeObjectAccessHook(OAT_POST_CREATE,
4353 RelationRelationId, myrelid, newattnum);
4355 heap_close(pgclass, RowExclusiveLock);
4357 /* Make the attribute's catalog entry visible */
4358 CommandCounterIncrement();
4361 * Store the DEFAULT, if any, in the catalogs
4363 if (colDef->raw_default)
4365 RawColumnDefault *rawEnt;
4367 if (relkind == RELKIND_FOREIGN_TABLE)
4369 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4370 errmsg("default values on foreign tables are not supported")));
4372 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
4373 rawEnt->attnum = attribute.attnum;
4374 rawEnt->raw_default = copyObject(colDef->raw_default);
4377 * This function is intended for CREATE TABLE, so it processes a
4378 * _list_ of defaults, but we just do one.
4380 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL, false, true);
4382 /* Make the additional catalog changes visible */
4383 CommandCounterIncrement();
4387 * Tell Phase 3 to fill in the default expression, if there is one.
4389 * If there is no default, Phase 3 doesn't have to do anything, because
4390 * that effectively means that the default is NULL. The heap tuple access
4391 * routines always check for attnum > # of attributes in tuple, and return
4392 * NULL if so, so without any modification of the tuple data we will get
4393 * the effect of NULL values in the new column.
4395 * An exception occurs when the new column is of a domain type: the domain
4396 * might have a NOT NULL constraint, or a check constraint that indirectly
4397 * rejects nulls. If there are any domain constraints then we construct
4398 * an explicit NULL default value that will be passed through
4399 * CoerceToDomain processing. (This is a tad inefficient, since it causes
4400 * rewriting the table which we really don't have to do, but the present
4401 * design of domain processing doesn't offer any simple way of checking
4402 * the constraints more directly.)
4404 * Note: we use build_column_default, and not just the cooked default
4405 * returned by AddRelationNewConstraints, so that the right thing happens
4406 * when a datatype's default applies.
4408 * We skip this step completely for views and foreign tables. For a view,
4409 * we can only get here from CREATE OR REPLACE VIEW, which historically
4410 * doesn't set up defaults, not even for domain-typed columns. And in any
4411 * case we mustn't invoke Phase 3 on a view or foreign table, since they
4414 if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE
4415 && relkind != RELKIND_FOREIGN_TABLE && attribute.attnum > 0)
4417 defval = (Expr *) build_column_default(rel, attribute.attnum);
4419 if (!defval && GetDomainConstraints(typeOid) != NIL)
4425 baseTypeMod = typmod;
4426 baseTypeId = getBaseTypeAndTypmod(typeOid, &baseTypeMod);
4427 baseTypeColl = get_typcollation(baseTypeId);
4428 defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod, baseTypeColl);
4429 defval = (Expr *) coerce_to_target_type(NULL,
4434 COERCION_ASSIGNMENT,
4435 COERCE_IMPLICIT_CAST,
4437 if (defval == NULL) /* should not happen */
4438 elog(ERROR, "failed to coerce base type to domain");
4443 NewColumnValue *newval;
4445 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
4446 newval->attnum = attribute.attnum;
4447 newval->expr = expression_planner(defval);
4449 tab->newvals = lappend(tab->newvals, newval);
4450 tab->rewrite = true;
4454 * If the new column is NOT NULL, tell Phase 3 it needs to test that.
4455 * (Note we don't do this for an OID column. OID will be marked not
4456 * null, but since it's filled specially, there's no need to test
4459 tab->new_notnull |= colDef->is_not_null;
4463 * If we are adding an OID column, we have to tell Phase 3 to rewrite the
4464 * table to fix that.
4467 tab->rewrite = true;
4470 * Add needed dependency entries for the new column.
4472 add_column_datatype_dependency(myrelid, newattnum, attribute.atttypid);
4473 add_column_collation_dependency(myrelid, newattnum, attribute.attcollation);
4476 * Propagate to children as appropriate. Unlike most other ALTER
4477 * routines, we have to do this one level of recursion at a time; we can't
4478 * use find_all_inheritors to do it in one pass.
4480 children = find_inheritance_children(RelationGetRelid(rel), lockmode);
4483 * If we are told not to recurse, there had better not be any child
4484 * tables; else the addition would put them out of step.
4486 if (children && !recurse)
4488 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4489 errmsg("column must be added to child tables too")));
4491 /* Children should see column as singly inherited */
4494 colDef = copyObject(colDef);
4495 colDef->inhcount = 1;
4496 colDef->is_local = false;
4499 foreach(child, children)
4501 Oid childrelid = lfirst_oid(child);
4503 AlteredTableInfo *childtab;
4505 /* find_inheritance_children already got lock */
4506 childrel = heap_open(childrelid, NoLock);
4507 CheckTableNotInUse(childrel, "ALTER TABLE");
4509 /* Find or create work queue entry for this table */
4510 childtab = ATGetQueueEntry(wqueue, childrel);
4512 /* Recurse to child */
4513 ATExecAddColumn(wqueue, childtab, childrel,
4514 colDef, isOid, recurse, true, lockmode);
4516 heap_close(childrel, NoLock);
4521 * Install a column's dependency on its datatype.
4524 add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
4526 ObjectAddress myself,
4529 myself.classId = RelationRelationId;
4530 myself.objectId = relid;
4531 myself.objectSubId = attnum;
4532 referenced.classId = TypeRelationId;
4533 referenced.objectId = typid;
4534 referenced.objectSubId = 0;
4535 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
4539 * Install a column's dependency on its collation.
4542 add_column_collation_dependency(Oid relid, int32 attnum, Oid collid)
4544 ObjectAddress myself,
4547 /* We know the default collation is pinned, so don't bother recording it */
4548 if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
4550 myself.classId = RelationRelationId;
4551 myself.objectId = relid;
4552 myself.objectSubId = attnum;
4553 referenced.classId = CollationRelationId;
4554 referenced.objectId = collid;
4555 referenced.objectSubId = 0;
4556 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
4561 * ALTER TABLE SET WITH OIDS
4563 * Basically this is an ADD COLUMN for the special OID column. We have
4564 * to cons up a ColumnDef node because the ADD COLUMN code needs one.
4567 ATPrepAddOids(List **wqueue, Relation rel, bool recurse, AlterTableCmd *cmd, LOCKMODE lockmode)
4569 /* If we're recursing to a child table, the ColumnDef is already set up */
4570 if (cmd->def == NULL)
4572 ColumnDef *cdef = makeNode(ColumnDef);
4574 cdef->colname = pstrdup("oid");
4575 cdef->typeName = makeTypeNameFromOid(OIDOID, -1);
4577 cdef->is_local = true;
4578 cdef->is_not_null = true;
4580 cmd->def = (Node *) cdef;
4582 ATPrepAddColumn(wqueue, rel, recurse, false, cmd, lockmode);
4585 cmd->subtype = AT_AddOidsRecurse;
4589 * ALTER TABLE ALTER COLUMN DROP NOT NULL
4592 ATExecDropNotNull(Relation rel, const char *colName, LOCKMODE lockmode)
4598 ListCell *indexoidscan;
4601 * lookup the attribute
4603 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
4605 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4607 if (!HeapTupleIsValid(tuple))
4609 (errcode(ERRCODE_UNDEFINED_COLUMN),
4610 errmsg("column \"%s\" of relation \"%s\" does not exist",
4611 colName, RelationGetRelationName(rel))));
4613 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
4615 /* Prevent them from altering a system attribute */
4618 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4619 errmsg("cannot alter system column \"%s\"",
4623 * Check that the attribute is not in a primary key
4626 /* Loop over all indexes on the relation */
4627 indexoidlist = RelationGetIndexList(rel);
4629 foreach(indexoidscan, indexoidlist)
4631 Oid indexoid = lfirst_oid(indexoidscan);
4632 HeapTuple indexTuple;
4633 Form_pg_index indexStruct;
4636 indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
4637 if (!HeapTupleIsValid(indexTuple))
4638 elog(ERROR, "cache lookup failed for index %u", indexoid);
4639 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4641 /* If the index is not a primary key, skip the check */
4642 if (indexStruct->indisprimary)
4645 * Loop over each attribute in the primary key and see if it
4646 * matches the to-be-altered attribute
4648 for (i = 0; i < indexStruct->indnatts; i++)
4650 if (indexStruct->indkey.values[i] == attnum)
4652 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4653 errmsg("column \"%s\" is in a primary key",
4658 ReleaseSysCache(indexTuple);
4661 list_free(indexoidlist);
4664 * Okay, actually perform the catalog change ... if needed
4666 if (((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
4668 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = FALSE;
4670 simple_heap_update(attr_rel, &tuple->t_self, tuple);
4672 /* keep the system catalog indexes current */
4673 CatalogUpdateIndexes(attr_rel, tuple);
4676 heap_close(attr_rel, RowExclusiveLock);
4680 * ALTER TABLE ALTER COLUMN SET NOT NULL
4683 ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
4684 const char *colName, LOCKMODE lockmode)
4691 * lookup the attribute
4693 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
4695 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4697 if (!HeapTupleIsValid(tuple))
4699 (errcode(ERRCODE_UNDEFINED_COLUMN),
4700 errmsg("column \"%s\" of relation \"%s\" does not exist",
4701 colName, RelationGetRelationName(rel))));
4703 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
4705 /* Prevent them from altering a system attribute */
4708 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4709 errmsg("cannot alter system column \"%s\"",
4713 * Okay, actually perform the catalog change ... if needed
4715 if (!((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
4717 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = TRUE;
4719 simple_heap_update(attr_rel, &tuple->t_self, tuple);
4721 /* keep the system catalog indexes current */
4722 CatalogUpdateIndexes(attr_rel, tuple);
4724 /* Tell Phase 3 it needs to test the constraint */
4725 tab->new_notnull = true;
4728 heap_close(attr_rel, RowExclusiveLock);
4732 * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
4735 ATExecColumnDefault(Relation rel, const char *colName,
4736 Node *newDefault, LOCKMODE lockmode)
4741 * get the number of the attribute
4743 attnum = get_attnum(RelationGetRelid(rel), colName);
4744 if (attnum == InvalidAttrNumber)
4746 (errcode(ERRCODE_UNDEFINED_COLUMN),
4747 errmsg("column \"%s\" of relation \"%s\" does not exist",
4748 colName, RelationGetRelationName(rel))));
4750 /* Prevent them from altering a system attribute */
4753 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4754 errmsg("cannot alter system column \"%s\"",
4758 * Remove any old default for the column. We use RESTRICT here for
4759 * safety, but at present we do not expect anything to depend on the
4762 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false);
4767 RawColumnDefault *rawEnt;
4769 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
4770 rawEnt->attnum = attnum;
4771 rawEnt->raw_default = newDefault;
4774 * This function is intended for CREATE TABLE, so it processes a
4775 * _list_ of defaults, but we just do one.
4777 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL, false, true);
4782 * ALTER TABLE ALTER COLUMN SET STATISTICS
4785 ATPrepSetStatistics(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
4788 * We do our own permission checking because (a) we want to allow SET
4789 * STATISTICS on indexes (for expressional index columns), and (b) we want
4790 * to allow SET STATISTICS on system catalogs without requiring
4791 * allowSystemTableMods to be turned on.
4793 if (rel->rd_rel->relkind != RELKIND_RELATION &&
4794 rel->rd_rel->relkind != RELKIND_INDEX)
4796 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4797 errmsg("\"%s\" is not a table or index",
4798 RelationGetRelationName(rel))));
4800 /* Permissions checks */
4801 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
4802 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
4803 RelationGetRelationName(rel));
4807 ATExecSetStatistics(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
4810 Relation attrelation;
4812 Form_pg_attribute attrtuple;
4814 Assert(IsA(newValue, Integer));
4815 newtarget = intVal(newValue);
4818 * Limit target to a sane range
4823 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4824 errmsg("statistics target %d is too low",
4827 else if (newtarget > 10000)
4831 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4832 errmsg("lowering statistics target to %d",
4836 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
4838 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4840 if (!HeapTupleIsValid(tuple))
4842 (errcode(ERRCODE_UNDEFINED_COLUMN),
4843 errmsg("column \"%s\" of relation \"%s\" does not exist",
4844 colName, RelationGetRelationName(rel))));
4845 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
4847 if (attrtuple->attnum <= 0)
4849 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4850 errmsg("cannot alter system column \"%s\"",
4853 attrtuple->attstattarget = newtarget;
4855 simple_heap_update(attrelation, &tuple->t_self, tuple);
4857 /* keep system catalog indexes current */
4858 CatalogUpdateIndexes(attrelation, tuple);
4860 heap_freetuple(tuple);
4862 heap_close(attrelation, RowExclusiveLock);
4866 ATExecSetOptions(Relation rel, const char *colName, Node *options,
4867 bool isReset, LOCKMODE lockmode)
4869 Relation attrelation;
4872 Form_pg_attribute attrtuple;
4876 Datum repl_val[Natts_pg_attribute];
4877 bool repl_null[Natts_pg_attribute];
4878 bool repl_repl[Natts_pg_attribute];
4880 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
4882 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
4884 if (!HeapTupleIsValid(tuple))
4886 (errcode(ERRCODE_UNDEFINED_COLUMN),
4887 errmsg("column \"%s\" of relation \"%s\" does not exist",
4888 colName, RelationGetRelationName(rel))));
4889 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
4891 if (attrtuple->attnum <= 0)
4893 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4894 errmsg("cannot alter system column \"%s\"",
4897 /* Generate new proposed attoptions (text array) */
4898 Assert(IsA(options, List));
4899 datum = SysCacheGetAttr(ATTNAME, tuple, Anum_pg_attribute_attoptions,
4901 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
4902 (List *) options, NULL, NULL, false,
4904 /* Validate new options */
4905 (void) attribute_reloptions(newOptions, true);
4907 /* Build new tuple. */
4908 memset(repl_null, false, sizeof(repl_null));
4909 memset(repl_repl, false, sizeof(repl_repl));
4910 if (newOptions != (Datum) 0)
4911 repl_val[Anum_pg_attribute_attoptions - 1] = newOptions;
4913 repl_null[Anum_pg_attribute_attoptions - 1] = true;
4914 repl_repl[Anum_pg_attribute_attoptions - 1] = true;
4915 newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrelation),
4916 repl_val, repl_null, repl_repl);
4917 ReleaseSysCache(tuple);
4919 /* Update system catalog. */
4920 simple_heap_update(attrelation, &newtuple->t_self, newtuple);
4921 CatalogUpdateIndexes(attrelation, newtuple);
4922 heap_freetuple(newtuple);
4924 heap_close(attrelation, RowExclusiveLock);
4928 * ALTER TABLE ALTER COLUMN SET STORAGE
4931 ATExecSetStorage(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
4935 Relation attrelation;
4937 Form_pg_attribute attrtuple;
4939 Assert(IsA(newValue, String));
4940 storagemode = strVal(newValue);
4942 if (pg_strcasecmp(storagemode, "plain") == 0)
4944 else if (pg_strcasecmp(storagemode, "external") == 0)
4946 else if (pg_strcasecmp(storagemode, "extended") == 0)
4948 else if (pg_strcasecmp(storagemode, "main") == 0)
4953 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4954 errmsg("invalid storage type \"%s\"",
4956 newstorage = 0; /* keep compiler quiet */
4959 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
4961 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4963 if (!HeapTupleIsValid(tuple))
4965 (errcode(ERRCODE_UNDEFINED_COLUMN),
4966 errmsg("column \"%s\" of relation \"%s\" does not exist",
4967 colName, RelationGetRelationName(rel))));
4968 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
4970 if (attrtuple->attnum <= 0)
4972 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4973 errmsg("cannot alter system column \"%s\"",
4977 * safety check: do not allow toasted storage modes unless column datatype
4980 if (newstorage == 'p' || TypeIsToastable(attrtuple->atttypid))
4981 attrtuple->attstorage = newstorage;
4984 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4985 errmsg("column data type %s can only have storage PLAIN",
4986 format_type_be(attrtuple->atttypid))));
4988 simple_heap_update(attrelation, &tuple->t_self, tuple);
4990 /* keep system catalog indexes current */
4991 CatalogUpdateIndexes(attrelation, tuple);
4993 heap_freetuple(tuple);
4995 heap_close(attrelation, RowExclusiveLock);
5000 * ALTER TABLE DROP COLUMN
5002 * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
5003 * because we have to decide at runtime whether to recurse or not depending
5004 * on whether attinhcount goes to zero or not. (We can't check this in a
5005 * static pre-pass because it won't handle multiple inheritance situations
5009 ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
5010 AlterTableCmd *cmd, LOCKMODE lockmode)
5012 if (rel->rd_rel->reloftype && !recursing)
5014 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5015 errmsg("cannot drop column from typed table")));
5017 if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
5018 ATTypedTableRecursion(wqueue, rel, cmd, lockmode);
5021 cmd->subtype = AT_DropColumnRecurse;
5025 ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
5026 DropBehavior behavior,
5027 bool recurse, bool recursing,
5028 bool missing_ok, LOCKMODE lockmode)
5031 Form_pg_attribute targetatt;
5034 ObjectAddress object;
5036 /* At top level, permission check was done in ATPrepCmd, else do it */
5038 ATSimplePermissions(rel, ATT_TABLE);
5041 * get the number of the attribute
5043 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
5044 if (!HeapTupleIsValid(tuple))
5049 (errcode(ERRCODE_UNDEFINED_COLUMN),
5050 errmsg("column \"%s\" of relation \"%s\" does not exist",
5051 colName, RelationGetRelationName(rel))));
5056 (errmsg("column \"%s\" of relation \"%s\" does not exist, skipping",
5057 colName, RelationGetRelationName(rel))));
5061 targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
5063 attnum = targetatt->attnum;
5065 /* Can't drop a system attribute, except OID */
5066 if (attnum <= 0 && attnum != ObjectIdAttributeNumber)
5068 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5069 errmsg("cannot drop system column \"%s\"",
5072 /* Don't drop inherited columns */
5073 if (targetatt->attinhcount > 0 && !recursing)
5075 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5076 errmsg("cannot drop inherited column \"%s\"",
5079 ReleaseSysCache(tuple);
5082 * Propagate to children as appropriate. Unlike most other ALTER
5083 * routines, we have to do this one level of recursion at a time; we can't
5084 * use find_all_inheritors to do it in one pass.
5086 children = find_inheritance_children(RelationGetRelid(rel), lockmode);
5093 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
5094 foreach(child, children)
5096 Oid childrelid = lfirst_oid(child);
5098 Form_pg_attribute childatt;
5100 /* find_inheritance_children already got lock */
5101 childrel = heap_open(childrelid, NoLock);
5102 CheckTableNotInUse(childrel, "ALTER TABLE");
5104 tuple = SearchSysCacheCopyAttName(childrelid, colName);
5105 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
5106 elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
5107 colName, childrelid);
5108 childatt = (Form_pg_attribute) GETSTRUCT(tuple);
5110 if (childatt->attinhcount <= 0) /* shouldn't happen */
5111 elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
5112 childrelid, colName);
5117 * If the child column has other definition sources, just
5118 * decrement its inheritance count; if not, recurse to delete
5121 if (childatt->attinhcount == 1 && !childatt->attislocal)
5123 /* Time to delete this child column, too */
5124 ATExecDropColumn(wqueue, childrel, colName,
5125 behavior, true, true,
5130 /* Child column must survive my deletion */
5131 childatt->attinhcount--;
5133 simple_heap_update(attr_rel, &tuple->t_self, tuple);
5135 /* keep the system catalog indexes current */
5136 CatalogUpdateIndexes(attr_rel, tuple);
5138 /* Make update visible */
5139 CommandCounterIncrement();
5145 * If we were told to drop ONLY in this table (no recursion),
5146 * we need to mark the inheritors' attributes as locally
5147 * defined rather than inherited.
5149 childatt->attinhcount--;
5150 childatt->attislocal = true;
5152 simple_heap_update(attr_rel, &tuple->t_self, tuple);
5154 /* keep the system catalog indexes current */
5155 CatalogUpdateIndexes(attr_rel, tuple);
5157 /* Make update visible */
5158 CommandCounterIncrement();
5161 heap_freetuple(tuple);
5163 heap_close(childrel, NoLock);
5165 heap_close(attr_rel, RowExclusiveLock);
5169 * Perform the actual column deletion
5171 object.classId = RelationRelationId;
5172 object.objectId = RelationGetRelid(rel);
5173 object.objectSubId = attnum;
5175 performDeletion(&object, behavior);
5178 * If we dropped the OID column, must adjust pg_class.relhasoids and tell
5179 * Phase 3 to physically get rid of the column. We formerly left the
5180 * column in place physically, but this caused subtle problems. See
5181 * http://archives.postgresql.org/pgsql-hackers/2009-02/msg00363.php
5183 if (attnum == ObjectIdAttributeNumber)
5186 Form_pg_class tuple_class;
5187 AlteredTableInfo *tab;
5189 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
5191 tuple = SearchSysCacheCopy1(RELOID,
5192 ObjectIdGetDatum(RelationGetRelid(rel)));
5193 if (!HeapTupleIsValid(tuple))
5194 elog(ERROR, "cache lookup failed for relation %u",
5195 RelationGetRelid(rel));
5196 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
5198 tuple_class->relhasoids = false;
5199 simple_heap_update(class_rel, &tuple->t_self, tuple);
5201 /* Keep the catalog indexes up to date */
5202 CatalogUpdateIndexes(class_rel, tuple);
5204 heap_close(class_rel, RowExclusiveLock);
5206 /* Find or create work queue entry for this table */
5207 tab = ATGetQueueEntry(wqueue, rel);
5209 /* Tell Phase 3 to physically remove the OID column */
5210 tab->rewrite = true;
5215 * ALTER TABLE ADD INDEX
5217 * There is no such command in the grammar, but parse_utilcmd.c converts
5218 * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands. This lets
5219 * us schedule creation of the index at the appropriate time during ALTER.
5222 ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
5223 IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
5229 Assert(IsA(stmt, IndexStmt));
5231 /* suppress schema rights check when rebuilding existing index */
5232 check_rights = !is_rebuild;
5233 /* skip index build if phase 3 will have to rewrite table anyway */
5234 skip_build = tab->rewrite;
5235 /* suppress notices when rebuilding existing index */
5238 /* The IndexStmt has already been through transformIndexStmt */
5240 DefineIndex(stmt->relation, /* relation */
5241 stmt->idxname, /* index name */
5242 InvalidOid, /* no predefined OID */
5243 stmt->accessMethod, /* am name */
5245 stmt->indexParams, /* parameters */
5246 (Expr *) stmt->whereClause,
5248 stmt->excludeOpNames,
5254 true, /* is_alter_table */
5262 * ALTER TABLE ADD CONSTRAINT USING INDEX
5265 ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
5266 IndexStmt *stmt, LOCKMODE lockmode)
5268 Oid index_oid = stmt->indexOid;
5271 IndexInfo *indexInfo;
5272 char *constraintName;
5273 char constraintType;
5275 Assert(IsA(stmt, IndexStmt));
5276 Assert(OidIsValid(index_oid));
5277 Assert(stmt->isconstraint);
5279 indexRel = index_open(index_oid, AccessShareLock);
5281 indexName = pstrdup(RelationGetRelationName(indexRel));
5283 indexInfo = BuildIndexInfo(indexRel);
5285 /* this should have been checked at parse time */
5286 if (!indexInfo->ii_Unique)
5287 elog(ERROR, "index \"%s\" is not unique", indexName);
5290 * Determine name to assign to constraint. We require a constraint to
5291 * have the same name as the underlying index; therefore, use the index's
5292 * existing name as the default constraint name, and if the user
5293 * explicitly gives some other name for the constraint, rename the index
5296 constraintName = stmt->idxname;
5297 if (constraintName == NULL)
5298 constraintName = indexName;
5299 else if (strcmp(constraintName, indexName) != 0)
5302 (errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index \"%s\" to \"%s\"",
5303 indexName, constraintName)));
5304 RenameRelation(index_oid, constraintName, OBJECT_INDEX);
5307 /* Extra checks needed if making primary key */
5309 index_check_primary_key(rel, indexInfo, true);
5311 /* Note we currently don't support EXCLUSION constraints here */
5313 constraintType = CONSTRAINT_PRIMARY;
5315 constraintType = CONSTRAINT_UNIQUE;
5317 /* Create the catalog entries for the constraint */
5318 index_constraint_create(rel,
5327 allowSystemTableMods);
5329 index_close(indexRel, NoLock);
5333 * ALTER TABLE ADD CONSTRAINT
5336 ATExecAddConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
5337 Constraint *newConstraint, bool recurse, LOCKMODE lockmode)
5339 Assert(IsA(newConstraint, Constraint));
5342 * Currently, we only expect to see CONSTR_CHECK and CONSTR_FOREIGN nodes
5343 * arriving here (see the preprocessing done in parse_utilcmd.c). Use a
5344 * switch anyway to make it easier to add more code later.
5346 switch (newConstraint->contype)
5349 ATAddCheckConstraint(wqueue, tab, rel,
5350 newConstraint, recurse, false, lockmode);
5353 case CONSTR_FOREIGN:
5356 * Note that we currently never recurse for FK constraints, so the
5357 * "recurse" flag is silently ignored.
5359 * Assign or validate constraint name
5361 if (newConstraint->conname)
5363 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
5364 RelationGetRelid(rel),
5365 RelationGetNamespace(rel),
5366 newConstraint->conname))
5368 (errcode(ERRCODE_DUPLICATE_OBJECT),
5369 errmsg("constraint \"%s\" for relation \"%s\" already exists",
5370 newConstraint->conname,
5371 RelationGetRelationName(rel))));
5374 newConstraint->conname =
5375 ChooseConstraintName(RelationGetRelationName(rel),
5376 strVal(linitial(newConstraint->fk_attrs)),
5378 RelationGetNamespace(rel),
5381 ATAddForeignKeyConstraint(tab, rel, newConstraint, lockmode);
5385 elog(ERROR, "unrecognized constraint type: %d",
5386 (int) newConstraint->contype);
5391 * Add a check constraint to a single table and its children
5393 * Subroutine for ATExecAddConstraint.
5395 * We must recurse to child tables during execution, rather than using
5396 * ALTER TABLE's normal prep-time recursion. The reason is that all the
5397 * constraints *must* be given the same name, else they won't be seen as
5398 * related later. If the user didn't explicitly specify a name, then
5399 * AddRelationNewConstraints would normally assign different names to the
5400 * child constraints. To fix that, we must capture the name assigned at
5401 * the parent table and pass that down.
5404 ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
5405 Constraint *constr, bool recurse, bool recursing,
5413 /* At top level, permission check was done in ATPrepCmd, else do it */
5415 ATSimplePermissions(rel, ATT_TABLE);
5418 * Call AddRelationNewConstraints to do the work, making sure it works on
5419 * a copy of the Constraint so transformExpr can't modify the original. It
5420 * returns a list of cooked constraints.
5422 * If the constraint ends up getting merged with a pre-existing one, it's
5423 * omitted from the returned list, which is what we want: we do not need
5424 * to do any validation work. That can only happen at child tables,
5425 * though, since we disallow merging at the top level.
5427 newcons = AddRelationNewConstraints(rel, NIL,
5428 list_make1(copyObject(constr)),
5429 recursing, !recursing);
5431 /* Add each to-be-validated constraint to Phase 3's queue */
5432 foreach(lcon, newcons)
5434 CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
5436 if (!ccon->skip_validation)
5438 NewConstraint *newcon;
5440 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
5441 newcon->name = ccon->name;
5442 newcon->contype = ccon->contype;
5443 /* ExecQual wants implicit-AND format */
5444 newcon->qual = (Node *) make_ands_implicit((Expr *) ccon->expr);
5446 tab->constraints = lappend(tab->constraints, newcon);
5449 /* Save the actually assigned name if it was defaulted */
5450 if (constr->conname == NULL)
5451 constr->conname = ccon->name;
5454 /* At this point we must have a locked-down name to use */
5455 Assert(constr->conname != NULL);
5457 /* Advance command counter in case same table is visited multiple times */
5458 CommandCounterIncrement();
5461 * If the constraint got merged with an existing constraint, we're done.
5462 * We mustn't recurse to child tables in this case, because they've
5463 * already got the constraint, and visiting them again would lead to an
5464 * incorrect value for coninhcount.
5470 * Propagate to children as appropriate. Unlike most other ALTER
5471 * routines, we have to do this one level of recursion at a time; we can't
5472 * use find_all_inheritors to do it in one pass.
5474 children = find_inheritance_children(RelationGetRelid(rel), lockmode);
5477 * If we are told not to recurse, there had better not be any child
5478 * tables; else the addition would put them out of step.
5480 if (children && !recurse)
5482 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5483 errmsg("constraint must be added to child tables too")));
5485 foreach(child, children)
5487 Oid childrelid = lfirst_oid(child);
5489 AlteredTableInfo *childtab;
5491 /* find_inheritance_children already got lock */
5492 childrel = heap_open(childrelid, NoLock);
5493 CheckTableNotInUse(childrel, "ALTER TABLE");
5495 /* Find or create work queue entry for this table */
5496 childtab = ATGetQueueEntry(wqueue, childrel);
5498 /* Recurse to child */
5499 ATAddCheckConstraint(wqueue, childtab, childrel,
5500 constr, recurse, true, lockmode);
5502 heap_close(childrel, NoLock);
5507 * Add a foreign-key constraint to a single table
5509 * Subroutine for ATExecAddConstraint. Must already hold exclusive
5510 * lock on the rel, and have done appropriate validity checks for it.
5511 * We do permissions checks here, however.
5514 ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
5515 Constraint *fkconstraint, LOCKMODE lockmode)
5518 int16 pkattnum[INDEX_MAX_KEYS];
5519 int16 fkattnum[INDEX_MAX_KEYS];
5520 Oid pktypoid[INDEX_MAX_KEYS];
5521 Oid fktypoid[INDEX_MAX_KEYS];
5522 Oid opclasses[INDEX_MAX_KEYS];
5523 Oid pfeqoperators[INDEX_MAX_KEYS];
5524 Oid ppeqoperators[INDEX_MAX_KEYS];
5525 Oid ffeqoperators[INDEX_MAX_KEYS];
5532 pkrel = heap_openrv(fkconstraint->pktable, lockmode);
5535 * Validity checks (permission checks wait till we have the column
5538 if (pkrel->rd_rel->relkind != RELKIND_RELATION)
5540 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5541 errmsg("referenced relation \"%s\" is not a table",
5542 RelationGetRelationName(pkrel))));
5544 if (!allowSystemTableMods && IsSystemRelation(pkrel))
5546 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5547 errmsg("permission denied: \"%s\" is a system catalog",
5548 RelationGetRelationName(pkrel))));
5551 * References from permanent or unlogged tables to temp tables, and from
5552 * permanent tables to unlogged tables, are disallowed because the
5553 * referenced data can vanish out from under us. References from temp
5554 * tables to any other table type are also disallowed, because other
5555 * backends might need to run the RI triggers on the perm table, but they
5556 * can't reliably see tuples in the local buffers of other backends.
5558 switch (rel->rd_rel->relpersistence)
5560 case RELPERSISTENCE_PERMANENT:
5561 if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT)
5563 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5564 errmsg("constraints on permanent tables may reference only permanent tables")));
5566 case RELPERSISTENCE_UNLOGGED:
5567 if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT
5568 && pkrel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED)
5570 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5571 errmsg("constraints on unlogged tables may reference only permanent or unlogged tables")));
5573 case RELPERSISTENCE_TEMP:
5574 if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
5576 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5577 errmsg("constraints on temporary tables may reference only temporary tables")));
5582 * Look up the referencing attributes to make sure they exist, and record
5583 * their attnums and type OIDs.
5585 MemSet(pkattnum, 0, sizeof(pkattnum));
5586 MemSet(fkattnum, 0, sizeof(fkattnum));
5587 MemSet(pktypoid, 0, sizeof(pktypoid));
5588 MemSet(fktypoid, 0, sizeof(fktypoid));
5589 MemSet(opclasses, 0, sizeof(opclasses));
5590 MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
5591 MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
5592 MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
5594 numfks = transformColumnNameList(RelationGetRelid(rel),
5595 fkconstraint->fk_attrs,
5596 fkattnum, fktypoid);
5599 * If the attribute list for the referenced table was omitted, lookup the
5600 * definition of the primary key and use it. Otherwise, validate the
5601 * supplied attribute list. In either case, discover the index OID and
5602 * index opclasses, and the attnums and type OIDs of the attributes.
5604 if (fkconstraint->pk_attrs == NIL)
5606 numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
5607 &fkconstraint->pk_attrs,
5613 numpks = transformColumnNameList(RelationGetRelid(pkrel),
5614 fkconstraint->pk_attrs,
5615 pkattnum, pktypoid);
5616 /* Look for an index matching the column list */
5617 indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
5622 * Now we can check permissions.
5624 checkFkeyPermissions(pkrel, pkattnum, numpks);
5625 checkFkeyPermissions(rel, fkattnum, numfks);
5628 * Look up the equality operators to use in the constraint.
5630 * Note that we have to be careful about the difference between the actual
5631 * PK column type and the opclass' declared input type, which might be
5632 * only binary-compatible with it. The declared opcintype is the right
5633 * thing to probe pg_amop with.
5635 if (numfks != numpks)
5637 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
5638 errmsg("number of referencing and referenced columns for foreign key disagree")));
5640 for (i = 0; i < numpks; i++)
5642 Oid pktype = pktypoid[i];
5643 Oid fktype = fktypoid[i];
5646 Form_pg_opclass cla_tup;
5655 /* We need several fields out of the pg_opclass entry */
5656 cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclasses[i]));
5657 if (!HeapTupleIsValid(cla_ht))
5658 elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
5659 cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
5660 amid = cla_tup->opcmethod;
5661 opfamily = cla_tup->opcfamily;
5662 opcintype = cla_tup->opcintype;
5663 ReleaseSysCache(cla_ht);
5666 * Check it's a btree; currently this can never fail since no other
5667 * index AMs support unique indexes. If we ever did have other types
5668 * of unique indexes, we'd need a way to determine which operator
5669 * strategy number is equality. (Is it reasonable to insist that
5670 * every such index AM use btree's number for equality?)
5672 if (amid != BTREE_AM_OID)
5673 elog(ERROR, "only b-tree indexes are supported for foreign keys");
5674 eqstrategy = BTEqualStrategyNumber;
5677 * There had better be a primary equality operator for the index.
5678 * We'll use it for PK = PK comparisons.
5680 ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
5683 if (!OidIsValid(ppeqop))
5684 elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
5685 eqstrategy, opcintype, opcintype, opfamily);
5688 * Are there equality operators that take exactly the FK type? Assume
5689 * we should look through any domain here.
5691 fktyped = getBaseType(fktype);
5693 pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
5695 if (OidIsValid(pfeqop))
5696 ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
5699 ffeqop = InvalidOid; /* keep compiler quiet */
5701 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
5704 * Otherwise, look for an implicit cast from the FK type to the
5705 * opcintype, and if found, use the primary equality operator.
5706 * This is a bit tricky because opcintype might be a polymorphic
5707 * type such as ANYARRAY or ANYENUM; so what we have to test is
5708 * whether the two actual column types can be concurrently cast to
5709 * that type. (Otherwise, we'd fail to reject combinations such
5710 * as int[] and point[].)
5712 Oid input_typeids[2];
5713 Oid target_typeids[2];
5715 input_typeids[0] = pktype;
5716 input_typeids[1] = fktype;
5717 target_typeids[0] = opcintype;
5718 target_typeids[1] = opcintype;
5719 if (can_coerce_type(2, input_typeids, target_typeids,
5721 pfeqop = ffeqop = ppeqop;
5724 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
5726 (errcode(ERRCODE_DATATYPE_MISMATCH),
5727 errmsg("foreign key constraint \"%s\" "
5728 "cannot be implemented",
5729 fkconstraint->conname),
5730 errdetail("Key columns \"%s\" and \"%s\" "
5731 "are of incompatible types: %s and %s.",
5732 strVal(list_nth(fkconstraint->fk_attrs, i)),
5733 strVal(list_nth(fkconstraint->pk_attrs, i)),
5734 format_type_be(fktype),
5735 format_type_be(pktype))));
5737 pfeqoperators[i] = pfeqop;
5738 ppeqoperators[i] = ppeqop;
5739 ffeqoperators[i] = ffeqop;
5743 * Record the FK constraint in pg_constraint.
5745 constrOid = CreateConstraintEntry(fkconstraint->conname,
5746 RelationGetNamespace(rel),
5748 fkconstraint->deferrable,
5749 fkconstraint->initdeferred,
5750 fkconstraint->initially_valid,
5751 RelationGetRelid(rel),
5754 InvalidOid, /* not a domain
5757 RelationGetRelid(pkrel),
5763 fkconstraint->fk_upd_action,
5764 fkconstraint->fk_del_action,
5765 fkconstraint->fk_matchtype,
5766 NULL, /* no exclusion constraint */
5767 NULL, /* no check constraint */
5774 * Create the triggers that will enforce the constraint.
5776 createForeignKeyTriggers(rel, fkconstraint, constrOid, indexOid);
5779 * Tell Phase 3 to check that the constraint is satisfied by existing rows.
5780 * We can skip this during table creation, or if requested explicitly by
5781 * specifying NOT VALID in an ADD FOREIGN KEY command.
5783 if (!fkconstraint->skip_validation)
5785 NewConstraint *newcon;
5787 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
5788 newcon->name = fkconstraint->conname;
5789 newcon->contype = CONSTR_FOREIGN;
5790 newcon->refrelid = RelationGetRelid(pkrel);
5791 newcon->refindid = indexOid;
5792 newcon->conid = constrOid;
5793 newcon->qual = (Node *) fkconstraint;
5795 tab->constraints = lappend(tab->constraints, newcon);
5799 * Close pk table, but keep lock until we've committed.
5801 heap_close(pkrel, NoLock);
5805 * ALTER TABLE VALIDATE CONSTRAINT
5807 * XXX The reason we handle recursion here rather than at Phase 1 is because
5808 * there's no good way to skip recursing when handling foreign keys: there is
5809 * no need to lock children in that case, yet we wouldn't be able to avoid
5810 * doing so at that level.
5813 ATExecValidateConstraint(Relation rel, char *constrName, bool recurse,
5814 bool recursing, LOCKMODE lockmode)
5820 Form_pg_constraint con = NULL;
5823 conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
5826 * Find and check the target constraint
5829 Anum_pg_constraint_conrelid,
5830 BTEqualStrategyNumber, F_OIDEQ,
5831 ObjectIdGetDatum(RelationGetRelid(rel)));
5832 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
5833 true, SnapshotNow, 1, &key);
5835 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
5837 con = (Form_pg_constraint) GETSTRUCT(tuple);
5838 if (strcmp(NameStr(con->conname), constrName) == 0)
5847 (errcode(ERRCODE_UNDEFINED_OBJECT),
5848 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
5849 constrName, RelationGetRelationName(rel))));
5851 if (con->contype != CONSTRAINT_FOREIGN &&
5852 con->contype != CONSTRAINT_CHECK)
5854 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5855 errmsg("constraint \"%s\" of relation \"%s\" is not a foreign key or check constraint",
5856 constrName, RelationGetRelationName(rel))));
5858 if (!con->convalidated)
5860 HeapTuple copyTuple;
5861 Form_pg_constraint copy_con;
5863 if (con->contype == CONSTRAINT_FOREIGN)
5865 Oid conid = HeapTupleGetOid(tuple);
5869 * Triggers are already in place on both tables, so a concurrent write
5870 * that alters the result here is not possible. Normally we can run a
5871 * query here to do the validation, which would only require
5872 * AccessShareLock. In some cases, it is possible that we might need
5873 * to fire triggers to perform the check, so we take a lock at
5874 * RowShareLock level just in case.
5876 refrel = heap_open(con->confrelid, RowShareLock);
5878 validateForeignKeyConstraint(constrName, rel, refrel,
5881 heap_close(refrel, NoLock);
5884 * Foreign keys do not inherit, so we purposedly ignore the
5885 * recursion bit here
5888 else if (con->contype == CONSTRAINT_CHECK)
5890 List *children = NIL;
5894 * If we're recursing, the parent has already done this, so skip
5898 children = find_all_inheritors(RelationGetRelid(rel),
5902 * For CHECK constraints, we must ensure that we only mark the
5903 * constraint as validated on the parent if it's already validated
5906 * We recurse before validating on the parent, to reduce risk of
5909 foreach(child, children)
5911 Oid childoid = lfirst_oid(child);
5914 if (childoid == RelationGetRelid(rel))
5918 * If we are told not to recurse, there had better not be any
5919 * child tables; else the addition would put them out of step.
5923 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5924 errmsg("constraint must be validated on child tables too")));
5926 /* find_all_inheritors already got lock */
5927 childrel = heap_open(childoid, NoLock);
5929 ATExecValidateConstraint(childrel, constrName, false,
5931 heap_close(childrel, NoLock);
5934 validateCheckConstraint(rel, tuple);
5937 * Invalidate relcache so that others see the new validated
5940 CacheInvalidateRelcache(rel);
5944 * Now update the catalog, while we have the door open.
5946 copyTuple = heap_copytuple(tuple);
5947 copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
5948 copy_con->convalidated = true;
5949 simple_heap_update(conrel, ©Tuple->t_self, copyTuple);
5950 CatalogUpdateIndexes(conrel, copyTuple);
5951 heap_freetuple(copyTuple);
5954 systable_endscan(scan);
5956 heap_close(conrel, RowExclusiveLock);
5961 * transformColumnNameList - transform list of column names
5963 * Lookup each name and return its attnum and type OID
5966 transformColumnNameList(Oid relId, List *colList,
5967 int16 *attnums, Oid *atttypids)
5975 char *attname = strVal(lfirst(l));
5978 atttuple = SearchSysCacheAttName(relId, attname);
5979 if (!HeapTupleIsValid(atttuple))
5981 (errcode(ERRCODE_UNDEFINED_COLUMN),
5982 errmsg("column \"%s\" referenced in foreign key constraint does not exist",
5984 if (attnum >= INDEX_MAX_KEYS)
5986 (errcode(ERRCODE_TOO_MANY_COLUMNS),
5987 errmsg("cannot have more than %d keys in a foreign key",
5989 attnums[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->attnum;
5990 atttypids[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->atttypid;
5991 ReleaseSysCache(atttuple);
5999 * transformFkeyGetPrimaryKey -
6001 * Look up the names, attnums, and types of the primary key attributes
6002 * for the pkrel. Also return the index OID and index opclasses of the
6003 * index supporting the primary key.
6005 * All parameters except pkrel are output parameters. Also, the function
6006 * return value is the number of attributes in the primary key.
6008 * Used when the column list in the REFERENCES specification is omitted.
6011 transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
6013 int16 *attnums, Oid *atttypids,
6017 ListCell *indexoidscan;
6018 HeapTuple indexTuple = NULL;
6019 Form_pg_index indexStruct = NULL;
6020 Datum indclassDatum;
6022 oidvector *indclass;
6026 * Get the list of index OIDs for the table from the relcache, and look up
6027 * each one in the pg_index syscache until we find one marked primary key
6028 * (hopefully there isn't more than one such).
6030 *indexOid = InvalidOid;
6032 indexoidlist = RelationGetIndexList(pkrel);
6034 foreach(indexoidscan, indexoidlist)
6036 Oid indexoid = lfirst_oid(indexoidscan);
6038 indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
6039 if (!HeapTupleIsValid(indexTuple))
6040 elog(ERROR, "cache lookup failed for index %u", indexoid);
6041 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
6042 if (indexStruct->indisprimary)
6045 * Refuse to use a deferrable primary key. This is per SQL spec,
6046 * and there would be a lot of interesting semantic problems if we
6047 * tried to allow it.
6049 if (!indexStruct->indimmediate)
6051 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6052 errmsg("cannot use a deferrable primary key for referenced table \"%s\"",
6053 RelationGetRelationName(pkrel))));
6055 *indexOid = indexoid;
6058 ReleaseSysCache(indexTuple);
6061 list_free(indexoidlist);
6064 * Check that we found it
6066 if (!OidIsValid(*indexOid))
6068 (errcode(ERRCODE_UNDEFINED_OBJECT),
6069 errmsg("there is no primary key for referenced table \"%s\"",
6070 RelationGetRelationName(pkrel))));
6072 /* Must get indclass the hard way */
6073 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
6074 Anum_pg_index_indclass, &isnull);
6076 indclass = (oidvector *) DatumGetPointer(indclassDatum);
6079 * Now build the list of PK attributes from the indkey definition (we
6080 * assume a primary key cannot have expressional elements)
6083 for (i = 0; i < indexStruct->indnatts; i++)
6085 int pkattno = indexStruct->indkey.values[i];
6087 attnums[i] = pkattno;
6088 atttypids[i] = attnumTypeId(pkrel, pkattno);
6089 opclasses[i] = indclass->values[i];
6090 *attnamelist = lappend(*attnamelist,
6091 makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
6094 ReleaseSysCache(indexTuple);
6100 * transformFkeyCheckAttrs -
6102 * Make sure that the attributes of a referenced table belong to a unique
6103 * (or primary key) constraint. Return the OID of the index supporting
6104 * the constraint, as well as the opclasses associated with the index
6108 transformFkeyCheckAttrs(Relation pkrel,
6109 int numattrs, int16 *attnums,
6110 Oid *opclasses) /* output parameter */
6112 Oid indexoid = InvalidOid;
6114 bool found_deferrable = false;
6116 ListCell *indexoidscan;
6119 * Get the list of index OIDs for the table from the relcache, and look up
6120 * each one in the pg_index syscache, and match unique indexes to the list
6121 * of attnums we are given.
6123 indexoidlist = RelationGetIndexList(pkrel);
6125 foreach(indexoidscan, indexoidlist)
6127 HeapTuple indexTuple;
6128 Form_pg_index indexStruct;
6132 indexoid = lfirst_oid(indexoidscan);
6133 indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
6134 if (!HeapTupleIsValid(indexTuple))
6135 elog(ERROR, "cache lookup failed for index %u", indexoid);
6136 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
6139 * Must have the right number of columns; must be unique and not a
6140 * partial index; forget it if there are any expressions, too
6142 if (indexStruct->indnatts == numattrs &&
6143 indexStruct->indisunique &&
6144 heap_attisnull(indexTuple, Anum_pg_index_indpred) &&
6145 heap_attisnull(indexTuple, Anum_pg_index_indexprs))
6147 /* Must get indclass the hard way */
6148 Datum indclassDatum;
6150 oidvector *indclass;
6152 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
6153 Anum_pg_index_indclass, &isnull);
6155 indclass = (oidvector *) DatumGetPointer(indclassDatum);
6158 * The given attnum list may match the index columns in any order.
6159 * Check that each list is a subset of the other.
6161 for (i = 0; i < numattrs; i++)
6164 for (j = 0; j < numattrs; j++)
6166 if (attnums[i] == indexStruct->indkey.values[j])
6177 for (i = 0; i < numattrs; i++)
6180 for (j = 0; j < numattrs; j++)
6182 if (attnums[j] == indexStruct->indkey.values[i])
6184 opclasses[j] = indclass->values[i];
6195 * Refuse to use a deferrable unique/primary key. This is per SQL
6196 * spec, and there would be a lot of interesting semantic problems
6197 * if we tried to allow it.
6199 if (found && !indexStruct->indimmediate)
6202 * Remember that we found an otherwise matching index, so that
6203 * we can generate a more appropriate error message.
6205 found_deferrable = true;
6209 ReleaseSysCache(indexTuple);
6216 if (found_deferrable)
6218 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6219 errmsg("cannot use a deferrable unique constraint for referenced table \"%s\"",
6220 RelationGetRelationName(pkrel))));
6223 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
6224 errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
6225 RelationGetRelationName(pkrel))));
6228 list_free(indexoidlist);
6233 /* Permissions checks for ADD FOREIGN KEY */
6235 checkFkeyPermissions(Relation rel, int16 *attnums, int natts)
6237 Oid roleid = GetUserId();
6238 AclResult aclresult;
6241 /* Okay if we have relation-level REFERENCES permission */
6242 aclresult = pg_class_aclcheck(RelationGetRelid(rel), roleid,
6244 if (aclresult == ACLCHECK_OK)
6246 /* Else we must have REFERENCES on each column */
6247 for (i = 0; i < natts; i++)
6249 aclresult = pg_attribute_aclcheck(RelationGetRelid(rel), attnums[i],
6250 roleid, ACL_REFERENCES);
6251 if (aclresult != ACLCHECK_OK)
6252 aclcheck_error(aclresult, ACL_KIND_CLASS,
6253 RelationGetRelationName(rel));
6258 * Scan the existing rows in a table to verify they meet a proposed
6261 * The caller must have opened and locked the relation appropriately.
6264 validateCheckConstraint(Relation rel, HeapTuple constrtup)
6274 ExprContext *econtext;
6275 MemoryContext oldcxt;
6276 TupleTableSlot *slot;
6277 Form_pg_constraint constrForm;
6280 constrForm = (Form_pg_constraint) GETSTRUCT(constrtup);
6282 estate = CreateExecutorState();
6284 * XXX this tuple doesn't really come from a syscache, but this doesn't
6285 * matter to SysCacheGetAttr, because it only wants to be able to fetch the
6288 val = SysCacheGetAttr(CONSTROID, constrtup, Anum_pg_constraint_conbin,
6291 elog(ERROR, "null conbin for constraint %u",
6292 HeapTupleGetOid(constrtup));
6293 conbin = TextDatumGetCString(val);
6294 origexpr = (Expr *) stringToNode(conbin);
6295 exprstate = (List *)
6296 ExecPrepareExpr((Expr *) make_ands_implicit(origexpr), estate);
6298 econtext = GetPerTupleExprContext(estate);
6299 tupdesc = RelationGetDescr(rel);
6300 slot = MakeSingleTupleTableSlot(tupdesc);
6301 econtext->ecxt_scantuple = slot;
6303 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
6306 * Switch to per-tuple memory context and reset it for each tuple
6307 * produced, so we don't leak memory.
6309 oldcxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
6311 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
6313 ExecStoreTuple(tuple, slot, InvalidBuffer, false);
6315 if (!ExecQual(exprstate, econtext, true))
6317 (errcode(ERRCODE_CHECK_VIOLATION),
6318 errmsg("check constraint \"%s\" is violated by some row",
6319 NameStr(constrForm->conname))));
6321 ResetExprContext(econtext);
6324 MemoryContextSwitchTo(oldcxt);
6326 ExecDropSingleTupleTableSlot(slot);
6327 FreeExecutorState(estate);
6331 * Scan the existing rows in a table to verify they meet a proposed FK
6334 * Caller must have opened and locked both relations appropriately.
6337 validateForeignKeyConstraint(char *conname,
6348 (errmsg("validating foreign key constraint \"%s\"", conname)));
6351 * Build a trigger call structure; we'll need it either way.
6353 MemSet(&trig, 0, sizeof(trig));
6354 trig.tgoid = InvalidOid;
6355 trig.tgname = conname;
6356 trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
6357 trig.tgisinternal = TRUE;
6358 trig.tgconstrrelid = RelationGetRelid(pkrel);
6359 trig.tgconstrindid = pkindOid;
6360 trig.tgconstraint = constraintOid;
6361 trig.tgdeferrable = FALSE;
6362 trig.tginitdeferred = FALSE;
6363 /* we needn't fill in tgargs or tgqual */
6366 * See if we can do it with a single LEFT JOIN query. A FALSE result
6367 * indicates we must proceed with the fire-the-trigger method.
6369 if (RI_Initial_Check(&trig, rel, pkrel))
6373 * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
6374 * if that tuple had just been inserted. If any of those fail, it should
6375 * ereport(ERROR) and that's that.
6377 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
6379 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
6381 FunctionCallInfoData fcinfo;
6382 TriggerData trigdata;
6385 * Make a call to the trigger function
6387 * No parameters are passed, but we do set a context
6389 MemSet(&fcinfo, 0, sizeof(fcinfo));
6392 * We assume RI_FKey_check_ins won't look at flinfo...
6394 trigdata.type = T_TriggerData;
6395 trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
6396 trigdata.tg_relation = rel;
6397 trigdata.tg_trigtuple = tuple;
6398 trigdata.tg_newtuple = NULL;
6399 trigdata.tg_trigger = &trig;
6400 trigdata.tg_trigtuplebuf = scan->rs_cbuf;
6401 trigdata.tg_newtuplebuf = InvalidBuffer;
6403 fcinfo.context = (Node *) &trigdata;
6405 RI_FKey_check_ins(&fcinfo);
6412 CreateFKCheckTrigger(RangeVar *myRel, Constraint *fkconstraint,
6413 Oid constraintOid, Oid indexOid, bool on_insert)
6415 CreateTrigStmt *fk_trigger;
6417 fk_trigger = makeNode(CreateTrigStmt);
6418 fk_trigger->trigname = "RI_ConstraintTrigger";
6419 fk_trigger->relation = myRel;
6420 fk_trigger->row = true;
6421 fk_trigger->timing = TRIGGER_TYPE_AFTER;
6423 /* Either ON INSERT or ON UPDATE */
6426 fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
6427 fk_trigger->events = TRIGGER_TYPE_INSERT;
6431 fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
6432 fk_trigger->events = TRIGGER_TYPE_UPDATE;
6435 fk_trigger->columns = NIL;
6436 fk_trigger->whenClause = NULL;
6437 fk_trigger->isconstraint = true;
6438 fk_trigger->deferrable = fkconstraint->deferrable;
6439 fk_trigger->initdeferred = fkconstraint->initdeferred;
6440 fk_trigger->constrrel = fkconstraint->pktable;
6441 fk_trigger->args = NIL;
6443 (void) CreateTrigger(fk_trigger, NULL, constraintOid, indexOid, true);
6445 /* Make changes-so-far visible */
6446 CommandCounterIncrement();
6450 * Create the triggers that implement an FK constraint.
6453 createForeignKeyTriggers(Relation rel, Constraint *fkconstraint,
6454 Oid constraintOid, Oid indexOid)
6457 CreateTrigStmt *fk_trigger;
6460 * Reconstruct a RangeVar for my relation (not passed in, unfortunately).
6462 myRel = makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
6463 pstrdup(RelationGetRelationName(rel)),
6466 /* Make changes-so-far visible */
6467 CommandCounterIncrement();
6470 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the CHECK
6471 * action for both INSERTs and UPDATEs on the referencing table.
6473 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, indexOid, true);
6474 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, indexOid, false);
6477 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
6478 * DELETE action on the referenced table.
6480 fk_trigger = makeNode(CreateTrigStmt);
6481 fk_trigger->trigname = "RI_ConstraintTrigger";
6482 fk_trigger->relation = fkconstraint->pktable;
6483 fk_trigger->row = true;
6484 fk_trigger->timing = TRIGGER_TYPE_AFTER;
6485 fk_trigger->events = TRIGGER_TYPE_DELETE;
6486 fk_trigger->columns = NIL;
6487 fk_trigger->whenClause = NULL;
6488 fk_trigger->isconstraint = true;
6489 fk_trigger->constrrel = myRel;
6490 switch (fkconstraint->fk_del_action)
6492 case FKCONSTR_ACTION_NOACTION:
6493 fk_trigger->deferrable = fkconstraint->deferrable;
6494 fk_trigger->initdeferred = fkconstraint->initdeferred;
6495 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
6497 case FKCONSTR_ACTION_RESTRICT:
6498 fk_trigger->deferrable = false;
6499 fk_trigger->initdeferred = false;
6500 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
6502 case FKCONSTR_ACTION_CASCADE:
6503 fk_trigger->deferrable = false;
6504 fk_trigger->initdeferred = false;
6505 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
6507 case FKCONSTR_ACTION_SETNULL:
6508 fk_trigger->deferrable = false;
6509 fk_trigger->initdeferred = false;
6510 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
6512 case FKCONSTR_ACTION_SETDEFAULT:
6513 fk_trigger->deferrable = false;
6514 fk_trigger->initdeferred = false;
6515 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
6518 elog(ERROR, "unrecognized FK action type: %d",
6519 (int) fkconstraint->fk_del_action);
6522 fk_trigger->args = NIL;
6524 (void) CreateTrigger(fk_trigger, NULL, constraintOid, indexOid, true);
6526 /* Make changes-so-far visible */
6527 CommandCounterIncrement();
6530 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
6531 * UPDATE action on the referenced table.
6533 fk_trigger = makeNode(CreateTrigStmt);
6534 fk_trigger->trigname = "RI_ConstraintTrigger";
6535 fk_trigger->relation = fkconstraint->pktable;
6536 fk_trigger->row = true;
6537 fk_trigger->timing = TRIGGER_TYPE_AFTER;
6538 fk_trigger->events = TRIGGER_TYPE_UPDATE;
6539 fk_trigger->columns = NIL;
6540 fk_trigger->whenClause = NULL;
6541 fk_trigger->isconstraint = true;
6542 fk_trigger->constrrel = myRel;
6543 switch (fkconstraint->fk_upd_action)
6545 case FKCONSTR_ACTION_NOACTION:
6546 fk_trigger->deferrable = fkconstraint->deferrable;
6547 fk_trigger->initdeferred = fkconstraint->initdeferred;
6548 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
6550 case FKCONSTR_ACTION_RESTRICT:
6551 fk_trigger->deferrable = false;
6552 fk_trigger->initdeferred = false;
6553 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
6555 case FKCONSTR_ACTION_CASCADE:
6556 fk_trigger->deferrable = false;
6557 fk_trigger->initdeferred = false;
6558 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
6560 case FKCONSTR_ACTION_SETNULL:
6561 fk_trigger->deferrable = false;
6562 fk_trigger->initdeferred = false;
6563 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
6565 case FKCONSTR_ACTION_SETDEFAULT:
6566 fk_trigger->deferrable = false;
6567 fk_trigger->initdeferred = false;
6568 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
6571 elog(ERROR, "unrecognized FK action type: %d",
6572 (int) fkconstraint->fk_upd_action);
6575 fk_trigger->args = NIL;
6577 (void) CreateTrigger(fk_trigger, NULL, constraintOid, indexOid, true);
6581 * ALTER TABLE DROP CONSTRAINT
6583 * Like DROP COLUMN, we can't use the normal ALTER TABLE recursion mechanism.
6586 ATExecDropConstraint(Relation rel, const char *constrName,
6587 DropBehavior behavior,
6588 bool recurse, bool recursing,
6589 bool missing_ok, LOCKMODE lockmode)
6594 Form_pg_constraint con;
6599 bool is_check_constraint = false;
6601 /* At top level, permission check was done in ATPrepCmd, else do it */
6603 ATSimplePermissions(rel, ATT_TABLE);
6605 conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
6608 * Find and drop the target constraint
6611 Anum_pg_constraint_conrelid,
6612 BTEqualStrategyNumber, F_OIDEQ,
6613 ObjectIdGetDatum(RelationGetRelid(rel)));
6614 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
6615 true, SnapshotNow, 1, &key);
6617 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
6619 ObjectAddress conobj;
6621 con = (Form_pg_constraint) GETSTRUCT(tuple);
6623 if (strcmp(NameStr(con->conname), constrName) != 0)
6626 /* Don't drop inherited constraints */
6627 if (con->coninhcount > 0 && !recursing)
6629 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6630 errmsg("cannot drop inherited constraint \"%s\" of relation \"%s\"",
6631 constrName, RelationGetRelationName(rel))));
6633 /* Right now only CHECK constraints can be inherited */
6634 if (con->contype == CONSTRAINT_CHECK)
6635 is_check_constraint = true;
6638 * Perform the actual constraint deletion
6640 conobj.classId = ConstraintRelationId;
6641 conobj.objectId = HeapTupleGetOid(tuple);
6642 conobj.objectSubId = 0;
6644 performDeletion(&conobj, behavior);
6649 systable_endscan(scan);
6656 (errcode(ERRCODE_UNDEFINED_OBJECT),
6657 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
6658 constrName, RelationGetRelationName(rel))));
6663 (errmsg("constraint \"%s\" of relation \"%s\" does not exist, skipping",
6664 constrName, RelationGetRelationName(rel))));
6665 heap_close(conrel, RowExclusiveLock);
6671 * Propagate to children as appropriate. Unlike most other ALTER
6672 * routines, we have to do this one level of recursion at a time; we can't
6673 * use find_all_inheritors to do it in one pass.
6675 if (is_check_constraint)
6676 children = find_inheritance_children(RelationGetRelid(rel), lockmode);
6680 foreach(child, children)
6682 Oid childrelid = lfirst_oid(child);
6685 /* find_inheritance_children already got lock */
6686 childrel = heap_open(childrelid, NoLock);
6687 CheckTableNotInUse(childrel, "ALTER TABLE");
6690 Anum_pg_constraint_conrelid,
6691 BTEqualStrategyNumber, F_OIDEQ,
6692 ObjectIdGetDatum(childrelid));
6693 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
6694 true, SnapshotNow, 1, &key);
6698 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
6700 HeapTuple copy_tuple;
6702 con = (Form_pg_constraint) GETSTRUCT(tuple);
6704 /* Right now only CHECK constraints can be inherited */
6705 if (con->contype != CONSTRAINT_CHECK)
6708 if (strcmp(NameStr(con->conname), constrName) != 0)
6713 if (con->coninhcount <= 0) /* shouldn't happen */
6714 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
6715 childrelid, constrName);
6717 copy_tuple = heap_copytuple(tuple);
6718 con = (Form_pg_constraint) GETSTRUCT(copy_tuple);
6723 * If the child constraint has other definition sources, just
6724 * decrement its inheritance count; if not, recurse to delete
6727 if (con->coninhcount == 1 && !con->conislocal)
6729 /* Time to delete this child constraint, too */
6730 ATExecDropConstraint(childrel, constrName, behavior,
6736 /* Child constraint must survive my deletion */
6738 simple_heap_update(conrel, ©_tuple->t_self, copy_tuple);
6739 CatalogUpdateIndexes(conrel, copy_tuple);
6741 /* Make update visible */
6742 CommandCounterIncrement();
6748 * If we were told to drop ONLY in this table (no recursion),
6749 * we need to mark the inheritors' constraints as locally
6750 * defined rather than inherited.
6753 con->conislocal = true;
6755 simple_heap_update(conrel, ©_tuple->t_self, copy_tuple);
6756 CatalogUpdateIndexes(conrel, copy_tuple);
6758 /* Make update visible */
6759 CommandCounterIncrement();
6762 heap_freetuple(copy_tuple);
6765 systable_endscan(scan);
6769 (errcode(ERRCODE_UNDEFINED_OBJECT),
6770 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
6772 RelationGetRelationName(childrel))));
6774 heap_close(childrel, NoLock);
6777 heap_close(conrel, RowExclusiveLock);
6784 ATPrepAlterColumnType(List **wqueue,
6785 AlteredTableInfo *tab, Relation rel,
6786 bool recurse, bool recursing,
6787 AlterTableCmd *cmd, LOCKMODE lockmode)
6789 char *colName = cmd->name;
6790 ColumnDef *def = (ColumnDef *) cmd->def;
6791 TypeName *typeName = def->typeName;
6792 Node *transform = def->raw_default;
6794 Form_pg_attribute attTup;
6799 NewColumnValue *newval;
6800 ParseState *pstate = make_parsestate(NULL);
6802 if (rel->rd_rel->reloftype && !recursing)
6804 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6805 errmsg("cannot alter column type of typed table")));
6807 /* lookup the attribute so we can check inheritance status */
6808 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
6809 if (!HeapTupleIsValid(tuple))
6811 (errcode(ERRCODE_UNDEFINED_COLUMN),
6812 errmsg("column \"%s\" of relation \"%s\" does not exist",
6813 colName, RelationGetRelationName(rel))));
6814 attTup = (Form_pg_attribute) GETSTRUCT(tuple);
6815 attnum = attTup->attnum;
6817 /* Can't alter a system attribute */
6820 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6821 errmsg("cannot alter system column \"%s\"",
6824 /* Don't alter inherited columns */
6825 if (attTup->attinhcount > 0 && !recursing)
6827 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6828 errmsg("cannot alter inherited column \"%s\"",
6831 /* Look up the target type */
6832 typenameTypeIdAndMod(NULL, typeName, &targettype, &targettypmod);
6834 /* And the collation */
6835 targetcollid = GetColumnDefCollation(NULL, def, targettype);
6837 /* make sure datatype is legal for a column */
6838 CheckAttributeType(colName, targettype, targetcollid,
6839 list_make1_oid(rel->rd_rel->reltype),
6842 if (tab->relkind == RELKIND_RELATION)
6845 * Set up an expression to transform the old data value to the new
6846 * type. If a USING option was given, transform and use that
6847 * expression, else just take the old value and try to coerce it. We
6848 * do this first so that type incompatibility can be detected before
6849 * we waste effort, and because we need the expression to be parsed
6850 * against the original table row type.
6856 /* Expression must be able to access vars of old table */
6857 rte = addRangeTableEntryForRelation(pstate,
6862 addRTEtoQuery(pstate, rte, false, true, true);
6864 transform = transformExpr(pstate, transform);
6866 /* It can't return a set */
6867 if (expression_returns_set(transform))
6869 (errcode(ERRCODE_DATATYPE_MISMATCH),
6870 errmsg("transform expression must not return a set")));
6872 /* No subplans or aggregates, either... */
6873 if (pstate->p_hasSubLinks)
6875 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6876 errmsg("cannot use subquery in transform expression")));
6877 if (pstate->p_hasAggs)
6879 (errcode(ERRCODE_GROUPING_ERROR),
6880 errmsg("cannot use aggregate function in transform expression")));
6881 if (pstate->p_hasWindowFuncs)
6883 (errcode(ERRCODE_WINDOWING_ERROR),
6884 errmsg("cannot use window function in transform expression")));
6888 transform = (Node *) makeVar(1, attnum,
6889 attTup->atttypid, attTup->atttypmod,
6890 attTup->attcollation,
6894 transform = coerce_to_target_type(pstate,
6895 transform, exprType(transform),
6896 targettype, targettypmod,
6897 COERCION_ASSIGNMENT,
6898 COERCE_IMPLICIT_CAST,
6900 if (transform == NULL)
6902 (errcode(ERRCODE_DATATYPE_MISMATCH),
6903 errmsg("column \"%s\" cannot be cast to type %s",
6904 colName, format_type_be(targettype))));
6906 /* Fix collations after all else */
6907 assign_expr_collations(pstate, transform);
6909 /* Plan the expr now so we can accurately assess the need to rewrite. */
6910 transform = (Node *) expression_planner((Expr *) transform);
6913 * Add a work queue item to make ATRewriteTable update the column
6916 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
6917 newval->attnum = attnum;
6918 newval->expr = (Expr *) transform;
6920 tab->newvals = lappend(tab->newvals, newval);
6921 if (ATColumnChangeRequiresRewrite(transform, attnum))
6922 tab->rewrite = true;
6926 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6927 errmsg("\"%s\" is not a table",
6928 RelationGetRelationName(rel))));
6930 if (tab->relkind == RELKIND_COMPOSITE_TYPE ||
6931 tab->relkind == RELKIND_FOREIGN_TABLE)
6934 * For composite types, do this check now. Tables will check it later
6935 * when the table is being rewritten.
6937 find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
6940 ReleaseSysCache(tuple);
6943 * The recursion case is handled by ATSimpleRecursion. However, if we are
6944 * told not to recurse, there had better not be any child tables; else the
6945 * alter would put them out of step.
6948 ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode);
6949 else if (!recursing &&
6950 find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL)
6952 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6953 errmsg("type of inherited column \"%s\" must be changed in child tables too",
6956 if (tab->relkind == RELKIND_COMPOSITE_TYPE)
6957 ATTypedTableRecursion(wqueue, rel, cmd, lockmode);
6961 * When the data type of a column is changed, a rewrite might not be required
6962 * if the new type is sufficiently identical to the old one, and the USING
6963 * clause isn't trying to insert some other value. It's safe to skip the
6964 * rewrite if the old type is binary coercible to the new type, or if the
6965 * new type is an unconstrained domain over the old type. In the case of a
6966 * constrained domain, we could get by with scanning the table and checking
6967 * the constraint rather than actually rewriting it, but we don't currently
6971 ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno)
6973 Assert(expr != NULL);
6977 /* only one varno, so no need to check that */
6978 if (IsA(expr, Var) &&((Var *) expr)->varattno == varattno)
6980 else if (IsA(expr, RelabelType))
6981 expr = (Node *) ((RelabelType *) expr)->arg;
6982 else if (IsA(expr, CoerceToDomain))
6984 CoerceToDomain *d = (CoerceToDomain *) expr;
6986 if (GetDomainConstraints(d->resulttype) != NIL)
6988 expr = (Node *) d->arg;
6996 ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
6997 AlterTableCmd *cmd, LOCKMODE lockmode)
6999 char *colName = cmd->name;
7000 ColumnDef *def = (ColumnDef *) cmd->def;
7001 TypeName *typeName = def->typeName;
7003 Form_pg_attribute attTup;
7005 HeapTuple typeTuple;
7011 Relation attrelation;
7017 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
7019 /* Look up the target column */
7020 heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
7021 if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
7023 (errcode(ERRCODE_UNDEFINED_COLUMN),
7024 errmsg("column \"%s\" of relation \"%s\" does not exist",
7025 colName, RelationGetRelationName(rel))));
7026 attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
7027 attnum = attTup->attnum;
7029 /* Check for multiple ALTER TYPE on same column --- can't cope */
7030 if (attTup->atttypid != tab->oldDesc->attrs[attnum - 1]->atttypid ||
7031 attTup->atttypmod != tab->oldDesc->attrs[attnum - 1]->atttypmod)
7033 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7034 errmsg("cannot alter type of column \"%s\" twice",
7037 /* Look up the target type (should not fail, since prep found it) */
7038 typeTuple = typenameType(NULL, typeName, &targettypmod);
7039 tform = (Form_pg_type) GETSTRUCT(typeTuple);
7040 targettype = HeapTupleGetOid(typeTuple);
7041 /* And the collation */
7042 targetcollid = GetColumnDefCollation(NULL, def, targettype);
7045 * If there is a default expression for the column, get it and ensure we
7046 * can coerce it to the new datatype. (We must do this before changing
7047 * the column type, because build_column_default itself will try to
7048 * coerce, and will not issue the error message we want if it fails.)
7050 * We remove any implicit coercion steps at the top level of the old
7051 * default expression; this has been agreed to satisfy the principle of
7052 * least surprise. (The conversion to the new column type should act like
7053 * it started from what the user sees as the stored expression, and the
7054 * implicit coercions aren't going to be shown.)
7056 if (attTup->atthasdef)
7058 defaultexpr = build_column_default(rel, attnum);
7059 Assert(defaultexpr);
7060 defaultexpr = strip_implicit_coercions(defaultexpr);
7061 defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
7062 defaultexpr, exprType(defaultexpr),
7063 targettype, targettypmod,
7064 COERCION_ASSIGNMENT,
7065 COERCE_IMPLICIT_CAST,
7067 if (defaultexpr == NULL)
7069 (errcode(ERRCODE_DATATYPE_MISMATCH),
7070 errmsg("default for column \"%s\" cannot be cast to type %s",
7071 colName, format_type_be(targettype))));
7077 * Find everything that depends on the column (constraints, indexes, etc),
7078 * and record enough information to let us recreate the objects.
7080 * The actual recreation does not happen here, but only after we have
7081 * performed all the individual ALTER TYPE operations. We have to save
7082 * the info before executing ALTER TYPE, though, else the deparser will
7085 * There could be multiple entries for the same object, so we must check
7086 * to ensure we process each one only once. Note: we assume that an index
7087 * that implements a constraint will not show a direct dependency on the
7090 depRel = heap_open(DependRelationId, RowExclusiveLock);
7092 ScanKeyInit(&key[0],
7093 Anum_pg_depend_refclassid,
7094 BTEqualStrategyNumber, F_OIDEQ,
7095 ObjectIdGetDatum(RelationRelationId));
7096 ScanKeyInit(&key[1],
7097 Anum_pg_depend_refobjid,
7098 BTEqualStrategyNumber, F_OIDEQ,
7099 ObjectIdGetDatum(RelationGetRelid(rel)));
7100 ScanKeyInit(&key[2],
7101 Anum_pg_depend_refobjsubid,
7102 BTEqualStrategyNumber, F_INT4EQ,
7103 Int32GetDatum((int32) attnum));
7105 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
7106 SnapshotNow, 3, key);
7108 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
7110 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
7111 ObjectAddress foundObject;
7113 /* We don't expect any PIN dependencies on columns */
7114 if (foundDep->deptype == DEPENDENCY_PIN)
7115 elog(ERROR, "cannot alter type of a pinned column");
7117 foundObject.classId = foundDep->classid;
7118 foundObject.objectId = foundDep->objid;
7119 foundObject.objectSubId = foundDep->objsubid;
7121 switch (getObjectClass(&foundObject))
7125 char relKind = get_rel_relkind(foundObject.objectId);
7127 if (relKind == RELKIND_INDEX)
7129 Assert(foundObject.objectSubId == 0);
7130 if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
7132 tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
7133 foundObject.objectId);
7134 tab->changedIndexDefs = lappend(tab->changedIndexDefs,
7135 pg_get_indexdef_string(foundObject.objectId));
7138 else if (relKind == RELKIND_SEQUENCE)
7141 * This must be a SERIAL column's sequence. We need
7142 * not do anything to it.
7144 Assert(foundObject.objectSubId == 0);
7148 /* Not expecting any other direct dependencies... */
7149 elog(ERROR, "unexpected object depending on column: %s",
7150 getObjectDescription(&foundObject));
7155 case OCLASS_CONSTRAINT:
7156 Assert(foundObject.objectSubId == 0);
7157 if (!list_member_oid(tab->changedConstraintOids,
7158 foundObject.objectId))
7160 char *defstring = pg_get_constraintdef_string(foundObject.objectId);
7163 * Put NORMAL dependencies at the front of the list and
7164 * AUTO dependencies at the back. This makes sure that
7165 * foreign-key constraints depending on this column will
7166 * be dropped before unique or primary-key constraints of
7167 * the column; which we must have because the FK
7168 * constraints depend on the indexes belonging to the
7169 * unique constraints.
7171 if (foundDep->deptype == DEPENDENCY_NORMAL)
7173 tab->changedConstraintOids =
7174 lcons_oid(foundObject.objectId,
7175 tab->changedConstraintOids);
7176 tab->changedConstraintDefs =
7178 tab->changedConstraintDefs);
7182 tab->changedConstraintOids =
7183 lappend_oid(tab->changedConstraintOids,
7184 foundObject.objectId);
7185 tab->changedConstraintDefs =
7186 lappend(tab->changedConstraintDefs,
7192 case OCLASS_REWRITE:
7193 /* XXX someday see if we can cope with revising views */
7195 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7196 errmsg("cannot alter type of a column used by a view or rule"),
7197 errdetail("%s depends on column \"%s\"",
7198 getObjectDescription(&foundObject),
7202 case OCLASS_TRIGGER:
7205 * A trigger can depend on a column because the column is
7206 * specified as an update target, or because the column is
7207 * used in the trigger's WHEN condition. The first case would
7208 * not require any extra work, but the second case would
7209 * require updating the WHEN expression, which will take a
7210 * significant amount of new code. Since we can't easily tell
7211 * which case applies, we punt for both. FIXME someday.
7214 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7215 errmsg("cannot alter type of a column used in a trigger definition"),
7216 errdetail("%s depends on column \"%s\"",
7217 getObjectDescription(&foundObject),
7221 case OCLASS_DEFAULT:
7224 * Ignore the column's default expression, since we will fix
7227 Assert(defaultexpr);
7233 case OCLASS_COLLATION:
7234 case OCLASS_CONVERSION:
7235 case OCLASS_LANGUAGE:
7236 case OCLASS_LARGEOBJECT:
7237 case OCLASS_OPERATOR:
7238 case OCLASS_OPCLASS:
7239 case OCLASS_OPFAMILY:
7243 case OCLASS_TSPARSER:
7245 case OCLASS_TSTEMPLATE:
7246 case OCLASS_TSCONFIG:
7248 case OCLASS_DATABASE:
7249 case OCLASS_TBLSPACE:
7251 case OCLASS_FOREIGN_SERVER:
7252 case OCLASS_USER_MAPPING:
7254 case OCLASS_EXTENSION:
7257 * We don't expect any of these sorts of objects to depend on
7260 elog(ERROR, "unexpected object depending on column: %s",
7261 getObjectDescription(&foundObject));
7265 elog(ERROR, "unrecognized object class: %u",
7266 foundObject.classId);
7270 systable_endscan(scan);
7273 * Now scan for dependencies of this column on other things. The only
7274 * thing we should find is the dependency on the column datatype, which we
7275 * want to remove, and possibly a collation dependency.
7277 ScanKeyInit(&key[0],
7278 Anum_pg_depend_classid,
7279 BTEqualStrategyNumber, F_OIDEQ,
7280 ObjectIdGetDatum(RelationRelationId));
7281 ScanKeyInit(&key[1],
7282 Anum_pg_depend_objid,
7283 BTEqualStrategyNumber, F_OIDEQ,
7284 ObjectIdGetDatum(RelationGetRelid(rel)));
7285 ScanKeyInit(&key[2],
7286 Anum_pg_depend_objsubid,
7287 BTEqualStrategyNumber, F_INT4EQ,
7288 Int32GetDatum((int32) attnum));
7290 scan = systable_beginscan(depRel, DependDependerIndexId, true,
7291 SnapshotNow, 3, key);
7293 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
7295 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
7297 if (foundDep->deptype != DEPENDENCY_NORMAL)
7298 elog(ERROR, "found unexpected dependency type '%c'",
7300 if (!(foundDep->refclassid == TypeRelationId &&
7301 foundDep->refobjid == attTup->atttypid) &&
7302 !(foundDep->refclassid == CollationRelationId &&
7303 foundDep->refobjid == attTup->attcollation))
7304 elog(ERROR, "found unexpected dependency for column");
7306 simple_heap_delete(depRel, &depTup->t_self);
7309 systable_endscan(scan);
7311 heap_close(depRel, RowExclusiveLock);
7314 * Here we go --- change the recorded column type and collation. (Note
7315 * heapTup is a copy of the syscache entry, so okay to scribble on.)
7317 attTup->atttypid = targettype;
7318 attTup->atttypmod = targettypmod;
7319 attTup->attcollation = targetcollid;
7320 attTup->attndims = list_length(typeName->arrayBounds);
7321 attTup->attlen = tform->typlen;
7322 attTup->attbyval = tform->typbyval;
7323 attTup->attalign = tform->typalign;
7324 attTup->attstorage = tform->typstorage;
7326 ReleaseSysCache(typeTuple);
7328 simple_heap_update(attrelation, &heapTup->t_self, heapTup);
7330 /* keep system catalog indexes current */
7331 CatalogUpdateIndexes(attrelation, heapTup);
7333 heap_close(attrelation, RowExclusiveLock);
7335 /* Install dependencies on new datatype and collation */
7336 add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
7337 add_column_collation_dependency(RelationGetRelid(rel), attnum, targetcollid);
7340 * Drop any pg_statistic entry for the column, since it's now wrong type
7342 RemoveStatistics(RelationGetRelid(rel), attnum);
7345 * Update the default, if present, by brute force --- remove and re-add
7346 * the default. Probably unsafe to take shortcuts, since the new version
7347 * may well have additional dependencies. (It's okay to do this now,
7348 * rather than after other ALTER TYPE commands, since the default won't
7349 * depend on other column types.)
7353 /* Must make new row visible since it will be updated again */
7354 CommandCounterIncrement();
7357 * We use RESTRICT here for safety, but at present we do not expect
7358 * anything to depend on the default.
7360 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true);
7362 StoreAttrDefault(rel, attnum, defaultexpr);
7366 heap_freetuple(heapTup);
7370 * Cleanup after we've finished all the ALTER TYPE operations for a
7371 * particular relation. We have to drop and recreate all the indexes
7372 * and constraints that depend on the altered columns.
7375 ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)
7381 * Re-parse the index and constraint definitions, and attach them to the
7382 * appropriate work queue entries. We do this before dropping because in
7383 * the case of a FOREIGN KEY constraint, we might not yet have exclusive
7384 * lock on the table the constraint is attached to, and we need to get
7385 * that before dropping. It's safe because the parser won't actually look
7386 * at the catalogs to detect the existing entry.
7388 foreach(l, tab->changedIndexDefs)
7389 ATPostAlterTypeParse((char *) lfirst(l), wqueue, lockmode);
7390 foreach(l, tab->changedConstraintDefs)
7391 ATPostAlterTypeParse((char *) lfirst(l), wqueue, lockmode);
7394 * Now we can drop the existing constraints and indexes --- constraints
7395 * first, since some of them might depend on the indexes. In fact, we
7396 * have to delete FOREIGN KEY constraints before UNIQUE constraints, but
7397 * we already ordered the constraint list to ensure that would happen. It
7398 * should be okay to use DROP_RESTRICT here, since nothing else should be
7399 * depending on these objects.
7401 foreach(l, tab->changedConstraintOids)
7403 obj.classId = ConstraintRelationId;
7404 obj.objectId = lfirst_oid(l);
7405 obj.objectSubId = 0;
7406 performDeletion(&obj, DROP_RESTRICT);
7409 foreach(l, tab->changedIndexOids)
7411 obj.classId = RelationRelationId;
7412 obj.objectId = lfirst_oid(l);
7413 obj.objectSubId = 0;
7414 performDeletion(&obj, DROP_RESTRICT);
7418 * The objects will get recreated during subsequent passes over the work
7424 ATPostAlterTypeParse(char *cmd, List **wqueue, LOCKMODE lockmode)
7426 List *raw_parsetree_list;
7427 List *querytree_list;
7428 ListCell *list_item;
7431 * We expect that we will get only ALTER TABLE and CREATE INDEX
7432 * statements. Hence, there is no need to pass them through
7433 * parse_analyze() or the rewriter, but instead we need to pass them
7434 * through parse_utilcmd.c to make them ready for execution.
7436 raw_parsetree_list = raw_parser(cmd);
7437 querytree_list = NIL;
7438 foreach(list_item, raw_parsetree_list)
7440 Node *stmt = (Node *) lfirst(list_item);
7442 if (IsA(stmt, IndexStmt))
7443 querytree_list = lappend(querytree_list,
7444 transformIndexStmt((IndexStmt *) stmt,
7446 else if (IsA(stmt, AlterTableStmt))
7447 querytree_list = list_concat(querytree_list,
7448 transformAlterTableStmt((AlterTableStmt *) stmt,
7451 querytree_list = lappend(querytree_list, stmt);
7455 * Attach each generated command to the proper place in the work queue.
7456 * Note this could result in creation of entirely new work-queue entries.
7458 foreach(list_item, querytree_list)
7460 Node *stm = (Node *) lfirst(list_item);
7462 AlteredTableInfo *tab;
7464 switch (nodeTag(stm))
7468 IndexStmt *stmt = (IndexStmt *) stm;
7469 AlterTableCmd *newcmd;
7471 rel = relation_openrv(stmt->relation, lockmode);
7472 tab = ATGetQueueEntry(wqueue, rel);
7473 newcmd = makeNode(AlterTableCmd);
7474 newcmd->subtype = AT_ReAddIndex;
7475 newcmd->def = (Node *) stmt;
7476 tab->subcmds[AT_PASS_OLD_INDEX] =
7477 lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
7478 relation_close(rel, NoLock);
7481 case T_AlterTableStmt:
7483 AlterTableStmt *stmt = (AlterTableStmt *) stm;
7486 rel = relation_openrv(stmt->relation, lockmode);
7487 tab = ATGetQueueEntry(wqueue, rel);
7488 foreach(lcmd, stmt->cmds)
7490 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
7492 switch (cmd->subtype)
7495 cmd->subtype = AT_ReAddIndex;
7496 tab->subcmds[AT_PASS_OLD_INDEX] =
7497 lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
7499 case AT_AddConstraint:
7500 tab->subcmds[AT_PASS_OLD_CONSTR] =
7501 lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
7504 elog(ERROR, "unexpected statement type: %d",
7505 (int) cmd->subtype);
7508 relation_close(rel, NoLock);
7512 elog(ERROR, "unexpected statement type: %d",
7513 (int) nodeTag(stm));
7522 * recursing is true if we are recursing from a table to its indexes,
7523 * sequences, or toast table. We don't allow the ownership of those things to
7524 * be changed separately from the parent table. Also, we can skip permission
7525 * checks (this is necessary not just an optimization, else we'd fail to
7526 * handle toast tables properly).
7528 * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
7529 * free-standing composite type.
7532 ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
7534 Relation target_rel;
7537 Form_pg_class tuple_class;
7540 * Get exclusive lock till end of transaction on the target table. Use
7541 * relation_open so that we can work on indexes and sequences.
7543 target_rel = relation_open(relationOid, lockmode);
7545 /* Get its pg_class tuple, too */
7546 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
7548 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
7549 if (!HeapTupleIsValid(tuple))
7550 elog(ERROR, "cache lookup failed for relation %u", relationOid);
7551 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
7553 /* Can we change the ownership of this tuple? */
7554 switch (tuple_class->relkind)
7556 case RELKIND_RELATION:
7558 case RELKIND_FOREIGN_TABLE:
7559 /* ok to change owner */
7565 * Because ALTER INDEX OWNER used to be allowed, and in fact
7566 * is generated by old versions of pg_dump, we give a warning
7567 * and do nothing rather than erroring out. Also, to avoid
7568 * unnecessary chatter while restoring those old dumps, say
7569 * nothing at all if the command would be a no-op anyway.
7571 if (tuple_class->relowner != newOwnerId)
7573 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7574 errmsg("cannot change owner of index \"%s\"",
7575 NameStr(tuple_class->relname)),
7576 errhint("Change the ownership of the index's table, instead.")));
7577 /* quick hack to exit via the no-op path */
7578 newOwnerId = tuple_class->relowner;
7581 case RELKIND_SEQUENCE:
7583 tuple_class->relowner != newOwnerId)
7585 /* if it's an owned sequence, disallow changing it by itself */
7589 if (sequenceIsOwned(relationOid, &tableId, &colId))
7591 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7592 errmsg("cannot change owner of sequence \"%s\"",
7593 NameStr(tuple_class->relname)),
7594 errdetail("Sequence \"%s\" is linked to table \"%s\".",
7595 NameStr(tuple_class->relname),
7596 get_rel_name(tableId))));
7599 case RELKIND_COMPOSITE_TYPE:
7603 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7604 errmsg("\"%s\" is a composite type",
7605 NameStr(tuple_class->relname)),
7606 errhint("Use ALTER TYPE instead.")));
7608 case RELKIND_TOASTVALUE:
7614 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7615 errmsg("\"%s\" is not a table, view, sequence, or foreign table",
7616 NameStr(tuple_class->relname))));
7620 * If the new owner is the same as the existing owner, consider the
7621 * command to have succeeded. This is for dump restoration purposes.
7623 if (tuple_class->relowner != newOwnerId)
7625 Datum repl_val[Natts_pg_class];
7626 bool repl_null[Natts_pg_class];
7627 bool repl_repl[Natts_pg_class];
7633 /* skip permission checks when recursing to index or toast table */
7636 /* Superusers can always do it */
7639 Oid namespaceOid = tuple_class->relnamespace;
7640 AclResult aclresult;
7642 /* Otherwise, must be owner of the existing object */
7643 if (!pg_class_ownercheck(relationOid, GetUserId()))
7644 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
7645 RelationGetRelationName(target_rel));
7647 /* Must be able to become new owner */
7648 check_is_member_of_role(GetUserId(), newOwnerId);
7650 /* New owner must have CREATE privilege on namespace */
7651 aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
7653 if (aclresult != ACLCHECK_OK)
7654 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
7655 get_namespace_name(namespaceOid));
7659 memset(repl_null, false, sizeof(repl_null));
7660 memset(repl_repl, false, sizeof(repl_repl));
7662 repl_repl[Anum_pg_class_relowner - 1] = true;
7663 repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
7666 * Determine the modified ACL for the new owner. This is only
7667 * necessary when the ACL is non-null.
7669 aclDatum = SysCacheGetAttr(RELOID, tuple,
7670 Anum_pg_class_relacl,
7674 newAcl = aclnewowner(DatumGetAclP(aclDatum),
7675 tuple_class->relowner, newOwnerId);
7676 repl_repl[Anum_pg_class_relacl - 1] = true;
7677 repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
7680 newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
7682 simple_heap_update(class_rel, &newtuple->t_self, newtuple);
7683 CatalogUpdateIndexes(class_rel, newtuple);
7685 heap_freetuple(newtuple);
7688 * Update owner dependency reference, if any. A composite type has
7689 * none, because it's tracked for the pg_type entry instead of here;
7690 * indexes and TOAST tables don't have their own entries either.
7692 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
7693 tuple_class->relkind != RELKIND_INDEX &&
7694 tuple_class->relkind != RELKIND_TOASTVALUE)
7695 changeDependencyOnOwner(RelationRelationId, relationOid,
7699 * Also change the ownership of the table's row type, if it has one
7701 if (tuple_class->relkind != RELKIND_INDEX)
7702 AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId,
7703 tuple_class->relkind == RELKIND_COMPOSITE_TYPE);
7706 * If we are operating on a table, also change the ownership of any
7707 * indexes and sequences that belong to the table, as well as the
7708 * table's toast table (if it has one)
7710 if (tuple_class->relkind == RELKIND_RELATION ||
7711 tuple_class->relkind == RELKIND_TOASTVALUE)
7713 List *index_oid_list;
7716 /* Find all the indexes belonging to this relation */
7717 index_oid_list = RelationGetIndexList(target_rel);
7719 /* For each index, recursively change its ownership */
7720 foreach(i, index_oid_list)
7721 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
7723 list_free(index_oid_list);
7726 if (tuple_class->relkind == RELKIND_RELATION)
7728 /* If it has a toast table, recurse to change its ownership */
7729 if (tuple_class->reltoastrelid != InvalidOid)
7730 ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
7733 /* If it has dependent sequences, recurse to change them too */
7734 change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
7738 ReleaseSysCache(tuple);
7739 heap_close(class_rel, RowExclusiveLock);
7740 relation_close(target_rel, NoLock);
7744 * change_owner_recurse_to_sequences
7746 * Helper function for ATExecChangeOwner. Examines pg_depend searching
7747 * for sequences that are dependent on serial columns, and changes their
7751 change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
7759 * SERIAL sequences are those having an auto dependency on one of the
7760 * table's columns (we don't care *which* column, exactly).
7762 depRel = heap_open(DependRelationId, AccessShareLock);
7764 ScanKeyInit(&key[0],
7765 Anum_pg_depend_refclassid,
7766 BTEqualStrategyNumber, F_OIDEQ,
7767 ObjectIdGetDatum(RelationRelationId));
7768 ScanKeyInit(&key[1],
7769 Anum_pg_depend_refobjid,
7770 BTEqualStrategyNumber, F_OIDEQ,
7771 ObjectIdGetDatum(relationOid));
7772 /* we leave refobjsubid unspecified */
7774 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
7775 SnapshotNow, 2, key);
7777 while (HeapTupleIsValid(tup = systable_getnext(scan)))
7779 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
7782 /* skip dependencies other than auto dependencies on columns */
7783 if (depForm->refobjsubid == 0 ||
7784 depForm->classid != RelationRelationId ||
7785 depForm->objsubid != 0 ||
7786 depForm->deptype != DEPENDENCY_AUTO)
7789 /* Use relation_open just in case it's an index */
7790 seqRel = relation_open(depForm->objid, lockmode);
7792 /* skip non-sequence relations */
7793 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
7795 /* No need to keep the lock */
7796 relation_close(seqRel, lockmode);
7800 /* We don't need to close the sequence while we alter it. */
7801 ATExecChangeOwner(depForm->objid, newOwnerId, true, lockmode);
7803 /* Now we can close it. Keep the lock till end of transaction. */
7804 relation_close(seqRel, NoLock);
7807 systable_endscan(scan);
7809 relation_close(depRel, AccessShareLock);
7813 * ALTER TABLE CLUSTER ON
7815 * The only thing we have to do is to change the indisclustered bits.
7818 ATExecClusterOn(Relation rel, const char *indexName, LOCKMODE lockmode)
7822 indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
7824 if (!OidIsValid(indexOid))
7826 (errcode(ERRCODE_UNDEFINED_OBJECT),
7827 errmsg("index \"%s\" for table \"%s\" does not exist",
7828 indexName, RelationGetRelationName(rel))));
7830 /* Check index is valid to cluster on */
7831 check_index_is_clusterable(rel, indexOid, false, lockmode);
7833 /* And do the work */
7834 mark_index_clustered(rel, indexOid);
7838 * ALTER TABLE SET WITHOUT CLUSTER
7840 * We have to find any indexes on the table that have indisclustered bit
7841 * set and turn it off.
7844 ATExecDropCluster(Relation rel, LOCKMODE lockmode)
7846 mark_index_clustered(rel, InvalidOid);
7850 * ALTER TABLE SET TABLESPACE
7853 ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, char *tablespacename, LOCKMODE lockmode)
7856 AclResult aclresult;
7858 /* Check that the tablespace exists */
7859 tablespaceId = get_tablespace_oid(tablespacename, false);
7861 /* Check its permissions */
7862 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(), ACL_CREATE);
7863 if (aclresult != ACLCHECK_OK)
7864 aclcheck_error(aclresult, ACL_KIND_TABLESPACE, tablespacename);
7866 /* Save info for Phase 3 to do the real work */
7867 if (OidIsValid(tab->newTableSpace))
7869 (errcode(ERRCODE_SYNTAX_ERROR),
7870 errmsg("cannot have multiple SET TABLESPACE subcommands")));
7871 tab->newTableSpace = tablespaceId;
7875 * ALTER TABLE/INDEX SET (...) or RESET (...)
7878 ATExecSetRelOptions(Relation rel, List *defList, bool isReset, LOCKMODE lockmode)
7887 Datum repl_val[Natts_pg_class];
7888 bool repl_null[Natts_pg_class];
7889 bool repl_repl[Natts_pg_class];
7890 static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
7893 return; /* nothing to do */
7895 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
7897 /* Get the old reloptions */
7898 relid = RelationGetRelid(rel);
7899 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
7900 if (!HeapTupleIsValid(tuple))
7901 elog(ERROR, "cache lookup failed for relation %u", relid);
7903 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions, &isnull);
7905 /* Generate new proposed reloptions (text array) */
7906 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
7907 defList, NULL, validnsps, false, isReset);
7910 switch (rel->rd_rel->relkind)
7912 case RELKIND_RELATION:
7913 case RELKIND_TOASTVALUE:
7914 (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
7917 (void) index_reloptions(rel->rd_am->amoptions, newOptions, true);
7921 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7922 errmsg("\"%s\" is not a table, index, or TOAST table",
7923 RelationGetRelationName(rel))));
7928 * All we need do here is update the pg_class row; the new options will be
7929 * propagated into relcaches during post-commit cache inval.
7931 memset(repl_val, 0, sizeof(repl_val));
7932 memset(repl_null, false, sizeof(repl_null));
7933 memset(repl_repl, false, sizeof(repl_repl));
7935 if (newOptions != (Datum) 0)
7936 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
7938 repl_null[Anum_pg_class_reloptions - 1] = true;
7940 repl_repl[Anum_pg_class_reloptions - 1] = true;
7942 newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
7943 repl_val, repl_null, repl_repl);
7945 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
7947 CatalogUpdateIndexes(pgclass, newtuple);
7949 heap_freetuple(newtuple);
7951 ReleaseSysCache(tuple);
7953 /* repeat the whole exercise for the toast table, if there's one */
7954 if (OidIsValid(rel->rd_rel->reltoastrelid))
7957 Oid toastid = rel->rd_rel->reltoastrelid;
7959 toastrel = heap_open(toastid, lockmode);
7961 /* Get the old reloptions */
7962 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(toastid));
7963 if (!HeapTupleIsValid(tuple))
7964 elog(ERROR, "cache lookup failed for relation %u", toastid);
7966 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions, &isnull);
7968 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
7969 defList, "toast", validnsps, false, isReset);
7971 (void) heap_reloptions(RELKIND_TOASTVALUE, newOptions, true);
7973 memset(repl_val, 0, sizeof(repl_val));
7974 memset(repl_null, false, sizeof(repl_null));
7975 memset(repl_repl, false, sizeof(repl_repl));
7977 if (newOptions != (Datum) 0)
7978 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
7980 repl_null[Anum_pg_class_reloptions - 1] = true;
7982 repl_repl[Anum_pg_class_reloptions - 1] = true;
7984 newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
7985 repl_val, repl_null, repl_repl);
7987 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
7989 CatalogUpdateIndexes(pgclass, newtuple);
7991 heap_freetuple(newtuple);
7993 ReleaseSysCache(tuple);
7995 heap_close(toastrel, NoLock);
7998 heap_close(pgclass, RowExclusiveLock);
8002 * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
8003 * rewriting to be done, so we just want to copy the data as fast as possible.
8006 ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode)
8013 RelFileNode newrnode;
8014 SMgrRelation dstrel;
8017 Form_pg_class rd_rel;
8021 * Need lock here in case we are recursing to toast table or index
8023 rel = relation_open(tableOid, lockmode);
8026 * No work if no change in tablespace.
8028 oldTableSpace = rel->rd_rel->reltablespace;
8029 if (newTableSpace == oldTableSpace ||
8030 (newTableSpace == MyDatabaseTableSpace && oldTableSpace == 0))
8032 relation_close(rel, NoLock);
8037 * We cannot support moving mapped relations into different tablespaces.
8038 * (In particular this eliminates all shared catalogs.)
8040 if (RelationIsMapped(rel))
8042 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8043 errmsg("cannot move system relation \"%s\"",
8044 RelationGetRelationName(rel))));
8046 /* Can't move a non-shared relation into pg_global */
8047 if (newTableSpace == GLOBALTABLESPACE_OID)
8049 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
8050 errmsg("only shared relations can be placed in pg_global tablespace")));
8053 * Don't allow moving temp tables of other backends ... their local buffer
8054 * manager is not going to cope.
8056 if (RELATION_IS_OTHER_TEMP(rel))
8058 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8059 errmsg("cannot move temporary tables of other sessions")));
8061 reltoastrelid = rel->rd_rel->reltoastrelid;
8062 reltoastidxid = rel->rd_rel->reltoastidxid;
8064 /* Get a modifiable copy of the relation's pg_class row */
8065 pg_class = heap_open(RelationRelationId, RowExclusiveLock);
8067 tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(tableOid));
8068 if (!HeapTupleIsValid(tuple))
8069 elog(ERROR, "cache lookup failed for relation %u", tableOid);
8070 rd_rel = (Form_pg_class) GETSTRUCT(tuple);
8073 * Since we copy the file directly without looking at the shared buffers,
8074 * we'd better first flush out any pages of the source relation that are
8075 * in shared buffers. We assume no new changes will be made while we are
8076 * holding exclusive lock on the rel.
8078 FlushRelationBuffers(rel);
8081 * Relfilenodes are not unique across tablespaces, so we need to allocate
8082 * a new one in the new tablespace.
8084 newrelfilenode = GetNewRelFileNode(newTableSpace, NULL,
8085 rel->rd_rel->relpersistence);
8087 /* Open old and new relation */
8088 newrnode = rel->rd_node;
8089 newrnode.relNode = newrelfilenode;
8090 newrnode.spcNode = newTableSpace;
8091 dstrel = smgropen(newrnode, rel->rd_backend);
8093 RelationOpenSmgr(rel);
8096 * Create and copy all forks of the relation, and schedule unlinking of
8097 * old physical files.
8099 * NOTE: any conflict in relfilenode value will be caught in
8100 * RelationCreateStorage().
8102 RelationCreateStorage(newrnode, rel->rd_rel->relpersistence);
8104 /* copy main fork */
8105 copy_relation_data(rel->rd_smgr, dstrel, MAIN_FORKNUM,
8106 rel->rd_rel->relpersistence);
8108 /* copy those extra forks that exist */
8109 for (forkNum = MAIN_FORKNUM + 1; forkNum <= MAX_FORKNUM; forkNum++)
8111 if (smgrexists(rel->rd_smgr, forkNum))
8113 smgrcreate(dstrel, forkNum, false);
8114 copy_relation_data(rel->rd_smgr, dstrel, forkNum,
8115 rel->rd_rel->relpersistence);
8119 /* drop old relation, and close new one */
8120 RelationDropStorage(rel);
8123 /* update the pg_class row */
8124 rd_rel->reltablespace = (newTableSpace == MyDatabaseTableSpace) ? InvalidOid : newTableSpace;
8125 rd_rel->relfilenode = newrelfilenode;
8126 simple_heap_update(pg_class, &tuple->t_self, tuple);
8127 CatalogUpdateIndexes(pg_class, tuple);
8129 heap_freetuple(tuple);
8131 heap_close(pg_class, RowExclusiveLock);
8133 relation_close(rel, NoLock);
8135 /* Make sure the reltablespace change is visible */
8136 CommandCounterIncrement();
8138 /* Move associated toast relation and/or index, too */
8139 if (OidIsValid(reltoastrelid))
8140 ATExecSetTableSpace(reltoastrelid, newTableSpace, lockmode);
8141 if (OidIsValid(reltoastidxid))
8142 ATExecSetTableSpace(reltoastidxid, newTableSpace, lockmode);
8146 * Copy data, block by block
8149 copy_relation_data(SMgrRelation src, SMgrRelation dst,
8150 ForkNumber forkNum, char relpersistence)
8155 BlockNumber nblocks;
8159 * palloc the buffer so that it's MAXALIGN'd. If it were just a local
8160 * char[] array, the compiler might align it on any byte boundary, which
8161 * can seriously hurt transfer speed to and from the kernel; not to
8162 * mention possibly making log_newpage's accesses to the page header fail.
8164 buf = (char *) palloc(BLCKSZ);
8168 * We need to log the copied data in WAL iff WAL archiving/streaming is
8169 * enabled AND it's a permanent relation.
8171 use_wal = XLogIsNeeded() && relpersistence == RELPERSISTENCE_PERMANENT;
8173 nblocks = smgrnblocks(src, forkNum);
8175 for (blkno = 0; blkno < nblocks; blkno++)
8177 /* If we got a cancel signal during the copy of the data, quit */
8178 CHECK_FOR_INTERRUPTS();
8180 smgrread(src, forkNum, blkno, buf);
8184 log_newpage(&dst->smgr_rnode.node, forkNum, blkno, page);
8187 * Now write the page. We say isTemp = true even if it's not a temp
8188 * rel, because there's no need for smgr to schedule an fsync for this
8189 * write; we'll do it ourselves below.
8191 smgrextend(dst, forkNum, blkno, buf, true);
8197 * If the rel isn't temp, we must fsync it down to disk before it's safe
8198 * to commit the transaction. (For a temp rel we don't care since the rel
8199 * will be uninteresting after a crash anyway.)
8201 * It's obvious that we must do this when not WAL-logging the copy. It's
8202 * less obvious that we have to do it even if we did WAL-log the copied
8203 * pages. The reason is that since we're copying outside shared buffers, a
8204 * CHECKPOINT occurring during the copy has no way to flush the previously
8205 * written data to disk (indeed it won't know the new rel even exists). A
8206 * crash later on would replay WAL from the checkpoint, therefore it
8207 * wouldn't replay our earlier WAL entries. If we do not fsync those pages
8208 * here, they might still not be on disk when the crash occurs.
8210 if (relpersistence == RELPERSISTENCE_PERMANENT)
8211 smgrimmedsync(dst, forkNum);
8215 * ALTER TABLE ENABLE/DISABLE TRIGGER
8217 * We just pass this off to trigger.c.
8220 ATExecEnableDisableTrigger(Relation rel, char *trigname,
8221 char fires_when, bool skip_system, LOCKMODE lockmode)
8223 EnableDisableTrigger(rel, trigname, fires_when, skip_system);
8227 * ALTER TABLE ENABLE/DISABLE RULE
8229 * We just pass this off to rewriteDefine.c.
8232 ATExecEnableDisableRule(Relation rel, char *trigname,
8233 char fires_when, LOCKMODE lockmode)
8235 EnableDisableRule(rel, trigname, fires_when);
8239 * ALTER TABLE INHERIT
8241 * Add a parent to the child's parents. This verifies that all the columns and
8242 * check constraints of the parent appear in the child and that they have the
8243 * same data types and expressions.
8246 ATPrepAddInherit(Relation child_rel)
8248 if (child_rel->rd_rel->reloftype)
8250 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8251 errmsg("cannot change inheritance of typed table")));
8255 ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode)
8257 Relation parent_rel,
8261 HeapTuple inheritsTuple;
8266 * A self-exclusive lock is needed here. See the similar case in
8267 * MergeAttributes() for a full explanation.
8269 parent_rel = heap_openrv(parent, ShareUpdateExclusiveLock);
8272 * Must be owner of both parent and child -- child was checked by
8273 * ATSimplePermissions call in ATPrepCmd
8275 ATSimplePermissions(parent_rel, ATT_TABLE);
8277 /* Permanent rels cannot inherit from temporary ones */
8278 if (RelationUsesTempNamespace(parent_rel)
8279 && !RelationUsesTempNamespace(child_rel))
8281 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8282 errmsg("cannot inherit from temporary relation \"%s\"",
8283 RelationGetRelationName(parent_rel))));
8286 * Check for duplicates in the list of parents, and determine the highest
8287 * inhseqno already present; we'll use the next one for the new parent.
8288 * (Note: get RowExclusiveLock because we will write pg_inherits below.)
8290 * Note: we do not reject the case where the child already inherits from
8291 * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
8293 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
8295 Anum_pg_inherits_inhrelid,
8296 BTEqualStrategyNumber, F_OIDEQ,
8297 ObjectIdGetDatum(RelationGetRelid(child_rel)));
8298 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
8299 true, SnapshotNow, 1, &key);
8301 /* inhseqno sequences start at 1 */
8303 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
8305 Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
8307 if (inh->inhparent == RelationGetRelid(parent_rel))
8309 (errcode(ERRCODE_DUPLICATE_TABLE),
8310 errmsg("relation \"%s\" would be inherited from more than once",
8311 RelationGetRelationName(parent_rel))));
8312 if (inh->inhseqno > inhseqno)
8313 inhseqno = inh->inhseqno;
8315 systable_endscan(scan);
8318 * Prevent circularity by seeing if proposed parent inherits from child.
8319 * (In particular, this disallows making a rel inherit from itself.)
8321 * This is not completely bulletproof because of race conditions: in
8322 * multi-level inheritance trees, someone else could concurrently be
8323 * making another inheritance link that closes the loop but does not join
8324 * either of the rels we have locked. Preventing that seems to require
8325 * exclusive locks on the entire inheritance tree, which is a cure worse
8326 * than the disease. find_all_inheritors() will cope with circularity
8327 * anyway, so don't sweat it too much.
8329 * We use weakest lock we can on child's children, namely AccessShareLock.
8331 children = find_all_inheritors(RelationGetRelid(child_rel),
8332 AccessShareLock, NULL);
8334 if (list_member_oid(children, RelationGetRelid(parent_rel)))
8336 (errcode(ERRCODE_DUPLICATE_TABLE),
8337 errmsg("circular inheritance not allowed"),
8338 errdetail("\"%s\" is already a child of \"%s\".",
8340 RelationGetRelationName(child_rel))));
8342 /* If parent has OIDs then child must have OIDs */
8343 if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
8345 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8346 errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
8347 RelationGetRelationName(child_rel),
8348 RelationGetRelationName(parent_rel))));
8350 /* Match up the columns and bump attinhcount as needed */
8351 MergeAttributesIntoExisting(child_rel, parent_rel);
8353 /* Match up the constraints and bump coninhcount as needed */
8354 MergeConstraintsIntoExisting(child_rel, parent_rel);
8357 * OK, it looks valid. Make the catalog entries that show inheritance.
8359 StoreCatalogInheritance1(RelationGetRelid(child_rel),
8360 RelationGetRelid(parent_rel),
8364 /* Now we're done with pg_inherits */
8365 heap_close(catalogRelation, RowExclusiveLock);
8367 /* keep our lock on the parent relation until commit */
8368 heap_close(parent_rel, NoLock);
8372 * Obtain the source-text form of the constraint expression for a check
8373 * constraint, given its pg_constraint tuple
8376 decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
8378 Form_pg_constraint con;
8383 con = (Form_pg_constraint) GETSTRUCT(contup);
8384 attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
8386 elog(ERROR, "null conbin for constraint %u", HeapTupleGetOid(contup));
8388 expr = DirectFunctionCall2(pg_get_expr, attr,
8389 ObjectIdGetDatum(con->conrelid));
8390 return TextDatumGetCString(expr);
8394 * Determine whether two check constraints are functionally equivalent
8396 * The test we apply is to see whether they reverse-compile to the same
8397 * source string. This insulates us from issues like whether attributes
8398 * have the same physical column numbers in parent and child relations.
8401 constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
8403 Form_pg_constraint acon = (Form_pg_constraint) GETSTRUCT(a);
8404 Form_pg_constraint bcon = (Form_pg_constraint) GETSTRUCT(b);
8406 if (acon->condeferrable != bcon->condeferrable ||
8407 acon->condeferred != bcon->condeferred ||
8408 strcmp(decompile_conbin(a, tupleDesc),
8409 decompile_conbin(b, tupleDesc)) != 0)
8416 * Check columns in child table match up with columns in parent, and increment
8417 * their attinhcount.
8419 * Called by ATExecAddInherit
8421 * Currently all parent columns must be found in child. Missing columns are an
8422 * error. One day we might consider creating new columns like CREATE TABLE
8423 * does. However, that is widely unpopular --- in the common use case of
8424 * partitioned tables it's a foot-gun.
8426 * The data type must match exactly. If the parent column is NOT NULL then
8427 * the child must be as well. Defaults are not compared, however.
8430 MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel)
8433 AttrNumber parent_attno;
8435 TupleDesc tupleDesc;
8438 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
8440 tupleDesc = RelationGetDescr(parent_rel);
8441 parent_natts = tupleDesc->natts;
8443 for (parent_attno = 1; parent_attno <= parent_natts; parent_attno++)
8445 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
8446 char *attributeName = NameStr(attribute->attname);
8448 /* Ignore dropped columns in the parent. */
8449 if (attribute->attisdropped)
8452 /* Find same column in child (matching on column name). */
8453 tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel),
8455 if (HeapTupleIsValid(tuple))
8457 /* Check they are same type, typmod, and collation */
8458 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
8460 if (attribute->atttypid != childatt->atttypid ||
8461 attribute->atttypmod != childatt->atttypmod)
8463 (errcode(ERRCODE_DATATYPE_MISMATCH),
8464 errmsg("child table \"%s\" has different type for column \"%s\"",
8465 RelationGetRelationName(child_rel),
8468 if (attribute->attcollation != childatt->attcollation)
8470 (errcode(ERRCODE_COLLATION_MISMATCH),
8471 errmsg("child table \"%s\" has different collation for column \"%s\"",
8472 RelationGetRelationName(child_rel),
8476 * Check child doesn't discard NOT NULL property. (Other
8477 * constraints are checked elsewhere.)
8479 if (attribute->attnotnull && !childatt->attnotnull)
8481 (errcode(ERRCODE_DATATYPE_MISMATCH),
8482 errmsg("column \"%s\" in child table must be marked NOT NULL",
8486 * OK, bump the child column's inheritance count. (If we fail
8487 * later on, this change will just roll back.)
8489 childatt->attinhcount++;
8490 simple_heap_update(attrrel, &tuple->t_self, tuple);
8491 CatalogUpdateIndexes(attrrel, tuple);
8492 heap_freetuple(tuple);
8497 (errcode(ERRCODE_DATATYPE_MISMATCH),
8498 errmsg("child table is missing column \"%s\"",
8503 heap_close(attrrel, RowExclusiveLock);
8507 * Check constraints in child table match up with constraints in parent,
8508 * and increment their coninhcount.
8510 * Called by ATExecAddInherit
8512 * Currently all constraints in parent must be present in the child. One day we
8513 * may consider adding new constraints like CREATE TABLE does. We may also want
8514 * to allow an optional flag on parent table constraints indicating they are
8515 * intended to ONLY apply to the master table, not to the children. That would
8516 * make it possible to ensure no records are mistakenly inserted into the
8517 * master in partitioned tables rather than the appropriate child.
8519 * XXX This is O(N^2) which may be an issue with tables with hundreds of
8520 * constraints. As long as tables have more like 10 constraints it shouldn't be
8521 * a problem though. Even 100 constraints ought not be the end of the world.
8524 MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
8526 Relation catalog_relation;
8527 TupleDesc tuple_desc;
8528 SysScanDesc parent_scan;
8529 ScanKeyData parent_key;
8530 HeapTuple parent_tuple;
8532 catalog_relation = heap_open(ConstraintRelationId, RowExclusiveLock);
8533 tuple_desc = RelationGetDescr(catalog_relation);
8535 /* Outer loop scans through the parent's constraint definitions */
8536 ScanKeyInit(&parent_key,
8537 Anum_pg_constraint_conrelid,
8538 BTEqualStrategyNumber, F_OIDEQ,
8539 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
8540 parent_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
8541 true, SnapshotNow, 1, &parent_key);
8543 while (HeapTupleIsValid(parent_tuple = systable_getnext(parent_scan)))
8545 Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(parent_tuple);
8546 SysScanDesc child_scan;
8547 ScanKeyData child_key;
8548 HeapTuple child_tuple;
8551 if (parent_con->contype != CONSTRAINT_CHECK)
8554 /* Search for a child constraint matching this one */
8555 ScanKeyInit(&child_key,
8556 Anum_pg_constraint_conrelid,
8557 BTEqualStrategyNumber, F_OIDEQ,
8558 ObjectIdGetDatum(RelationGetRelid(child_rel)));
8559 child_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
8560 true, SnapshotNow, 1, &child_key);
8562 while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
8564 Form_pg_constraint child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
8565 HeapTuple child_copy;
8567 if (child_con->contype != CONSTRAINT_CHECK)
8570 if (strcmp(NameStr(parent_con->conname),
8571 NameStr(child_con->conname)) != 0)
8574 if (!constraints_equivalent(parent_tuple, child_tuple, tuple_desc))
8576 (errcode(ERRCODE_DATATYPE_MISMATCH),
8577 errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
8578 RelationGetRelationName(child_rel),
8579 NameStr(parent_con->conname))));
8582 * OK, bump the child constraint's inheritance count. (If we fail
8583 * later on, this change will just roll back.)
8585 child_copy = heap_copytuple(child_tuple);
8586 child_con = (Form_pg_constraint) GETSTRUCT(child_copy);
8587 child_con->coninhcount++;
8588 simple_heap_update(catalog_relation, &child_copy->t_self, child_copy);
8589 CatalogUpdateIndexes(catalog_relation, child_copy);
8590 heap_freetuple(child_copy);
8596 systable_endscan(child_scan);
8600 (errcode(ERRCODE_DATATYPE_MISMATCH),
8601 errmsg("child table is missing constraint \"%s\"",
8602 NameStr(parent_con->conname))));
8605 systable_endscan(parent_scan);
8606 heap_close(catalog_relation, RowExclusiveLock);
8610 * ALTER TABLE NO INHERIT
8612 * Drop a parent from the child's parents. This just adjusts the attinhcount
8613 * and attislocal of the columns and removes the pg_inherit and pg_depend
8616 * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
8617 * up attislocal stays true, which means if a child is ever removed from a
8618 * parent then its columns will never be automatically dropped which may
8619 * surprise. But at least we'll never surprise by dropping columns someone
8620 * isn't expecting to be dropped which would actually mean data loss.
8622 * coninhcount and conislocal for inherited constraints are adjusted in
8623 * exactly the same way.
8626 ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode)
8628 Relation parent_rel;
8629 Relation catalogRelation;
8632 HeapTuple inheritsTuple,
8639 * AccessShareLock on the parent is probably enough, seeing that DROP
8640 * TABLE doesn't lock parent tables at all. We need some lock since we'll
8641 * be inspecting the parent's schema.
8643 parent_rel = heap_openrv(parent, AccessShareLock);
8646 * We don't bother to check ownership of the parent table --- ownership of
8647 * the child is presumed enough rights.
8651 * Find and destroy the pg_inherits entry linking the two, or error out if
8654 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
8655 ScanKeyInit(&key[0],
8656 Anum_pg_inherits_inhrelid,
8657 BTEqualStrategyNumber, F_OIDEQ,
8658 ObjectIdGetDatum(RelationGetRelid(rel)));
8659 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
8660 true, SnapshotNow, 1, key);
8662 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
8666 inhparent = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
8667 if (inhparent == RelationGetRelid(parent_rel))
8669 simple_heap_delete(catalogRelation, &inheritsTuple->t_self);
8675 systable_endscan(scan);
8676 heap_close(catalogRelation, RowExclusiveLock);
8680 (errcode(ERRCODE_UNDEFINED_TABLE),
8681 errmsg("relation \"%s\" is not a parent of relation \"%s\"",
8682 RelationGetRelationName(parent_rel),
8683 RelationGetRelationName(rel))));
8686 * Search through child columns looking for ones matching parent rel
8688 catalogRelation = heap_open(AttributeRelationId, RowExclusiveLock);
8689 ScanKeyInit(&key[0],
8690 Anum_pg_attribute_attrelid,
8691 BTEqualStrategyNumber, F_OIDEQ,
8692 ObjectIdGetDatum(RelationGetRelid(rel)));
8693 scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
8694 true, SnapshotNow, 1, key);
8695 while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
8697 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
8699 /* Ignore if dropped or not inherited */
8700 if (att->attisdropped)
8702 if (att->attinhcount <= 0)
8705 if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
8706 NameStr(att->attname)))
8708 /* Decrement inhcount and possibly set islocal to true */
8709 HeapTuple copyTuple = heap_copytuple(attributeTuple);
8710 Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
8712 copy_att->attinhcount--;
8713 if (copy_att->attinhcount == 0)
8714 copy_att->attislocal = true;
8716 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
8717 CatalogUpdateIndexes(catalogRelation, copyTuple);
8718 heap_freetuple(copyTuple);
8721 systable_endscan(scan);
8722 heap_close(catalogRelation, RowExclusiveLock);
8725 * Likewise, find inherited check constraints and disinherit them. To do
8726 * this, we first need a list of the names of the parent's check
8727 * constraints. (We cheat a bit by only checking for name matches,
8728 * assuming that the expressions will match.)
8730 catalogRelation = heap_open(ConstraintRelationId, RowExclusiveLock);
8731 ScanKeyInit(&key[0],
8732 Anum_pg_constraint_conrelid,
8733 BTEqualStrategyNumber, F_OIDEQ,
8734 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
8735 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
8736 true, SnapshotNow, 1, key);
8740 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
8742 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
8744 if (con->contype == CONSTRAINT_CHECK)
8745 connames = lappend(connames, pstrdup(NameStr(con->conname)));
8748 systable_endscan(scan);
8750 /* Now scan the child's constraints */
8751 ScanKeyInit(&key[0],
8752 Anum_pg_constraint_conrelid,
8753 BTEqualStrategyNumber, F_OIDEQ,
8754 ObjectIdGetDatum(RelationGetRelid(rel)));
8755 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
8756 true, SnapshotNow, 1, key);
8758 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
8760 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
8764 if (con->contype != CONSTRAINT_CHECK)
8768 foreach(lc, connames)
8770 if (strcmp(NameStr(con->conname), (char *) lfirst(lc)) == 0)
8779 /* Decrement inhcount and possibly set islocal to true */
8780 HeapTuple copyTuple = heap_copytuple(constraintTuple);
8781 Form_pg_constraint copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
8783 if (copy_con->coninhcount <= 0) /* shouldn't happen */
8784 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
8785 RelationGetRelid(rel), NameStr(copy_con->conname));
8787 copy_con->coninhcount--;
8788 if (copy_con->coninhcount == 0)
8789 copy_con->conislocal = true;
8791 simple_heap_update(catalogRelation, ©Tuple->t_self, copyTuple);
8792 CatalogUpdateIndexes(catalogRelation, copyTuple);
8793 heap_freetuple(copyTuple);
8797 systable_endscan(scan);
8798 heap_close(catalogRelation, RowExclusiveLock);
8800 drop_parent_dependency(RelationGetRelid(rel),
8802 RelationGetRelid(parent_rel));
8804 /* keep our lock on the parent relation until commit */
8805 heap_close(parent_rel, NoLock);
8809 * Drop the dependency created by StoreCatalogInheritance1 (CREATE TABLE
8810 * INHERITS/ALTER TABLE INHERIT -- refclassid will be RelationRelationId) or
8811 * heap_create_with_catalog (CREATE TABLE OF/ALTER TABLE OF -- refclassid will
8812 * be TypeRelationId). There's no convenient way to do this, so go trawling
8813 * through pg_depend.
8816 drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid)
8818 Relation catalogRelation;
8823 catalogRelation = heap_open(DependRelationId, RowExclusiveLock);
8825 ScanKeyInit(&key[0],
8826 Anum_pg_depend_classid,
8827 BTEqualStrategyNumber, F_OIDEQ,
8828 ObjectIdGetDatum(RelationRelationId));
8829 ScanKeyInit(&key[1],
8830 Anum_pg_depend_objid,
8831 BTEqualStrategyNumber, F_OIDEQ,
8832 ObjectIdGetDatum(relid));
8833 ScanKeyInit(&key[2],
8834 Anum_pg_depend_objsubid,
8835 BTEqualStrategyNumber, F_INT4EQ,
8838 scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
8839 SnapshotNow, 3, key);
8841 while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
8843 Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
8845 if (dep->refclassid == refclassid &&
8846 dep->refobjid == refobjid &&
8847 dep->refobjsubid == 0 &&
8848 dep->deptype == DEPENDENCY_NORMAL)
8849 simple_heap_delete(catalogRelation, &depTuple->t_self);
8852 systable_endscan(scan);
8853 heap_close(catalogRelation, RowExclusiveLock);
8859 * Attach a table to a composite type, as though it had been created with CREATE
8860 * TABLE OF. All attname, atttypid, atttypmod and attcollation must match. The
8861 * subject table must not have inheritance parents. These restrictions ensure
8862 * that you cannot create a configuration impossible with CREATE TABLE OF alone.
8865 ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode)
8867 Oid relid = RelationGetRelid(rel);
8870 Relation inheritsRelation,
8874 AttrNumber table_attno,
8876 TupleDesc typeTupleDesc,
8878 ObjectAddress tableobj,
8880 HeapTuple classtuple;
8882 /* Validate the type. */
8883 typetuple = typenameType(NULL, ofTypename, NULL);
8884 check_of_type(typetuple);
8885 typeid = HeapTupleGetOid(typetuple);
8887 /* Fail if the table has any inheritance parents. */
8888 inheritsRelation = heap_open(InheritsRelationId, AccessShareLock);
8890 Anum_pg_inherits_inhrelid,
8891 BTEqualStrategyNumber, F_OIDEQ,
8892 ObjectIdGetDatum(relid));
8893 scan = systable_beginscan(inheritsRelation, InheritsRelidSeqnoIndexId,
8894 true, SnapshotNow, 1, &key);
8895 if (HeapTupleIsValid(systable_getnext(scan)))
8897 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8898 errmsg("typed tables cannot inherit")));
8899 systable_endscan(scan);
8900 heap_close(inheritsRelation, AccessShareLock);
8903 * Check the tuple descriptors for compatibility. Unlike inheritance, we
8904 * require that the order also match. However, attnotnull need not match.
8905 * Also unlike inheritance, we do not require matching relhasoids.
8907 typeTupleDesc = lookup_rowtype_tupdesc(typeid, -1);
8908 tableTupleDesc = RelationGetDescr(rel);
8910 for (type_attno = 1; type_attno <= typeTupleDesc->natts; type_attno++)
8912 Form_pg_attribute type_attr,
8914 const char *type_attname,
8917 /* Get the next non-dropped type attribute. */
8918 type_attr = typeTupleDesc->attrs[type_attno - 1];
8919 if (type_attr->attisdropped)
8921 type_attname = NameStr(type_attr->attname);
8923 /* Get the next non-dropped table attribute. */
8926 if (table_attno > tableTupleDesc->natts)
8928 (errcode(ERRCODE_DATATYPE_MISMATCH),
8929 errmsg("table is missing column \"%s\"",
8931 table_attr = tableTupleDesc->attrs[table_attno++ - 1];
8932 } while (table_attr->attisdropped);
8933 table_attname = NameStr(table_attr->attname);
8936 if (strncmp(table_attname, type_attname, NAMEDATALEN) != 0)
8938 (errcode(ERRCODE_DATATYPE_MISMATCH),
8939 errmsg("table has column \"%s\" where type requires \"%s\"",
8940 table_attname, type_attname)));
8943 if (table_attr->atttypid != type_attr->atttypid ||
8944 table_attr->atttypmod != type_attr->atttypmod ||
8945 table_attr->attcollation != type_attr->attcollation)
8947 (errcode(ERRCODE_DATATYPE_MISMATCH),
8948 errmsg("table \"%s\" has different type for column \"%s\"",
8949 RelationGetRelationName(rel), type_attname)));
8951 DecrTupleDescRefCount(typeTupleDesc);
8953 /* Any remaining columns at the end of the table had better be dropped. */
8954 for (; table_attno <= tableTupleDesc->natts; table_attno++)
8956 Form_pg_attribute table_attr = tableTupleDesc->attrs[table_attno - 1];
8958 if (!table_attr->attisdropped)
8960 (errcode(ERRCODE_DATATYPE_MISMATCH),
8961 errmsg("table has extra column \"%s\"",
8962 NameStr(table_attr->attname))));
8965 /* If the table was already typed, drop the existing dependency. */
8966 if (rel->rd_rel->reloftype)
8967 drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype);
8969 /* Record a dependency on the new type. */
8970 tableobj.classId = RelationRelationId;
8971 tableobj.objectId = relid;
8972 tableobj.objectSubId = 0;
8973 typeobj.classId = TypeRelationId;
8974 typeobj.objectId = typeid;
8975 typeobj.objectSubId = 0;
8976 recordDependencyOn(&tableobj, &typeobj, DEPENDENCY_NORMAL);
8978 /* Update pg_class.reloftype */
8979 relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
8980 classtuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
8981 if (!HeapTupleIsValid(classtuple))
8982 elog(ERROR, "cache lookup failed for relation %u", relid);
8983 ((Form_pg_class) GETSTRUCT(classtuple))->reloftype = typeid;
8984 simple_heap_update(relationRelation, &classtuple->t_self, classtuple);
8985 CatalogUpdateIndexes(relationRelation, classtuple);
8986 heap_freetuple(classtuple);
8987 heap_close(relationRelation, RowExclusiveLock);
8989 ReleaseSysCache(typetuple);
8993 * ALTER TABLE NOT OF
8995 * Detach a typed table from its originating type. Just clear reloftype and
8996 * remove the dependency.
8999 ATExecDropOf(Relation rel, LOCKMODE lockmode)
9001 Oid relid = RelationGetRelid(rel);
9002 Relation relationRelation;
9005 if (!OidIsValid(rel->rd_rel->reloftype))
9007 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9008 errmsg("\"%s\" is not a typed table",
9009 RelationGetRelationName(rel))));
9012 * We don't bother to check ownership of the type --- ownership of the
9013 * table is presumed enough rights. No lock required on the type, either.
9016 drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype);
9018 /* Clear pg_class.reloftype */
9019 relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
9020 tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
9021 if (!HeapTupleIsValid(tuple))
9022 elog(ERROR, "cache lookup failed for relation %u", relid);
9023 ((Form_pg_class) GETSTRUCT(tuple))->reloftype = InvalidOid;
9024 simple_heap_update(relationRelation, &tuple->t_self, tuple);
9025 CatalogUpdateIndexes(relationRelation, tuple);
9026 heap_freetuple(tuple);
9027 heap_close(relationRelation, RowExclusiveLock);
9031 * ALTER FOREIGN TABLE <name> OPTIONS (...)
9034 ATExecGenericOptions(Relation rel, List *options)
9037 ForeignServer *server;
9038 ForeignDataWrapper *fdw;
9041 Datum repl_val[Natts_pg_foreign_table];
9042 bool repl_null[Natts_pg_foreign_table];
9043 bool repl_repl[Natts_pg_foreign_table];
9045 Form_pg_foreign_table tableform;
9050 ftrel = heap_open(ForeignTableRelationId, RowExclusiveLock);
9052 tuple = SearchSysCacheCopy1(FOREIGNTABLEREL, rel->rd_id);
9053 if (!HeapTupleIsValid(tuple))
9055 (errcode(ERRCODE_UNDEFINED_OBJECT),
9056 errmsg("foreign table \"%s\" does not exist",
9057 RelationGetRelationName(rel))));
9058 tableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
9059 server = GetForeignServer(tableform->ftserver);
9060 fdw = GetForeignDataWrapper(server->fdwid);
9062 memset(repl_val, 0, sizeof(repl_val));
9063 memset(repl_null, false, sizeof(repl_null));
9064 memset(repl_repl, false, sizeof(repl_repl));
9066 /* Extract the current options */
9067 datum = SysCacheGetAttr(FOREIGNTABLEREL,
9069 Anum_pg_foreign_table_ftoptions,
9072 datum = PointerGetDatum(NULL);
9074 /* Transform the options */
9075 datum = transformGenericOptions(ForeignTableRelationId,
9080 if (PointerIsValid(DatumGetPointer(datum)))
9081 repl_val[Anum_pg_foreign_table_ftoptions - 1] = datum;
9083 repl_null[Anum_pg_foreign_table_ftoptions - 1] = true;
9085 repl_repl[Anum_pg_foreign_table_ftoptions - 1] = true;
9087 /* Everything looks good - update the tuple */
9089 tuple = heap_modify_tuple(tuple, RelationGetDescr(ftrel),
9090 repl_val, repl_null, repl_repl);
9092 simple_heap_update(ftrel, &tuple->t_self, tuple);
9093 CatalogUpdateIndexes(ftrel, tuple);
9095 heap_close(ftrel, RowExclusiveLock);
9097 heap_freetuple(tuple);
9102 * Execute ALTER TABLE SET SCHEMA
9104 * Note: caller must have checked ownership of the relation already
9107 AlterTableNamespace(RangeVar *relation, const char *newschema,
9108 ObjectType stmttype, LOCKMODE lockmode)
9116 rel = relation_openrv(relation, lockmode);
9118 relid = RelationGetRelid(rel);
9119 oldNspOid = RelationGetNamespace(rel);
9121 /* Check relation type against type specified in the ALTER command */
9127 * For mostly-historical reasons, we allow ALTER TABLE to apply to
9128 * all relation types.
9132 case OBJECT_SEQUENCE:
9133 if (rel->rd_rel->relkind != RELKIND_SEQUENCE)
9135 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9136 errmsg("\"%s\" is not a sequence",
9137 RelationGetRelationName(rel))));
9141 if (rel->rd_rel->relkind != RELKIND_VIEW)
9143 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9144 errmsg("\"%s\" is not a view",
9145 RelationGetRelationName(rel))));
9148 case OBJECT_FOREIGN_TABLE:
9149 if (rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
9151 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9152 errmsg("\"%s\" is not a foreign table",
9153 RelationGetRelationName(rel))));
9157 elog(ERROR, "unrecognized object type: %d", (int) stmttype);
9160 /* Can we change the schema of this tuple? */
9161 switch (rel->rd_rel->relkind)
9163 case RELKIND_RELATION:
9165 case RELKIND_FOREIGN_TABLE:
9166 /* ok to change schema */
9168 case RELKIND_SEQUENCE:
9170 /* if it's an owned sequence, disallow moving it by itself */
9174 if (sequenceIsOwned(relid, &tableId, &colId))
9176 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9177 errmsg("cannot move an owned sequence into another schema"),
9178 errdetail("Sequence \"%s\" is linked to table \"%s\".",
9179 RelationGetRelationName(rel),
9180 get_rel_name(tableId))));
9183 case RELKIND_COMPOSITE_TYPE:
9185 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9186 errmsg("\"%s\" is a composite type",
9187 RelationGetRelationName(rel)),
9188 errhint("Use ALTER TYPE instead.")));
9191 case RELKIND_TOASTVALUE:
9195 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9196 errmsg("\"%s\" is not a table, view, sequence, or foreign table",
9197 RelationGetRelationName(rel))));
9200 /* get schema OID and check its permissions */
9201 nspOid = LookupCreationNamespace(newschema);
9203 /* common checks on switching namespaces */
9204 CheckSetNamespace(oldNspOid, nspOid, RelationRelationId, relid);
9206 /* OK, modify the pg_class row and pg_depend entry */
9207 classRel = heap_open(RelationRelationId, RowExclusiveLock);
9209 AlterRelationNamespaceInternal(classRel, relid, oldNspOid, nspOid, true);
9211 /* Fix the table's row type too */
9212 AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid, false, false);
9214 /* Fix other dependent stuff */
9215 if (rel->rd_rel->relkind == RELKIND_RELATION)
9217 AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid);
9218 AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid, newschema, lockmode);
9219 AlterConstraintNamespaces(relid, oldNspOid, nspOid, false);
9222 heap_close(classRel, RowExclusiveLock);
9224 /* close rel, but keep lock until commit */
9225 relation_close(rel, NoLock);
9229 * The guts of relocating a relation to another namespace: fix the pg_class
9230 * entry, and the pg_depend entry if any. Caller must already have
9231 * opened and write-locked pg_class.
9234 AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
9235 Oid oldNspOid, Oid newNspOid,
9236 bool hasDependEntry)
9239 Form_pg_class classForm;
9241 classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
9242 if (!HeapTupleIsValid(classTup))
9243 elog(ERROR, "cache lookup failed for relation %u", relOid);
9244 classForm = (Form_pg_class) GETSTRUCT(classTup);
9246 Assert(classForm->relnamespace == oldNspOid);
9248 /* check for duplicate name (more friendly than unique-index failure) */
9249 if (get_relname_relid(NameStr(classForm->relname),
9250 newNspOid) != InvalidOid)
9252 (errcode(ERRCODE_DUPLICATE_TABLE),
9253 errmsg("relation \"%s\" already exists in schema \"%s\"",
9254 NameStr(classForm->relname),
9255 get_namespace_name(newNspOid))));
9257 /* classTup is a copy, so OK to scribble on */
9258 classForm->relnamespace = newNspOid;
9260 simple_heap_update(classRel, &classTup->t_self, classTup);
9261 CatalogUpdateIndexes(classRel, classTup);
9263 /* Update dependency on schema if caller said so */
9264 if (hasDependEntry &&
9265 changeDependencyFor(RelationRelationId, relOid,
9266 NamespaceRelationId, oldNspOid, newNspOid) != 1)
9267 elog(ERROR, "failed to change schema dependency for relation \"%s\"",
9268 NameStr(classForm->relname));
9270 heap_freetuple(classTup);
9274 * Move all indexes for the specified relation to another namespace.
9276 * Note: we assume adequate permission checking was done by the caller,
9277 * and that the caller has a suitable lock on the owning relation.
9280 AlterIndexNamespaces(Relation classRel, Relation rel,
9281 Oid oldNspOid, Oid newNspOid)
9286 indexList = RelationGetIndexList(rel);
9288 foreach(l, indexList)
9290 Oid indexOid = lfirst_oid(l);
9293 * Note: currently, the index will not have its own dependency on the
9294 * namespace, so we don't need to do changeDependencyFor(). There's no
9295 * row type in pg_type, either.
9297 AlterRelationNamespaceInternal(classRel, indexOid,
9298 oldNspOid, newNspOid,
9302 list_free(indexList);
9306 * Move all SERIAL-column sequences of the specified relation to another
9309 * Note: we assume adequate permission checking was done by the caller,
9310 * and that the caller has a suitable lock on the owning relation.
9313 AlterSeqNamespaces(Relation classRel, Relation rel,
9314 Oid oldNspOid, Oid newNspOid, const char *newNspName, LOCKMODE lockmode)
9322 * SERIAL sequences are those having an auto dependency on one of the
9323 * table's columns (we don't care *which* column, exactly).
9325 depRel = heap_open(DependRelationId, AccessShareLock);
9327 ScanKeyInit(&key[0],
9328 Anum_pg_depend_refclassid,
9329 BTEqualStrategyNumber, F_OIDEQ,
9330 ObjectIdGetDatum(RelationRelationId));
9331 ScanKeyInit(&key[1],
9332 Anum_pg_depend_refobjid,
9333 BTEqualStrategyNumber, F_OIDEQ,
9334 ObjectIdGetDatum(RelationGetRelid(rel)));
9335 /* we leave refobjsubid unspecified */
9337 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
9338 SnapshotNow, 2, key);
9340 while (HeapTupleIsValid(tup = systable_getnext(scan)))
9342 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
9345 /* skip dependencies other than auto dependencies on columns */
9346 if (depForm->refobjsubid == 0 ||
9347 depForm->classid != RelationRelationId ||
9348 depForm->objsubid != 0 ||
9349 depForm->deptype != DEPENDENCY_AUTO)
9352 /* Use relation_open just in case it's an index */
9353 seqRel = relation_open(depForm->objid, lockmode);
9355 /* skip non-sequence relations */
9356 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
9358 /* No need to keep the lock */
9359 relation_close(seqRel, lockmode);
9363 /* Fix the pg_class and pg_depend entries */
9364 AlterRelationNamespaceInternal(classRel, depForm->objid,
9365 oldNspOid, newNspOid,
9369 * Sequences have entries in pg_type. We need to be careful to move
9370 * them to the new namespace, too.
9372 AlterTypeNamespaceInternal(RelationGetForm(seqRel)->reltype,
9373 newNspOid, false, false);
9375 /* Now we can close it. Keep the lock till end of transaction. */
9376 relation_close(seqRel, NoLock);
9379 systable_endscan(scan);
9381 relation_close(depRel, AccessShareLock);
9386 * This code supports
9387 * CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
9389 * Because we only support this for TEMP tables, it's sufficient to remember
9390 * the state in a backend-local data structure.
9394 * Register a newly-created relation's ON COMMIT action.
9397 register_on_commit_action(Oid relid, OnCommitAction action)
9400 MemoryContext oldcxt;
9403 * We needn't bother registering the relation unless there is an ON COMMIT
9404 * action we need to take.
9406 if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
9409 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
9411 oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
9413 oc->oncommit = action;
9414 oc->creating_subid = GetCurrentSubTransactionId();
9415 oc->deleting_subid = InvalidSubTransactionId;
9417 on_commits = lcons(oc, on_commits);
9419 MemoryContextSwitchTo(oldcxt);
9423 * Unregister any ON COMMIT action when a relation is deleted.
9425 * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
9428 remove_on_commit_action(Oid relid)
9432 foreach(l, on_commits)
9434 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
9436 if (oc->relid == relid)
9438 oc->deleting_subid = GetCurrentSubTransactionId();
9445 * Perform ON COMMIT actions.
9447 * This is invoked just before actually committing, since it's possible
9448 * to encounter errors.
9451 PreCommit_on_commit_actions(void)
9454 List *oids_to_truncate = NIL;
9456 foreach(l, on_commits)
9458 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
9460 /* Ignore entry if already dropped in this xact */
9461 if (oc->deleting_subid != InvalidSubTransactionId)
9464 switch (oc->oncommit)
9467 case ONCOMMIT_PRESERVE_ROWS:
9468 /* Do nothing (there shouldn't be such entries, actually) */
9470 case ONCOMMIT_DELETE_ROWS:
9471 oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
9475 ObjectAddress object;
9477 object.classId = RelationRelationId;
9478 object.objectId = oc->relid;
9479 object.objectSubId = 0;
9480 performDeletion(&object, DROP_CASCADE);
9483 * Note that table deletion will call
9484 * remove_on_commit_action, so the entry should get marked
9487 Assert(oc->deleting_subid != InvalidSubTransactionId);
9492 if (oids_to_truncate != NIL)
9494 heap_truncate(oids_to_truncate);
9495 CommandCounterIncrement(); /* XXX needed? */
9500 * Post-commit or post-abort cleanup for ON COMMIT management.
9502 * All we do here is remove no-longer-needed OnCommitItem entries.
9504 * During commit, remove entries that were deleted during this transaction;
9505 * during abort, remove those created during this transaction.
9508 AtEOXact_on_commit_actions(bool isCommit)
9511 ListCell *prev_item;
9514 cur_item = list_head(on_commits);
9516 while (cur_item != NULL)
9518 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
9520 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
9521 oc->creating_subid != InvalidSubTransactionId)
9523 /* cur_item must be removed */
9524 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
9527 cur_item = lnext(prev_item);
9529 cur_item = list_head(on_commits);
9533 /* cur_item must be preserved */
9534 oc->creating_subid = InvalidSubTransactionId;
9535 oc->deleting_subid = InvalidSubTransactionId;
9536 prev_item = cur_item;
9537 cur_item = lnext(prev_item);
9543 * Post-subcommit or post-subabort cleanup for ON COMMIT management.
9545 * During subabort, we can immediately remove entries created during this
9546 * subtransaction. During subcommit, just relabel entries marked during
9547 * this subtransaction as being the parent's responsibility.
9550 AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
9551 SubTransactionId parentSubid)
9554 ListCell *prev_item;
9557 cur_item = list_head(on_commits);
9559 while (cur_item != NULL)
9561 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
9563 if (!isCommit && oc->creating_subid == mySubid)
9565 /* cur_item must be removed */
9566 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
9569 cur_item = lnext(prev_item);
9571 cur_item = list_head(on_commits);
9575 /* cur_item must be preserved */
9576 if (oc->creating_subid == mySubid)
9577 oc->creating_subid = parentSubid;
9578 if (oc->deleting_subid == mySubid)
9579 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
9580 prev_item = cur_item;
9581 cur_item = lnext(prev_item);