Force a checkpoint in CREATE DATABASE before starting to copy the files,
[PostgreSQL.git] / src / backend / commands / tablecmds.c
blobb039227c3c257bc5279a694a66bd4f3f7e74ec09
1 /*-------------------------------------------------------------------------
3 * tablecmds.c
4 * Commands for creating and altering table structures and settings
6 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * IDENTIFICATION
11 * $PostgreSQL$
13 *-------------------------------------------------------------------------
15 #include "postgres.h"
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/pg_constraint.h"
30 #include "catalog/pg_depend.h"
31 #include "catalog/pg_inherits.h"
32 #include "catalog/pg_namespace.h"
33 #include "catalog/pg_opclass.h"
34 #include "catalog/pg_tablespace.h"
35 #include "catalog/pg_trigger.h"
36 #include "catalog/pg_type.h"
37 #include "catalog/pg_type_fn.h"
38 #include "catalog/toasting.h"
39 #include "commands/cluster.h"
40 #include "commands/defrem.h"
41 #include "commands/sequence.h"
42 #include "commands/tablecmds.h"
43 #include "commands/tablespace.h"
44 #include "commands/trigger.h"
45 #include "commands/typecmds.h"
46 #include "executor/executor.h"
47 #include "miscadmin.h"
48 #include "nodes/makefuncs.h"
49 #include "nodes/nodeFuncs.h"
50 #include "nodes/parsenodes.h"
51 #include "optimizer/clauses.h"
52 #include "optimizer/plancat.h"
53 #include "optimizer/prep.h"
54 #include "parser/gramparse.h"
55 #include "parser/parse_clause.h"
56 #include "parser/parse_coerce.h"
57 #include "parser/parse_expr.h"
58 #include "parser/parse_oper.h"
59 #include "parser/parse_relation.h"
60 #include "parser/parse_type.h"
61 #include "parser/parse_utilcmd.h"
62 #include "parser/parser.h"
63 #include "rewrite/rewriteDefine.h"
64 #include "rewrite/rewriteHandler.h"
65 #include "storage/bufmgr.h"
66 #include "storage/lmgr.h"
67 #include "storage/smgr.h"
68 #include "utils/acl.h"
69 #include "utils/builtins.h"
70 #include "utils/fmgroids.h"
71 #include "utils/inval.h"
72 #include "utils/lsyscache.h"
73 #include "utils/memutils.h"
74 #include "utils/relcache.h"
75 #include "utils/snapmgr.h"
76 #include "utils/syscache.h"
77 #include "utils/tqual.h"
81 * ON COMMIT action list
83 typedef struct OnCommitItem
85 Oid relid; /* relid of relation */
86 OnCommitAction oncommit; /* what to do at end of xact */
89 * If this entry was created during the current transaction,
90 * creating_subid is the ID of the creating subxact; if created in a prior
91 * transaction, creating_subid is zero. If deleted during the current
92 * transaction, deleting_subid is the ID of the deleting subxact; if no
93 * deletion request is pending, deleting_subid is zero.
95 SubTransactionId creating_subid;
96 SubTransactionId deleting_subid;
97 } OnCommitItem;
99 static List *on_commits = NIL;
103 * State information for ALTER TABLE
105 * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
106 * structs, one for each table modified by the operation (the named table
107 * plus any child tables that are affected). We save lists of subcommands
108 * to apply to this table (possibly modified by parse transformation steps);
109 * these lists will be executed in Phase 2. If a Phase 3 step is needed,
110 * necessary information is stored in the constraints and newvals lists.
112 * Phase 2 is divided into multiple passes; subcommands are executed in
113 * a pass determined by subcommand type.
116 #define AT_PASS_DROP 0 /* DROP (all flavors) */
117 #define AT_PASS_ALTER_TYPE 1 /* ALTER COLUMN TYPE */
118 #define AT_PASS_OLD_INDEX 2 /* re-add existing indexes */
119 #define AT_PASS_OLD_CONSTR 3 /* re-add existing constraints */
120 #define AT_PASS_COL_ATTRS 4 /* set other column attributes */
121 /* We could support a RENAME COLUMN pass here, but not currently used */
122 #define AT_PASS_ADD_COL 5 /* ADD COLUMN */
123 #define AT_PASS_ADD_INDEX 6 /* ADD indexes */
124 #define AT_PASS_ADD_CONSTR 7 /* ADD constraints, defaults */
125 #define AT_PASS_MISC 8 /* other stuff */
126 #define AT_NUM_PASSES 9
128 typedef struct AlteredTableInfo
130 /* Information saved before any work commences: */
131 Oid relid; /* Relation to work on */
132 char relkind; /* Its relkind */
133 TupleDesc oldDesc; /* Pre-modification tuple descriptor */
134 /* Information saved by Phase 1 for Phase 2: */
135 List *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
136 /* Information saved by Phases 1/2 for Phase 3: */
137 List *constraints; /* List of NewConstraint */
138 List *newvals; /* List of NewColumnValue */
139 bool new_notnull; /* T if we added new NOT NULL constraints */
140 Oid newTableSpace; /* new tablespace; 0 means no change */
141 /* Objects to rebuild after completing ALTER TYPE operations */
142 List *changedConstraintOids; /* OIDs of constraints to rebuild */
143 List *changedConstraintDefs; /* string definitions of same */
144 List *changedIndexOids; /* OIDs of indexes to rebuild */
145 List *changedIndexDefs; /* string definitions of same */
146 } AlteredTableInfo;
148 /* Struct describing one new constraint to check in Phase 3 scan */
149 /* Note: new NOT NULL constraints are handled elsewhere */
150 typedef struct NewConstraint
152 char *name; /* Constraint name, or NULL if none */
153 ConstrType contype; /* CHECK or FOREIGN */
154 Oid refrelid; /* PK rel, if FOREIGN */
155 Oid conid; /* OID of pg_constraint entry, if FOREIGN */
156 Node *qual; /* Check expr or FkConstraint struct */
157 List *qualstate; /* Execution state for CHECK */
158 } NewConstraint;
161 * Struct describing one new column value that needs to be computed during
162 * Phase 3 copy (this could be either a new column with a non-null default, or
163 * a column that we're changing the type of). Columns without such an entry
164 * are just copied from the old table during ATRewriteTable. Note that the
165 * expr is an expression over *old* table values.
167 typedef struct NewColumnValue
169 AttrNumber attnum; /* which column */
170 Expr *expr; /* expression to compute */
171 ExprState *exprstate; /* execution state */
172 } NewColumnValue;
175 * Error-reporting support for RemoveRelations
177 struct dropmsgstrings
179 char kind;
180 int nonexistent_code;
181 const char *nonexistent_msg;
182 const char *skipping_msg;
183 const char *nota_msg;
184 const char *drophint_msg;
187 static const struct dropmsgstrings dropmsgstringarray[] = {
188 {RELKIND_RELATION,
189 ERRCODE_UNDEFINED_TABLE,
190 gettext_noop("table \"%s\" does not exist"),
191 gettext_noop("table \"%s\" does not exist, skipping"),
192 gettext_noop("\"%s\" is not a table"),
193 gettext_noop("Use DROP TABLE to remove a table.")},
194 {RELKIND_SEQUENCE,
195 ERRCODE_UNDEFINED_TABLE,
196 gettext_noop("sequence \"%s\" does not exist"),
197 gettext_noop("sequence \"%s\" does not exist, skipping"),
198 gettext_noop("\"%s\" is not a sequence"),
199 gettext_noop("Use DROP SEQUENCE to remove a sequence.")},
200 {RELKIND_VIEW,
201 ERRCODE_UNDEFINED_TABLE,
202 gettext_noop("view \"%s\" does not exist"),
203 gettext_noop("view \"%s\" does not exist, skipping"),
204 gettext_noop("\"%s\" is not a view"),
205 gettext_noop("Use DROP VIEW to remove a view.")},
206 {RELKIND_INDEX,
207 ERRCODE_UNDEFINED_OBJECT,
208 gettext_noop("index \"%s\" does not exist"),
209 gettext_noop("index \"%s\" does not exist, skipping"),
210 gettext_noop("\"%s\" is not an index"),
211 gettext_noop("Use DROP INDEX to remove an index.")},
212 {RELKIND_COMPOSITE_TYPE,
213 ERRCODE_UNDEFINED_OBJECT,
214 gettext_noop("type \"%s\" does not exist"),
215 gettext_noop("type \"%s\" does not exist, skipping"),
216 gettext_noop("\"%s\" is not a type"),
217 gettext_noop("Use DROP TYPE to remove a type.")},
218 {'\0', 0, NULL, NULL, NULL, NULL}
222 static void truncate_check_rel(Relation rel);
223 static List *MergeAttributes(List *schema, List *supers, bool istemp,
224 List **supOids, List **supconstr, int *supOidCount);
225 static bool MergeCheckConstraint(List *constraints, char *name, Node *expr);
226 static bool change_varattnos_walker(Node *node, const AttrNumber *newattno);
227 static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel);
228 static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
229 static void StoreCatalogInheritance(Oid relationId, List *supers);
230 static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
231 int16 seqNumber, Relation inhRelation);
232 static int findAttrByName(const char *attributeName, List *schema);
233 static void setRelhassubclassInRelation(Oid relationId, bool relhassubclass);
234 static void AlterIndexNamespaces(Relation classRel, Relation rel,
235 Oid oldNspOid, Oid newNspOid);
236 static void AlterSeqNamespaces(Relation classRel, Relation rel,
237 Oid oldNspOid, Oid newNspOid,
238 const char *newNspName);
239 static int transformColumnNameList(Oid relId, List *colList,
240 int16 *attnums, Oid *atttypids);
241 static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
242 List **attnamelist,
243 int16 *attnums, Oid *atttypids,
244 Oid *opclasses);
245 static Oid transformFkeyCheckAttrs(Relation pkrel,
246 int numattrs, int16 *attnums,
247 Oid *opclasses);
248 static void validateForeignKeyConstraint(FkConstraint *fkconstraint,
249 Relation rel, Relation pkrel, Oid constraintOid);
250 static void createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
251 Oid constraintOid);
252 static void ATController(Relation rel, List *cmds, bool recurse);
253 static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
254 bool recurse, bool recursing);
255 static void ATRewriteCatalogs(List **wqueue);
256 static void ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
257 AlterTableCmd *cmd);
258 static void ATRewriteTables(List **wqueue);
259 static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap);
260 static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
261 static void ATSimplePermissions(Relation rel, bool allowView);
262 static void ATSimplePermissionsRelationOrIndex(Relation rel);
263 static void ATSimpleRecursion(List **wqueue, Relation rel,
264 AlterTableCmd *cmd, bool recurse);
265 static void ATOneLevelRecursion(List **wqueue, Relation rel,
266 AlterTableCmd *cmd);
267 static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
268 AlterTableCmd *cmd);
269 static void ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
270 ColumnDef *colDef);
271 static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
272 static void ATExecDropNotNull(Relation rel, const char *colName);
273 static void ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
274 const char *colName);
275 static void ATExecColumnDefault(Relation rel, const char *colName,
276 Node *newDefault);
277 static void ATPrepSetStatistics(Relation rel, const char *colName,
278 Node *flagValue);
279 static void ATExecSetStatistics(Relation rel, const char *colName,
280 Node *newValue);
281 static void ATExecSetStorage(Relation rel, const char *colName,
282 Node *newValue);
283 static void ATExecDropColumn(Relation rel, const char *colName,
284 DropBehavior behavior,
285 bool recurse, bool recursing);
286 static void ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
287 IndexStmt *stmt, bool is_rebuild);
288 static void ATExecAddConstraint(List **wqueue,
289 AlteredTableInfo *tab, Relation rel,
290 Node *newConstraint, bool recurse);
291 static void ATAddCheckConstraint(List **wqueue,
292 AlteredTableInfo *tab, Relation rel,
293 Constraint *constr,
294 bool recurse, bool recursing);
295 static void ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
296 FkConstraint *fkconstraint);
297 static void ATExecDropConstraint(Relation rel, const char *constrName,
298 DropBehavior behavior,
299 bool recurse, bool recursing);
300 static void ATPrepAlterColumnType(List **wqueue,
301 AlteredTableInfo *tab, Relation rel,
302 bool recurse, bool recursing,
303 AlterTableCmd *cmd);
304 static void ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
305 const char *colName, TypeName *typename);
306 static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab);
307 static void ATPostAlterTypeParse(char *cmd, List **wqueue);
308 static void change_owner_recurse_to_sequences(Oid relationOid,
309 Oid newOwnerId);
310 static void ATExecClusterOn(Relation rel, const char *indexName);
311 static void ATExecDropCluster(Relation rel);
312 static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
313 char *tablespacename);
314 static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace);
315 static void ATExecSetRelOptions(Relation rel, List *defList, bool isReset);
316 static void ATExecEnableDisableTrigger(Relation rel, char *trigname,
317 char fires_when, bool skip_system);
318 static void ATExecEnableDisableRule(Relation rel, char *rulename,
319 char fires_when);
320 static void ATExecAddInherit(Relation rel, RangeVar *parent);
321 static void ATExecDropInherit(Relation rel, RangeVar *parent);
322 static void copy_relation_data(SMgrRelation rel, SMgrRelation dst,
323 ForkNumber forkNum, bool istemp);
326 /* ----------------------------------------------------------------
327 * DefineRelation
328 * Creates a new relation.
330 * If successful, returns the OID of the new relation.
331 * ----------------------------------------------------------------
334 DefineRelation(CreateStmt *stmt, char relkind)
336 char relname[NAMEDATALEN];
337 Oid namespaceId;
338 List *schema = stmt->tableElts;
339 Oid relationId;
340 Oid tablespaceId;
341 Relation rel;
342 TupleDesc descriptor;
343 List *inheritOids;
344 List *old_constraints;
345 bool localHasOids;
346 int parentOidCount;
347 List *rawDefaults;
348 List *cookedDefaults;
349 Datum reloptions;
350 ListCell *listptr;
351 AttrNumber attnum;
354 * Truncate relname to appropriate length (probably a waste of time, as
355 * parser should have done this already).
357 StrNCpy(relname, stmt->relation->relname, NAMEDATALEN);
360 * Check consistency of arguments
362 if (stmt->oncommit != ONCOMMIT_NOOP && !stmt->relation->istemp)
363 ereport(ERROR,
364 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
365 errmsg("ON COMMIT can only be used on temporary tables")));
368 * Look up the namespace in which we are supposed to create the relation.
369 * Check we have permission to create there. Skip check if bootstrapping,
370 * since permissions machinery may not be working yet.
372 namespaceId = RangeVarGetCreationNamespace(stmt->relation);
374 if (!IsBootstrapProcessingMode())
376 AclResult aclresult;
378 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
379 ACL_CREATE);
380 if (aclresult != ACLCHECK_OK)
381 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
382 get_namespace_name(namespaceId));
386 * Select tablespace to use. If not specified, use default tablespace
387 * (which may in turn default to database's default).
389 if (stmt->tablespacename)
391 tablespaceId = get_tablespace_oid(stmt->tablespacename);
392 if (!OidIsValid(tablespaceId))
393 ereport(ERROR,
394 (errcode(ERRCODE_UNDEFINED_OBJECT),
395 errmsg("tablespace \"%s\" does not exist",
396 stmt->tablespacename)));
398 else
400 tablespaceId = GetDefaultTablespace(stmt->relation->istemp);
401 /* note InvalidOid is OK in this case */
404 /* Check permissions except when using database's default */
405 if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
407 AclResult aclresult;
409 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
410 ACL_CREATE);
411 if (aclresult != ACLCHECK_OK)
412 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
413 get_tablespace_name(tablespaceId));
417 * Parse and validate reloptions, if any.
419 reloptions = transformRelOptions((Datum) 0, stmt->options, true, false);
421 (void) heap_reloptions(relkind, reloptions, true);
424 * Look up inheritance ancestors and generate relation schema, including
425 * inherited attributes.
427 schema = MergeAttributes(schema, stmt->inhRelations,
428 stmt->relation->istemp,
429 &inheritOids, &old_constraints, &parentOidCount);
432 * Create a tuple descriptor from the relation schema. Note that this
433 * deals with column names, types, and NOT NULL constraints, but not
434 * default values or CHECK constraints; we handle those below.
436 descriptor = BuildDescForRelation(schema);
438 localHasOids = interpretOidsOption(stmt->options);
439 descriptor->tdhasoid = (localHasOids || parentOidCount > 0);
442 * Find columns with default values and prepare for insertion of the
443 * defaults. Pre-cooked (that is, inherited) defaults go into a list of
444 * CookedConstraint structs that we'll pass to heap_create_with_catalog,
445 * while raw defaults go into a list of RawColumnDefault structs that
446 * will be processed by AddRelationNewConstraints. (We can't deal with
447 * raw expressions until we can do transformExpr.)
449 * We can set the atthasdef flags now in the tuple descriptor; this just
450 * saves StoreAttrDefault from having to do an immediate update of the
451 * pg_attribute rows.
453 rawDefaults = NIL;
454 cookedDefaults = NIL;
455 attnum = 0;
457 foreach(listptr, schema)
459 ColumnDef *colDef = lfirst(listptr);
461 attnum++;
463 if (colDef->raw_default != NULL)
465 RawColumnDefault *rawEnt;
467 Assert(colDef->cooked_default == NULL);
469 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
470 rawEnt->attnum = attnum;
471 rawEnt->raw_default = colDef->raw_default;
472 rawDefaults = lappend(rawDefaults, rawEnt);
473 descriptor->attrs[attnum - 1]->atthasdef = true;
475 else if (colDef->cooked_default != NULL)
477 CookedConstraint *cooked;
479 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
480 cooked->contype = CONSTR_DEFAULT;
481 cooked->name = NULL;
482 cooked->attnum = attnum;
483 cooked->expr = stringToNode(colDef->cooked_default);
484 cooked->is_local = true; /* not used for defaults */
485 cooked->inhcount = 0; /* ditto */
486 cookedDefaults = lappend(cookedDefaults, cooked);
487 descriptor->attrs[attnum - 1]->atthasdef = true;
492 * Create the relation. Inherited defaults and constraints are passed
493 * in for immediate handling --- since they don't need parsing, they
494 * can be stored immediately.
496 relationId = heap_create_with_catalog(relname,
497 namespaceId,
498 tablespaceId,
499 InvalidOid,
500 GetUserId(),
501 descriptor,
502 list_concat(cookedDefaults,
503 old_constraints),
504 relkind,
505 false,
506 localHasOids,
507 parentOidCount,
508 stmt->oncommit,
509 reloptions,
510 allowSystemTableMods);
512 StoreCatalogInheritance(relationId, inheritOids);
515 * We must bump the command counter to make the newly-created relation
516 * tuple visible for opening.
518 CommandCounterIncrement();
521 * Open the new relation and acquire exclusive lock on it. This isn't
522 * really necessary for locking out other backends (since they can't see
523 * the new rel anyway until we commit), but it keeps the lock manager from
524 * complaining about deadlock risks.
526 rel = relation_open(relationId, AccessExclusiveLock);
529 * Now add any newly specified column default values and CHECK constraints
530 * to the new relation. These are passed to us in the form of raw
531 * parsetrees; we need to transform them to executable expression trees
532 * before they can be added. The most convenient way to do that is to
533 * apply the parser's transformExpr routine, but transformExpr doesn't
534 * work unless we have a pre-existing relation. So, the transformation has
535 * to be postponed to this final step of CREATE TABLE.
537 if (rawDefaults || stmt->constraints)
538 AddRelationNewConstraints(rel, rawDefaults, stmt->constraints,
539 true, true);
542 * Clean up. We keep lock on new relation (although it shouldn't be
543 * visible to anyone else anyway, until commit).
545 relation_close(rel, NoLock);
547 return relationId;
551 * Emit the right error or warning message for a "DROP" command issued on a
552 * non-existent relation
554 static void
555 DropErrorMsgNonExistent(const char *relname, char rightkind, bool missing_ok)
557 const struct dropmsgstrings *rentry;
559 for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
561 if (rentry->kind == rightkind)
563 if (!missing_ok)
565 ereport(ERROR,
566 (errcode(rentry->nonexistent_code),
567 errmsg(rentry->nonexistent_msg, relname)));
569 else
571 ereport(NOTICE, (errmsg(rentry->skipping_msg, relname)));
572 break;
577 Assert(rentry->kind != '\0'); /* Should be impossible */
581 * Emit the right error message for a "DROP" command issued on a
582 * relation of the wrong type
584 static void
585 DropErrorMsgWrongType(const char *relname, char wrongkind, char rightkind)
587 const struct dropmsgstrings *rentry;
588 const struct dropmsgstrings *wentry;
590 for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
591 if (rentry->kind == rightkind)
592 break;
593 Assert(rentry->kind != '\0');
595 for (wentry = dropmsgstringarray; wentry->kind != '\0'; wentry++)
596 if (wentry->kind == wrongkind)
597 break;
598 /* wrongkind could be something we don't have in our table... */
600 ereport(ERROR,
601 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
602 errmsg(rentry->nota_msg, relname),
603 (wentry->kind != '\0') ? errhint(wentry->drophint_msg) : 0));
607 * RemoveRelations
608 * Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW
610 void
611 RemoveRelations(DropStmt *drop)
613 ObjectAddresses *objects;
614 char relkind;
615 ListCell *cell;
618 * First we identify all the relations, then we delete them in a single
619 * performMultipleDeletions() call. This is to avoid unwanted
620 * DROP RESTRICT errors if one of the relations depends on another.
623 /* Determine required relkind */
624 switch (drop->removeType)
626 case OBJECT_TABLE:
627 relkind = RELKIND_RELATION;
628 break;
630 case OBJECT_INDEX:
631 relkind = RELKIND_INDEX;
632 break;
634 case OBJECT_SEQUENCE:
635 relkind = RELKIND_SEQUENCE;
636 break;
638 case OBJECT_VIEW:
639 relkind = RELKIND_VIEW;
640 break;
642 default:
643 elog(ERROR, "unrecognized drop object type: %d",
644 (int) drop->removeType);
645 relkind = 0; /* keep compiler quiet */
646 break;
649 /* Lock and validate each relation; build a list of object addresses */
650 objects = new_object_addresses();
652 foreach(cell, drop->objects)
654 RangeVar *rel = makeRangeVarFromNameList((List *) lfirst(cell));
655 Oid relOid;
656 HeapTuple tuple;
657 Form_pg_class classform;
658 ObjectAddress obj;
661 * These next few steps are a great deal like relation_openrv, but we
662 * don't bother building a relcache entry since we don't need it.
664 * Check for shared-cache-inval messages before trying to access the
665 * relation. This is needed to cover the case where the name
666 * identifies a rel that has been dropped and recreated since the
667 * start of our transaction: if we don't flush the old syscache entry,
668 * then we'll latch onto that entry and suffer an error later.
670 AcceptInvalidationMessages();
672 /* Look up the appropriate relation using namespace search */
673 relOid = RangeVarGetRelid(rel, true);
675 /* Not there? */
676 if (!OidIsValid(relOid))
678 DropErrorMsgNonExistent(rel->relname, relkind, drop->missing_ok);
679 continue;
683 * In DROP INDEX, attempt to acquire lock on the parent table before
684 * locking the index. index_drop() will need this anyway, and since
685 * regular queries lock tables before their indexes, we risk deadlock
686 * if we do it the other way around. No error if we don't find a
687 * pg_index entry, though --- that most likely means it isn't an
688 * index, and we'll fail below.
690 if (relkind == RELKIND_INDEX)
692 tuple = SearchSysCache(INDEXRELID,
693 ObjectIdGetDatum(relOid),
694 0, 0, 0);
695 if (HeapTupleIsValid(tuple))
697 Form_pg_index index = (Form_pg_index) GETSTRUCT(tuple);
699 LockRelationOid(index->indrelid, AccessExclusiveLock);
700 ReleaseSysCache(tuple);
704 /* Get the lock before trying to fetch the syscache entry */
705 LockRelationOid(relOid, AccessExclusiveLock);
707 tuple = SearchSysCache(RELOID,
708 ObjectIdGetDatum(relOid),
709 0, 0, 0);
710 if (!HeapTupleIsValid(tuple))
711 elog(ERROR, "cache lookup failed for relation %u", relOid);
712 classform = (Form_pg_class) GETSTRUCT(tuple);
714 if (classform->relkind != relkind)
715 DropErrorMsgWrongType(rel->relname, classform->relkind, relkind);
717 /* Allow DROP to either table owner or schema owner */
718 if (!pg_class_ownercheck(relOid, GetUserId()) &&
719 !pg_namespace_ownercheck(classform->relnamespace, GetUserId()))
720 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
721 rel->relname);
723 if (!allowSystemTableMods && IsSystemClass(classform))
724 ereport(ERROR,
725 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
726 errmsg("permission denied: \"%s\" is a system catalog",
727 rel->relname)));
729 /* OK, we're ready to delete this one */
730 obj.classId = RelationRelationId;
731 obj.objectId = relOid;
732 obj.objectSubId = 0;
734 add_exact_object_address(&obj, objects);
736 ReleaseSysCache(tuple);
739 performMultipleDeletions(objects, drop->behavior);
741 free_object_addresses(objects);
745 * ExecuteTruncate
746 * Executes a TRUNCATE command.
748 * This is a multi-relation truncate. We first open and grab exclusive
749 * lock on all relations involved, checking permissions and otherwise
750 * verifying that the relation is OK for truncation. In CASCADE mode,
751 * relations having FK references to the targeted relations are automatically
752 * added to the group; in RESTRICT mode, we check that all FK references are
753 * internal to the group that's being truncated. Finally all the relations
754 * are truncated and reindexed.
756 void
757 ExecuteTruncate(TruncateStmt *stmt)
759 List *rels = NIL;
760 List *relids = NIL;
761 List *seq_relids = NIL;
762 EState *estate;
763 ResultRelInfo *resultRelInfos;
764 ResultRelInfo *resultRelInfo;
765 ListCell *cell;
768 * Open, exclusive-lock, and check all the explicitly-specified relations
770 foreach(cell, stmt->relations)
772 RangeVar *rv = lfirst(cell);
773 Relation rel;
775 rel = heap_openrv(rv, AccessExclusiveLock);
776 /* don't throw error for "TRUNCATE foo, foo" */
777 if (list_member_oid(relids, RelationGetRelid(rel)))
779 heap_close(rel, AccessExclusiveLock);
780 continue;
782 truncate_check_rel(rel);
783 rels = lappend(rels, rel);
784 relids = lappend_oid(relids, RelationGetRelid(rel));
788 * In CASCADE mode, suck in all referencing relations as well. This
789 * requires multiple iterations to find indirectly-dependent relations. At
790 * each phase, we need to exclusive-lock new rels before looking for their
791 * dependencies, else we might miss something. Also, we check each rel as
792 * soon as we open it, to avoid a faux pas such as holding lock for a long
793 * time on a rel we have no permissions for.
795 if (stmt->behavior == DROP_CASCADE)
797 for (;;)
799 List *newrelids;
801 newrelids = heap_truncate_find_FKs(relids);
802 if (newrelids == NIL)
803 break; /* nothing else to add */
805 foreach(cell, newrelids)
807 Oid relid = lfirst_oid(cell);
808 Relation rel;
810 rel = heap_open(relid, AccessExclusiveLock);
811 ereport(NOTICE,
812 (errmsg("truncate cascades to table \"%s\"",
813 RelationGetRelationName(rel))));
814 truncate_check_rel(rel);
815 rels = lappend(rels, rel);
816 relids = lappend_oid(relids, relid);
822 * Check foreign key references. In CASCADE mode, this should be
823 * unnecessary since we just pulled in all the references; but as a
824 * cross-check, do it anyway if in an Assert-enabled build.
826 #ifdef USE_ASSERT_CHECKING
827 heap_truncate_check_FKs(rels, false);
828 #else
829 if (stmt->behavior == DROP_RESTRICT)
830 heap_truncate_check_FKs(rels, false);
831 #endif
834 * If we are asked to restart sequences, find all the sequences,
835 * lock them (we only need AccessShareLock because that's all that
836 * ALTER SEQUENCE takes), and check permissions. We want to do this
837 * early since it's pointless to do all the truncation work only to fail
838 * on sequence permissions.
840 if (stmt->restart_seqs)
842 foreach(cell, rels)
844 Relation rel = (Relation) lfirst(cell);
845 List *seqlist = getOwnedSequences(RelationGetRelid(rel));
846 ListCell *seqcell;
848 foreach(seqcell, seqlist)
850 Oid seq_relid = lfirst_oid(seqcell);
851 Relation seq_rel;
853 seq_rel = relation_open(seq_relid, AccessShareLock);
855 /* This check must match AlterSequence! */
856 if (!pg_class_ownercheck(seq_relid, GetUserId()))
857 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
858 RelationGetRelationName(seq_rel));
860 seq_relids = lappend_oid(seq_relids, seq_relid);
862 relation_close(seq_rel, NoLock);
867 /* Prepare to catch AFTER triggers. */
868 AfterTriggerBeginQuery();
871 * To fire triggers, we'll need an EState as well as a ResultRelInfo
872 * for each relation.
874 estate = CreateExecutorState();
875 resultRelInfos = (ResultRelInfo *)
876 palloc(list_length(rels) * sizeof(ResultRelInfo));
877 resultRelInfo = resultRelInfos;
878 foreach(cell, rels)
880 Relation rel = (Relation) lfirst(cell);
882 InitResultRelInfo(resultRelInfo,
883 rel,
884 0, /* dummy rangetable index */
885 CMD_DELETE, /* don't need any index info */
886 false);
887 resultRelInfo++;
889 estate->es_result_relations = resultRelInfos;
890 estate->es_num_result_relations = list_length(rels);
893 * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
894 * truncating (this is because one of them might throw an error).
895 * Also, if we were to allow them to prevent statement execution,
896 * that would need to be handled here.
898 resultRelInfo = resultRelInfos;
899 foreach(cell, rels)
901 estate->es_result_relation_info = resultRelInfo;
902 ExecBSTruncateTriggers(estate, resultRelInfo);
903 resultRelInfo++;
907 * OK, truncate each table.
909 foreach(cell, rels)
911 Relation rel = (Relation) lfirst(cell);
912 Oid heap_relid;
913 Oid toast_relid;
916 * Create a new empty storage file for the relation, and assign it as
917 * the relfilenode value. The old storage file is scheduled for
918 * deletion at commit.
920 setNewRelfilenode(rel, RecentXmin);
922 heap_relid = RelationGetRelid(rel);
923 toast_relid = rel->rd_rel->reltoastrelid;
926 * The same for the toast table, if any.
928 if (OidIsValid(toast_relid))
930 rel = relation_open(toast_relid, AccessExclusiveLock);
931 setNewRelfilenode(rel, RecentXmin);
932 heap_close(rel, NoLock);
936 * Reconstruct the indexes to match, and we're done.
938 reindex_relation(heap_relid, true);
942 * Process all AFTER STATEMENT TRUNCATE triggers.
944 resultRelInfo = resultRelInfos;
945 foreach(cell, rels)
947 estate->es_result_relation_info = resultRelInfo;
948 ExecASTruncateTriggers(estate, resultRelInfo);
949 resultRelInfo++;
952 /* Handle queued AFTER triggers */
953 AfterTriggerEndQuery(estate);
955 /* We can clean up the EState now */
956 FreeExecutorState(estate);
958 /* And close the rels (can't do this while EState still holds refs) */
959 foreach(cell, rels)
961 Relation rel = (Relation) lfirst(cell);
963 heap_close(rel, NoLock);
967 * Lastly, restart any owned sequences if we were asked to. This is done
968 * last because it's nontransactional: restarts will not roll back if
969 * we abort later. Hence it's important to postpone them as long as
970 * possible. (This is also a big reason why we locked and
971 * permission-checked the sequences beforehand.)
973 if (stmt->restart_seqs)
975 List *options = list_make1(makeDefElem("restart", NULL));
977 foreach(cell, seq_relids)
979 Oid seq_relid = lfirst_oid(cell);
981 AlterSequenceInternal(seq_relid, options);
987 * Check that a given rel is safe to truncate. Subroutine for ExecuteTruncate
989 static void
990 truncate_check_rel(Relation rel)
992 AclResult aclresult;
994 /* Only allow truncate on regular tables */
995 if (rel->rd_rel->relkind != RELKIND_RELATION)
996 ereport(ERROR,
997 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
998 errmsg("\"%s\" is not a table",
999 RelationGetRelationName(rel))));
1001 /* Permissions checks */
1002 aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
1003 ACL_TRUNCATE);
1004 if (aclresult != ACLCHECK_OK)
1005 aclcheck_error(aclresult, ACL_KIND_CLASS,
1006 RelationGetRelationName(rel));
1008 if (!allowSystemTableMods && IsSystemRelation(rel))
1009 ereport(ERROR,
1010 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1011 errmsg("permission denied: \"%s\" is a system catalog",
1012 RelationGetRelationName(rel))));
1015 * We can never allow truncation of shared or nailed-in-cache relations,
1016 * because we can't support changing their relfilenode values.
1018 if (rel->rd_rel->relisshared || rel->rd_isnailed)
1019 ereport(ERROR,
1020 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1021 errmsg("cannot truncate system relation \"%s\"",
1022 RelationGetRelationName(rel))));
1025 * Don't allow truncate on temp tables of other backends ... their local
1026 * buffer manager is not going to cope.
1028 if (isOtherTempNamespace(RelationGetNamespace(rel)))
1029 ereport(ERROR,
1030 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1031 errmsg("cannot truncate temporary tables of other sessions")));
1034 * Also check for active uses of the relation in the current transaction,
1035 * including open scans and pending AFTER trigger events.
1037 CheckTableNotInUse(rel, "TRUNCATE");
1040 /*----------
1041 * MergeAttributes
1042 * Returns new schema given initial schema and superclasses.
1044 * Input arguments:
1045 * 'schema' is the column/attribute definition for the table. (It's a list
1046 * of ColumnDef's.) It is destructively changed.
1047 * 'supers' is a list of names (as RangeVar nodes) of parent relations.
1048 * 'istemp' is TRUE if we are creating a temp relation.
1050 * Output arguments:
1051 * 'supOids' receives a list of the OIDs of the parent relations.
1052 * 'supconstr' receives a list of constraints belonging to the parents,
1053 * updated as necessary to be valid for the child.
1054 * 'supOidCount' is set to the number of parents that have OID columns.
1056 * Return value:
1057 * Completed schema list.
1059 * Notes:
1060 * The order in which the attributes are inherited is very important.
1061 * Intuitively, the inherited attributes should come first. If a table
1062 * inherits from multiple parents, the order of those attributes are
1063 * according to the order of the parents specified in CREATE TABLE.
1065 * Here's an example:
1067 * create table person (name text, age int4, location point);
1068 * create table emp (salary int4, manager text) inherits(person);
1069 * create table student (gpa float8) inherits (person);
1070 * create table stud_emp (percent int4) inherits (emp, student);
1072 * The order of the attributes of stud_emp is:
1074 * person {1:name, 2:age, 3:location}
1075 * / \
1076 * {6:gpa} student emp {4:salary, 5:manager}
1077 * \ /
1078 * stud_emp {7:percent}
1080 * If the same attribute name appears multiple times, then it appears
1081 * in the result table in the proper location for its first appearance.
1083 * Constraints (including NOT NULL constraints) for the child table
1084 * are the union of all relevant constraints, from both the child schema
1085 * and parent tables.
1087 * The default value for a child column is defined as:
1088 * (1) If the child schema specifies a default, that value is used.
1089 * (2) If neither the child nor any parent specifies a default, then
1090 * the column will not have a default.
1091 * (3) If conflicting defaults are inherited from different parents
1092 * (and not overridden by the child), an error is raised.
1093 * (4) Otherwise the inherited default is used.
1094 * Rule (3) is new in Postgres 7.1; in earlier releases you got a
1095 * rather arbitrary choice of which parent default to use.
1096 *----------
1098 static List *
1099 MergeAttributes(List *schema, List *supers, bool istemp,
1100 List **supOids, List **supconstr, int *supOidCount)
1102 ListCell *entry;
1103 List *inhSchema = NIL;
1104 List *parentOids = NIL;
1105 List *constraints = NIL;
1106 int parentsWithOids = 0;
1107 bool have_bogus_defaults = false;
1108 char *bogus_marker = "Bogus!"; /* marks conflicting defaults */
1109 int child_attno;
1112 * Check for and reject tables with too many columns. We perform this
1113 * check relatively early for two reasons: (a) we don't run the risk of
1114 * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
1115 * okay if we're processing <= 1600 columns, but could take minutes to
1116 * execute if the user attempts to create a table with hundreds of
1117 * thousands of columns.
1119 * Note that we also need to check that any we do not exceed this figure
1120 * after including columns from inherited relations.
1122 if (list_length(schema) > MaxHeapAttributeNumber)
1123 ereport(ERROR,
1124 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1125 errmsg("tables can have at most %d columns",
1126 MaxHeapAttributeNumber)));
1129 * Check for duplicate names in the explicit list of attributes.
1131 * Although we might consider merging such entries in the same way that we
1132 * handle name conflicts for inherited attributes, it seems to make more
1133 * sense to assume such conflicts are errors.
1135 foreach(entry, schema)
1137 ColumnDef *coldef = lfirst(entry);
1138 ListCell *rest;
1140 for_each_cell(rest, lnext(entry))
1142 ColumnDef *restdef = lfirst(rest);
1144 if (strcmp(coldef->colname, restdef->colname) == 0)
1145 ereport(ERROR,
1146 (errcode(ERRCODE_DUPLICATE_COLUMN),
1147 errmsg("column \"%s\" specified more than once",
1148 coldef->colname)));
1153 * Scan the parents left-to-right, and merge their attributes to form a
1154 * list of inherited attributes (inhSchema). Also check to see if we need
1155 * to inherit an OID column.
1157 child_attno = 0;
1158 foreach(entry, supers)
1160 RangeVar *parent = (RangeVar *) lfirst(entry);
1161 Relation relation;
1162 TupleDesc tupleDesc;
1163 TupleConstr *constr;
1164 AttrNumber *newattno;
1165 AttrNumber parent_attno;
1167 relation = heap_openrv(parent, AccessShareLock);
1169 if (relation->rd_rel->relkind != RELKIND_RELATION)
1170 ereport(ERROR,
1171 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1172 errmsg("inherited relation \"%s\" is not a table",
1173 parent->relname)));
1174 /* Permanent rels cannot inherit from temporary ones */
1175 if (!istemp && isTempNamespace(RelationGetNamespace(relation)))
1176 ereport(ERROR,
1177 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1178 errmsg("cannot inherit from temporary relation \"%s\"",
1179 parent->relname)));
1182 * We should have an UNDER permission flag for this, but for now,
1183 * demand that creator of a child table own the parent.
1185 if (!pg_class_ownercheck(RelationGetRelid(relation), GetUserId()))
1186 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1187 RelationGetRelationName(relation));
1190 * Reject duplications in the list of parents.
1192 if (list_member_oid(parentOids, RelationGetRelid(relation)))
1193 ereport(ERROR,
1194 (errcode(ERRCODE_DUPLICATE_TABLE),
1195 errmsg("relation \"%s\" would be inherited from more than once",
1196 parent->relname)));
1198 parentOids = lappend_oid(parentOids, RelationGetRelid(relation));
1200 if (relation->rd_rel->relhasoids)
1201 parentsWithOids++;
1203 tupleDesc = RelationGetDescr(relation);
1204 constr = tupleDesc->constr;
1207 * newattno[] will contain the child-table attribute numbers for the
1208 * attributes of this parent table. (They are not the same for
1209 * parents after the first one, nor if we have dropped columns.)
1211 newattno = (AttrNumber *)
1212 palloc(tupleDesc->natts * sizeof(AttrNumber));
1214 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1215 parent_attno++)
1217 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
1218 char *attributeName = NameStr(attribute->attname);
1219 int exist_attno;
1220 ColumnDef *def;
1223 * Ignore dropped columns in the parent.
1225 if (attribute->attisdropped)
1228 * change_varattnos_of_a_node asserts that this is greater
1229 * than zero, so if anything tries to use it, we should find
1230 * out.
1232 newattno[parent_attno - 1] = 0;
1233 continue;
1237 * Does it conflict with some previously inherited column?
1239 exist_attno = findAttrByName(attributeName, inhSchema);
1240 if (exist_attno > 0)
1242 Oid defTypeId;
1243 int32 deftypmod;
1246 * Yes, try to merge the two column definitions. They must
1247 * have the same type and typmod.
1249 ereport(NOTICE,
1250 (errmsg("merging multiple inherited definitions of column \"%s\"",
1251 attributeName)));
1252 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1253 defTypeId = typenameTypeId(NULL, def->typename, &deftypmod);
1254 if (defTypeId != attribute->atttypid ||
1255 deftypmod != attribute->atttypmod)
1256 ereport(ERROR,
1257 (errcode(ERRCODE_DATATYPE_MISMATCH),
1258 errmsg("inherited column \"%s\" has a type conflict",
1259 attributeName),
1260 errdetail("%s versus %s",
1261 TypeNameToString(def->typename),
1262 format_type_be(attribute->atttypid))));
1263 def->inhcount++;
1264 /* Merge of NOT NULL constraints = OR 'em together */
1265 def->is_not_null |= attribute->attnotnull;
1266 /* Default and other constraints are handled below */
1267 newattno[parent_attno - 1] = exist_attno;
1269 else
1272 * No, create a new inherited column
1274 def = makeNode(ColumnDef);
1275 def->colname = pstrdup(attributeName);
1276 def->typename = makeTypeNameFromOid(attribute->atttypid,
1277 attribute->atttypmod);
1278 def->inhcount = 1;
1279 def->is_local = false;
1280 def->is_not_null = attribute->attnotnull;
1281 def->raw_default = NULL;
1282 def->cooked_default = NULL;
1283 def->constraints = NIL;
1284 inhSchema = lappend(inhSchema, def);
1285 newattno[parent_attno - 1] = ++child_attno;
1289 * Copy default if any
1291 if (attribute->atthasdef)
1293 char *this_default = NULL;
1294 AttrDefault *attrdef;
1295 int i;
1297 /* Find default in constraint structure */
1298 Assert(constr != NULL);
1299 attrdef = constr->defval;
1300 for (i = 0; i < constr->num_defval; i++)
1302 if (attrdef[i].adnum == parent_attno)
1304 this_default = attrdef[i].adbin;
1305 break;
1308 Assert(this_default != NULL);
1311 * If default expr could contain any vars, we'd need to fix
1312 * 'em, but it can't; so default is ready to apply to child.
1314 * If we already had a default from some prior parent, check
1315 * to see if they are the same. If so, no problem; if not,
1316 * mark the column as having a bogus default. Below, we will
1317 * complain if the bogus default isn't overridden by the child
1318 * schema.
1320 Assert(def->raw_default == NULL);
1321 if (def->cooked_default == NULL)
1322 def->cooked_default = pstrdup(this_default);
1323 else if (strcmp(def->cooked_default, this_default) != 0)
1325 def->cooked_default = bogus_marker;
1326 have_bogus_defaults = true;
1332 * Now copy the CHECK constraints of this parent, adjusting attnos
1333 * using the completed newattno[] map. Identically named constraints
1334 * are merged if possible, else we throw error.
1336 if (constr && constr->num_check > 0)
1338 ConstrCheck *check = constr->check;
1339 int i;
1341 for (i = 0; i < constr->num_check; i++)
1343 char *name = check[i].ccname;
1344 Node *expr;
1346 /* adjust varattnos of ccbin here */
1347 expr = stringToNode(check[i].ccbin);
1348 change_varattnos_of_a_node(expr, newattno);
1350 /* check for duplicate */
1351 if (!MergeCheckConstraint(constraints, name, expr))
1353 /* nope, this is a new one */
1354 CookedConstraint *cooked;
1356 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1357 cooked->contype = CONSTR_CHECK;
1358 cooked->name = pstrdup(name);
1359 cooked->attnum = 0; /* not used for constraints */
1360 cooked->expr = expr;
1361 cooked->is_local = false;
1362 cooked->inhcount = 1;
1363 constraints = lappend(constraints, cooked);
1368 pfree(newattno);
1371 * Close the parent rel, but keep our AccessShareLock on it until xact
1372 * commit. That will prevent someone else from deleting or ALTERing
1373 * the parent before the child is committed.
1375 heap_close(relation, NoLock);
1379 * If we had no inherited attributes, the result schema is just the
1380 * explicitly declared columns. Otherwise, we need to merge the declared
1381 * columns into the inherited schema list.
1383 if (inhSchema != NIL)
1385 foreach(entry, schema)
1387 ColumnDef *newdef = lfirst(entry);
1388 char *attributeName = newdef->colname;
1389 int exist_attno;
1392 * Does it conflict with some previously inherited column?
1394 exist_attno = findAttrByName(attributeName, inhSchema);
1395 if (exist_attno > 0)
1397 ColumnDef *def;
1398 Oid defTypeId,
1399 newTypeId;
1400 int32 deftypmod,
1401 newtypmod;
1404 * Yes, try to merge the two column definitions. They must
1405 * have the same type and typmod.
1407 ereport(NOTICE,
1408 (errmsg("merging column \"%s\" with inherited definition",
1409 attributeName)));
1410 def = (ColumnDef *) list_nth(inhSchema, exist_attno - 1);
1411 defTypeId = typenameTypeId(NULL, def->typename, &deftypmod);
1412 newTypeId = typenameTypeId(NULL, newdef->typename, &newtypmod);
1413 if (defTypeId != newTypeId || deftypmod != newtypmod)
1414 ereport(ERROR,
1415 (errcode(ERRCODE_DATATYPE_MISMATCH),
1416 errmsg("column \"%s\" has a type conflict",
1417 attributeName),
1418 errdetail("%s versus %s",
1419 TypeNameToString(def->typename),
1420 TypeNameToString(newdef->typename))));
1421 /* Mark the column as locally defined */
1422 def->is_local = true;
1423 /* Merge of NOT NULL constraints = OR 'em together */
1424 def->is_not_null |= newdef->is_not_null;
1425 /* If new def has a default, override previous default */
1426 if (newdef->raw_default != NULL)
1428 def->raw_default = newdef->raw_default;
1429 def->cooked_default = newdef->cooked_default;
1432 else
1435 * No, attach new column to result schema
1437 inhSchema = lappend(inhSchema, newdef);
1441 schema = inhSchema;
1444 * Check that we haven't exceeded the legal # of columns after merging
1445 * in inherited columns.
1447 if (list_length(schema) > MaxHeapAttributeNumber)
1448 ereport(ERROR,
1449 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1450 errmsg("tables can have at most %d columns",
1451 MaxHeapAttributeNumber)));
1455 * If we found any conflicting parent default values, check to make sure
1456 * they were overridden by the child.
1458 if (have_bogus_defaults)
1460 foreach(entry, schema)
1462 ColumnDef *def = lfirst(entry);
1464 if (def->cooked_default == bogus_marker)
1465 ereport(ERROR,
1466 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
1467 errmsg("column \"%s\" inherits conflicting default values",
1468 def->colname),
1469 errhint("To resolve the conflict, specify a default explicitly.")));
1473 *supOids = parentOids;
1474 *supconstr = constraints;
1475 *supOidCount = parentsWithOids;
1476 return schema;
1481 * MergeCheckConstraint
1482 * Try to merge an inherited CHECK constraint with previous ones
1484 * If we inherit identically-named constraints from multiple parents, we must
1485 * merge them, or throw an error if they don't have identical definitions.
1487 * constraints is a list of CookedConstraint structs for previous constraints.
1489 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
1490 * got a so-far-unique name, or throws error if conflict.
1492 static bool
1493 MergeCheckConstraint(List *constraints, char *name, Node *expr)
1495 ListCell *lc;
1497 foreach(lc, constraints)
1499 CookedConstraint *ccon = (CookedConstraint *) lfirst(lc);
1501 Assert(ccon->contype == CONSTR_CHECK);
1503 /* Non-matching names never conflict */
1504 if (strcmp(ccon->name, name) != 0)
1505 continue;
1507 if (equal(expr, ccon->expr))
1509 /* OK to merge */
1510 ccon->inhcount++;
1511 return true;
1514 ereport(ERROR,
1515 (errcode(ERRCODE_DUPLICATE_OBJECT),
1516 errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
1517 name)));
1520 return false;
1525 * Replace varattno values in an expression tree according to the given
1526 * map array, that is, varattno N is replaced by newattno[N-1]. It is
1527 * caller's responsibility to ensure that the array is long enough to
1528 * define values for all user varattnos present in the tree. System column
1529 * attnos remain unchanged.
1531 * Note that the passed node tree is modified in-place!
1533 void
1534 change_varattnos_of_a_node(Node *node, const AttrNumber *newattno)
1536 /* no setup needed, so away we go */
1537 (void) change_varattnos_walker(node, newattno);
1540 static bool
1541 change_varattnos_walker(Node *node, const AttrNumber *newattno)
1543 if (node == NULL)
1544 return false;
1545 if (IsA(node, Var))
1547 Var *var = (Var *) node;
1549 if (var->varlevelsup == 0 && var->varno == 1 &&
1550 var->varattno > 0)
1553 * ??? the following may be a problem when the node is multiply
1554 * referenced though stringToNode() doesn't create such a node
1555 * currently.
1557 Assert(newattno[var->varattno - 1] > 0);
1558 var->varattno = var->varoattno = newattno[var->varattno - 1];
1560 return false;
1562 return expression_tree_walker(node, change_varattnos_walker,
1563 (void *) newattno);
1567 * Generate a map for change_varattnos_of_a_node from old and new TupleDesc's,
1568 * matching according to column name.
1570 AttrNumber *
1571 varattnos_map(TupleDesc old, TupleDesc new)
1573 AttrNumber *attmap;
1574 int i,
1577 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * old->natts);
1578 for (i = 1; i <= old->natts; i++)
1580 if (old->attrs[i - 1]->attisdropped)
1581 continue; /* leave the entry as zero */
1583 for (j = 1; j <= new->natts; j++)
1585 if (strcmp(NameStr(old->attrs[i - 1]->attname),
1586 NameStr(new->attrs[j - 1]->attname)) == 0)
1588 attmap[i - 1] = j;
1589 break;
1593 return attmap;
1597 * Generate a map for change_varattnos_of_a_node from a TupleDesc and a list
1598 * of ColumnDefs
1600 AttrNumber *
1601 varattnos_map_schema(TupleDesc old, List *schema)
1603 AttrNumber *attmap;
1604 int i;
1606 attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * old->natts);
1607 for (i = 1; i <= old->natts; i++)
1609 if (old->attrs[i - 1]->attisdropped)
1610 continue; /* leave the entry as zero */
1612 attmap[i - 1] = findAttrByName(NameStr(old->attrs[i - 1]->attname),
1613 schema);
1615 return attmap;
1620 * StoreCatalogInheritance
1621 * Updates the system catalogs with proper inheritance information.
1623 * supers is a list of the OIDs of the new relation's direct ancestors.
1625 static void
1626 StoreCatalogInheritance(Oid relationId, List *supers)
1628 Relation relation;
1629 int16 seqNumber;
1630 ListCell *entry;
1633 * sanity checks
1635 AssertArg(OidIsValid(relationId));
1637 if (supers == NIL)
1638 return;
1641 * Store INHERITS information in pg_inherits using direct ancestors only.
1642 * Also enter dependencies on the direct ancestors, and make sure they are
1643 * marked with relhassubclass = true.
1645 * (Once upon a time, both direct and indirect ancestors were found here
1646 * and then entered into pg_ipl. Since that catalog doesn't exist
1647 * anymore, there's no need to look for indirect ancestors.)
1649 relation = heap_open(InheritsRelationId, RowExclusiveLock);
1651 seqNumber = 1;
1652 foreach(entry, supers)
1654 Oid parentOid = lfirst_oid(entry);
1656 StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation);
1657 seqNumber++;
1660 heap_close(relation, RowExclusiveLock);
1664 * Make catalog entries showing relationId as being an inheritance child
1665 * of parentOid. inhRelation is the already-opened pg_inherits catalog.
1667 static void
1668 StoreCatalogInheritance1(Oid relationId, Oid parentOid,
1669 int16 seqNumber, Relation inhRelation)
1671 TupleDesc desc = RelationGetDescr(inhRelation);
1672 Datum datum[Natts_pg_inherits];
1673 char nullarr[Natts_pg_inherits];
1674 ObjectAddress childobject,
1675 parentobject;
1676 HeapTuple tuple;
1679 * Make the pg_inherits entry
1681 datum[0] = ObjectIdGetDatum(relationId); /* inhrelid */
1682 datum[1] = ObjectIdGetDatum(parentOid); /* inhparent */
1683 datum[2] = Int16GetDatum(seqNumber); /* inhseqno */
1685 nullarr[0] = ' ';
1686 nullarr[1] = ' ';
1687 nullarr[2] = ' ';
1689 tuple = heap_formtuple(desc, datum, nullarr);
1691 simple_heap_insert(inhRelation, tuple);
1693 CatalogUpdateIndexes(inhRelation, tuple);
1695 heap_freetuple(tuple);
1698 * Store a dependency too
1700 parentobject.classId = RelationRelationId;
1701 parentobject.objectId = parentOid;
1702 parentobject.objectSubId = 0;
1703 childobject.classId = RelationRelationId;
1704 childobject.objectId = relationId;
1705 childobject.objectSubId = 0;
1707 recordDependencyOn(&childobject, &parentobject, DEPENDENCY_NORMAL);
1710 * Mark the parent as having subclasses.
1712 setRelhassubclassInRelation(parentOid, true);
1716 * Look for an existing schema entry with the given name.
1718 * Returns the index (starting with 1) if attribute already exists in schema,
1719 * 0 if it doesn't.
1721 static int
1722 findAttrByName(const char *attributeName, List *schema)
1724 ListCell *s;
1725 int i = 1;
1727 foreach(s, schema)
1729 ColumnDef *def = lfirst(s);
1731 if (strcmp(attributeName, def->colname) == 0)
1732 return i;
1734 i++;
1736 return 0;
1740 * Update a relation's pg_class.relhassubclass entry to the given value
1742 static void
1743 setRelhassubclassInRelation(Oid relationId, bool relhassubclass)
1745 Relation relationRelation;
1746 HeapTuple tuple;
1747 Form_pg_class classtuple;
1750 * Fetch a modifiable copy of the tuple, modify it, update pg_class.
1752 * If the tuple already has the right relhassubclass setting, we don't
1753 * need to update it, but we still need to issue an SI inval message.
1755 relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
1756 tuple = SearchSysCacheCopy(RELOID,
1757 ObjectIdGetDatum(relationId),
1758 0, 0, 0);
1759 if (!HeapTupleIsValid(tuple))
1760 elog(ERROR, "cache lookup failed for relation %u", relationId);
1761 classtuple = (Form_pg_class) GETSTRUCT(tuple);
1763 if (classtuple->relhassubclass != relhassubclass)
1765 classtuple->relhassubclass = relhassubclass;
1766 simple_heap_update(relationRelation, &tuple->t_self, tuple);
1768 /* keep the catalog indexes up to date */
1769 CatalogUpdateIndexes(relationRelation, tuple);
1771 else
1773 /* no need to change tuple, but force relcache rebuild anyway */
1774 CacheInvalidateRelcacheByTuple(tuple);
1777 heap_freetuple(tuple);
1778 heap_close(relationRelation, RowExclusiveLock);
1783 * renameatt - changes the name of a attribute in a relation
1785 * Attname attribute is changed in attribute catalog.
1786 * No record of the previous attname is kept (correct?).
1788 * get proper relrelation from relation catalog (if not arg)
1789 * scan attribute catalog
1790 * for name conflict (within rel)
1791 * for original attribute (if not arg)
1792 * modify attname in attribute tuple
1793 * insert modified attribute in attribute catalog
1794 * delete original attribute from attribute catalog
1796 void
1797 renameatt(Oid myrelid,
1798 const char *oldattname,
1799 const char *newattname,
1800 bool recurse,
1801 bool recursing)
1803 Relation targetrelation;
1804 Relation attrelation;
1805 HeapTuple atttup;
1806 Form_pg_attribute attform;
1807 int attnum;
1808 List *indexoidlist;
1809 ListCell *indexoidscan;
1812 * Grab an exclusive lock on the target table, which we will NOT release
1813 * until end of transaction.
1815 targetrelation = relation_open(myrelid, AccessExclusiveLock);
1818 * permissions checking. this would normally be done in utility.c, but
1819 * this particular routine is recursive.
1821 * normally, only the owner of a class can change its schema.
1823 if (!pg_class_ownercheck(myrelid, GetUserId()))
1824 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
1825 RelationGetRelationName(targetrelation));
1826 if (!allowSystemTableMods && IsSystemRelation(targetrelation))
1827 ereport(ERROR,
1828 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1829 errmsg("permission denied: \"%s\" is a system catalog",
1830 RelationGetRelationName(targetrelation))));
1833 * if the 'recurse' flag is set then we are supposed to rename this
1834 * attribute in all classes that inherit from 'relname' (as well as in
1835 * 'relname').
1837 * any permissions or problems with duplicate attributes will cause the
1838 * whole transaction to abort, which is what we want -- all or nothing.
1840 if (recurse)
1842 ListCell *child;
1843 List *children;
1845 /* this routine is actually in the planner */
1846 children = find_all_inheritors(myrelid);
1849 * find_all_inheritors does the recursive search of the inheritance
1850 * hierarchy, so all we have to do is process all of the relids in the
1851 * list that it returns.
1853 foreach(child, children)
1855 Oid childrelid = lfirst_oid(child);
1857 if (childrelid == myrelid)
1858 continue;
1859 /* note we need not recurse again */
1860 renameatt(childrelid, oldattname, newattname, false, true);
1863 else
1866 * If we are told not to recurse, there had better not be any child
1867 * tables; else the rename would put them out of step.
1869 if (!recursing &&
1870 find_inheritance_children(myrelid) != NIL)
1871 ereport(ERROR,
1872 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1873 errmsg("inherited column \"%s\" must be renamed in child tables too",
1874 oldattname)));
1877 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
1879 atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
1880 if (!HeapTupleIsValid(atttup))
1881 ereport(ERROR,
1882 (errcode(ERRCODE_UNDEFINED_COLUMN),
1883 errmsg("column \"%s\" does not exist",
1884 oldattname)));
1885 attform = (Form_pg_attribute) GETSTRUCT(atttup);
1887 attnum = attform->attnum;
1888 if (attnum <= 0)
1889 ereport(ERROR,
1890 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1891 errmsg("cannot rename system column \"%s\"",
1892 oldattname)));
1895 * if the attribute is inherited, forbid the renaming, unless we are
1896 * already inside a recursive rename.
1898 if (attform->attinhcount > 0 && !recursing)
1899 ereport(ERROR,
1900 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1901 errmsg("cannot rename inherited column \"%s\"",
1902 oldattname)));
1904 /* should not already exist */
1905 /* this test is deliberately not attisdropped-aware */
1906 if (SearchSysCacheExists(ATTNAME,
1907 ObjectIdGetDatum(myrelid),
1908 PointerGetDatum(newattname),
1909 0, 0))
1910 ereport(ERROR,
1911 (errcode(ERRCODE_DUPLICATE_COLUMN),
1912 errmsg("column \"%s\" of relation \"%s\" already exists",
1913 newattname, RelationGetRelationName(targetrelation))));
1915 namestrcpy(&(attform->attname), newattname);
1917 simple_heap_update(attrelation, &atttup->t_self, atttup);
1919 /* keep system catalog indexes current */
1920 CatalogUpdateIndexes(attrelation, atttup);
1922 heap_freetuple(atttup);
1925 * Update column names of indexes that refer to the column being renamed.
1927 indexoidlist = RelationGetIndexList(targetrelation);
1929 foreach(indexoidscan, indexoidlist)
1931 Oid indexoid = lfirst_oid(indexoidscan);
1932 HeapTuple indextup;
1933 Form_pg_index indexform;
1934 int i;
1937 * Scan through index columns to see if there's any simple index
1938 * entries for this attribute. We ignore expressional entries.
1940 indextup = SearchSysCache(INDEXRELID,
1941 ObjectIdGetDatum(indexoid),
1942 0, 0, 0);
1943 if (!HeapTupleIsValid(indextup))
1944 elog(ERROR, "cache lookup failed for index %u", indexoid);
1945 indexform = (Form_pg_index) GETSTRUCT(indextup);
1947 for (i = 0; i < indexform->indnatts; i++)
1949 if (attnum != indexform->indkey.values[i])
1950 continue;
1953 * Found one, rename it.
1955 atttup = SearchSysCacheCopy(ATTNUM,
1956 ObjectIdGetDatum(indexoid),
1957 Int16GetDatum(i + 1),
1958 0, 0);
1959 if (!HeapTupleIsValid(atttup))
1960 continue; /* should we raise an error? */
1963 * Update the (copied) attribute tuple.
1965 namestrcpy(&(((Form_pg_attribute) GETSTRUCT(atttup))->attname),
1966 newattname);
1968 simple_heap_update(attrelation, &atttup->t_self, atttup);
1970 /* keep system catalog indexes current */
1971 CatalogUpdateIndexes(attrelation, atttup);
1973 heap_freetuple(atttup);
1976 ReleaseSysCache(indextup);
1979 list_free(indexoidlist);
1981 heap_close(attrelation, RowExclusiveLock);
1983 relation_close(targetrelation, NoLock); /* close rel but keep lock */
1988 * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW RENAME
1990 * Caller has already done permissions checks.
1992 void
1993 RenameRelation(Oid myrelid, const char *newrelname, ObjectType reltype)
1995 Relation targetrelation;
1996 Oid namespaceId;
1997 char relkind;
2000 * Grab an exclusive lock on the target table, index, sequence or view,
2001 * which we will NOT release until end of transaction.
2003 targetrelation = relation_open(myrelid, AccessExclusiveLock);
2005 namespaceId = RelationGetNamespace(targetrelation);
2006 relkind = targetrelation->rd_rel->relkind;
2009 * For compatibility with prior releases, we don't complain if ALTER TABLE
2010 * or ALTER INDEX is used to rename a sequence or view.
2012 if (reltype == OBJECT_SEQUENCE && relkind != RELKIND_SEQUENCE)
2013 ereport(ERROR,
2014 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2015 errmsg("\"%s\" is not a sequence",
2016 RelationGetRelationName(targetrelation))));
2018 if (reltype == OBJECT_VIEW && relkind != RELKIND_VIEW)
2019 ereport(ERROR,
2020 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2021 errmsg("\"%s\" is not a view",
2022 RelationGetRelationName(targetrelation))));
2025 * Don't allow ALTER TABLE on composite types.
2026 * We want people to use ALTER TYPE for that.
2028 if (relkind == RELKIND_COMPOSITE_TYPE)
2029 ereport(ERROR,
2030 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2031 errmsg("\"%s\" is a composite type",
2032 RelationGetRelationName(targetrelation)),
2033 errhint("Use ALTER TYPE instead.")));
2035 /* Do the work */
2036 RenameRelationInternal(myrelid, newrelname, namespaceId);
2039 * Close rel, but keep exclusive lock!
2041 relation_close(targetrelation, NoLock);
2045 * RenameRelationInternal - change the name of a relation
2047 * XXX - When renaming sequences, we don't bother to modify the
2048 * sequence name that is stored within the sequence itself
2049 * (this would cause problems with MVCC). In the future,
2050 * the sequence name should probably be removed from the
2051 * sequence, AFAIK there's no need for it to be there.
2053 void
2054 RenameRelationInternal(Oid myrelid, const char *newrelname, Oid namespaceId)
2056 Relation targetrelation;
2057 Relation relrelation; /* for RELATION relation */
2058 HeapTuple reltup;
2059 Form_pg_class relform;
2062 * Grab an exclusive lock on the target table, index, sequence or
2063 * view, which we will NOT release until end of transaction.
2065 targetrelation = relation_open(myrelid, AccessExclusiveLock);
2068 * Find relation's pg_class tuple, and make sure newrelname isn't in use.
2070 relrelation = heap_open(RelationRelationId, RowExclusiveLock);
2072 reltup = SearchSysCacheCopy(RELOID,
2073 ObjectIdGetDatum(myrelid),
2074 0, 0, 0);
2075 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
2076 elog(ERROR, "cache lookup failed for relation %u", myrelid);
2077 relform = (Form_pg_class) GETSTRUCT(reltup);
2079 if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
2080 ereport(ERROR,
2081 (errcode(ERRCODE_DUPLICATE_TABLE),
2082 errmsg("relation \"%s\" already exists",
2083 newrelname)));
2086 * Update pg_class tuple with new relname. (Scribbling on reltup is OK
2087 * because it's a copy...)
2089 namestrcpy(&(relform->relname), newrelname);
2091 simple_heap_update(relrelation, &reltup->t_self, reltup);
2093 /* keep the system catalog indexes current */
2094 CatalogUpdateIndexes(relrelation, reltup);
2096 heap_freetuple(reltup);
2097 heap_close(relrelation, RowExclusiveLock);
2100 * Also rename the associated type, if any.
2102 if (OidIsValid(targetrelation->rd_rel->reltype))
2103 RenameTypeInternal(targetrelation->rd_rel->reltype,
2104 newrelname, namespaceId);
2107 * Also rename the associated constraint, if any.
2109 if (targetrelation->rd_rel->relkind == RELKIND_INDEX)
2111 Oid constraintId = get_index_constraint(myrelid);
2113 if (OidIsValid(constraintId))
2114 RenameConstraintById(constraintId, newrelname);
2118 * Close rel, but keep exclusive lock!
2120 relation_close(targetrelation, NoLock);
2124 * Disallow ALTER TABLE (and similar commands) when the current backend has
2125 * any open reference to the target table besides the one just acquired by
2126 * the calling command; this implies there's an open cursor or active plan.
2127 * We need this check because our AccessExclusiveLock doesn't protect us
2128 * against stomping on our own foot, only other people's feet!
2130 * For ALTER TABLE, the only case known to cause serious trouble is ALTER
2131 * COLUMN TYPE, and some changes are obviously pretty benign, so this could
2132 * possibly be relaxed to only error out for certain types of alterations.
2133 * But the use-case for allowing any of these things is not obvious, so we
2134 * won't work hard at it for now.
2136 * We also reject these commands if there are any pending AFTER trigger events
2137 * for the rel. This is certainly necessary for the rewriting variants of
2138 * ALTER TABLE, because they don't preserve tuple TIDs and so the pending
2139 * events would try to fetch the wrong tuples. It might be overly cautious
2140 * in other cases, but again it seems better to err on the side of paranoia.
2142 * REINDEX calls this with "rel" referencing the index to be rebuilt; here
2143 * we are worried about active indexscans on the index. The trigger-event
2144 * check can be skipped, since we are doing no damage to the parent table.
2146 * The statement name (eg, "ALTER TABLE") is passed for use in error messages.
2148 void
2149 CheckTableNotInUse(Relation rel, const char *stmt)
2151 int expected_refcnt;
2153 expected_refcnt = rel->rd_isnailed ? 2 : 1;
2154 if (rel->rd_refcnt != expected_refcnt)
2155 ereport(ERROR,
2156 (errcode(ERRCODE_OBJECT_IN_USE),
2157 /* translator: first %s is a SQL command, eg ALTER TABLE */
2158 errmsg("cannot %s \"%s\" because "
2159 "it is being used by active queries in this session",
2160 stmt, RelationGetRelationName(rel))));
2162 if (rel->rd_rel->relkind != RELKIND_INDEX &&
2163 AfterTriggerPendingOnRel(RelationGetRelid(rel)))
2164 ereport(ERROR,
2165 (errcode(ERRCODE_OBJECT_IN_USE),
2166 /* translator: first %s is a SQL command, eg ALTER TABLE */
2167 errmsg("cannot %s \"%s\" because "
2168 "it has pending trigger events",
2169 stmt, RelationGetRelationName(rel))));
2173 * AlterTable
2174 * Execute ALTER TABLE, which can be a list of subcommands
2176 * ALTER TABLE is performed in three phases:
2177 * 1. Examine subcommands and perform pre-transformation checking.
2178 * 2. Update system catalogs.
2179 * 3. Scan table(s) to check new constraints, and optionally recopy
2180 * the data into new table(s).
2181 * Phase 3 is not performed unless one or more of the subcommands requires
2182 * it. The intention of this design is to allow multiple independent
2183 * updates of the table schema to be performed with only one pass over the
2184 * data.
2186 * ATPrepCmd performs phase 1. A "work queue" entry is created for
2187 * each table to be affected (there may be multiple affected tables if the
2188 * commands traverse a table inheritance hierarchy). Also we do preliminary
2189 * validation of the subcommands, including parse transformation of those
2190 * expressions that need to be evaluated with respect to the old table
2191 * schema.
2193 * ATRewriteCatalogs performs phase 2 for each affected table. (Note that
2194 * phases 2 and 3 normally do no explicit recursion, since phase 1 already
2195 * did it --- although some subcommands have to recurse in phase 2 instead.)
2196 * Certain subcommands need to be performed before others to avoid
2197 * unnecessary conflicts; for example, DROP COLUMN should come before
2198 * ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
2199 * lists, one for each logical "pass" of phase 2.
2201 * ATRewriteTables performs phase 3 for those tables that need it.
2203 * Thanks to the magic of MVCC, an error anywhere along the way rolls back
2204 * the whole operation; we don't have to do anything special to clean up.
2206 void
2207 AlterTable(AlterTableStmt *stmt)
2209 Relation rel = relation_openrv(stmt->relation, AccessExclusiveLock);
2211 CheckTableNotInUse(rel, "ALTER TABLE");
2213 /* Check relation type against type specified in the ALTER command */
2214 switch (stmt->relkind)
2216 case OBJECT_TABLE:
2218 * For mostly-historical reasons, we allow ALTER TABLE to apply
2219 * to all relation types.
2221 break;
2223 case OBJECT_INDEX:
2224 if (rel->rd_rel->relkind != RELKIND_INDEX)
2225 ereport(ERROR,
2226 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2227 errmsg("\"%s\" is not an index",
2228 RelationGetRelationName(rel))));
2229 break;
2231 case OBJECT_SEQUENCE:
2232 if (rel->rd_rel->relkind != RELKIND_SEQUENCE)
2233 ereport(ERROR,
2234 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2235 errmsg("\"%s\" is not a sequence",
2236 RelationGetRelationName(rel))));
2237 break;
2239 case OBJECT_VIEW:
2240 if (rel->rd_rel->relkind != RELKIND_VIEW)
2241 ereport(ERROR,
2242 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2243 errmsg("\"%s\" is not a view",
2244 RelationGetRelationName(rel))));
2245 break;
2247 default:
2248 elog(ERROR, "unrecognized object type: %d", (int) stmt->relkind);
2251 ATController(rel, stmt->cmds, interpretInhOption(stmt->relation->inhOpt));
2255 * AlterTableInternal
2257 * ALTER TABLE with target specified by OID
2259 * We do not reject if the relation is already open, because it's quite
2260 * likely that one or more layers of caller have it open. That means it
2261 * is unsafe to use this entry point for alterations that could break
2262 * existing query plans. On the assumption it's not used for such, we
2263 * don't have to reject pending AFTER triggers, either.
2265 void
2266 AlterTableInternal(Oid relid, List *cmds, bool recurse)
2268 Relation rel = relation_open(relid, AccessExclusiveLock);
2270 ATController(rel, cmds, recurse);
2273 static void
2274 ATController(Relation rel, List *cmds, bool recurse)
2276 List *wqueue = NIL;
2277 ListCell *lcmd;
2279 /* Phase 1: preliminary examination of commands, create work queue */
2280 foreach(lcmd, cmds)
2282 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2284 ATPrepCmd(&wqueue, rel, cmd, recurse, false);
2287 /* Close the relation, but keep lock until commit */
2288 relation_close(rel, NoLock);
2290 /* Phase 2: update system catalogs */
2291 ATRewriteCatalogs(&wqueue);
2293 /* Phase 3: scan/rewrite tables as needed */
2294 ATRewriteTables(&wqueue);
2298 * ATPrepCmd
2300 * Traffic cop for ALTER TABLE Phase 1 operations, including simple
2301 * recursion and permission checks.
2303 * Caller must have acquired AccessExclusiveLock on relation already.
2304 * This lock should be held until commit.
2306 static void
2307 ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
2308 bool recurse, bool recursing)
2310 AlteredTableInfo *tab;
2311 int pass;
2313 /* Find or create work queue entry for this table */
2314 tab = ATGetQueueEntry(wqueue, rel);
2317 * Copy the original subcommand for each table. This avoids conflicts
2318 * when different child tables need to make different parse
2319 * transformations (for example, the same column may have different column
2320 * numbers in different children).
2322 cmd = copyObject(cmd);
2325 * Do permissions checking, recursion to child tables if needed, and any
2326 * additional phase-1 processing needed.
2328 switch (cmd->subtype)
2330 case AT_AddColumn: /* ADD COLUMN */
2331 ATSimplePermissions(rel, false);
2332 /* Performs own recursion */
2333 ATPrepAddColumn(wqueue, rel, recurse, cmd);
2334 pass = AT_PASS_ADD_COL;
2335 break;
2336 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
2339 * We allow defaults on views so that INSERT into a view can have
2340 * default-ish behavior. This works because the rewriter
2341 * substitutes default values into INSERTs before it expands
2342 * rules.
2344 ATSimplePermissions(rel, true);
2345 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2346 /* No command-specific prep needed */
2347 pass = cmd->def ? AT_PASS_ADD_CONSTR : AT_PASS_DROP;
2348 break;
2349 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
2350 ATSimplePermissions(rel, false);
2351 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2352 /* No command-specific prep needed */
2353 pass = AT_PASS_DROP;
2354 break;
2355 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
2356 ATSimplePermissions(rel, false);
2357 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2358 /* No command-specific prep needed */
2359 pass = AT_PASS_ADD_CONSTR;
2360 break;
2361 case AT_SetStatistics: /* ALTER COLUMN STATISTICS */
2362 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2363 /* Performs own permission checks */
2364 ATPrepSetStatistics(rel, cmd->name, cmd->def);
2365 pass = AT_PASS_COL_ATTRS;
2366 break;
2367 case AT_SetStorage: /* ALTER COLUMN STORAGE */
2368 ATSimplePermissions(rel, false);
2369 ATSimpleRecursion(wqueue, rel, cmd, recurse);
2370 /* No command-specific prep needed */
2371 pass = AT_PASS_COL_ATTRS;
2372 break;
2373 case AT_DropColumn: /* DROP COLUMN */
2374 ATSimplePermissions(rel, false);
2375 /* Recursion occurs during execution phase */
2376 /* No command-specific prep needed except saving recurse flag */
2377 if (recurse)
2378 cmd->subtype = AT_DropColumnRecurse;
2379 pass = AT_PASS_DROP;
2380 break;
2381 case AT_AddIndex: /* ADD INDEX */
2382 ATSimplePermissions(rel, false);
2383 /* This command never recurses */
2384 /* No command-specific prep needed */
2385 pass = AT_PASS_ADD_INDEX;
2386 break;
2387 case AT_AddConstraint: /* ADD CONSTRAINT */
2388 ATSimplePermissions(rel, false);
2389 /* Recursion occurs during execution phase */
2390 /* No command-specific prep needed except saving recurse flag */
2391 if (recurse)
2392 cmd->subtype = AT_AddConstraintRecurse;
2393 pass = AT_PASS_ADD_CONSTR;
2394 break;
2395 case AT_DropConstraint: /* DROP CONSTRAINT */
2396 ATSimplePermissions(rel, false);
2397 /* Recursion occurs during execution phase */
2398 /* No command-specific prep needed except saving recurse flag */
2399 if (recurse)
2400 cmd->subtype = AT_DropConstraintRecurse;
2401 pass = AT_PASS_DROP;
2402 break;
2403 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
2404 ATSimplePermissions(rel, false);
2405 /* Performs own recursion */
2406 ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd);
2407 pass = AT_PASS_ALTER_TYPE;
2408 break;
2409 case AT_ChangeOwner: /* ALTER OWNER */
2410 /* This command never recurses */
2411 /* No command-specific prep needed */
2412 pass = AT_PASS_MISC;
2413 break;
2414 case AT_ClusterOn: /* CLUSTER ON */
2415 case AT_DropCluster: /* SET WITHOUT CLUSTER */
2416 ATSimplePermissions(rel, false);
2417 /* These commands never recurse */
2418 /* No command-specific prep needed */
2419 pass = AT_PASS_MISC;
2420 break;
2421 case AT_DropOids: /* SET WITHOUT OIDS */
2422 ATSimplePermissions(rel, false);
2423 /* Performs own recursion */
2424 if (rel->rd_rel->relhasoids)
2426 AlterTableCmd *dropCmd = makeNode(AlterTableCmd);
2428 dropCmd->subtype = AT_DropColumn;
2429 dropCmd->name = pstrdup("oid");
2430 dropCmd->behavior = cmd->behavior;
2431 ATPrepCmd(wqueue, rel, dropCmd, recurse, false);
2433 pass = AT_PASS_DROP;
2434 break;
2435 case AT_SetTableSpace: /* SET TABLESPACE */
2436 ATSimplePermissionsRelationOrIndex(rel);
2437 /* This command never recurses */
2438 ATPrepSetTableSpace(tab, rel, cmd->name);
2439 pass = AT_PASS_MISC; /* doesn't actually matter */
2440 break;
2441 case AT_SetRelOptions: /* SET (...) */
2442 case AT_ResetRelOptions: /* RESET (...) */
2443 ATSimplePermissionsRelationOrIndex(rel);
2444 /* This command never recurses */
2445 /* No command-specific prep needed */
2446 pass = AT_PASS_MISC;
2447 break;
2448 case AT_EnableTrig: /* ENABLE TRIGGER variants */
2449 case AT_EnableAlwaysTrig:
2450 case AT_EnableReplicaTrig:
2451 case AT_EnableTrigAll:
2452 case AT_EnableTrigUser:
2453 case AT_DisableTrig: /* DISABLE TRIGGER variants */
2454 case AT_DisableTrigAll:
2455 case AT_DisableTrigUser:
2456 case AT_EnableRule: /* ENABLE/DISABLE RULE variants */
2457 case AT_EnableAlwaysRule:
2458 case AT_EnableReplicaRule:
2459 case AT_DisableRule:
2460 case AT_AddInherit: /* INHERIT / NO INHERIT */
2461 case AT_DropInherit:
2462 ATSimplePermissions(rel, false);
2463 /* These commands never recurse */
2464 /* No command-specific prep needed */
2465 pass = AT_PASS_MISC;
2466 break;
2467 default: /* oops */
2468 elog(ERROR, "unrecognized alter table type: %d",
2469 (int) cmd->subtype);
2470 pass = 0; /* keep compiler quiet */
2471 break;
2474 /* Add the subcommand to the appropriate list for phase 2 */
2475 tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
2479 * ATRewriteCatalogs
2481 * Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
2482 * dispatched in a "safe" execution order (designed to avoid unnecessary
2483 * conflicts).
2485 static void
2486 ATRewriteCatalogs(List **wqueue)
2488 int pass;
2489 ListCell *ltab;
2492 * We process all the tables "in parallel", one pass at a time. This is
2493 * needed because we may have to propagate work from one table to another
2494 * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
2495 * re-adding of the foreign key constraint to the other table). Work can
2496 * only be propagated into later passes, however.
2498 for (pass = 0; pass < AT_NUM_PASSES; pass++)
2500 /* Go through each table that needs to be processed */
2501 foreach(ltab, *wqueue)
2503 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2504 List *subcmds = tab->subcmds[pass];
2505 Relation rel;
2506 ListCell *lcmd;
2508 if (subcmds == NIL)
2509 continue;
2512 * Exclusive lock was obtained by phase 1, needn't get it again
2514 rel = relation_open(tab->relid, NoLock);
2516 foreach(lcmd, subcmds)
2517 ATExecCmd(wqueue, tab, rel, (AlterTableCmd *) lfirst(lcmd));
2520 * After the ALTER TYPE pass, do cleanup work (this is not done in
2521 * ATExecAlterColumnType since it should be done only once if
2522 * multiple columns of a table are altered).
2524 if (pass == AT_PASS_ALTER_TYPE)
2525 ATPostAlterTypeCleanup(wqueue, tab);
2527 relation_close(rel, NoLock);
2532 * Check to see if a toast table must be added, if we executed any
2533 * subcommands that might have added a column or changed column storage.
2535 foreach(ltab, *wqueue)
2537 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2539 if (tab->relkind == RELKIND_RELATION &&
2540 (tab->subcmds[AT_PASS_ADD_COL] ||
2541 tab->subcmds[AT_PASS_ALTER_TYPE] ||
2542 tab->subcmds[AT_PASS_COL_ATTRS]))
2543 AlterTableCreateToastTable(tab->relid);
2548 * ATExecCmd: dispatch a subcommand to appropriate execution routine
2550 static void
2551 ATExecCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
2552 AlterTableCmd *cmd)
2554 switch (cmd->subtype)
2556 case AT_AddColumn: /* ADD COLUMN */
2557 ATExecAddColumn(tab, rel, (ColumnDef *) cmd->def);
2558 break;
2559 case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
2560 ATExecColumnDefault(rel, cmd->name, cmd->def);
2561 break;
2562 case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
2563 ATExecDropNotNull(rel, cmd->name);
2564 break;
2565 case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
2566 ATExecSetNotNull(tab, rel, cmd->name);
2567 break;
2568 case AT_SetStatistics: /* ALTER COLUMN STATISTICS */
2569 ATExecSetStatistics(rel, cmd->name, cmd->def);
2570 break;
2571 case AT_SetStorage: /* ALTER COLUMN STORAGE */
2572 ATExecSetStorage(rel, cmd->name, cmd->def);
2573 break;
2574 case AT_DropColumn: /* DROP COLUMN */
2575 ATExecDropColumn(rel, cmd->name, cmd->behavior, false, false);
2576 break;
2577 case AT_DropColumnRecurse: /* DROP COLUMN with recursion */
2578 ATExecDropColumn(rel, cmd->name, cmd->behavior, true, false);
2579 break;
2580 case AT_AddIndex: /* ADD INDEX */
2581 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false);
2582 break;
2583 case AT_ReAddIndex: /* ADD INDEX */
2584 ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true);
2585 break;
2586 case AT_AddConstraint: /* ADD CONSTRAINT */
2587 ATExecAddConstraint(wqueue, tab, rel, cmd->def, false);
2588 break;
2589 case AT_AddConstraintRecurse: /* ADD CONSTRAINT with recursion */
2590 ATExecAddConstraint(wqueue, tab, rel, cmd->def, true);
2591 break;
2592 case AT_DropConstraint: /* DROP CONSTRAINT */
2593 ATExecDropConstraint(rel, cmd->name, cmd->behavior, false, false);
2594 break;
2595 case AT_DropConstraintRecurse: /* DROP CONSTRAINT with recursion */
2596 ATExecDropConstraint(rel, cmd->name, cmd->behavior, true, false);
2597 break;
2598 case AT_AlterColumnType: /* ALTER COLUMN TYPE */
2599 ATExecAlterColumnType(tab, rel, cmd->name, (TypeName *) cmd->def);
2600 break;
2601 case AT_ChangeOwner: /* ALTER OWNER */
2602 ATExecChangeOwner(RelationGetRelid(rel),
2603 get_roleid_checked(cmd->name),
2604 false);
2605 break;
2606 case AT_ClusterOn: /* CLUSTER ON */
2607 ATExecClusterOn(rel, cmd->name);
2608 break;
2609 case AT_DropCluster: /* SET WITHOUT CLUSTER */
2610 ATExecDropCluster(rel);
2611 break;
2612 case AT_DropOids: /* SET WITHOUT OIDS */
2615 * Nothing to do here; we'll have generated a DropColumn
2616 * subcommand to do the real work
2618 break;
2619 case AT_SetTableSpace: /* SET TABLESPACE */
2622 * Nothing to do here; Phase 3 does the work
2624 break;
2625 case AT_SetRelOptions: /* SET (...) */
2626 ATExecSetRelOptions(rel, (List *) cmd->def, false);
2627 break;
2628 case AT_ResetRelOptions: /* RESET (...) */
2629 ATExecSetRelOptions(rel, (List *) cmd->def, true);
2630 break;
2632 case AT_EnableTrig: /* ENABLE TRIGGER name */
2633 ATExecEnableDisableTrigger(rel, cmd->name,
2634 TRIGGER_FIRES_ON_ORIGIN, false);
2635 break;
2636 case AT_EnableAlwaysTrig: /* ENABLE ALWAYS TRIGGER name */
2637 ATExecEnableDisableTrigger(rel, cmd->name,
2638 TRIGGER_FIRES_ALWAYS, false);
2639 break;
2640 case AT_EnableReplicaTrig: /* ENABLE REPLICA TRIGGER name */
2641 ATExecEnableDisableTrigger(rel, cmd->name,
2642 TRIGGER_FIRES_ON_REPLICA, false);
2643 break;
2644 case AT_DisableTrig: /* DISABLE TRIGGER name */
2645 ATExecEnableDisableTrigger(rel, cmd->name,
2646 TRIGGER_DISABLED, false);
2647 break;
2648 case AT_EnableTrigAll: /* ENABLE TRIGGER ALL */
2649 ATExecEnableDisableTrigger(rel, NULL,
2650 TRIGGER_FIRES_ON_ORIGIN, false);
2651 break;
2652 case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
2653 ATExecEnableDisableTrigger(rel, NULL,
2654 TRIGGER_DISABLED, false);
2655 break;
2656 case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
2657 ATExecEnableDisableTrigger(rel, NULL,
2658 TRIGGER_FIRES_ON_ORIGIN, true);
2659 break;
2660 case AT_DisableTrigUser: /* DISABLE TRIGGER USER */
2661 ATExecEnableDisableTrigger(rel, NULL,
2662 TRIGGER_DISABLED, true);
2663 break;
2665 case AT_EnableRule: /* ENABLE RULE name */
2666 ATExecEnableDisableRule(rel, cmd->name,
2667 RULE_FIRES_ON_ORIGIN);
2668 break;
2669 case AT_EnableAlwaysRule: /* ENABLE ALWAYS RULE name */
2670 ATExecEnableDisableRule(rel, cmd->name,
2671 RULE_FIRES_ALWAYS);
2672 break;
2673 case AT_EnableReplicaRule: /* ENABLE REPLICA RULE name */
2674 ATExecEnableDisableRule(rel, cmd->name,
2675 RULE_FIRES_ON_REPLICA);
2676 break;
2677 case AT_DisableRule: /* DISABLE RULE name */
2678 ATExecEnableDisableRule(rel, cmd->name,
2679 RULE_DISABLED);
2680 break;
2682 case AT_AddInherit:
2683 ATExecAddInherit(rel, (RangeVar *) cmd->def);
2684 break;
2685 case AT_DropInherit:
2686 ATExecDropInherit(rel, (RangeVar *) cmd->def);
2687 break;
2688 default: /* oops */
2689 elog(ERROR, "unrecognized alter table type: %d",
2690 (int) cmd->subtype);
2691 break;
2695 * Bump the command counter to ensure the next subcommand in the sequence
2696 * can see the changes so far
2698 CommandCounterIncrement();
2702 * ATRewriteTables: ALTER TABLE phase 3
2704 static void
2705 ATRewriteTables(List **wqueue)
2707 ListCell *ltab;
2709 /* Go through each table that needs to be checked or rewritten */
2710 foreach(ltab, *wqueue)
2712 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2715 * We only need to rewrite the table if at least one column needs to
2716 * be recomputed.
2718 if (tab->newvals != NIL)
2720 /* Build a temporary relation and copy data */
2721 Oid OIDNewHeap;
2722 char NewHeapName[NAMEDATALEN];
2723 Oid NewTableSpace;
2724 Relation OldHeap;
2725 ObjectAddress object;
2727 OldHeap = heap_open(tab->relid, NoLock);
2730 * We can never allow rewriting of shared or nailed-in-cache
2731 * relations, because we can't support changing their relfilenode
2732 * values.
2734 if (OldHeap->rd_rel->relisshared || OldHeap->rd_isnailed)
2735 ereport(ERROR,
2736 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2737 errmsg("cannot rewrite system relation \"%s\"",
2738 RelationGetRelationName(OldHeap))));
2741 * Don't allow rewrite on temp tables of other backends ... their
2742 * local buffer manager is not going to cope.
2744 if (isOtherTempNamespace(RelationGetNamespace(OldHeap)))
2745 ereport(ERROR,
2746 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2747 errmsg("cannot rewrite temporary tables of other sessions")));
2750 * Select destination tablespace (same as original unless user
2751 * requested a change)
2753 if (tab->newTableSpace)
2754 NewTableSpace = tab->newTableSpace;
2755 else
2756 NewTableSpace = OldHeap->rd_rel->reltablespace;
2758 heap_close(OldHeap, NoLock);
2761 * Create the new heap, using a temporary name in the same
2762 * namespace as the existing table. NOTE: there is some risk of
2763 * collision with user relnames. Working around this seems more
2764 * trouble than it's worth; in particular, we can't create the new
2765 * heap in a different namespace from the old, or we will have
2766 * problems with the TEMP status of temp tables.
2768 snprintf(NewHeapName, sizeof(NewHeapName),
2769 "pg_temp_%u", tab->relid);
2771 OIDNewHeap = make_new_heap(tab->relid, NewHeapName, NewTableSpace);
2774 * Copy the heap data into the new table with the desired
2775 * modifications, and test the current data within the table
2776 * against new constraints generated by ALTER TABLE commands.
2778 ATRewriteTable(tab, OIDNewHeap);
2781 * Swap the physical files of the old and new heaps. Since we are
2782 * generating a new heap, we can use RecentXmin for the table's
2783 * new relfrozenxid because we rewrote all the tuples on
2784 * ATRewriteTable, so no older Xid remains on the table.
2786 swap_relation_files(tab->relid, OIDNewHeap, RecentXmin);
2788 CommandCounterIncrement();
2790 /* Destroy new heap with old filenode */
2791 object.classId = RelationRelationId;
2792 object.objectId = OIDNewHeap;
2793 object.objectSubId = 0;
2796 * The new relation is local to our transaction and we know
2797 * nothing depends on it, so DROP_RESTRICT should be OK.
2799 performDeletion(&object, DROP_RESTRICT);
2800 /* performDeletion does CommandCounterIncrement at end */
2803 * Rebuild each index on the relation (but not the toast table,
2804 * which is all-new anyway). We do not need
2805 * CommandCounterIncrement() because reindex_relation does it.
2807 reindex_relation(tab->relid, false);
2809 else
2812 * Test the current data within the table against new constraints
2813 * generated by ALTER TABLE commands, but don't rebuild data.
2815 if (tab->constraints != NIL || tab->new_notnull)
2816 ATRewriteTable(tab, InvalidOid);
2819 * If we had SET TABLESPACE but no reason to reconstruct tuples,
2820 * just do a block-by-block copy.
2822 if (tab->newTableSpace)
2823 ATExecSetTableSpace(tab->relid, tab->newTableSpace);
2828 * Foreign key constraints are checked in a final pass, since (a) it's
2829 * generally best to examine each one separately, and (b) it's at least
2830 * theoretically possible that we have changed both relations of the
2831 * foreign key, and we'd better have finished both rewrites before we try
2832 * to read the tables.
2834 foreach(ltab, *wqueue)
2836 AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
2837 Relation rel = NULL;
2838 ListCell *lcon;
2840 foreach(lcon, tab->constraints)
2842 NewConstraint *con = lfirst(lcon);
2844 if (con->contype == CONSTR_FOREIGN)
2846 FkConstraint *fkconstraint = (FkConstraint *) con->qual;
2847 Relation refrel;
2849 if (rel == NULL)
2851 /* Long since locked, no need for another */
2852 rel = heap_open(tab->relid, NoLock);
2855 refrel = heap_open(con->refrelid, RowShareLock);
2857 validateForeignKeyConstraint(fkconstraint, rel, refrel,
2858 con->conid);
2860 heap_close(refrel, NoLock);
2864 if (rel)
2865 heap_close(rel, NoLock);
2870 * ATRewriteTable: scan or rewrite one table
2872 * OIDNewHeap is InvalidOid if we don't need to rewrite
2874 static void
2875 ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap)
2877 Relation oldrel;
2878 Relation newrel;
2879 TupleDesc oldTupDesc;
2880 TupleDesc newTupDesc;
2881 bool needscan = false;
2882 List *notnull_attrs;
2883 int i;
2884 ListCell *l;
2885 EState *estate;
2888 * Open the relation(s). We have surely already locked the existing
2889 * table.
2891 oldrel = heap_open(tab->relid, NoLock);
2892 oldTupDesc = tab->oldDesc;
2893 newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
2895 if (OidIsValid(OIDNewHeap))
2896 newrel = heap_open(OIDNewHeap, AccessExclusiveLock);
2897 else
2898 newrel = NULL;
2901 * If we need to rewrite the table, the operation has to be propagated to
2902 * tables that use this table's rowtype as a column type.
2904 * (Eventually this will probably become true for scans as well, but at
2905 * the moment a composite type does not enforce any constraints, so it's
2906 * not necessary/appropriate to enforce them just during ALTER.)
2908 if (newrel)
2909 find_composite_type_dependencies(oldrel->rd_rel->reltype,
2910 RelationGetRelationName(oldrel),
2911 NULL);
2914 * Generate the constraint and default execution states
2917 estate = CreateExecutorState();
2919 /* Build the needed expression execution states */
2920 foreach(l, tab->constraints)
2922 NewConstraint *con = lfirst(l);
2924 switch (con->contype)
2926 case CONSTR_CHECK:
2927 needscan = true;
2928 con->qualstate = (List *)
2929 ExecPrepareExpr((Expr *) con->qual, estate);
2930 break;
2931 case CONSTR_FOREIGN:
2932 /* Nothing to do here */
2933 break;
2934 default:
2935 elog(ERROR, "unrecognized constraint type: %d",
2936 (int) con->contype);
2940 foreach(l, tab->newvals)
2942 NewColumnValue *ex = lfirst(l);
2944 needscan = true;
2946 ex->exprstate = ExecPrepareExpr((Expr *) ex->expr, estate);
2949 notnull_attrs = NIL;
2950 if (newrel || tab->new_notnull)
2953 * If we are rebuilding the tuples OR if we added any new NOT NULL
2954 * constraints, check all not-null constraints. This is a bit of
2955 * overkill but it minimizes risk of bugs, and heap_attisnull is a
2956 * pretty cheap test anyway.
2958 for (i = 0; i < newTupDesc->natts; i++)
2960 if (newTupDesc->attrs[i]->attnotnull &&
2961 !newTupDesc->attrs[i]->attisdropped)
2962 notnull_attrs = lappend_int(notnull_attrs, i);
2964 if (notnull_attrs)
2965 needscan = true;
2968 if (needscan)
2970 ExprContext *econtext;
2971 Datum *values;
2972 bool *isnull;
2973 TupleTableSlot *oldslot;
2974 TupleTableSlot *newslot;
2975 HeapScanDesc scan;
2976 HeapTuple tuple;
2977 MemoryContext oldCxt;
2978 List *dropped_attrs = NIL;
2979 ListCell *lc;
2981 econtext = GetPerTupleExprContext(estate);
2984 * Make tuple slots for old and new tuples. Note that even when the
2985 * tuples are the same, the tupDescs might not be (consider ADD COLUMN
2986 * without a default).
2988 oldslot = MakeSingleTupleTableSlot(oldTupDesc);
2989 newslot = MakeSingleTupleTableSlot(newTupDesc);
2991 /* Preallocate values/isnull arrays */
2992 i = Max(newTupDesc->natts, oldTupDesc->natts);
2993 values = (Datum *) palloc(i * sizeof(Datum));
2994 isnull = (bool *) palloc(i * sizeof(bool));
2995 memset(values, 0, i * sizeof(Datum));
2996 memset(isnull, true, i * sizeof(bool));
2999 * Any attributes that are dropped according to the new tuple
3000 * descriptor can be set to NULL. We precompute the list of dropped
3001 * attributes to avoid needing to do so in the per-tuple loop.
3003 for (i = 0; i < newTupDesc->natts; i++)
3005 if (newTupDesc->attrs[i]->attisdropped)
3006 dropped_attrs = lappend_int(dropped_attrs, i);
3010 * Scan through the rows, generating a new row if needed and then
3011 * checking all the constraints.
3013 scan = heap_beginscan(oldrel, SnapshotNow, 0, NULL);
3016 * Switch to per-tuple memory context and reset it for each tuple
3017 * produced, so we don't leak memory.
3019 oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
3021 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
3023 if (newrel)
3025 Oid tupOid = InvalidOid;
3027 /* Extract data from old tuple */
3028 heap_deform_tuple(tuple, oldTupDesc, values, isnull);
3029 if (oldTupDesc->tdhasoid)
3030 tupOid = HeapTupleGetOid(tuple);
3032 /* Set dropped attributes to null in new tuple */
3033 foreach(lc, dropped_attrs)
3034 isnull[lfirst_int(lc)] = true;
3037 * Process supplied expressions to replace selected columns.
3038 * Expression inputs come from the old tuple.
3040 ExecStoreTuple(tuple, oldslot, InvalidBuffer, false);
3041 econtext->ecxt_scantuple = oldslot;
3043 foreach(l, tab->newvals)
3045 NewColumnValue *ex = lfirst(l);
3047 values[ex->attnum - 1] = ExecEvalExpr(ex->exprstate,
3048 econtext,
3049 &isnull[ex->attnum - 1],
3050 NULL);
3054 * Form the new tuple. Note that we don't explicitly pfree it,
3055 * since the per-tuple memory context will be reset shortly.
3057 tuple = heap_form_tuple(newTupDesc, values, isnull);
3059 /* Preserve OID, if any */
3060 if (newTupDesc->tdhasoid)
3061 HeapTupleSetOid(tuple, tupOid);
3064 /* Now check any constraints on the possibly-changed tuple */
3065 ExecStoreTuple(tuple, newslot, InvalidBuffer, false);
3066 econtext->ecxt_scantuple = newslot;
3068 foreach(l, notnull_attrs)
3070 int attn = lfirst_int(l);
3072 if (heap_attisnull(tuple, attn + 1))
3073 ereport(ERROR,
3074 (errcode(ERRCODE_NOT_NULL_VIOLATION),
3075 errmsg("column \"%s\" contains null values",
3076 NameStr(newTupDesc->attrs[attn]->attname))));
3079 foreach(l, tab->constraints)
3081 NewConstraint *con = lfirst(l);
3083 switch (con->contype)
3085 case CONSTR_CHECK:
3086 if (!ExecQual(con->qualstate, econtext, true))
3087 ereport(ERROR,
3088 (errcode(ERRCODE_CHECK_VIOLATION),
3089 errmsg("check constraint \"%s\" is violated by some row",
3090 con->name)));
3091 break;
3092 case CONSTR_FOREIGN:
3093 /* Nothing to do here */
3094 break;
3095 default:
3096 elog(ERROR, "unrecognized constraint type: %d",
3097 (int) con->contype);
3101 /* Write the tuple out to the new relation */
3102 if (newrel)
3103 simple_heap_insert(newrel, tuple);
3105 ResetExprContext(econtext);
3107 CHECK_FOR_INTERRUPTS();
3110 MemoryContextSwitchTo(oldCxt);
3111 heap_endscan(scan);
3113 ExecDropSingleTupleTableSlot(oldslot);
3114 ExecDropSingleTupleTableSlot(newslot);
3117 FreeExecutorState(estate);
3119 heap_close(oldrel, NoLock);
3120 if (newrel)
3121 heap_close(newrel, NoLock);
3125 * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
3127 static AlteredTableInfo *
3128 ATGetQueueEntry(List **wqueue, Relation rel)
3130 Oid relid = RelationGetRelid(rel);
3131 AlteredTableInfo *tab;
3132 ListCell *ltab;
3134 foreach(ltab, *wqueue)
3136 tab = (AlteredTableInfo *) lfirst(ltab);
3137 if (tab->relid == relid)
3138 return tab;
3142 * Not there, so add it. Note that we make a copy of the relation's
3143 * existing descriptor before anything interesting can happen to it.
3145 tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
3146 tab->relid = relid;
3147 tab->relkind = rel->rd_rel->relkind;
3148 tab->oldDesc = CreateTupleDescCopy(RelationGetDescr(rel));
3150 *wqueue = lappend(*wqueue, tab);
3152 return tab;
3156 * ATSimplePermissions
3158 * - Ensure that it is a relation (or possibly a view)
3159 * - Ensure this user is the owner
3160 * - Ensure that it is not a system table
3162 static void
3163 ATSimplePermissions(Relation rel, bool allowView)
3165 if (rel->rd_rel->relkind != RELKIND_RELATION)
3167 if (allowView)
3169 if (rel->rd_rel->relkind != RELKIND_VIEW)
3170 ereport(ERROR,
3171 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3172 errmsg("\"%s\" is not a table or view",
3173 RelationGetRelationName(rel))));
3175 else
3176 ereport(ERROR,
3177 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3178 errmsg("\"%s\" is not a table",
3179 RelationGetRelationName(rel))));
3182 /* Permissions checks */
3183 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3184 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3185 RelationGetRelationName(rel));
3187 if (!allowSystemTableMods && IsSystemRelation(rel))
3188 ereport(ERROR,
3189 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3190 errmsg("permission denied: \"%s\" is a system catalog",
3191 RelationGetRelationName(rel))));
3195 * ATSimplePermissionsRelationOrIndex
3197 * - Ensure that it is a relation or an index
3198 * - Ensure this user is the owner
3199 * - Ensure that it is not a system table
3201 static void
3202 ATSimplePermissionsRelationOrIndex(Relation rel)
3204 if (rel->rd_rel->relkind != RELKIND_RELATION &&
3205 rel->rd_rel->relkind != RELKIND_INDEX)
3206 ereport(ERROR,
3207 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3208 errmsg("\"%s\" is not a table or index",
3209 RelationGetRelationName(rel))));
3211 /* Permissions checks */
3212 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3213 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3214 RelationGetRelationName(rel));
3216 if (!allowSystemTableMods && IsSystemRelation(rel))
3217 ereport(ERROR,
3218 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3219 errmsg("permission denied: \"%s\" is a system catalog",
3220 RelationGetRelationName(rel))));
3224 * ATSimpleRecursion
3226 * Simple table recursion sufficient for most ALTER TABLE operations.
3227 * All direct and indirect children are processed in an unspecified order.
3228 * Note that if a child inherits from the original table via multiple
3229 * inheritance paths, it will be visited just once.
3231 static void
3232 ATSimpleRecursion(List **wqueue, Relation rel,
3233 AlterTableCmd *cmd, bool recurse)
3236 * Propagate to children if desired. Non-table relations never have
3237 * children, so no need to search in that case.
3239 if (recurse && rel->rd_rel->relkind == RELKIND_RELATION)
3241 Oid relid = RelationGetRelid(rel);
3242 ListCell *child;
3243 List *children;
3245 /* this routine is actually in the planner */
3246 children = find_all_inheritors(relid);
3249 * find_all_inheritors does the recursive search of the inheritance
3250 * hierarchy, so all we have to do is process all of the relids in the
3251 * list that it returns.
3253 foreach(child, children)
3255 Oid childrelid = lfirst_oid(child);
3256 Relation childrel;
3258 if (childrelid == relid)
3259 continue;
3260 childrel = relation_open(childrelid, AccessExclusiveLock);
3261 CheckTableNotInUse(childrel, "ALTER TABLE");
3262 ATPrepCmd(wqueue, childrel, cmd, false, true);
3263 relation_close(childrel, NoLock);
3269 * ATOneLevelRecursion
3271 * Here, we visit only direct inheritance children. It is expected that
3272 * the command's prep routine will recurse again to find indirect children.
3273 * When using this technique, a multiply-inheriting child will be visited
3274 * multiple times.
3276 static void
3277 ATOneLevelRecursion(List **wqueue, Relation rel,
3278 AlterTableCmd *cmd)
3280 Oid relid = RelationGetRelid(rel);
3281 ListCell *child;
3282 List *children;
3284 /* this routine is actually in the planner */
3285 children = find_inheritance_children(relid);
3287 foreach(child, children)
3289 Oid childrelid = lfirst_oid(child);
3290 Relation childrel;
3292 childrel = relation_open(childrelid, AccessExclusiveLock);
3293 CheckTableNotInUse(childrel, "ALTER TABLE");
3294 ATPrepCmd(wqueue, childrel, cmd, true, true);
3295 relation_close(childrel, NoLock);
3301 * find_composite_type_dependencies
3303 * Check to see if a composite type is being used as a column in some
3304 * other table (possibly nested several levels deep in composite types!).
3305 * Eventually, we'd like to propagate the check or rewrite operation
3306 * into other such tables, but for now, just error out if we find any.
3308 * Caller should provide either a table name or a type name (not both) to
3309 * report in the error message, if any.
3311 * We assume that functions and views depending on the type are not reasons
3312 * to reject the ALTER. (How safe is this really?)
3314 void
3315 find_composite_type_dependencies(Oid typeOid,
3316 const char *origTblName,
3317 const char *origTypeName)
3319 Relation depRel;
3320 ScanKeyData key[2];
3321 SysScanDesc depScan;
3322 HeapTuple depTup;
3323 Oid arrayOid;
3326 * We scan pg_depend to find those things that depend on the rowtype. (We
3327 * assume we can ignore refobjsubid for a rowtype.)
3329 depRel = heap_open(DependRelationId, AccessShareLock);
3331 ScanKeyInit(&key[0],
3332 Anum_pg_depend_refclassid,
3333 BTEqualStrategyNumber, F_OIDEQ,
3334 ObjectIdGetDatum(TypeRelationId));
3335 ScanKeyInit(&key[1],
3336 Anum_pg_depend_refobjid,
3337 BTEqualStrategyNumber, F_OIDEQ,
3338 ObjectIdGetDatum(typeOid));
3340 depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
3341 SnapshotNow, 2, key);
3343 while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
3345 Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
3346 Relation rel;
3347 Form_pg_attribute att;
3349 /* Ignore dependees that aren't user columns of relations */
3350 /* (we assume system columns are never of rowtypes) */
3351 if (pg_depend->classid != RelationRelationId ||
3352 pg_depend->objsubid <= 0)
3353 continue;
3355 rel = relation_open(pg_depend->objid, AccessShareLock);
3356 att = rel->rd_att->attrs[pg_depend->objsubid - 1];
3358 if (rel->rd_rel->relkind == RELKIND_RELATION)
3360 if (origTblName)
3361 ereport(ERROR,
3362 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3363 errmsg("cannot alter table \"%s\" because column \"%s\".\"%s\" uses its rowtype",
3364 origTblName,
3365 RelationGetRelationName(rel),
3366 NameStr(att->attname))));
3367 else
3368 ereport(ERROR,
3369 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3370 errmsg("cannot alter type \"%s\" because column \"%s\".\"%s\" uses it",
3371 origTypeName,
3372 RelationGetRelationName(rel),
3373 NameStr(att->attname))));
3375 else if (OidIsValid(rel->rd_rel->reltype))
3378 * A view or composite type itself isn't a problem, but we must
3379 * recursively check for indirect dependencies via its rowtype.
3381 find_composite_type_dependencies(rel->rd_rel->reltype,
3382 origTblName, origTypeName);
3385 relation_close(rel, AccessShareLock);
3388 systable_endscan(depScan);
3390 relation_close(depRel, AccessShareLock);
3393 * If there's an array type for the rowtype, must check for uses of it,
3394 * too.
3396 arrayOid = get_array_type(typeOid);
3397 if (OidIsValid(arrayOid))
3398 find_composite_type_dependencies(arrayOid, origTblName, origTypeName);
3403 * ALTER TABLE ADD COLUMN
3405 * Adds an additional attribute to a relation making the assumption that
3406 * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
3407 * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
3408 * AlterTableCmd's.
3410 static void
3411 ATPrepAddColumn(List **wqueue, Relation rel, bool recurse,
3412 AlterTableCmd *cmd)
3415 * Recurse to add the column to child classes, if requested.
3417 * We must recurse one level at a time, so that multiply-inheriting
3418 * children are visited the right number of times and end up with the
3419 * right attinhcount.
3421 if (recurse)
3423 AlterTableCmd *childCmd = copyObject(cmd);
3424 ColumnDef *colDefChild = (ColumnDef *) childCmd->def;
3426 /* Child should see column as singly inherited */
3427 colDefChild->inhcount = 1;
3428 colDefChild->is_local = false;
3430 ATOneLevelRecursion(wqueue, rel, childCmd);
3432 else
3435 * If we are told not to recurse, there had better not be any child
3436 * tables; else the addition would put them out of step.
3438 if (find_inheritance_children(RelationGetRelid(rel)) != NIL)
3439 ereport(ERROR,
3440 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3441 errmsg("column must be added to child tables too")));
3445 static void
3446 ATExecAddColumn(AlteredTableInfo *tab, Relation rel,
3447 ColumnDef *colDef)
3449 Oid myrelid = RelationGetRelid(rel);
3450 Relation pgclass,
3451 attrdesc;
3452 HeapTuple reltup;
3453 HeapTuple attributeTuple;
3454 Form_pg_attribute attribute;
3455 FormData_pg_attribute attributeD;
3456 int i;
3457 int minattnum,
3458 maxatts;
3459 HeapTuple typeTuple;
3460 Oid typeOid;
3461 int32 typmod;
3462 Form_pg_type tform;
3463 Expr *defval;
3465 attrdesc = heap_open(AttributeRelationId, RowExclusiveLock);
3468 * Are we adding the column to a recursion child? If so, check whether to
3469 * merge with an existing definition for the column.
3471 if (colDef->inhcount > 0)
3473 HeapTuple tuple;
3475 /* Does child already have a column by this name? */
3476 tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
3477 if (HeapTupleIsValid(tuple))
3479 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
3480 Oid ctypeId;
3481 int32 ctypmod;
3483 /* Okay if child matches by type */
3484 ctypeId = typenameTypeId(NULL, colDef->typename, &ctypmod);
3485 if (ctypeId != childatt->atttypid ||
3486 ctypmod != childatt->atttypmod)
3487 ereport(ERROR,
3488 (errcode(ERRCODE_DATATYPE_MISMATCH),
3489 errmsg("child table \"%s\" has different type for column \"%s\"",
3490 RelationGetRelationName(rel), colDef->colname)));
3492 /* Bump the existing child att's inhcount */
3493 childatt->attinhcount++;
3494 simple_heap_update(attrdesc, &tuple->t_self, tuple);
3495 CatalogUpdateIndexes(attrdesc, tuple);
3497 heap_freetuple(tuple);
3499 /* Inform the user about the merge */
3500 ereport(NOTICE,
3501 (errmsg("merging definition of column \"%s\" for child \"%s\"",
3502 colDef->colname, RelationGetRelationName(rel))));
3504 heap_close(attrdesc, RowExclusiveLock);
3505 return;
3509 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
3511 reltup = SearchSysCacheCopy(RELOID,
3512 ObjectIdGetDatum(myrelid),
3513 0, 0, 0);
3514 if (!HeapTupleIsValid(reltup))
3515 elog(ERROR, "cache lookup failed for relation %u", myrelid);
3518 * this test is deliberately not attisdropped-aware, since if one tries to
3519 * add a column matching a dropped column name, it's gonna fail anyway.
3521 if (SearchSysCacheExists(ATTNAME,
3522 ObjectIdGetDatum(myrelid),
3523 PointerGetDatum(colDef->colname),
3524 0, 0))
3525 ereport(ERROR,
3526 (errcode(ERRCODE_DUPLICATE_COLUMN),
3527 errmsg("column \"%s\" of relation \"%s\" already exists",
3528 colDef->colname, RelationGetRelationName(rel))));
3530 minattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts;
3531 maxatts = minattnum + 1;
3532 if (maxatts > MaxHeapAttributeNumber)
3533 ereport(ERROR,
3534 (errcode(ERRCODE_TOO_MANY_COLUMNS),
3535 errmsg("tables can have at most %d columns",
3536 MaxHeapAttributeNumber)));
3537 i = minattnum + 1;
3539 typeTuple = typenameType(NULL, colDef->typename, &typmod);
3540 tform = (Form_pg_type) GETSTRUCT(typeTuple);
3541 typeOid = HeapTupleGetOid(typeTuple);
3543 /* make sure datatype is legal for a column */
3544 CheckAttributeType(colDef->colname, typeOid);
3546 attributeTuple = heap_addheader(Natts_pg_attribute,
3547 false,
3548 ATTRIBUTE_TUPLE_SIZE,
3549 (void *) &attributeD);
3551 attribute = (Form_pg_attribute) GETSTRUCT(attributeTuple);
3553 attribute->attrelid = myrelid;
3554 namestrcpy(&(attribute->attname), colDef->colname);
3555 attribute->atttypid = typeOid;
3556 attribute->attstattarget = -1;
3557 attribute->attlen = tform->typlen;
3558 attribute->attcacheoff = -1;
3559 attribute->atttypmod = typmod;
3560 attribute->attnum = i;
3561 attribute->attbyval = tform->typbyval;
3562 attribute->attndims = list_length(colDef->typename->arrayBounds);
3563 attribute->attstorage = tform->typstorage;
3564 attribute->attalign = tform->typalign;
3565 attribute->attnotnull = colDef->is_not_null;
3566 attribute->atthasdef = false;
3567 attribute->attisdropped = false;
3568 attribute->attislocal = colDef->is_local;
3569 attribute->attinhcount = colDef->inhcount;
3571 ReleaseSysCache(typeTuple);
3573 simple_heap_insert(attrdesc, attributeTuple);
3575 /* Update indexes on pg_attribute */
3576 CatalogUpdateIndexes(attrdesc, attributeTuple);
3578 heap_close(attrdesc, RowExclusiveLock);
3581 * Update number of attributes in pg_class tuple
3583 ((Form_pg_class) GETSTRUCT(reltup))->relnatts = maxatts;
3585 simple_heap_update(pgclass, &reltup->t_self, reltup);
3587 /* keep catalog indexes current */
3588 CatalogUpdateIndexes(pgclass, reltup);
3590 heap_freetuple(reltup);
3592 heap_close(pgclass, RowExclusiveLock);
3594 /* Make the attribute's catalog entry visible */
3595 CommandCounterIncrement();
3598 * Store the DEFAULT, if any, in the catalogs
3600 if (colDef->raw_default)
3602 RawColumnDefault *rawEnt;
3604 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3605 rawEnt->attnum = attribute->attnum;
3606 rawEnt->raw_default = copyObject(colDef->raw_default);
3609 * This function is intended for CREATE TABLE, so it processes a
3610 * _list_ of defaults, but we just do one.
3612 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL, false, true);
3614 /* Make the additional catalog changes visible */
3615 CommandCounterIncrement();
3619 * Tell Phase 3 to fill in the default expression, if there is one.
3621 * If there is no default, Phase 3 doesn't have to do anything, because
3622 * that effectively means that the default is NULL. The heap tuple access
3623 * routines always check for attnum > # of attributes in tuple, and return
3624 * NULL if so, so without any modification of the tuple data we will get
3625 * the effect of NULL values in the new column.
3627 * An exception occurs when the new column is of a domain type: the domain
3628 * might have a NOT NULL constraint, or a check constraint that indirectly
3629 * rejects nulls. If there are any domain constraints then we construct
3630 * an explicit NULL default value that will be passed through
3631 * CoerceToDomain processing. (This is a tad inefficient, since it causes
3632 * rewriting the table which we really don't have to do, but the present
3633 * design of domain processing doesn't offer any simple way of checking
3634 * the constraints more directly.)
3636 * Note: we use build_column_default, and not just the cooked default
3637 * returned by AddRelationNewConstraints, so that the right thing happens
3638 * when a datatype's default applies.
3640 defval = (Expr *) build_column_default(rel, attribute->attnum);
3642 if (!defval && GetDomainConstraints(typeOid) != NIL)
3644 Oid baseTypeId;
3645 int32 baseTypeMod;
3647 baseTypeMod = typmod;
3648 baseTypeId = getBaseTypeAndTypmod(typeOid, &baseTypeMod);
3649 defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod);
3650 defval = (Expr *) coerce_to_target_type(NULL,
3651 (Node *) defval,
3652 baseTypeId,
3653 typeOid,
3654 typmod,
3655 COERCION_ASSIGNMENT,
3656 COERCE_IMPLICIT_CAST,
3657 -1);
3658 if (defval == NULL) /* should not happen */
3659 elog(ERROR, "failed to coerce base type to domain");
3662 if (defval)
3664 NewColumnValue *newval;
3666 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
3667 newval->attnum = attribute->attnum;
3668 newval->expr = defval;
3670 tab->newvals = lappend(tab->newvals, newval);
3674 * If the new column is NOT NULL, tell Phase 3 it needs to test that.
3676 tab->new_notnull |= colDef->is_not_null;
3679 * Add needed dependency entries for the new column.
3681 add_column_datatype_dependency(myrelid, i, attribute->atttypid);
3685 * Install a column's dependency on its datatype.
3687 static void
3688 add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
3690 ObjectAddress myself,
3691 referenced;
3693 myself.classId = RelationRelationId;
3694 myself.objectId = relid;
3695 myself.objectSubId = attnum;
3696 referenced.classId = TypeRelationId;
3697 referenced.objectId = typid;
3698 referenced.objectSubId = 0;
3699 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
3703 * ALTER TABLE ALTER COLUMN DROP NOT NULL
3705 static void
3706 ATExecDropNotNull(Relation rel, const char *colName)
3708 HeapTuple tuple;
3709 AttrNumber attnum;
3710 Relation attr_rel;
3711 List *indexoidlist;
3712 ListCell *indexoidscan;
3715 * lookup the attribute
3717 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3719 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3721 if (!HeapTupleIsValid(tuple))
3722 ereport(ERROR,
3723 (errcode(ERRCODE_UNDEFINED_COLUMN),
3724 errmsg("column \"%s\" of relation \"%s\" does not exist",
3725 colName, RelationGetRelationName(rel))));
3727 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3729 /* Prevent them from altering a system attribute */
3730 if (attnum <= 0)
3731 ereport(ERROR,
3732 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3733 errmsg("cannot alter system column \"%s\"",
3734 colName)));
3737 * Check that the attribute is not in a primary key
3740 /* Loop over all indexes on the relation */
3741 indexoidlist = RelationGetIndexList(rel);
3743 foreach(indexoidscan, indexoidlist)
3745 Oid indexoid = lfirst_oid(indexoidscan);
3746 HeapTuple indexTuple;
3747 Form_pg_index indexStruct;
3748 int i;
3750 indexTuple = SearchSysCache(INDEXRELID,
3751 ObjectIdGetDatum(indexoid),
3752 0, 0, 0);
3753 if (!HeapTupleIsValid(indexTuple))
3754 elog(ERROR, "cache lookup failed for index %u", indexoid);
3755 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
3757 /* If the index is not a primary key, skip the check */
3758 if (indexStruct->indisprimary)
3761 * Loop over each attribute in the primary key and see if it
3762 * matches the to-be-altered attribute
3764 for (i = 0; i < indexStruct->indnatts; i++)
3766 if (indexStruct->indkey.values[i] == attnum)
3767 ereport(ERROR,
3768 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3769 errmsg("column \"%s\" is in a primary key",
3770 colName)));
3774 ReleaseSysCache(indexTuple);
3777 list_free(indexoidlist);
3780 * Okay, actually perform the catalog change ... if needed
3782 if (((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3784 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = FALSE;
3786 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3788 /* keep the system catalog indexes current */
3789 CatalogUpdateIndexes(attr_rel, tuple);
3792 heap_close(attr_rel, RowExclusiveLock);
3796 * ALTER TABLE ALTER COLUMN SET NOT NULL
3798 static void
3799 ATExecSetNotNull(AlteredTableInfo *tab, Relation rel,
3800 const char *colName)
3802 HeapTuple tuple;
3803 AttrNumber attnum;
3804 Relation attr_rel;
3807 * lookup the attribute
3809 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
3811 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3813 if (!HeapTupleIsValid(tuple))
3814 ereport(ERROR,
3815 (errcode(ERRCODE_UNDEFINED_COLUMN),
3816 errmsg("column \"%s\" of relation \"%s\" does not exist",
3817 colName, RelationGetRelationName(rel))));
3819 attnum = ((Form_pg_attribute) GETSTRUCT(tuple))->attnum;
3821 /* Prevent them from altering a system attribute */
3822 if (attnum <= 0)
3823 ereport(ERROR,
3824 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3825 errmsg("cannot alter system column \"%s\"",
3826 colName)));
3829 * Okay, actually perform the catalog change ... if needed
3831 if (!((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull)
3833 ((Form_pg_attribute) GETSTRUCT(tuple))->attnotnull = TRUE;
3835 simple_heap_update(attr_rel, &tuple->t_self, tuple);
3837 /* keep the system catalog indexes current */
3838 CatalogUpdateIndexes(attr_rel, tuple);
3840 /* Tell Phase 3 it needs to test the constraint */
3841 tab->new_notnull = true;
3844 heap_close(attr_rel, RowExclusiveLock);
3848 * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
3850 static void
3851 ATExecColumnDefault(Relation rel, const char *colName,
3852 Node *newDefault)
3854 AttrNumber attnum;
3857 * get the number of the attribute
3859 attnum = get_attnum(RelationGetRelid(rel), colName);
3860 if (attnum == InvalidAttrNumber)
3861 ereport(ERROR,
3862 (errcode(ERRCODE_UNDEFINED_COLUMN),
3863 errmsg("column \"%s\" of relation \"%s\" does not exist",
3864 colName, RelationGetRelationName(rel))));
3866 /* Prevent them from altering a system attribute */
3867 if (attnum <= 0)
3868 ereport(ERROR,
3869 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3870 errmsg("cannot alter system column \"%s\"",
3871 colName)));
3874 * Remove any old default for the column. We use RESTRICT here for
3875 * safety, but at present we do not expect anything to depend on the
3876 * default.
3878 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false);
3880 if (newDefault)
3882 /* SET DEFAULT */
3883 RawColumnDefault *rawEnt;
3885 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
3886 rawEnt->attnum = attnum;
3887 rawEnt->raw_default = newDefault;
3890 * This function is intended for CREATE TABLE, so it processes a
3891 * _list_ of defaults, but we just do one.
3893 AddRelationNewConstraints(rel, list_make1(rawEnt), NIL, false, true);
3898 * ALTER TABLE ALTER COLUMN SET STATISTICS
3900 static void
3901 ATPrepSetStatistics(Relation rel, const char *colName, Node *flagValue)
3904 * We do our own permission checking because (a) we want to allow SET
3905 * STATISTICS on indexes (for expressional index columns), and (b) we want
3906 * to allow SET STATISTICS on system catalogs without requiring
3907 * allowSystemTableMods to be turned on.
3909 if (rel->rd_rel->relkind != RELKIND_RELATION &&
3910 rel->rd_rel->relkind != RELKIND_INDEX)
3911 ereport(ERROR,
3912 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3913 errmsg("\"%s\" is not a table or index",
3914 RelationGetRelationName(rel))));
3916 /* Permissions checks */
3917 if (!pg_class_ownercheck(RelationGetRelid(rel), GetUserId()))
3918 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
3919 RelationGetRelationName(rel));
3922 static void
3923 ATExecSetStatistics(Relation rel, const char *colName, Node *newValue)
3925 int newtarget;
3926 Relation attrelation;
3927 HeapTuple tuple;
3928 Form_pg_attribute attrtuple;
3930 Assert(IsA(newValue, Integer));
3931 newtarget = intVal(newValue);
3934 * Limit target to a sane range
3936 if (newtarget < -1)
3938 ereport(ERROR,
3939 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3940 errmsg("statistics target %d is too low",
3941 newtarget)));
3943 else if (newtarget > 1000)
3945 newtarget = 1000;
3946 ereport(WARNING,
3947 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3948 errmsg("lowering statistics target to %d",
3949 newtarget)));
3952 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
3954 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
3956 if (!HeapTupleIsValid(tuple))
3957 ereport(ERROR,
3958 (errcode(ERRCODE_UNDEFINED_COLUMN),
3959 errmsg("column \"%s\" of relation \"%s\" does not exist",
3960 colName, RelationGetRelationName(rel))));
3961 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
3963 if (attrtuple->attnum <= 0)
3964 ereport(ERROR,
3965 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3966 errmsg("cannot alter system column \"%s\"",
3967 colName)));
3969 attrtuple->attstattarget = newtarget;
3971 simple_heap_update(attrelation, &tuple->t_self, tuple);
3973 /* keep system catalog indexes current */
3974 CatalogUpdateIndexes(attrelation, tuple);
3976 heap_freetuple(tuple);
3978 heap_close(attrelation, RowExclusiveLock);
3982 * ALTER TABLE ALTER COLUMN SET STORAGE
3984 static void
3985 ATExecSetStorage(Relation rel, const char *colName, Node *newValue)
3987 char *storagemode;
3988 char newstorage;
3989 Relation attrelation;
3990 HeapTuple tuple;
3991 Form_pg_attribute attrtuple;
3993 Assert(IsA(newValue, String));
3994 storagemode = strVal(newValue);
3996 if (pg_strcasecmp(storagemode, "plain") == 0)
3997 newstorage = 'p';
3998 else if (pg_strcasecmp(storagemode, "external") == 0)
3999 newstorage = 'e';
4000 else if (pg_strcasecmp(storagemode, "extended") == 0)
4001 newstorage = 'x';
4002 else if (pg_strcasecmp(storagemode, "main") == 0)
4003 newstorage = 'm';
4004 else
4006 ereport(ERROR,
4007 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4008 errmsg("invalid storage type \"%s\"",
4009 storagemode)));
4010 newstorage = 0; /* keep compiler quiet */
4013 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
4015 tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
4017 if (!HeapTupleIsValid(tuple))
4018 ereport(ERROR,
4019 (errcode(ERRCODE_UNDEFINED_COLUMN),
4020 errmsg("column \"%s\" of relation \"%s\" does not exist",
4021 colName, RelationGetRelationName(rel))));
4022 attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
4024 if (attrtuple->attnum <= 0)
4025 ereport(ERROR,
4026 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4027 errmsg("cannot alter system column \"%s\"",
4028 colName)));
4031 * safety check: do not allow toasted storage modes unless column datatype
4032 * is TOAST-aware.
4034 if (newstorage == 'p' || TypeIsToastable(attrtuple->atttypid))
4035 attrtuple->attstorage = newstorage;
4036 else
4037 ereport(ERROR,
4038 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4039 errmsg("column data type %s can only have storage PLAIN",
4040 format_type_be(attrtuple->atttypid))));
4042 simple_heap_update(attrelation, &tuple->t_self, tuple);
4044 /* keep system catalog indexes current */
4045 CatalogUpdateIndexes(attrelation, tuple);
4047 heap_freetuple(tuple);
4049 heap_close(attrelation, RowExclusiveLock);
4054 * ALTER TABLE DROP COLUMN
4056 * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
4057 * because we have to decide at runtime whether to recurse or not depending
4058 * on whether attinhcount goes to zero or not. (We can't check this in a
4059 * static pre-pass because it won't handle multiple inheritance situations
4060 * correctly.) Since DROP COLUMN doesn't need to create any work queue
4061 * entries for Phase 3, it's okay to recurse internally in this routine
4062 * without considering the work queue.
4064 static void
4065 ATExecDropColumn(Relation rel, const char *colName,
4066 DropBehavior behavior,
4067 bool recurse, bool recursing)
4069 HeapTuple tuple;
4070 Form_pg_attribute targetatt;
4071 AttrNumber attnum;
4072 List *children;
4073 ObjectAddress object;
4075 /* At top level, permission check was done in ATPrepCmd, else do it */
4076 if (recursing)
4077 ATSimplePermissions(rel, false);
4080 * get the number of the attribute
4082 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
4083 if (!HeapTupleIsValid(tuple))
4084 ereport(ERROR,
4085 (errcode(ERRCODE_UNDEFINED_COLUMN),
4086 errmsg("column \"%s\" of relation \"%s\" does not exist",
4087 colName, RelationGetRelationName(rel))));
4088 targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
4090 attnum = targetatt->attnum;
4092 /* Can't drop a system attribute, except OID */
4093 if (attnum <= 0 && attnum != ObjectIdAttributeNumber)
4094 ereport(ERROR,
4095 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4096 errmsg("cannot drop system column \"%s\"",
4097 colName)));
4099 /* Don't drop inherited columns */
4100 if (targetatt->attinhcount > 0 && !recursing)
4101 ereport(ERROR,
4102 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4103 errmsg("cannot drop inherited column \"%s\"",
4104 colName)));
4106 ReleaseSysCache(tuple);
4109 * Propagate to children as appropriate. Unlike most other ALTER
4110 * routines, we have to do this one level of recursion at a time; we can't
4111 * use find_all_inheritors to do it in one pass.
4113 children = find_inheritance_children(RelationGetRelid(rel));
4115 if (children)
4117 Relation attr_rel;
4118 ListCell *child;
4120 attr_rel = heap_open(AttributeRelationId, RowExclusiveLock);
4121 foreach(child, children)
4123 Oid childrelid = lfirst_oid(child);
4124 Relation childrel;
4125 Form_pg_attribute childatt;
4127 childrel = heap_open(childrelid, AccessExclusiveLock);
4128 CheckTableNotInUse(childrel, "ALTER TABLE");
4130 tuple = SearchSysCacheCopyAttName(childrelid, colName);
4131 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
4132 elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
4133 colName, childrelid);
4134 childatt = (Form_pg_attribute) GETSTRUCT(tuple);
4136 if (childatt->attinhcount <= 0) /* shouldn't happen */
4137 elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
4138 childrelid, colName);
4140 if (recurse)
4143 * If the child column has other definition sources, just
4144 * decrement its inheritance count; if not, recurse to delete
4145 * it.
4147 if (childatt->attinhcount == 1 && !childatt->attislocal)
4149 /* Time to delete this child column, too */
4150 ATExecDropColumn(childrel, colName, behavior, true, true);
4152 else
4154 /* Child column must survive my deletion */
4155 childatt->attinhcount--;
4157 simple_heap_update(attr_rel, &tuple->t_self, tuple);
4159 /* keep the system catalog indexes current */
4160 CatalogUpdateIndexes(attr_rel, tuple);
4162 /* Make update visible */
4163 CommandCounterIncrement();
4166 else
4169 * If we were told to drop ONLY in this table (no recursion),
4170 * we need to mark the inheritors' attributes as locally
4171 * defined rather than inherited.
4173 childatt->attinhcount--;
4174 childatt->attislocal = true;
4176 simple_heap_update(attr_rel, &tuple->t_self, tuple);
4178 /* keep the system catalog indexes current */
4179 CatalogUpdateIndexes(attr_rel, tuple);
4181 /* Make update visible */
4182 CommandCounterIncrement();
4185 heap_freetuple(tuple);
4187 heap_close(childrel, NoLock);
4189 heap_close(attr_rel, RowExclusiveLock);
4193 * Perform the actual column deletion
4195 object.classId = RelationRelationId;
4196 object.objectId = RelationGetRelid(rel);
4197 object.objectSubId = attnum;
4199 performDeletion(&object, behavior);
4202 * If we dropped the OID column, must adjust pg_class.relhasoids
4204 if (attnum == ObjectIdAttributeNumber)
4206 Relation class_rel;
4207 Form_pg_class tuple_class;
4209 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
4211 tuple = SearchSysCacheCopy(RELOID,
4212 ObjectIdGetDatum(RelationGetRelid(rel)),
4213 0, 0, 0);
4214 if (!HeapTupleIsValid(tuple))
4215 elog(ERROR, "cache lookup failed for relation %u",
4216 RelationGetRelid(rel));
4217 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
4219 tuple_class->relhasoids = false;
4220 simple_heap_update(class_rel, &tuple->t_self, tuple);
4222 /* Keep the catalog indexes up to date */
4223 CatalogUpdateIndexes(class_rel, tuple);
4225 heap_close(class_rel, RowExclusiveLock);
4230 * ALTER TABLE ADD INDEX
4232 * There is no such command in the grammar, but parse_utilcmd.c converts
4233 * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands. This lets
4234 * us schedule creation of the index at the appropriate time during ALTER.
4236 static void
4237 ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
4238 IndexStmt *stmt, bool is_rebuild)
4240 bool check_rights;
4241 bool skip_build;
4242 bool quiet;
4244 Assert(IsA(stmt, IndexStmt));
4246 /* suppress schema rights check when rebuilding existing index */
4247 check_rights = !is_rebuild;
4248 /* skip index build if phase 3 will have to rewrite table anyway */
4249 skip_build = (tab->newvals != NIL);
4250 /* suppress notices when rebuilding existing index */
4251 quiet = is_rebuild;
4253 /* The IndexStmt has already been through transformIndexStmt */
4255 DefineIndex(stmt->relation, /* relation */
4256 stmt->idxname, /* index name */
4257 InvalidOid, /* no predefined OID */
4258 stmt->accessMethod, /* am name */
4259 stmt->tableSpace,
4260 stmt->indexParams, /* parameters */
4261 (Expr *) stmt->whereClause,
4262 stmt->options,
4263 stmt->unique,
4264 stmt->primary,
4265 stmt->isconstraint,
4266 true, /* is_alter_table */
4267 check_rights,
4268 skip_build,
4269 quiet,
4270 false);
4274 * ALTER TABLE ADD CONSTRAINT
4276 static void
4277 ATExecAddConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
4278 Node *newConstraint, bool recurse)
4280 switch (nodeTag(newConstraint))
4282 case T_Constraint:
4284 Constraint *constr = (Constraint *) newConstraint;
4287 * Currently, we only expect to see CONSTR_CHECK nodes
4288 * arriving here (see the preprocessing done in
4289 * parse_utilcmd.c). Use a switch anyway to make it easier to
4290 * add more code later.
4292 switch (constr->contype)
4294 case CONSTR_CHECK:
4295 ATAddCheckConstraint(wqueue, tab, rel,
4296 constr, recurse, false);
4297 break;
4298 default:
4299 elog(ERROR, "unrecognized constraint type: %d",
4300 (int) constr->contype);
4302 break;
4304 case T_FkConstraint:
4306 FkConstraint *fkconstraint = (FkConstraint *) newConstraint;
4309 * Note that we currently never recurse for FK constraints,
4310 * so the "recurse" flag is silently ignored.
4312 * Assign or validate constraint name
4314 if (fkconstraint->constr_name)
4316 if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
4317 RelationGetRelid(rel),
4318 RelationGetNamespace(rel),
4319 fkconstraint->constr_name))
4320 ereport(ERROR,
4321 (errcode(ERRCODE_DUPLICATE_OBJECT),
4322 errmsg("constraint \"%s\" for relation \"%s\" already exists",
4323 fkconstraint->constr_name,
4324 RelationGetRelationName(rel))));
4326 else
4327 fkconstraint->constr_name =
4328 ChooseConstraintName(RelationGetRelationName(rel),
4329 strVal(linitial(fkconstraint->fk_attrs)),
4330 "fkey",
4331 RelationGetNamespace(rel),
4332 NIL);
4334 ATAddForeignKeyConstraint(tab, rel, fkconstraint);
4336 break;
4338 default:
4339 elog(ERROR, "unrecognized node type: %d",
4340 (int) nodeTag(newConstraint));
4345 * Add a check constraint to a single table and its children
4347 * Subroutine for ATExecAddConstraint.
4349 * We must recurse to child tables during execution, rather than using
4350 * ALTER TABLE's normal prep-time recursion. The reason is that all the
4351 * constraints *must* be given the same name, else they won't be seen as
4352 * related later. If the user didn't explicitly specify a name, then
4353 * AddRelationNewConstraints would normally assign different names to the
4354 * child constraints. To fix that, we must capture the name assigned at
4355 * the parent table and pass that down.
4357 static void
4358 ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
4359 Constraint *constr, bool recurse, bool recursing)
4361 List *newcons;
4362 ListCell *lcon;
4363 List *children;
4364 ListCell *child;
4366 /* At top level, permission check was done in ATPrepCmd, else do it */
4367 if (recursing)
4368 ATSimplePermissions(rel, false);
4371 * Call AddRelationNewConstraints to do the work, making sure it works on
4372 * a copy of the Constraint so transformExpr can't modify the original.
4373 * It returns a list of cooked constraints.
4375 * If the constraint ends up getting merged with a pre-existing one, it's
4376 * omitted from the returned list, which is what we want: we do not need
4377 * to do any validation work. That can only happen at child tables,
4378 * though, since we disallow merging at the top level.
4380 newcons = AddRelationNewConstraints(rel, NIL,
4381 list_make1(copyObject(constr)),
4382 recursing, !recursing);
4384 /* Add each constraint to Phase 3's queue */
4385 foreach(lcon, newcons)
4387 CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
4388 NewConstraint *newcon;
4390 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
4391 newcon->name = ccon->name;
4392 newcon->contype = ccon->contype;
4393 /* ExecQual wants implicit-AND format */
4394 newcon->qual = (Node *) make_ands_implicit((Expr *) ccon->expr);
4396 tab->constraints = lappend(tab->constraints, newcon);
4398 /* Save the actually assigned name if it was defaulted */
4399 if (constr->name == NULL)
4400 constr->name = ccon->name;
4403 /* At this point we must have a locked-down name to use */
4404 Assert(constr->name != NULL);
4406 /* Advance command counter in case same table is visited multiple times */
4407 CommandCounterIncrement();
4410 * Propagate to children as appropriate. Unlike most other ALTER
4411 * routines, we have to do this one level of recursion at a time; we can't
4412 * use find_all_inheritors to do it in one pass.
4414 children = find_inheritance_children(RelationGetRelid(rel));
4417 * If we are told not to recurse, there had better not be any child
4418 * tables; else the addition would put them out of step.
4420 if (children && !recurse)
4421 ereport(ERROR,
4422 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4423 errmsg("constraint must be added to child tables too")));
4425 foreach(child, children)
4427 Oid childrelid = lfirst_oid(child);
4428 Relation childrel;
4429 AlteredTableInfo *childtab;
4431 childrel = heap_open(childrelid, AccessExclusiveLock);
4432 CheckTableNotInUse(childrel, "ALTER TABLE");
4434 /* Find or create work queue entry for this table */
4435 childtab = ATGetQueueEntry(wqueue, childrel);
4437 /* Recurse to child */
4438 ATAddCheckConstraint(wqueue, childtab, childrel,
4439 constr, recurse, true);
4441 heap_close(childrel, NoLock);
4446 * Add a foreign-key constraint to a single table
4448 * Subroutine for ATExecAddConstraint. Must already hold exclusive
4449 * lock on the rel, and have done appropriate validity/permissions checks
4450 * for it.
4452 static void
4453 ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
4454 FkConstraint *fkconstraint)
4456 Relation pkrel;
4457 AclResult aclresult;
4458 int16 pkattnum[INDEX_MAX_KEYS];
4459 int16 fkattnum[INDEX_MAX_KEYS];
4460 Oid pktypoid[INDEX_MAX_KEYS];
4461 Oid fktypoid[INDEX_MAX_KEYS];
4462 Oid opclasses[INDEX_MAX_KEYS];
4463 Oid pfeqoperators[INDEX_MAX_KEYS];
4464 Oid ppeqoperators[INDEX_MAX_KEYS];
4465 Oid ffeqoperators[INDEX_MAX_KEYS];
4466 int i;
4467 int numfks,
4468 numpks;
4469 Oid indexOid;
4470 Oid constrOid;
4473 * Grab an exclusive lock on the pk table, so that someone doesn't delete
4474 * rows out from under us. (Although a lesser lock would do for that
4475 * purpose, we'll need exclusive lock anyway to add triggers to the pk
4476 * table; trying to start with a lesser lock will just create a risk of
4477 * deadlock.)
4479 pkrel = heap_openrv(fkconstraint->pktable, AccessExclusiveLock);
4482 * Validity and permissions checks
4484 * Note: REFERENCES permissions checks are redundant with CREATE TRIGGER,
4485 * but we may as well error out sooner instead of later.
4487 if (pkrel->rd_rel->relkind != RELKIND_RELATION)
4488 ereport(ERROR,
4489 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4490 errmsg("referenced relation \"%s\" is not a table",
4491 RelationGetRelationName(pkrel))));
4493 aclresult = pg_class_aclcheck(RelationGetRelid(pkrel), GetUserId(),
4494 ACL_REFERENCES);
4495 if (aclresult != ACLCHECK_OK)
4496 aclcheck_error(aclresult, ACL_KIND_CLASS,
4497 RelationGetRelationName(pkrel));
4499 if (!allowSystemTableMods && IsSystemRelation(pkrel))
4500 ereport(ERROR,
4501 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4502 errmsg("permission denied: \"%s\" is a system catalog",
4503 RelationGetRelationName(pkrel))));
4505 aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
4506 ACL_REFERENCES);
4507 if (aclresult != ACLCHECK_OK)
4508 aclcheck_error(aclresult, ACL_KIND_CLASS,
4509 RelationGetRelationName(rel));
4512 * Disallow reference from permanent table to temp table or vice versa.
4513 * (The ban on perm->temp is for fairly obvious reasons. The ban on
4514 * temp->perm is because other backends might need to run the RI triggers
4515 * on the perm table, but they can't reliably see tuples the owning
4516 * backend has created in the temp table, because non-shared buffers are
4517 * used for temp tables.)
4519 if (isTempNamespace(RelationGetNamespace(pkrel)))
4521 if (!isTempNamespace(RelationGetNamespace(rel)))
4522 ereport(ERROR,
4523 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4524 errmsg("cannot reference temporary table from permanent table constraint")));
4526 else
4528 if (isTempNamespace(RelationGetNamespace(rel)))
4529 ereport(ERROR,
4530 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4531 errmsg("cannot reference permanent table from temporary table constraint")));
4535 * Look up the referencing attributes to make sure they exist, and record
4536 * their attnums and type OIDs.
4538 MemSet(pkattnum, 0, sizeof(pkattnum));
4539 MemSet(fkattnum, 0, sizeof(fkattnum));
4540 MemSet(pktypoid, 0, sizeof(pktypoid));
4541 MemSet(fktypoid, 0, sizeof(fktypoid));
4542 MemSet(opclasses, 0, sizeof(opclasses));
4543 MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
4544 MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
4545 MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
4547 numfks = transformColumnNameList(RelationGetRelid(rel),
4548 fkconstraint->fk_attrs,
4549 fkattnum, fktypoid);
4552 * If the attribute list for the referenced table was omitted, lookup the
4553 * definition of the primary key and use it. Otherwise, validate the
4554 * supplied attribute list. In either case, discover the index OID and
4555 * index opclasses, and the attnums and type OIDs of the attributes.
4557 if (fkconstraint->pk_attrs == NIL)
4559 numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
4560 &fkconstraint->pk_attrs,
4561 pkattnum, pktypoid,
4562 opclasses);
4564 else
4566 numpks = transformColumnNameList(RelationGetRelid(pkrel),
4567 fkconstraint->pk_attrs,
4568 pkattnum, pktypoid);
4569 /* Look for an index matching the column list */
4570 indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
4571 opclasses);
4575 * Look up the equality operators to use in the constraint.
4577 * Note that we have to be careful about the difference between the actual
4578 * PK column type and the opclass' declared input type, which might be
4579 * only binary-compatible with it. The declared opcintype is the right
4580 * thing to probe pg_amop with.
4582 if (numfks != numpks)
4583 ereport(ERROR,
4584 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4585 errmsg("number of referencing and referenced columns for foreign key disagree")));
4587 for (i = 0; i < numpks; i++)
4589 Oid pktype = pktypoid[i];
4590 Oid fktype = fktypoid[i];
4591 Oid fktyped;
4592 HeapTuple cla_ht;
4593 Form_pg_opclass cla_tup;
4594 Oid amid;
4595 Oid opfamily;
4596 Oid opcintype;
4597 Oid pfeqop;
4598 Oid ppeqop;
4599 Oid ffeqop;
4600 int16 eqstrategy;
4602 /* We need several fields out of the pg_opclass entry */
4603 cla_ht = SearchSysCache(CLAOID,
4604 ObjectIdGetDatum(opclasses[i]),
4605 0, 0, 0);
4606 if (!HeapTupleIsValid(cla_ht))
4607 elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
4608 cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
4609 amid = cla_tup->opcmethod;
4610 opfamily = cla_tup->opcfamily;
4611 opcintype = cla_tup->opcintype;
4612 ReleaseSysCache(cla_ht);
4615 * Check it's a btree; currently this can never fail since no other
4616 * index AMs support unique indexes. If we ever did have other types
4617 * of unique indexes, we'd need a way to determine which operator
4618 * strategy number is equality. (Is it reasonable to insist that
4619 * every such index AM use btree's number for equality?)
4621 if (amid != BTREE_AM_OID)
4622 elog(ERROR, "only b-tree indexes are supported for foreign keys");
4623 eqstrategy = BTEqualStrategyNumber;
4626 * There had better be a primary equality operator for the index.
4627 * We'll use it for PK = PK comparisons.
4629 ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
4630 eqstrategy);
4632 if (!OidIsValid(ppeqop))
4633 elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
4634 eqstrategy, opcintype, opcintype, opfamily);
4637 * Are there equality operators that take exactly the FK type? Assume
4638 * we should look through any domain here.
4640 fktyped = getBaseType(fktype);
4642 pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
4643 eqstrategy);
4644 if (OidIsValid(pfeqop))
4645 ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
4646 eqstrategy);
4647 else
4648 ffeqop = InvalidOid; /* keep compiler quiet */
4650 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4653 * Otherwise, look for an implicit cast from the FK type to the
4654 * opcintype, and if found, use the primary equality operator.
4655 * This is a bit tricky because opcintype might be a polymorphic
4656 * type such as ANYARRAY or ANYENUM; so what we have to test is
4657 * whether the two actual column types can be concurrently cast to
4658 * that type. (Otherwise, we'd fail to reject combinations such
4659 * as int[] and point[].)
4661 Oid input_typeids[2];
4662 Oid target_typeids[2];
4664 input_typeids[0] = pktype;
4665 input_typeids[1] = fktype;
4666 target_typeids[0] = opcintype;
4667 target_typeids[1] = opcintype;
4668 if (can_coerce_type(2, input_typeids, target_typeids,
4669 COERCION_IMPLICIT))
4670 pfeqop = ffeqop = ppeqop;
4673 if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
4674 ereport(ERROR,
4675 (errcode(ERRCODE_DATATYPE_MISMATCH),
4676 errmsg("foreign key constraint \"%s\" "
4677 "cannot be implemented",
4678 fkconstraint->constr_name),
4679 errdetail("Key columns \"%s\" and \"%s\" "
4680 "are of incompatible types: %s and %s.",
4681 strVal(list_nth(fkconstraint->fk_attrs, i)),
4682 strVal(list_nth(fkconstraint->pk_attrs, i)),
4683 format_type_be(fktype),
4684 format_type_be(pktype))));
4686 pfeqoperators[i] = pfeqop;
4687 ppeqoperators[i] = ppeqop;
4688 ffeqoperators[i] = ffeqop;
4692 * Record the FK constraint in pg_constraint.
4694 constrOid = CreateConstraintEntry(fkconstraint->constr_name,
4695 RelationGetNamespace(rel),
4696 CONSTRAINT_FOREIGN,
4697 fkconstraint->deferrable,
4698 fkconstraint->initdeferred,
4699 RelationGetRelid(rel),
4700 fkattnum,
4701 numfks,
4702 InvalidOid, /* not a domain
4703 * constraint */
4704 RelationGetRelid(pkrel),
4705 pkattnum,
4706 pfeqoperators,
4707 ppeqoperators,
4708 ffeqoperators,
4709 numpks,
4710 fkconstraint->fk_upd_action,
4711 fkconstraint->fk_del_action,
4712 fkconstraint->fk_matchtype,
4713 indexOid,
4714 NULL, /* no check constraint */
4715 NULL,
4716 NULL,
4717 true, /* islocal */
4718 0); /* inhcount */
4721 * Create the triggers that will enforce the constraint.
4723 createForeignKeyTriggers(rel, fkconstraint, constrOid);
4726 * Tell Phase 3 to check that the constraint is satisfied by existing rows
4727 * (we can skip this during table creation).
4729 if (!fkconstraint->skip_validation)
4731 NewConstraint *newcon;
4733 newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
4734 newcon->name = fkconstraint->constr_name;
4735 newcon->contype = CONSTR_FOREIGN;
4736 newcon->refrelid = RelationGetRelid(pkrel);
4737 newcon->conid = constrOid;
4738 newcon->qual = (Node *) fkconstraint;
4740 tab->constraints = lappend(tab->constraints, newcon);
4744 * Close pk table, but keep lock until we've committed.
4746 heap_close(pkrel, NoLock);
4751 * transformColumnNameList - transform list of column names
4753 * Lookup each name and return its attnum and type OID
4755 static int
4756 transformColumnNameList(Oid relId, List *colList,
4757 int16 *attnums, Oid *atttypids)
4759 ListCell *l;
4760 int attnum;
4762 attnum = 0;
4763 foreach(l, colList)
4765 char *attname = strVal(lfirst(l));
4766 HeapTuple atttuple;
4768 atttuple = SearchSysCacheAttName(relId, attname);
4769 if (!HeapTupleIsValid(atttuple))
4770 ereport(ERROR,
4771 (errcode(ERRCODE_UNDEFINED_COLUMN),
4772 errmsg("column \"%s\" referenced in foreign key constraint does not exist",
4773 attname)));
4774 if (attnum >= INDEX_MAX_KEYS)
4775 ereport(ERROR,
4776 (errcode(ERRCODE_TOO_MANY_COLUMNS),
4777 errmsg("cannot have more than %d keys in a foreign key",
4778 INDEX_MAX_KEYS)));
4779 attnums[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->attnum;
4780 atttypids[attnum] = ((Form_pg_attribute) GETSTRUCT(atttuple))->atttypid;
4781 ReleaseSysCache(atttuple);
4782 attnum++;
4785 return attnum;
4789 * transformFkeyGetPrimaryKey -
4791 * Look up the names, attnums, and types of the primary key attributes
4792 * for the pkrel. Also return the index OID and index opclasses of the
4793 * index supporting the primary key.
4795 * All parameters except pkrel are output parameters. Also, the function
4796 * return value is the number of attributes in the primary key.
4798 * Used when the column list in the REFERENCES specification is omitted.
4800 static int
4801 transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
4802 List **attnamelist,
4803 int16 *attnums, Oid *atttypids,
4804 Oid *opclasses)
4806 List *indexoidlist;
4807 ListCell *indexoidscan;
4808 HeapTuple indexTuple = NULL;
4809 Form_pg_index indexStruct = NULL;
4810 Datum indclassDatum;
4811 bool isnull;
4812 oidvector *indclass;
4813 int i;
4816 * Get the list of index OIDs for the table from the relcache, and look up
4817 * each one in the pg_index syscache until we find one marked primary key
4818 * (hopefully there isn't more than one such).
4820 *indexOid = InvalidOid;
4822 indexoidlist = RelationGetIndexList(pkrel);
4824 foreach(indexoidscan, indexoidlist)
4826 Oid indexoid = lfirst_oid(indexoidscan);
4828 indexTuple = SearchSysCache(INDEXRELID,
4829 ObjectIdGetDatum(indexoid),
4830 0, 0, 0);
4831 if (!HeapTupleIsValid(indexTuple))
4832 elog(ERROR, "cache lookup failed for index %u", indexoid);
4833 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4834 if (indexStruct->indisprimary)
4836 *indexOid = indexoid;
4837 break;
4839 ReleaseSysCache(indexTuple);
4842 list_free(indexoidlist);
4845 * Check that we found it
4847 if (!OidIsValid(*indexOid))
4848 ereport(ERROR,
4849 (errcode(ERRCODE_UNDEFINED_OBJECT),
4850 errmsg("there is no primary key for referenced table \"%s\"",
4851 RelationGetRelationName(pkrel))));
4853 /* Must get indclass the hard way */
4854 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4855 Anum_pg_index_indclass, &isnull);
4856 Assert(!isnull);
4857 indclass = (oidvector *) DatumGetPointer(indclassDatum);
4860 * Now build the list of PK attributes from the indkey definition (we
4861 * assume a primary key cannot have expressional elements)
4863 *attnamelist = NIL;
4864 for (i = 0; i < indexStruct->indnatts; i++)
4866 int pkattno = indexStruct->indkey.values[i];
4868 attnums[i] = pkattno;
4869 atttypids[i] = attnumTypeId(pkrel, pkattno);
4870 opclasses[i] = indclass->values[i];
4871 *attnamelist = lappend(*attnamelist,
4872 makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
4875 ReleaseSysCache(indexTuple);
4877 return i;
4881 * transformFkeyCheckAttrs -
4883 * Make sure that the attributes of a referenced table belong to a unique
4884 * (or primary key) constraint. Return the OID of the index supporting
4885 * the constraint, as well as the opclasses associated with the index
4886 * columns.
4888 static Oid
4889 transformFkeyCheckAttrs(Relation pkrel,
4890 int numattrs, int16 *attnums,
4891 Oid *opclasses) /* output parameter */
4893 Oid indexoid = InvalidOid;
4894 bool found = false;
4895 List *indexoidlist;
4896 ListCell *indexoidscan;
4899 * Get the list of index OIDs for the table from the relcache, and look up
4900 * each one in the pg_index syscache, and match unique indexes to the list
4901 * of attnums we are given.
4903 indexoidlist = RelationGetIndexList(pkrel);
4905 foreach(indexoidscan, indexoidlist)
4907 HeapTuple indexTuple;
4908 Form_pg_index indexStruct;
4909 int i,
4912 indexoid = lfirst_oid(indexoidscan);
4913 indexTuple = SearchSysCache(INDEXRELID,
4914 ObjectIdGetDatum(indexoid),
4915 0, 0, 0);
4916 if (!HeapTupleIsValid(indexTuple))
4917 elog(ERROR, "cache lookup failed for index %u", indexoid);
4918 indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
4921 * Must have the right number of columns; must be unique and not a
4922 * partial index; forget it if there are any expressions, too
4924 if (indexStruct->indnatts == numattrs &&
4925 indexStruct->indisunique &&
4926 heap_attisnull(indexTuple, Anum_pg_index_indpred) &&
4927 heap_attisnull(indexTuple, Anum_pg_index_indexprs))
4929 /* Must get indclass the hard way */
4930 Datum indclassDatum;
4931 bool isnull;
4932 oidvector *indclass;
4934 indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
4935 Anum_pg_index_indclass, &isnull);
4936 Assert(!isnull);
4937 indclass = (oidvector *) DatumGetPointer(indclassDatum);
4940 * The given attnum list may match the index columns in any order.
4941 * Check that each list is a subset of the other.
4943 for (i = 0; i < numattrs; i++)
4945 found = false;
4946 for (j = 0; j < numattrs; j++)
4948 if (attnums[i] == indexStruct->indkey.values[j])
4950 found = true;
4951 break;
4954 if (!found)
4955 break;
4957 if (found)
4959 for (i = 0; i < numattrs; i++)
4961 found = false;
4962 for (j = 0; j < numattrs; j++)
4964 if (attnums[j] == indexStruct->indkey.values[i])
4966 opclasses[j] = indclass->values[i];
4967 found = true;
4968 break;
4971 if (!found)
4972 break;
4976 ReleaseSysCache(indexTuple);
4977 if (found)
4978 break;
4981 if (!found)
4982 ereport(ERROR,
4983 (errcode(ERRCODE_INVALID_FOREIGN_KEY),
4984 errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
4985 RelationGetRelationName(pkrel))));
4987 list_free(indexoidlist);
4989 return indexoid;
4993 * Scan the existing rows in a table to verify they meet a proposed FK
4994 * constraint.
4996 * Caller must have opened and locked both relations.
4998 static void
4999 validateForeignKeyConstraint(FkConstraint *fkconstraint,
5000 Relation rel,
5001 Relation pkrel,
5002 Oid constraintOid)
5004 HeapScanDesc scan;
5005 HeapTuple tuple;
5006 Trigger trig;
5009 * Build a trigger call structure; we'll need it either way.
5011 MemSet(&trig, 0, sizeof(trig));
5012 trig.tgoid = InvalidOid;
5013 trig.tgname = fkconstraint->constr_name;
5014 trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
5015 trig.tgisconstraint = TRUE;
5016 trig.tgconstrrelid = RelationGetRelid(pkrel);
5017 trig.tgconstraint = constraintOid;
5018 trig.tgdeferrable = FALSE;
5019 trig.tginitdeferred = FALSE;
5020 /* we needn't fill in tgargs */
5023 * See if we can do it with a single LEFT JOIN query. A FALSE result
5024 * indicates we must proceed with the fire-the-trigger method.
5026 if (RI_Initial_Check(&trig, rel, pkrel))
5027 return;
5030 * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
5031 * if that tuple had just been inserted. If any of those fail, it should
5032 * ereport(ERROR) and that's that.
5034 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
5036 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
5038 FunctionCallInfoData fcinfo;
5039 TriggerData trigdata;
5042 * Make a call to the trigger function
5044 * No parameters are passed, but we do set a context
5046 MemSet(&fcinfo, 0, sizeof(fcinfo));
5049 * We assume RI_FKey_check_ins won't look at flinfo...
5051 trigdata.type = T_TriggerData;
5052 trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
5053 trigdata.tg_relation = rel;
5054 trigdata.tg_trigtuple = tuple;
5055 trigdata.tg_newtuple = NULL;
5056 trigdata.tg_trigger = &trig;
5057 trigdata.tg_trigtuplebuf = scan->rs_cbuf;
5058 trigdata.tg_newtuplebuf = InvalidBuffer;
5060 fcinfo.context = (Node *) &trigdata;
5062 RI_FKey_check_ins(&fcinfo);
5065 heap_endscan(scan);
5068 static void
5069 CreateFKCheckTrigger(RangeVar *myRel, FkConstraint *fkconstraint,
5070 Oid constraintOid, bool on_insert)
5072 CreateTrigStmt *fk_trigger;
5074 fk_trigger = makeNode(CreateTrigStmt);
5075 fk_trigger->trigname = fkconstraint->constr_name;
5076 fk_trigger->relation = myRel;
5077 fk_trigger->before = false;
5078 fk_trigger->row = true;
5080 /* Either ON INSERT or ON UPDATE */
5081 if (on_insert)
5083 fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
5084 fk_trigger->actions[0] = 'i';
5086 else
5088 fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
5089 fk_trigger->actions[0] = 'u';
5091 fk_trigger->actions[1] = '\0';
5093 fk_trigger->isconstraint = true;
5094 fk_trigger->deferrable = fkconstraint->deferrable;
5095 fk_trigger->initdeferred = fkconstraint->initdeferred;
5096 fk_trigger->constrrel = fkconstraint->pktable;
5097 fk_trigger->args = NIL;
5099 (void) CreateTrigger(fk_trigger, constraintOid);
5101 /* Make changes-so-far visible */
5102 CommandCounterIncrement();
5106 * Create the triggers that implement an FK constraint.
5108 static void
5109 createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
5110 Oid constraintOid)
5112 RangeVar *myRel;
5113 CreateTrigStmt *fk_trigger;
5116 * Reconstruct a RangeVar for my relation (not passed in, unfortunately).
5118 myRel = makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
5119 pstrdup(RelationGetRelationName(rel)),
5120 -1);
5122 /* Make changes-so-far visible */
5123 CommandCounterIncrement();
5126 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the CHECK
5127 * action for both INSERTs and UPDATEs on the referencing table.
5129 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, true);
5130 CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, false);
5133 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
5134 * DELETE action on the referenced table.
5136 fk_trigger = makeNode(CreateTrigStmt);
5137 fk_trigger->trigname = fkconstraint->constr_name;
5138 fk_trigger->relation = fkconstraint->pktable;
5139 fk_trigger->before = false;
5140 fk_trigger->row = true;
5141 fk_trigger->actions[0] = 'd';
5142 fk_trigger->actions[1] = '\0';
5144 fk_trigger->isconstraint = true;
5145 fk_trigger->constrrel = myRel;
5146 switch (fkconstraint->fk_del_action)
5148 case FKCONSTR_ACTION_NOACTION:
5149 fk_trigger->deferrable = fkconstraint->deferrable;
5150 fk_trigger->initdeferred = fkconstraint->initdeferred;
5151 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
5152 break;
5153 case FKCONSTR_ACTION_RESTRICT:
5154 fk_trigger->deferrable = false;
5155 fk_trigger->initdeferred = false;
5156 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
5157 break;
5158 case FKCONSTR_ACTION_CASCADE:
5159 fk_trigger->deferrable = false;
5160 fk_trigger->initdeferred = false;
5161 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
5162 break;
5163 case FKCONSTR_ACTION_SETNULL:
5164 fk_trigger->deferrable = false;
5165 fk_trigger->initdeferred = false;
5166 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
5167 break;
5168 case FKCONSTR_ACTION_SETDEFAULT:
5169 fk_trigger->deferrable = false;
5170 fk_trigger->initdeferred = false;
5171 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
5172 break;
5173 default:
5174 elog(ERROR, "unrecognized FK action type: %d",
5175 (int) fkconstraint->fk_del_action);
5176 break;
5178 fk_trigger->args = NIL;
5180 (void) CreateTrigger(fk_trigger, constraintOid);
5182 /* Make changes-so-far visible */
5183 CommandCounterIncrement();
5186 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
5187 * UPDATE action on the referenced table.
5189 fk_trigger = makeNode(CreateTrigStmt);
5190 fk_trigger->trigname = fkconstraint->constr_name;
5191 fk_trigger->relation = fkconstraint->pktable;
5192 fk_trigger->before = false;
5193 fk_trigger->row = true;
5194 fk_trigger->actions[0] = 'u';
5195 fk_trigger->actions[1] = '\0';
5196 fk_trigger->isconstraint = true;
5197 fk_trigger->constrrel = myRel;
5198 switch (fkconstraint->fk_upd_action)
5200 case FKCONSTR_ACTION_NOACTION:
5201 fk_trigger->deferrable = fkconstraint->deferrable;
5202 fk_trigger->initdeferred = fkconstraint->initdeferred;
5203 fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
5204 break;
5205 case FKCONSTR_ACTION_RESTRICT:
5206 fk_trigger->deferrable = false;
5207 fk_trigger->initdeferred = false;
5208 fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
5209 break;
5210 case FKCONSTR_ACTION_CASCADE:
5211 fk_trigger->deferrable = false;
5212 fk_trigger->initdeferred = false;
5213 fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
5214 break;
5215 case FKCONSTR_ACTION_SETNULL:
5216 fk_trigger->deferrable = false;
5217 fk_trigger->initdeferred = false;
5218 fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
5219 break;
5220 case FKCONSTR_ACTION_SETDEFAULT:
5221 fk_trigger->deferrable = false;
5222 fk_trigger->initdeferred = false;
5223 fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
5224 break;
5225 default:
5226 elog(ERROR, "unrecognized FK action type: %d",
5227 (int) fkconstraint->fk_upd_action);
5228 break;
5230 fk_trigger->args = NIL;
5232 (void) CreateTrigger(fk_trigger, constraintOid);
5236 * ALTER TABLE DROP CONSTRAINT
5238 * Like DROP COLUMN, we can't use the normal ALTER TABLE recursion mechanism.
5240 static void
5241 ATExecDropConstraint(Relation rel, const char *constrName,
5242 DropBehavior behavior,
5243 bool recurse, bool recursing)
5245 List *children;
5246 ListCell *child;
5247 Relation conrel;
5248 Form_pg_constraint con;
5249 SysScanDesc scan;
5250 ScanKeyData key;
5251 HeapTuple tuple;
5252 bool found = false;
5253 bool is_check_constraint = false;
5255 /* At top level, permission check was done in ATPrepCmd, else do it */
5256 if (recursing)
5257 ATSimplePermissions(rel, false);
5259 conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
5262 * Find and drop the target constraint
5264 ScanKeyInit(&key,
5265 Anum_pg_constraint_conrelid,
5266 BTEqualStrategyNumber, F_OIDEQ,
5267 ObjectIdGetDatum(RelationGetRelid(rel)));
5268 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
5269 true, SnapshotNow, 1, &key);
5271 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
5273 ObjectAddress conobj;
5275 con = (Form_pg_constraint) GETSTRUCT(tuple);
5277 if (strcmp(NameStr(con->conname), constrName) != 0)
5278 continue;
5280 /* Don't drop inherited constraints */
5281 if (con->coninhcount > 0 && !recursing)
5282 ereport(ERROR,
5283 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5284 errmsg("cannot drop inherited constraint \"%s\" of relation \"%s\"",
5285 constrName, RelationGetRelationName(rel))));
5287 /* Right now only CHECK constraints can be inherited */
5288 if (con->contype == CONSTRAINT_CHECK)
5289 is_check_constraint = true;
5292 * Perform the actual constraint deletion
5294 conobj.classId = ConstraintRelationId;
5295 conobj.objectId = HeapTupleGetOid(tuple);
5296 conobj.objectSubId = 0;
5298 performDeletion(&conobj, behavior);
5300 found = true;
5303 systable_endscan(scan);
5305 if (!found)
5306 ereport(ERROR,
5307 (errcode(ERRCODE_UNDEFINED_OBJECT),
5308 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
5309 constrName, RelationGetRelationName(rel))));
5312 * Propagate to children as appropriate. Unlike most other ALTER
5313 * routines, we have to do this one level of recursion at a time; we can't
5314 * use find_all_inheritors to do it in one pass.
5316 if (is_check_constraint)
5317 children = find_inheritance_children(RelationGetRelid(rel));
5318 else
5319 children = NIL;
5321 foreach(child, children)
5323 Oid childrelid = lfirst_oid(child);
5324 Relation childrel;
5326 childrel = heap_open(childrelid, AccessExclusiveLock);
5327 CheckTableNotInUse(childrel, "ALTER TABLE");
5329 ScanKeyInit(&key,
5330 Anum_pg_constraint_conrelid,
5331 BTEqualStrategyNumber, F_OIDEQ,
5332 ObjectIdGetDatum(childrelid));
5333 scan = systable_beginscan(conrel, ConstraintRelidIndexId,
5334 true, SnapshotNow, 1, &key);
5336 found = false;
5338 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
5340 HeapTuple copy_tuple;
5342 con = (Form_pg_constraint) GETSTRUCT(tuple);
5344 /* Right now only CHECK constraints can be inherited */
5345 if (con->contype != CONSTRAINT_CHECK)
5346 continue;
5348 if (strcmp(NameStr(con->conname), constrName) != 0)
5349 continue;
5351 found = true;
5353 if (con->coninhcount <= 0) /* shouldn't happen */
5354 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
5355 childrelid, constrName);
5357 copy_tuple = heap_copytuple(tuple);
5358 con = (Form_pg_constraint) GETSTRUCT(copy_tuple);
5360 if (recurse)
5363 * If the child constraint has other definition sources,
5364 * just decrement its inheritance count; if not, recurse
5365 * to delete it.
5367 if (con->coninhcount == 1 && !con->conislocal)
5369 /* Time to delete this child constraint, too */
5370 ATExecDropConstraint(childrel, constrName, behavior,
5371 true, true);
5373 else
5375 /* Child constraint must survive my deletion */
5376 con->coninhcount--;
5377 simple_heap_update(conrel, &copy_tuple->t_self, copy_tuple);
5378 CatalogUpdateIndexes(conrel, copy_tuple);
5380 /* Make update visible */
5381 CommandCounterIncrement();
5384 else
5387 * If we were told to drop ONLY in this table (no
5388 * recursion), we need to mark the inheritors' constraints
5389 * as locally defined rather than inherited.
5391 con->coninhcount--;
5392 con->conislocal = true;
5394 simple_heap_update(conrel, &copy_tuple->t_self, copy_tuple);
5395 CatalogUpdateIndexes(conrel, copy_tuple);
5397 /* Make update visible */
5398 CommandCounterIncrement();
5401 heap_freetuple(copy_tuple);
5404 systable_endscan(scan);
5406 if (!found)
5407 ereport(ERROR,
5408 (errcode(ERRCODE_UNDEFINED_OBJECT),
5409 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
5410 constrName,
5411 RelationGetRelationName(childrel))));
5413 heap_close(childrel, NoLock);
5416 heap_close(conrel, RowExclusiveLock);
5420 * ALTER COLUMN TYPE
5422 static void
5423 ATPrepAlterColumnType(List **wqueue,
5424 AlteredTableInfo *tab, Relation rel,
5425 bool recurse, bool recursing,
5426 AlterTableCmd *cmd)
5428 char *colName = cmd->name;
5429 TypeName *typename = (TypeName *) cmd->def;
5430 HeapTuple tuple;
5431 Form_pg_attribute attTup;
5432 AttrNumber attnum;
5433 Oid targettype;
5434 int32 targettypmod;
5435 Node *transform;
5436 NewColumnValue *newval;
5437 ParseState *pstate = make_parsestate(NULL);
5439 /* lookup the attribute so we can check inheritance status */
5440 tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
5441 if (!HeapTupleIsValid(tuple))
5442 ereport(ERROR,
5443 (errcode(ERRCODE_UNDEFINED_COLUMN),
5444 errmsg("column \"%s\" of relation \"%s\" does not exist",
5445 colName, RelationGetRelationName(rel))));
5446 attTup = (Form_pg_attribute) GETSTRUCT(tuple);
5447 attnum = attTup->attnum;
5449 /* Can't alter a system attribute */
5450 if (attnum <= 0)
5451 ereport(ERROR,
5452 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5453 errmsg("cannot alter system column \"%s\"",
5454 colName)));
5456 /* Don't alter inherited columns */
5457 if (attTup->attinhcount > 0 && !recursing)
5458 ereport(ERROR,
5459 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5460 errmsg("cannot alter inherited column \"%s\"",
5461 colName)));
5463 /* Look up the target type */
5464 targettype = typenameTypeId(NULL, typename, &targettypmod);
5466 /* make sure datatype is legal for a column */
5467 CheckAttributeType(colName, targettype);
5470 * Set up an expression to transform the old data value to the new type.
5471 * If a USING option was given, transform and use that expression, else
5472 * just take the old value and try to coerce it. We do this first so that
5473 * type incompatibility can be detected before we waste effort, and
5474 * because we need the expression to be parsed against the original table
5475 * rowtype.
5477 if (cmd->transform)
5479 RangeTblEntry *rte;
5481 /* Expression must be able to access vars of old table */
5482 rte = addRangeTableEntryForRelation(pstate,
5483 rel,
5484 NULL,
5485 false,
5486 true);
5487 addRTEtoQuery(pstate, rte, false, true, true);
5489 transform = transformExpr(pstate, cmd->transform);
5491 /* It can't return a set */
5492 if (expression_returns_set(transform))
5493 ereport(ERROR,
5494 (errcode(ERRCODE_DATATYPE_MISMATCH),
5495 errmsg("transform expression must not return a set")));
5497 /* No subplans or aggregates, either... */
5498 if (pstate->p_hasSubLinks)
5499 ereport(ERROR,
5500 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5501 errmsg("cannot use subquery in transform expression")));
5502 if (pstate->p_hasAggs)
5503 ereport(ERROR,
5504 (errcode(ERRCODE_GROUPING_ERROR),
5505 errmsg("cannot use aggregate function in transform expression")));
5507 else
5509 transform = (Node *) makeVar(1, attnum,
5510 attTup->atttypid, attTup->atttypmod,
5514 transform = coerce_to_target_type(pstate,
5515 transform, exprType(transform),
5516 targettype, targettypmod,
5517 COERCION_ASSIGNMENT,
5518 COERCE_IMPLICIT_CAST,
5519 -1);
5520 if (transform == NULL)
5521 ereport(ERROR,
5522 (errcode(ERRCODE_DATATYPE_MISMATCH),
5523 errmsg("column \"%s\" cannot be cast to type \"%s\"",
5524 colName, TypeNameToString(typename))));
5527 * Add a work queue item to make ATRewriteTable update the column
5528 * contents.
5530 newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
5531 newval->attnum = attnum;
5532 newval->expr = (Expr *) transform;
5534 tab->newvals = lappend(tab->newvals, newval);
5536 ReleaseSysCache(tuple);
5539 * The recursion case is handled by ATSimpleRecursion. However, if we are
5540 * told not to recurse, there had better not be any child tables; else the
5541 * alter would put them out of step.
5543 if (recurse)
5544 ATSimpleRecursion(wqueue, rel, cmd, recurse);
5545 else if (!recursing &&
5546 find_inheritance_children(RelationGetRelid(rel)) != NIL)
5547 ereport(ERROR,
5548 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5549 errmsg("type of inherited column \"%s\" must be changed in child tables too",
5550 colName)));
5553 static void
5554 ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
5555 const char *colName, TypeName *typename)
5557 HeapTuple heapTup;
5558 Form_pg_attribute attTup;
5559 AttrNumber attnum;
5560 HeapTuple typeTuple;
5561 Form_pg_type tform;
5562 Oid targettype;
5563 int32 targettypmod;
5564 Node *defaultexpr;
5565 Relation attrelation;
5566 Relation depRel;
5567 ScanKeyData key[3];
5568 SysScanDesc scan;
5569 HeapTuple depTup;
5571 attrelation = heap_open(AttributeRelationId, RowExclusiveLock);
5573 /* Look up the target column */
5574 heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5575 if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
5576 ereport(ERROR,
5577 (errcode(ERRCODE_UNDEFINED_COLUMN),
5578 errmsg("column \"%s\" of relation \"%s\" does not exist",
5579 colName, RelationGetRelationName(rel))));
5580 attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
5581 attnum = attTup->attnum;
5583 /* Check for multiple ALTER TYPE on same column --- can't cope */
5584 if (attTup->atttypid != tab->oldDesc->attrs[attnum - 1]->atttypid ||
5585 attTup->atttypmod != tab->oldDesc->attrs[attnum - 1]->atttypmod)
5586 ereport(ERROR,
5587 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5588 errmsg("cannot alter type of column \"%s\" twice",
5589 colName)));
5591 /* Look up the target type (should not fail, since prep found it) */
5592 typeTuple = typenameType(NULL, typename, &targettypmod);
5593 tform = (Form_pg_type) GETSTRUCT(typeTuple);
5594 targettype = HeapTupleGetOid(typeTuple);
5597 * If there is a default expression for the column, get it and ensure we
5598 * can coerce it to the new datatype. (We must do this before changing
5599 * the column type, because build_column_default itself will try to
5600 * coerce, and will not issue the error message we want if it fails.)
5602 * We remove any implicit coercion steps at the top level of the old
5603 * default expression; this has been agreed to satisfy the principle of
5604 * least surprise. (The conversion to the new column type should act like
5605 * it started from what the user sees as the stored expression, and the
5606 * implicit coercions aren't going to be shown.)
5608 if (attTup->atthasdef)
5610 defaultexpr = build_column_default(rel, attnum);
5611 Assert(defaultexpr);
5612 defaultexpr = strip_implicit_coercions(defaultexpr);
5613 defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
5614 defaultexpr, exprType(defaultexpr),
5615 targettype, targettypmod,
5616 COERCION_ASSIGNMENT,
5617 COERCE_IMPLICIT_CAST,
5618 -1);
5619 if (defaultexpr == NULL)
5620 ereport(ERROR,
5621 (errcode(ERRCODE_DATATYPE_MISMATCH),
5622 errmsg("default for column \"%s\" cannot be cast to type \"%s\"",
5623 colName, TypeNameToString(typename))));
5625 else
5626 defaultexpr = NULL;
5629 * Find everything that depends on the column (constraints, indexes, etc),
5630 * and record enough information to let us recreate the objects.
5632 * The actual recreation does not happen here, but only after we have
5633 * performed all the individual ALTER TYPE operations. We have to save
5634 * the info before executing ALTER TYPE, though, else the deparser will
5635 * get confused.
5637 * There could be multiple entries for the same object, so we must check
5638 * to ensure we process each one only once. Note: we assume that an index
5639 * that implements a constraint will not show a direct dependency on the
5640 * column.
5642 depRel = heap_open(DependRelationId, RowExclusiveLock);
5644 ScanKeyInit(&key[0],
5645 Anum_pg_depend_refclassid,
5646 BTEqualStrategyNumber, F_OIDEQ,
5647 ObjectIdGetDatum(RelationRelationId));
5648 ScanKeyInit(&key[1],
5649 Anum_pg_depend_refobjid,
5650 BTEqualStrategyNumber, F_OIDEQ,
5651 ObjectIdGetDatum(RelationGetRelid(rel)));
5652 ScanKeyInit(&key[2],
5653 Anum_pg_depend_refobjsubid,
5654 BTEqualStrategyNumber, F_INT4EQ,
5655 Int32GetDatum((int32) attnum));
5657 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
5658 SnapshotNow, 3, key);
5660 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5662 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5663 ObjectAddress foundObject;
5665 /* We don't expect any PIN dependencies on columns */
5666 if (foundDep->deptype == DEPENDENCY_PIN)
5667 elog(ERROR, "cannot alter type of a pinned column");
5669 foundObject.classId = foundDep->classid;
5670 foundObject.objectId = foundDep->objid;
5671 foundObject.objectSubId = foundDep->objsubid;
5673 switch (getObjectClass(&foundObject))
5675 case OCLASS_CLASS:
5677 char relKind = get_rel_relkind(foundObject.objectId);
5679 if (relKind == RELKIND_INDEX)
5681 Assert(foundObject.objectSubId == 0);
5682 if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
5684 tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
5685 foundObject.objectId);
5686 tab->changedIndexDefs = lappend(tab->changedIndexDefs,
5687 pg_get_indexdef_string(foundObject.objectId));
5690 else if (relKind == RELKIND_SEQUENCE)
5693 * This must be a SERIAL column's sequence. We need
5694 * not do anything to it.
5696 Assert(foundObject.objectSubId == 0);
5698 else
5700 /* Not expecting any other direct dependencies... */
5701 elog(ERROR, "unexpected object depending on column: %s",
5702 getObjectDescription(&foundObject));
5704 break;
5707 case OCLASS_CONSTRAINT:
5708 Assert(foundObject.objectSubId == 0);
5709 if (!list_member_oid(tab->changedConstraintOids,
5710 foundObject.objectId))
5712 char *defstring = pg_get_constraintdef_string(foundObject.objectId);
5715 * Put NORMAL dependencies at the front of the list and
5716 * AUTO dependencies at the back. This makes sure that
5717 * foreign-key constraints depending on this column will
5718 * be dropped before unique or primary-key constraints of
5719 * the column; which we must have because the FK
5720 * constraints depend on the indexes belonging to the
5721 * unique constraints.
5723 if (foundDep->deptype == DEPENDENCY_NORMAL)
5725 tab->changedConstraintOids =
5726 lcons_oid(foundObject.objectId,
5727 tab->changedConstraintOids);
5728 tab->changedConstraintDefs =
5729 lcons(defstring,
5730 tab->changedConstraintDefs);
5732 else
5734 tab->changedConstraintOids =
5735 lappend_oid(tab->changedConstraintOids,
5736 foundObject.objectId);
5737 tab->changedConstraintDefs =
5738 lappend(tab->changedConstraintDefs,
5739 defstring);
5742 break;
5744 case OCLASS_REWRITE:
5745 /* XXX someday see if we can cope with revising views */
5746 ereport(ERROR,
5747 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5748 errmsg("cannot alter type of a column used by a view or rule"),
5749 errdetail("%s depends on column \"%s\"",
5750 getObjectDescription(&foundObject),
5751 colName)));
5752 break;
5754 case OCLASS_DEFAULT:
5757 * Ignore the column's default expression, since we will fix
5758 * it below.
5760 Assert(defaultexpr);
5761 break;
5763 case OCLASS_PROC:
5764 case OCLASS_TYPE:
5765 case OCLASS_CAST:
5766 case OCLASS_CONVERSION:
5767 case OCLASS_LANGUAGE:
5768 case OCLASS_OPERATOR:
5769 case OCLASS_OPCLASS:
5770 case OCLASS_OPFAMILY:
5771 case OCLASS_TRIGGER:
5772 case OCLASS_SCHEMA:
5773 case OCLASS_TSPARSER:
5774 case OCLASS_TSDICT:
5775 case OCLASS_TSTEMPLATE:
5776 case OCLASS_TSCONFIG:
5779 * We don't expect any of these sorts of objects to depend on
5780 * a column.
5782 elog(ERROR, "unexpected object depending on column: %s",
5783 getObjectDescription(&foundObject));
5784 break;
5786 default:
5787 elog(ERROR, "unrecognized object class: %u",
5788 foundObject.classId);
5792 systable_endscan(scan);
5795 * Now scan for dependencies of this column on other things. The only
5796 * thing we should find is the dependency on the column datatype, which we
5797 * want to remove.
5799 ScanKeyInit(&key[0],
5800 Anum_pg_depend_classid,
5801 BTEqualStrategyNumber, F_OIDEQ,
5802 ObjectIdGetDatum(RelationRelationId));
5803 ScanKeyInit(&key[1],
5804 Anum_pg_depend_objid,
5805 BTEqualStrategyNumber, F_OIDEQ,
5806 ObjectIdGetDatum(RelationGetRelid(rel)));
5807 ScanKeyInit(&key[2],
5808 Anum_pg_depend_objsubid,
5809 BTEqualStrategyNumber, F_INT4EQ,
5810 Int32GetDatum((int32) attnum));
5812 scan = systable_beginscan(depRel, DependDependerIndexId, true,
5813 SnapshotNow, 3, key);
5815 while (HeapTupleIsValid(depTup = systable_getnext(scan)))
5817 Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
5819 if (foundDep->deptype != DEPENDENCY_NORMAL)
5820 elog(ERROR, "found unexpected dependency type '%c'",
5821 foundDep->deptype);
5822 if (foundDep->refclassid != TypeRelationId ||
5823 foundDep->refobjid != attTup->atttypid)
5824 elog(ERROR, "found unexpected dependency for column");
5826 simple_heap_delete(depRel, &depTup->t_self);
5829 systable_endscan(scan);
5831 heap_close(depRel, RowExclusiveLock);
5834 * Here we go --- change the recorded column type. (Note heapTup is a
5835 * copy of the syscache entry, so okay to scribble on.)
5837 attTup->atttypid = targettype;
5838 attTup->atttypmod = targettypmod;
5839 attTup->attndims = list_length(typename->arrayBounds);
5840 attTup->attlen = tform->typlen;
5841 attTup->attbyval = tform->typbyval;
5842 attTup->attalign = tform->typalign;
5843 attTup->attstorage = tform->typstorage;
5845 ReleaseSysCache(typeTuple);
5847 simple_heap_update(attrelation, &heapTup->t_self, heapTup);
5849 /* keep system catalog indexes current */
5850 CatalogUpdateIndexes(attrelation, heapTup);
5852 heap_close(attrelation, RowExclusiveLock);
5854 /* Install dependency on new datatype */
5855 add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
5858 * Drop any pg_statistic entry for the column, since it's now wrong type
5860 RemoveStatistics(RelationGetRelid(rel), attnum);
5863 * Update the default, if present, by brute force --- remove and re-add
5864 * the default. Probably unsafe to take shortcuts, since the new version
5865 * may well have additional dependencies. (It's okay to do this now,
5866 * rather than after other ALTER TYPE commands, since the default won't
5867 * depend on other column types.)
5869 if (defaultexpr)
5871 /* Must make new row visible since it will be updated again */
5872 CommandCounterIncrement();
5875 * We use RESTRICT here for safety, but at present we do not expect
5876 * anything to depend on the default.
5878 RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true);
5880 StoreAttrDefault(rel, attnum, defaultexpr);
5883 /* Cleanup */
5884 heap_freetuple(heapTup);
5888 * Cleanup after we've finished all the ALTER TYPE operations for a
5889 * particular relation. We have to drop and recreate all the indexes
5890 * and constraints that depend on the altered columns.
5892 static void
5893 ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab)
5895 ObjectAddress obj;
5896 ListCell *l;
5899 * Re-parse the index and constraint definitions, and attach them to the
5900 * appropriate work queue entries. We do this before dropping because in
5901 * the case of a FOREIGN KEY constraint, we might not yet have exclusive
5902 * lock on the table the constraint is attached to, and we need to get
5903 * that before dropping. It's safe because the parser won't actually look
5904 * at the catalogs to detect the existing entry.
5906 foreach(l, tab->changedIndexDefs)
5907 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
5908 foreach(l, tab->changedConstraintDefs)
5909 ATPostAlterTypeParse((char *) lfirst(l), wqueue);
5912 * Now we can drop the existing constraints and indexes --- constraints
5913 * first, since some of them might depend on the indexes. In fact, we
5914 * have to delete FOREIGN KEY constraints before UNIQUE constraints, but
5915 * we already ordered the constraint list to ensure that would happen. It
5916 * should be okay to use DROP_RESTRICT here, since nothing else should be
5917 * depending on these objects.
5919 foreach(l, tab->changedConstraintOids)
5921 obj.classId = ConstraintRelationId;
5922 obj.objectId = lfirst_oid(l);
5923 obj.objectSubId = 0;
5924 performDeletion(&obj, DROP_RESTRICT);
5927 foreach(l, tab->changedIndexOids)
5929 obj.classId = RelationRelationId;
5930 obj.objectId = lfirst_oid(l);
5931 obj.objectSubId = 0;
5932 performDeletion(&obj, DROP_RESTRICT);
5936 * The objects will get recreated during subsequent passes over the work
5937 * queue.
5941 static void
5942 ATPostAlterTypeParse(char *cmd, List **wqueue)
5944 List *raw_parsetree_list;
5945 List *querytree_list;
5946 ListCell *list_item;
5949 * We expect that we will get only ALTER TABLE and CREATE INDEX
5950 * statements. Hence, there is no need to pass them through
5951 * parse_analyze() or the rewriter, but instead we need to pass them
5952 * through parse_utilcmd.c to make them ready for execution.
5954 raw_parsetree_list = raw_parser(cmd);
5955 querytree_list = NIL;
5956 foreach(list_item, raw_parsetree_list)
5958 Node *stmt = (Node *) lfirst(list_item);
5960 if (IsA(stmt, IndexStmt))
5961 querytree_list = lappend(querytree_list,
5962 transformIndexStmt((IndexStmt *) stmt,
5963 cmd));
5964 else if (IsA(stmt, AlterTableStmt))
5965 querytree_list = list_concat(querytree_list,
5966 transformAlterTableStmt((AlterTableStmt *) stmt,
5967 cmd));
5968 else
5969 querytree_list = lappend(querytree_list, stmt);
5973 * Attach each generated command to the proper place in the work queue.
5974 * Note this could result in creation of entirely new work-queue entries.
5976 foreach(list_item, querytree_list)
5978 Node *stm = (Node *) lfirst(list_item);
5979 Relation rel;
5980 AlteredTableInfo *tab;
5982 switch (nodeTag(stm))
5984 case T_IndexStmt:
5986 IndexStmt *stmt = (IndexStmt *) stm;
5987 AlterTableCmd *newcmd;
5989 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
5990 tab = ATGetQueueEntry(wqueue, rel);
5991 newcmd = makeNode(AlterTableCmd);
5992 newcmd->subtype = AT_ReAddIndex;
5993 newcmd->def = (Node *) stmt;
5994 tab->subcmds[AT_PASS_OLD_INDEX] =
5995 lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
5996 relation_close(rel, NoLock);
5997 break;
5999 case T_AlterTableStmt:
6001 AlterTableStmt *stmt = (AlterTableStmt *) stm;
6002 ListCell *lcmd;
6004 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
6005 tab = ATGetQueueEntry(wqueue, rel);
6006 foreach(lcmd, stmt->cmds)
6008 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
6010 switch (cmd->subtype)
6012 case AT_AddIndex:
6013 cmd->subtype = AT_ReAddIndex;
6014 tab->subcmds[AT_PASS_OLD_INDEX] =
6015 lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
6016 break;
6017 case AT_AddConstraint:
6018 tab->subcmds[AT_PASS_OLD_CONSTR] =
6019 lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
6020 break;
6021 default:
6022 elog(ERROR, "unexpected statement type: %d",
6023 (int) cmd->subtype);
6026 relation_close(rel, NoLock);
6027 break;
6029 default:
6030 elog(ERROR, "unexpected statement type: %d",
6031 (int) nodeTag(stm));
6038 * ALTER TABLE OWNER
6040 * recursing is true if we are recursing from a table to its indexes,
6041 * sequences, or toast table. We don't allow the ownership of those things to
6042 * be changed separately from the parent table. Also, we can skip permission
6043 * checks (this is necessary not just an optimization, else we'd fail to
6044 * handle toast tables properly).
6046 * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
6047 * free-standing composite type.
6049 void
6050 ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing)
6052 Relation target_rel;
6053 Relation class_rel;
6054 HeapTuple tuple;
6055 Form_pg_class tuple_class;
6058 * Get exclusive lock till end of transaction on the target table. Use
6059 * relation_open so that we can work on indexes and sequences.
6061 target_rel = relation_open(relationOid, AccessExclusiveLock);
6063 /* Get its pg_class tuple, too */
6064 class_rel = heap_open(RelationRelationId, RowExclusiveLock);
6066 tuple = SearchSysCache(RELOID,
6067 ObjectIdGetDatum(relationOid),
6068 0, 0, 0);
6069 if (!HeapTupleIsValid(tuple))
6070 elog(ERROR, "cache lookup failed for relation %u", relationOid);
6071 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
6073 /* Can we change the ownership of this tuple? */
6074 switch (tuple_class->relkind)
6076 case RELKIND_RELATION:
6077 case RELKIND_VIEW:
6078 /* ok to change owner */
6079 break;
6080 case RELKIND_INDEX:
6081 if (!recursing)
6084 * Because ALTER INDEX OWNER used to be allowed, and in fact
6085 * is generated by old versions of pg_dump, we give a warning
6086 * and do nothing rather than erroring out. Also, to avoid
6087 * unnecessary chatter while restoring those old dumps, say
6088 * nothing at all if the command would be a no-op anyway.
6090 if (tuple_class->relowner != newOwnerId)
6091 ereport(WARNING,
6092 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6093 errmsg("cannot change owner of index \"%s\"",
6094 NameStr(tuple_class->relname)),
6095 errhint("Change the ownership of the index's table, instead.")));
6096 /* quick hack to exit via the no-op path */
6097 newOwnerId = tuple_class->relowner;
6099 break;
6100 case RELKIND_SEQUENCE:
6101 if (!recursing &&
6102 tuple_class->relowner != newOwnerId)
6104 /* if it's an owned sequence, disallow changing it by itself */
6105 Oid tableId;
6106 int32 colId;
6108 if (sequenceIsOwned(relationOid, &tableId, &colId))
6109 ereport(ERROR,
6110 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6111 errmsg("cannot change owner of sequence \"%s\"",
6112 NameStr(tuple_class->relname)),
6113 errdetail("Sequence \"%s\" is linked to table \"%s\".",
6114 NameStr(tuple_class->relname),
6115 get_rel_name(tableId))));
6117 break;
6118 case RELKIND_COMPOSITE_TYPE:
6119 if (recursing)
6120 break;
6121 ereport(ERROR,
6122 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6123 errmsg("\"%s\" is a composite type",
6124 NameStr(tuple_class->relname)),
6125 errhint("Use ALTER TYPE instead.")));
6126 break;
6127 case RELKIND_TOASTVALUE:
6128 if (recursing)
6129 break;
6130 /* FALL THRU */
6131 default:
6132 ereport(ERROR,
6133 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6134 errmsg("\"%s\" is not a table, view, or sequence",
6135 NameStr(tuple_class->relname))));
6139 * If the new owner is the same as the existing owner, consider the
6140 * command to have succeeded. This is for dump restoration purposes.
6142 if (tuple_class->relowner != newOwnerId)
6144 Datum repl_val[Natts_pg_class];
6145 char repl_null[Natts_pg_class];
6146 char repl_repl[Natts_pg_class];
6147 Acl *newAcl;
6148 Datum aclDatum;
6149 bool isNull;
6150 HeapTuple newtuple;
6152 /* skip permission checks when recursing to index or toast table */
6153 if (!recursing)
6155 /* Superusers can always do it */
6156 if (!superuser())
6158 Oid namespaceOid = tuple_class->relnamespace;
6159 AclResult aclresult;
6161 /* Otherwise, must be owner of the existing object */
6162 if (!pg_class_ownercheck(relationOid, GetUserId()))
6163 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
6164 RelationGetRelationName(target_rel));
6166 /* Must be able to become new owner */
6167 check_is_member_of_role(GetUserId(), newOwnerId);
6169 /* New owner must have CREATE privilege on namespace */
6170 aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
6171 ACL_CREATE);
6172 if (aclresult != ACLCHECK_OK)
6173 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
6174 get_namespace_name(namespaceOid));
6178 memset(repl_null, ' ', sizeof(repl_null));
6179 memset(repl_repl, ' ', sizeof(repl_repl));
6181 repl_repl[Anum_pg_class_relowner - 1] = 'r';
6182 repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
6185 * Determine the modified ACL for the new owner. This is only
6186 * necessary when the ACL is non-null.
6188 aclDatum = SysCacheGetAttr(RELOID, tuple,
6189 Anum_pg_class_relacl,
6190 &isNull);
6191 if (!isNull)
6193 newAcl = aclnewowner(DatumGetAclP(aclDatum),
6194 tuple_class->relowner, newOwnerId);
6195 repl_repl[Anum_pg_class_relacl - 1] = 'r';
6196 repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
6199 newtuple = heap_modifytuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
6201 simple_heap_update(class_rel, &newtuple->t_self, newtuple);
6202 CatalogUpdateIndexes(class_rel, newtuple);
6204 heap_freetuple(newtuple);
6207 * Update owner dependency reference, if any. A composite type has
6208 * none, because it's tracked for the pg_type entry instead of here;
6209 * indexes and TOAST tables don't have their own entries either.
6211 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
6212 tuple_class->relkind != RELKIND_INDEX &&
6213 tuple_class->relkind != RELKIND_TOASTVALUE)
6214 changeDependencyOnOwner(RelationRelationId, relationOid,
6215 newOwnerId);
6218 * Also change the ownership of the table's rowtype, if it has one
6220 if (tuple_class->relkind != RELKIND_INDEX)
6221 AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId,
6222 tuple_class->relkind == RELKIND_COMPOSITE_TYPE);
6225 * If we are operating on a table, also change the ownership of any
6226 * indexes and sequences that belong to the table, as well as the
6227 * table's toast table (if it has one)
6229 if (tuple_class->relkind == RELKIND_RELATION ||
6230 tuple_class->relkind == RELKIND_TOASTVALUE)
6232 List *index_oid_list;
6233 ListCell *i;
6235 /* Find all the indexes belonging to this relation */
6236 index_oid_list = RelationGetIndexList(target_rel);
6238 /* For each index, recursively change its ownership */
6239 foreach(i, index_oid_list)
6240 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true);
6242 list_free(index_oid_list);
6245 if (tuple_class->relkind == RELKIND_RELATION)
6247 /* If it has a toast table, recurse to change its ownership */
6248 if (tuple_class->reltoastrelid != InvalidOid)
6249 ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
6250 true);
6252 /* If it has dependent sequences, recurse to change them too */
6253 change_owner_recurse_to_sequences(relationOid, newOwnerId);
6257 ReleaseSysCache(tuple);
6258 heap_close(class_rel, RowExclusiveLock);
6259 relation_close(target_rel, NoLock);
6263 * change_owner_recurse_to_sequences
6265 * Helper function for ATExecChangeOwner. Examines pg_depend searching
6266 * for sequences that are dependent on serial columns, and changes their
6267 * ownership.
6269 static void
6270 change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId)
6272 Relation depRel;
6273 SysScanDesc scan;
6274 ScanKeyData key[2];
6275 HeapTuple tup;
6278 * SERIAL sequences are those having an auto dependency on one of the
6279 * table's columns (we don't care *which* column, exactly).
6281 depRel = heap_open(DependRelationId, AccessShareLock);
6283 ScanKeyInit(&key[0],
6284 Anum_pg_depend_refclassid,
6285 BTEqualStrategyNumber, F_OIDEQ,
6286 ObjectIdGetDatum(RelationRelationId));
6287 ScanKeyInit(&key[1],
6288 Anum_pg_depend_refobjid,
6289 BTEqualStrategyNumber, F_OIDEQ,
6290 ObjectIdGetDatum(relationOid));
6291 /* we leave refobjsubid unspecified */
6293 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
6294 SnapshotNow, 2, key);
6296 while (HeapTupleIsValid(tup = systable_getnext(scan)))
6298 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
6299 Relation seqRel;
6301 /* skip dependencies other than auto dependencies on columns */
6302 if (depForm->refobjsubid == 0 ||
6303 depForm->classid != RelationRelationId ||
6304 depForm->objsubid != 0 ||
6305 depForm->deptype != DEPENDENCY_AUTO)
6306 continue;
6308 /* Use relation_open just in case it's an index */
6309 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
6311 /* skip non-sequence relations */
6312 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
6314 /* No need to keep the lock */
6315 relation_close(seqRel, AccessExclusiveLock);
6316 continue;
6319 /* We don't need to close the sequence while we alter it. */
6320 ATExecChangeOwner(depForm->objid, newOwnerId, true);
6322 /* Now we can close it. Keep the lock till end of transaction. */
6323 relation_close(seqRel, NoLock);
6326 systable_endscan(scan);
6328 relation_close(depRel, AccessShareLock);
6332 * ALTER TABLE CLUSTER ON
6334 * The only thing we have to do is to change the indisclustered bits.
6336 static void
6337 ATExecClusterOn(Relation rel, const char *indexName)
6339 Oid indexOid;
6341 indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
6343 if (!OidIsValid(indexOid))
6344 ereport(ERROR,
6345 (errcode(ERRCODE_UNDEFINED_OBJECT),
6346 errmsg("index \"%s\" for table \"%s\" does not exist",
6347 indexName, RelationGetRelationName(rel))));
6349 /* Check index is valid to cluster on */
6350 check_index_is_clusterable(rel, indexOid, false);
6352 /* And do the work */
6353 mark_index_clustered(rel, indexOid);
6357 * ALTER TABLE SET WITHOUT CLUSTER
6359 * We have to find any indexes on the table that have indisclustered bit
6360 * set and turn it off.
6362 static void
6363 ATExecDropCluster(Relation rel)
6365 mark_index_clustered(rel, InvalidOid);
6369 * ALTER TABLE SET TABLESPACE
6371 static void
6372 ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, char *tablespacename)
6374 Oid tablespaceId;
6375 AclResult aclresult;
6377 /* Check that the tablespace exists */
6378 tablespaceId = get_tablespace_oid(tablespacename);
6379 if (!OidIsValid(tablespaceId))
6380 ereport(ERROR,
6381 (errcode(ERRCODE_UNDEFINED_OBJECT),
6382 errmsg("tablespace \"%s\" does not exist", tablespacename)));
6384 /* Check its permissions */
6385 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(), ACL_CREATE);
6386 if (aclresult != ACLCHECK_OK)
6387 aclcheck_error(aclresult, ACL_KIND_TABLESPACE, tablespacename);
6389 /* Save info for Phase 3 to do the real work */
6390 if (OidIsValid(tab->newTableSpace))
6391 ereport(ERROR,
6392 (errcode(ERRCODE_SYNTAX_ERROR),
6393 errmsg("cannot have multiple SET TABLESPACE subcommands")));
6394 tab->newTableSpace = tablespaceId;
6398 * ALTER TABLE/INDEX SET (...) or RESET (...)
6400 static void
6401 ATExecSetRelOptions(Relation rel, List *defList, bool isReset)
6403 Oid relid;
6404 Relation pgclass;
6405 HeapTuple tuple;
6406 HeapTuple newtuple;
6407 Datum datum;
6408 bool isnull;
6409 Datum newOptions;
6410 Datum repl_val[Natts_pg_class];
6411 char repl_null[Natts_pg_class];
6412 char repl_repl[Natts_pg_class];
6414 if (defList == NIL)
6415 return; /* nothing to do */
6417 pgclass = heap_open(RelationRelationId, RowExclusiveLock);
6419 /* Get the old reloptions */
6420 relid = RelationGetRelid(rel);
6421 tuple = SearchSysCache(RELOID,
6422 ObjectIdGetDatum(relid),
6423 0, 0, 0);
6424 if (!HeapTupleIsValid(tuple))
6425 elog(ERROR, "cache lookup failed for relation %u", relid);
6427 datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions, &isnull);
6429 /* Generate new proposed reloptions (text array) */
6430 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
6431 defList, false, isReset);
6433 /* Validate */
6434 switch (rel->rd_rel->relkind)
6436 case RELKIND_RELATION:
6437 case RELKIND_TOASTVALUE:
6438 (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
6439 break;
6440 case RELKIND_INDEX:
6441 (void) index_reloptions(rel->rd_am->amoptions, newOptions, true);
6442 break;
6443 default:
6444 ereport(ERROR,
6445 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6446 errmsg("\"%s\" is not a table, index, or TOAST table",
6447 RelationGetRelationName(rel))));
6448 break;
6452 * All we need do here is update the pg_class row; the new options will be
6453 * propagated into relcaches during post-commit cache inval.
6455 memset(repl_val, 0, sizeof(repl_val));
6456 memset(repl_null, ' ', sizeof(repl_null));
6457 memset(repl_repl, ' ', sizeof(repl_repl));
6459 if (newOptions != (Datum) 0)
6460 repl_val[Anum_pg_class_reloptions - 1] = newOptions;
6461 else
6462 repl_null[Anum_pg_class_reloptions - 1] = 'n';
6464 repl_repl[Anum_pg_class_reloptions - 1] = 'r';
6466 newtuple = heap_modifytuple(tuple, RelationGetDescr(pgclass),
6467 repl_val, repl_null, repl_repl);
6469 simple_heap_update(pgclass, &newtuple->t_self, newtuple);
6471 CatalogUpdateIndexes(pgclass, newtuple);
6473 heap_freetuple(newtuple);
6475 ReleaseSysCache(tuple);
6477 heap_close(pgclass, RowExclusiveLock);
6481 * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
6482 * rewriting to be done, so we just want to copy the data as fast as possible.
6484 static void
6485 ATExecSetTableSpace(Oid tableOid, Oid newTableSpace)
6487 Relation rel;
6488 Oid oldTableSpace;
6489 Oid reltoastrelid;
6490 Oid reltoastidxid;
6491 Oid newrelfilenode;
6492 RelFileNode newrnode;
6493 SMgrRelation dstrel;
6494 Relation pg_class;
6495 HeapTuple tuple;
6496 Form_pg_class rd_rel;
6497 ForkNumber forkNum;
6500 * Need lock here in case we are recursing to toast table or index
6502 rel = relation_open(tableOid, AccessExclusiveLock);
6505 * We can never allow moving of shared or nailed-in-cache relations,
6506 * because we can't support changing their reltablespace values.
6508 if (rel->rd_rel->relisshared || rel->rd_isnailed)
6509 ereport(ERROR,
6510 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6511 errmsg("cannot move system relation \"%s\"",
6512 RelationGetRelationName(rel))));
6514 /* Can't move a non-shared relation into pg_global */
6515 if (newTableSpace == GLOBALTABLESPACE_OID)
6516 ereport(ERROR,
6517 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6518 errmsg("only shared relations can be placed in pg_global tablespace")));
6521 * Don't allow moving temp tables of other backends ... their local buffer
6522 * manager is not going to cope.
6524 if (isOtherTempNamespace(RelationGetNamespace(rel)))
6525 ereport(ERROR,
6526 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6527 errmsg("cannot move temporary tables of other sessions")));
6530 * No work if no change in tablespace.
6532 oldTableSpace = rel->rd_rel->reltablespace;
6533 if (newTableSpace == oldTableSpace ||
6534 (newTableSpace == MyDatabaseTableSpace && oldTableSpace == 0))
6536 relation_close(rel, NoLock);
6537 return;
6540 reltoastrelid = rel->rd_rel->reltoastrelid;
6541 reltoastidxid = rel->rd_rel->reltoastidxid;
6543 /* Get a modifiable copy of the relation's pg_class row */
6544 pg_class = heap_open(RelationRelationId, RowExclusiveLock);
6546 tuple = SearchSysCacheCopy(RELOID,
6547 ObjectIdGetDatum(tableOid),
6548 0, 0, 0);
6549 if (!HeapTupleIsValid(tuple))
6550 elog(ERROR, "cache lookup failed for relation %u", tableOid);
6551 rd_rel = (Form_pg_class) GETSTRUCT(tuple);
6554 * Since we copy the file directly without looking at the shared buffers,
6555 * we'd better first flush out any pages of the source relation that are
6556 * in shared buffers. We assume no new changes will be made while we are
6557 * holding exclusive lock on the rel.
6559 FlushRelationBuffers(rel);
6562 * Relfilenodes are not unique across tablespaces, so we need to allocate
6563 * a new one in the new tablespace.
6565 newrelfilenode = GetNewRelFileNode(newTableSpace,
6566 rel->rd_rel->relisshared,
6567 NULL);
6569 /* Open old and new relation */
6570 newrnode = rel->rd_node;
6571 newrnode.relNode = newrelfilenode;
6572 newrnode.spcNode = newTableSpace;
6573 dstrel = smgropen(newrnode);
6575 RelationOpenSmgr(rel);
6578 * Create and copy all forks of the relation, and schedule unlinking
6579 * of old physical files.
6581 * NOTE: any conflict in relfilenode value will be caught in
6582 * smgrcreate() below.
6584 for (forkNum = 0; forkNum <= MAX_FORKNUM; forkNum++)
6586 if (smgrexists(rel->rd_smgr, forkNum))
6588 smgrcreate(dstrel, forkNum, rel->rd_istemp, false);
6589 copy_relation_data(rel->rd_smgr, dstrel, forkNum, rel->rd_istemp);
6591 smgrscheduleunlink(rel->rd_smgr, forkNum, rel->rd_istemp);
6595 /* Close old and new relation */
6596 smgrclose(dstrel);
6597 RelationCloseSmgr(rel);
6599 /* update the pg_class row */
6600 rd_rel->reltablespace = (newTableSpace == MyDatabaseTableSpace) ? InvalidOid : newTableSpace;
6601 rd_rel->relfilenode = newrelfilenode;
6602 simple_heap_update(pg_class, &tuple->t_self, tuple);
6603 CatalogUpdateIndexes(pg_class, tuple);
6605 heap_freetuple(tuple);
6607 heap_close(pg_class, RowExclusiveLock);
6609 relation_close(rel, NoLock);
6611 /* Make sure the reltablespace change is visible */
6612 CommandCounterIncrement();
6614 /* Move associated toast relation and/or index, too */
6615 if (OidIsValid(reltoastrelid))
6616 ATExecSetTableSpace(reltoastrelid, newTableSpace);
6617 if (OidIsValid(reltoastidxid))
6618 ATExecSetTableSpace(reltoastidxid, newTableSpace);
6622 * Copy data, block by block
6624 static void
6625 copy_relation_data(SMgrRelation src, SMgrRelation dst,
6626 ForkNumber forkNum, bool istemp)
6628 bool use_wal;
6629 BlockNumber nblocks;
6630 BlockNumber blkno;
6631 char buf[BLCKSZ];
6632 Page page = (Page) buf;
6635 * We need to log the copied data in WAL iff WAL archiving is enabled AND
6636 * it's not a temp rel.
6638 use_wal = XLogArchivingActive() && !istemp;
6640 nblocks = smgrnblocks(src, forkNum);
6642 for (blkno = 0; blkno < nblocks; blkno++)
6644 smgrread(src, forkNum, blkno, buf);
6646 /* XLOG stuff */
6647 if (use_wal)
6648 log_newpage(&dst->smgr_rnode, forkNum, blkno, page);
6651 * Now write the page. We say isTemp = true even if it's not a temp
6652 * rel, because there's no need for smgr to schedule an fsync for this
6653 * write; we'll do it ourselves below.
6655 smgrextend(dst, forkNum, blkno, buf, true);
6659 * If the rel isn't temp, we must fsync it down to disk before it's safe
6660 * to commit the transaction. (For a temp rel we don't care since the rel
6661 * will be uninteresting after a crash anyway.)
6663 * It's obvious that we must do this when not WAL-logging the copy. It's
6664 * less obvious that we have to do it even if we did WAL-log the copied
6665 * pages. The reason is that since we're copying outside shared buffers, a
6666 * CHECKPOINT occurring during the copy has no way to flush the previously
6667 * written data to disk (indeed it won't know the new rel even exists). A
6668 * crash later on would replay WAL from the checkpoint, therefore it
6669 * wouldn't replay our earlier WAL entries. If we do not fsync those pages
6670 * here, they might still not be on disk when the crash occurs.
6672 if (!istemp)
6673 smgrimmedsync(dst, forkNum);
6677 * ALTER TABLE ENABLE/DISABLE TRIGGER
6679 * We just pass this off to trigger.c.
6681 static void
6682 ATExecEnableDisableTrigger(Relation rel, char *trigname,
6683 char fires_when, bool skip_system)
6685 EnableDisableTrigger(rel, trigname, fires_when, skip_system);
6689 * ALTER TABLE ENABLE/DISABLE RULE
6691 * We just pass this off to rewriteDefine.c.
6693 static void
6694 ATExecEnableDisableRule(Relation rel, char *trigname,
6695 char fires_when)
6697 EnableDisableRule(rel, trigname, fires_when);
6701 * ALTER TABLE INHERIT
6703 * Add a parent to the child's parents. This verifies that all the columns and
6704 * check constraints of the parent appear in the child and that they have the
6705 * same data types and expressions.
6707 static void
6708 ATExecAddInherit(Relation child_rel, RangeVar *parent)
6710 Relation parent_rel,
6711 catalogRelation;
6712 SysScanDesc scan;
6713 ScanKeyData key;
6714 HeapTuple inheritsTuple;
6715 int32 inhseqno;
6716 List *children;
6719 * AccessShareLock on the parent is what's obtained during normal CREATE
6720 * TABLE ... INHERITS ..., so should be enough here.
6722 parent_rel = heap_openrv(parent, AccessShareLock);
6725 * Must be owner of both parent and child -- child was checked by
6726 * ATSimplePermissions call in ATPrepCmd
6728 ATSimplePermissions(parent_rel, false);
6730 /* Permanent rels cannot inherit from temporary ones */
6731 if (!isTempNamespace(RelationGetNamespace(child_rel)) &&
6732 isTempNamespace(RelationGetNamespace(parent_rel)))
6733 ereport(ERROR,
6734 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6735 errmsg("cannot inherit from temporary relation \"%s\"",
6736 RelationGetRelationName(parent_rel))));
6739 * Check for duplicates in the list of parents, and determine the highest
6740 * inhseqno already present; we'll use the next one for the new parent.
6741 * (Note: get RowExclusiveLock because we will write pg_inherits below.)
6743 * Note: we do not reject the case where the child already inherits from
6744 * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
6746 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
6747 ScanKeyInit(&key,
6748 Anum_pg_inherits_inhrelid,
6749 BTEqualStrategyNumber, F_OIDEQ,
6750 ObjectIdGetDatum(RelationGetRelid(child_rel)));
6751 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
6752 true, SnapshotNow, 1, &key);
6754 /* inhseqno sequences start at 1 */
6755 inhseqno = 0;
6756 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
6758 Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
6760 if (inh->inhparent == RelationGetRelid(parent_rel))
6761 ereport(ERROR,
6762 (errcode(ERRCODE_DUPLICATE_TABLE),
6763 errmsg("relation \"%s\" would be inherited from more than once",
6764 RelationGetRelationName(parent_rel))));
6765 if (inh->inhseqno > inhseqno)
6766 inhseqno = inh->inhseqno;
6768 systable_endscan(scan);
6771 * Prevent circularity by seeing if proposed parent inherits from child.
6772 * (In particular, this disallows making a rel inherit from itself.)
6774 * This is not completely bulletproof because of race conditions: in
6775 * multi-level inheritance trees, someone else could concurrently be
6776 * making another inheritance link that closes the loop but does not join
6777 * either of the rels we have locked. Preventing that seems to require
6778 * exclusive locks on the entire inheritance tree, which is a cure worse
6779 * than the disease. find_all_inheritors() will cope with circularity
6780 * anyway, so don't sweat it too much.
6782 children = find_all_inheritors(RelationGetRelid(child_rel));
6784 if (list_member_oid(children, RelationGetRelid(parent_rel)))
6785 ereport(ERROR,
6786 (errcode(ERRCODE_DUPLICATE_TABLE),
6787 errmsg("circular inheritance not allowed"),
6788 errdetail("\"%s\" is already a child of \"%s\".",
6789 parent->relname,
6790 RelationGetRelationName(child_rel))));
6792 /* If parent has OIDs then child must have OIDs */
6793 if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
6794 ereport(ERROR,
6795 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6796 errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
6797 RelationGetRelationName(child_rel),
6798 RelationGetRelationName(parent_rel))));
6800 /* Match up the columns and bump attinhcount as needed */
6801 MergeAttributesIntoExisting(child_rel, parent_rel);
6803 /* Match up the constraints and bump coninhcount as needed */
6804 MergeConstraintsIntoExisting(child_rel, parent_rel);
6807 * OK, it looks valid. Make the catalog entries that show inheritance.
6809 StoreCatalogInheritance1(RelationGetRelid(child_rel),
6810 RelationGetRelid(parent_rel),
6811 inhseqno + 1,
6812 catalogRelation);
6814 /* Now we're done with pg_inherits */
6815 heap_close(catalogRelation, RowExclusiveLock);
6817 /* keep our lock on the parent relation until commit */
6818 heap_close(parent_rel, NoLock);
6822 * Obtain the source-text form of the constraint expression for a check
6823 * constraint, given its pg_constraint tuple
6825 static char *
6826 decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
6828 Form_pg_constraint con;
6829 bool isnull;
6830 Datum attr;
6831 Datum expr;
6833 con = (Form_pg_constraint) GETSTRUCT(contup);
6834 attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
6835 if (isnull)
6836 elog(ERROR, "null conbin for constraint %u", HeapTupleGetOid(contup));
6838 expr = DirectFunctionCall2(pg_get_expr, attr,
6839 ObjectIdGetDatum(con->conrelid));
6840 return TextDatumGetCString(expr);
6844 * Determine whether two check constraints are functionally equivalent
6846 * The test we apply is to see whether they reverse-compile to the same
6847 * source string. This insulates us from issues like whether attributes
6848 * have the same physical column numbers in parent and child relations.
6850 static bool
6851 constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
6853 Form_pg_constraint acon = (Form_pg_constraint) GETSTRUCT(a);
6854 Form_pg_constraint bcon = (Form_pg_constraint) GETSTRUCT(b);
6856 if (acon->condeferrable != bcon->condeferrable ||
6857 acon->condeferred != bcon->condeferred ||
6858 strcmp(decompile_conbin(a, tupleDesc),
6859 decompile_conbin(b, tupleDesc)) != 0)
6860 return false;
6861 else
6862 return true;
6866 * Check columns in child table match up with columns in parent, and increment
6867 * their attinhcount.
6869 * Called by ATExecAddInherit
6871 * Currently all parent columns must be found in child. Missing columns are an
6872 * error. One day we might consider creating new columns like CREATE TABLE
6873 * does. However, that is widely unpopular --- in the common use case of
6874 * partitioned tables it's a foot-gun.
6876 * The data type must match exactly. If the parent column is NOT NULL then
6877 * the child must be as well. Defaults are not compared, however.
6879 static void
6880 MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel)
6882 Relation attrrel;
6883 AttrNumber parent_attno;
6884 int parent_natts;
6885 TupleDesc tupleDesc;
6886 TupleConstr *constr;
6887 HeapTuple tuple;
6889 attrrel = heap_open(AttributeRelationId, RowExclusiveLock);
6891 tupleDesc = RelationGetDescr(parent_rel);
6892 parent_natts = tupleDesc->natts;
6893 constr = tupleDesc->constr;
6895 for (parent_attno = 1; parent_attno <= parent_natts; parent_attno++)
6897 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
6898 char *attributeName = NameStr(attribute->attname);
6900 /* Ignore dropped columns in the parent. */
6901 if (attribute->attisdropped)
6902 continue;
6904 /* Find same column in child (matching on column name). */
6905 tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel),
6906 attributeName);
6907 if (HeapTupleIsValid(tuple))
6909 /* Check they are same type and typmod */
6910 Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
6912 if (attribute->atttypid != childatt->atttypid ||
6913 attribute->atttypmod != childatt->atttypmod)
6914 ereport(ERROR,
6915 (errcode(ERRCODE_DATATYPE_MISMATCH),
6916 errmsg("child table \"%s\" has different type for column \"%s\"",
6917 RelationGetRelationName(child_rel),
6918 attributeName)));
6920 if (attribute->attnotnull && !childatt->attnotnull)
6921 ereport(ERROR,
6922 (errcode(ERRCODE_DATATYPE_MISMATCH),
6923 errmsg("column \"%s\" in child table must be marked NOT NULL",
6924 attributeName)));
6927 * OK, bump the child column's inheritance count. (If we fail
6928 * later on, this change will just roll back.)
6930 childatt->attinhcount++;
6931 simple_heap_update(attrrel, &tuple->t_self, tuple);
6932 CatalogUpdateIndexes(attrrel, tuple);
6933 heap_freetuple(tuple);
6935 else
6937 ereport(ERROR,
6938 (errcode(ERRCODE_DATATYPE_MISMATCH),
6939 errmsg("child table is missing column \"%s\"",
6940 attributeName)));
6944 heap_close(attrrel, RowExclusiveLock);
6948 * Check constraints in child table match up with constraints in parent,
6949 * and increment their coninhcount.
6951 * Called by ATExecAddInherit
6953 * Currently all constraints in parent must be present in the child. One day we
6954 * may consider adding new constraints like CREATE TABLE does. We may also want
6955 * to allow an optional flag on parent table constraints indicating they are
6956 * intended to ONLY apply to the master table, not to the children. That would
6957 * make it possible to ensure no records are mistakenly inserted into the
6958 * master in partitioned tables rather than the appropriate child.
6960 * XXX This is O(N^2) which may be an issue with tables with hundreds of
6961 * constraints. As long as tables have more like 10 constraints it shouldn't be
6962 * a problem though. Even 100 constraints ought not be the end of the world.
6964 static void
6965 MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
6967 Relation catalog_relation;
6968 TupleDesc tuple_desc;
6969 SysScanDesc parent_scan;
6970 ScanKeyData parent_key;
6971 HeapTuple parent_tuple;
6973 catalog_relation = heap_open(ConstraintRelationId, RowExclusiveLock);
6974 tuple_desc = RelationGetDescr(catalog_relation);
6976 /* Outer loop scans through the parent's constraint definitions */
6977 ScanKeyInit(&parent_key,
6978 Anum_pg_constraint_conrelid,
6979 BTEqualStrategyNumber, F_OIDEQ,
6980 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
6981 parent_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
6982 true, SnapshotNow, 1, &parent_key);
6984 while (HeapTupleIsValid(parent_tuple = systable_getnext(parent_scan)))
6986 Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(parent_tuple);
6987 SysScanDesc child_scan;
6988 ScanKeyData child_key;
6989 HeapTuple child_tuple;
6990 bool found = false;
6992 if (parent_con->contype != CONSTRAINT_CHECK)
6993 continue;
6995 /* Search for a child constraint matching this one */
6996 ScanKeyInit(&child_key,
6997 Anum_pg_constraint_conrelid,
6998 BTEqualStrategyNumber, F_OIDEQ,
6999 ObjectIdGetDatum(RelationGetRelid(child_rel)));
7000 child_scan = systable_beginscan(catalog_relation, ConstraintRelidIndexId,
7001 true, SnapshotNow, 1, &child_key);
7003 while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
7005 Form_pg_constraint child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
7006 HeapTuple child_copy;
7008 if (child_con->contype != CONSTRAINT_CHECK)
7009 continue;
7011 if (strcmp(NameStr(parent_con->conname),
7012 NameStr(child_con->conname)) != 0)
7013 continue;
7015 if (!constraints_equivalent(parent_tuple, child_tuple, tuple_desc))
7016 ereport(ERROR,
7017 (errcode(ERRCODE_DATATYPE_MISMATCH),
7018 errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
7019 RelationGetRelationName(child_rel),
7020 NameStr(parent_con->conname))));
7023 * OK, bump the child constraint's inheritance count. (If we fail
7024 * later on, this change will just roll back.)
7026 child_copy = heap_copytuple(child_tuple);
7027 child_con = (Form_pg_constraint) GETSTRUCT(child_copy);
7028 child_con->coninhcount++;
7029 simple_heap_update(catalog_relation, &child_copy->t_self, child_copy);
7030 CatalogUpdateIndexes(catalog_relation, child_copy);
7031 heap_freetuple(child_copy);
7033 found = true;
7034 break;
7037 systable_endscan(child_scan);
7039 if (!found)
7040 ereport(ERROR,
7041 (errcode(ERRCODE_DATATYPE_MISMATCH),
7042 errmsg("child table is missing constraint \"%s\"",
7043 NameStr(parent_con->conname))));
7046 systable_endscan(parent_scan);
7047 heap_close(catalog_relation, RowExclusiveLock);
7051 * ALTER TABLE NO INHERIT
7053 * Drop a parent from the child's parents. This just adjusts the attinhcount
7054 * and attislocal of the columns and removes the pg_inherit and pg_depend
7055 * entries.
7057 * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
7058 * up attislocal stays true, which means if a child is ever removed from a
7059 * parent then its columns will never be automatically dropped which may
7060 * surprise. But at least we'll never surprise by dropping columns someone
7061 * isn't expecting to be dropped which would actually mean data loss.
7063 * coninhcount and conislocal for inherited constraints are adjusted in
7064 * exactly the same way.
7066 static void
7067 ATExecDropInherit(Relation rel, RangeVar *parent)
7069 Relation parent_rel;
7070 Relation catalogRelation;
7071 SysScanDesc scan;
7072 ScanKeyData key[3];
7073 HeapTuple inheritsTuple,
7074 attributeTuple,
7075 constraintTuple,
7076 depTuple;
7077 List *connames;
7078 bool found = false;
7081 * AccessShareLock on the parent is probably enough, seeing that DROP
7082 * TABLE doesn't lock parent tables at all. We need some lock since we'll
7083 * be inspecting the parent's schema.
7085 parent_rel = heap_openrv(parent, AccessShareLock);
7088 * We don't bother to check ownership of the parent table --- ownership of
7089 * the child is presumed enough rights.
7093 * Find and destroy the pg_inherits entry linking the two, or error out if
7094 * there is none.
7096 catalogRelation = heap_open(InheritsRelationId, RowExclusiveLock);
7097 ScanKeyInit(&key[0],
7098 Anum_pg_inherits_inhrelid,
7099 BTEqualStrategyNumber, F_OIDEQ,
7100 ObjectIdGetDatum(RelationGetRelid(rel)));
7101 scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
7102 true, SnapshotNow, 1, key);
7104 while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
7106 Oid inhparent;
7108 inhparent = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
7109 if (inhparent == RelationGetRelid(parent_rel))
7111 simple_heap_delete(catalogRelation, &inheritsTuple->t_self);
7112 found = true;
7113 break;
7117 systable_endscan(scan);
7118 heap_close(catalogRelation, RowExclusiveLock);
7120 if (!found)
7121 ereport(ERROR,
7122 (errcode(ERRCODE_UNDEFINED_TABLE),
7123 errmsg("relation \"%s\" is not a parent of relation \"%s\"",
7124 RelationGetRelationName(parent_rel),
7125 RelationGetRelationName(rel))));
7128 * Search through child columns looking for ones matching parent rel
7130 catalogRelation = heap_open(AttributeRelationId, RowExclusiveLock);
7131 ScanKeyInit(&key[0],
7132 Anum_pg_attribute_attrelid,
7133 BTEqualStrategyNumber, F_OIDEQ,
7134 ObjectIdGetDatum(RelationGetRelid(rel)));
7135 scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
7136 true, SnapshotNow, 1, key);
7137 while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
7139 Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
7141 /* Ignore if dropped or not inherited */
7142 if (att->attisdropped)
7143 continue;
7144 if (att->attinhcount <= 0)
7145 continue;
7147 if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
7148 NameStr(att->attname)))
7150 /* Decrement inhcount and possibly set islocal to true */
7151 HeapTuple copyTuple = heap_copytuple(attributeTuple);
7152 Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
7154 copy_att->attinhcount--;
7155 if (copy_att->attinhcount == 0)
7156 copy_att->attislocal = true;
7158 simple_heap_update(catalogRelation, &copyTuple->t_self, copyTuple);
7159 CatalogUpdateIndexes(catalogRelation, copyTuple);
7160 heap_freetuple(copyTuple);
7163 systable_endscan(scan);
7164 heap_close(catalogRelation, RowExclusiveLock);
7167 * Likewise, find inherited check constraints and disinherit them.
7168 * To do this, we first need a list of the names of the parent's check
7169 * constraints. (We cheat a bit by only checking for name matches,
7170 * assuming that the expressions will match.)
7172 catalogRelation = heap_open(ConstraintRelationId, RowExclusiveLock);
7173 ScanKeyInit(&key[0],
7174 Anum_pg_constraint_conrelid,
7175 BTEqualStrategyNumber, F_OIDEQ,
7176 ObjectIdGetDatum(RelationGetRelid(parent_rel)));
7177 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
7178 true, SnapshotNow, 1, key);
7180 connames = NIL;
7182 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
7184 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
7186 if (con->contype == CONSTRAINT_CHECK)
7187 connames = lappend(connames, pstrdup(NameStr(con->conname)));
7190 systable_endscan(scan);
7192 /* Now scan the child's constraints */
7193 ScanKeyInit(&key[0],
7194 Anum_pg_constraint_conrelid,
7195 BTEqualStrategyNumber, F_OIDEQ,
7196 ObjectIdGetDatum(RelationGetRelid(rel)));
7197 scan = systable_beginscan(catalogRelation, ConstraintRelidIndexId,
7198 true, SnapshotNow, 1, key);
7200 while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
7202 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
7203 bool match;
7204 ListCell *lc;
7206 if (con->contype != CONSTRAINT_CHECK)
7207 continue;
7209 match = false;
7210 foreach (lc, connames)
7212 if (strcmp(NameStr(con->conname), (char *) lfirst(lc)) == 0)
7214 match = true;
7215 break;
7219 if (match)
7221 /* Decrement inhcount and possibly set islocal to true */
7222 HeapTuple copyTuple = heap_copytuple(constraintTuple);
7223 Form_pg_constraint copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
7224 if (copy_con->coninhcount <= 0) /* shouldn't happen */
7225 elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
7226 RelationGetRelid(rel), NameStr(copy_con->conname));
7228 copy_con->coninhcount--;
7229 if (copy_con->coninhcount == 0)
7230 copy_con->conislocal = true;
7232 simple_heap_update(catalogRelation, &copyTuple->t_self, copyTuple);
7233 CatalogUpdateIndexes(catalogRelation, copyTuple);
7234 heap_freetuple(copyTuple);
7238 systable_endscan(scan);
7239 heap_close(catalogRelation, RowExclusiveLock);
7242 * Drop the dependency
7244 * There's no convenient way to do this, so go trawling through pg_depend
7246 catalogRelation = heap_open(DependRelationId, RowExclusiveLock);
7248 ScanKeyInit(&key[0],
7249 Anum_pg_depend_classid,
7250 BTEqualStrategyNumber, F_OIDEQ,
7251 ObjectIdGetDatum(RelationRelationId));
7252 ScanKeyInit(&key[1],
7253 Anum_pg_depend_objid,
7254 BTEqualStrategyNumber, F_OIDEQ,
7255 ObjectIdGetDatum(RelationGetRelid(rel)));
7256 ScanKeyInit(&key[2],
7257 Anum_pg_depend_objsubid,
7258 BTEqualStrategyNumber, F_INT4EQ,
7259 Int32GetDatum(0));
7261 scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
7262 SnapshotNow, 3, key);
7264 while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
7266 Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
7268 if (dep->refclassid == RelationRelationId &&
7269 dep->refobjid == RelationGetRelid(parent_rel) &&
7270 dep->refobjsubid == 0 &&
7271 dep->deptype == DEPENDENCY_NORMAL)
7272 simple_heap_delete(catalogRelation, &depTuple->t_self);
7275 systable_endscan(scan);
7276 heap_close(catalogRelation, RowExclusiveLock);
7278 /* keep our lock on the parent relation until commit */
7279 heap_close(parent_rel, NoLock);
7284 * Execute ALTER TABLE SET SCHEMA
7286 * Note: caller must have checked ownership of the relation already
7288 void
7289 AlterTableNamespace(RangeVar *relation, const char *newschema,
7290 ObjectType stmttype)
7292 Relation rel;
7293 Oid relid;
7294 Oid oldNspOid;
7295 Oid nspOid;
7296 Relation classRel;
7298 rel = relation_openrv(relation, AccessExclusiveLock);
7300 relid = RelationGetRelid(rel);
7301 oldNspOid = RelationGetNamespace(rel);
7303 /* Check relation type against type specified in the ALTER command */
7304 switch (stmttype)
7306 case OBJECT_TABLE:
7308 * For mostly-historical reasons, we allow ALTER TABLE to apply
7309 * to all relation types.
7311 break;
7313 case OBJECT_SEQUENCE:
7314 if (rel->rd_rel->relkind != RELKIND_SEQUENCE)
7315 ereport(ERROR,
7316 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7317 errmsg("\"%s\" is not a sequence",
7318 RelationGetRelationName(rel))));
7319 break;
7321 case OBJECT_VIEW:
7322 if (rel->rd_rel->relkind != RELKIND_VIEW)
7323 ereport(ERROR,
7324 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7325 errmsg("\"%s\" is not a view",
7326 RelationGetRelationName(rel))));
7327 break;
7329 default:
7330 elog(ERROR, "unrecognized object type: %d", (int) stmttype);
7333 /* Can we change the schema of this tuple? */
7334 switch (rel->rd_rel->relkind)
7336 case RELKIND_RELATION:
7337 case RELKIND_VIEW:
7338 /* ok to change schema */
7339 break;
7340 case RELKIND_SEQUENCE:
7342 /* if it's an owned sequence, disallow moving it by itself */
7343 Oid tableId;
7344 int32 colId;
7346 if (sequenceIsOwned(relid, &tableId, &colId))
7347 ereport(ERROR,
7348 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7349 errmsg("cannot move an owned sequence into another schema"),
7350 errdetail("Sequence \"%s\" is linked to table \"%s\".",
7351 RelationGetRelationName(rel),
7352 get_rel_name(tableId))));
7354 break;
7355 case RELKIND_COMPOSITE_TYPE:
7356 ereport(ERROR,
7357 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7358 errmsg("\"%s\" is a composite type",
7359 RelationGetRelationName(rel)),
7360 errhint("Use ALTER TYPE instead.")));
7361 break;
7362 case RELKIND_INDEX:
7363 case RELKIND_TOASTVALUE:
7364 /* FALL THRU */
7365 default:
7366 ereport(ERROR,
7367 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7368 errmsg("\"%s\" is not a table, view, or sequence",
7369 RelationGetRelationName(rel))));
7372 /* get schema OID and check its permissions */
7373 nspOid = LookupCreationNamespace(newschema);
7375 if (oldNspOid == nspOid)
7376 ereport(ERROR,
7377 (errcode(ERRCODE_DUPLICATE_TABLE),
7378 errmsg("relation \"%s\" is already in schema \"%s\"",
7379 RelationGetRelationName(rel),
7380 newschema)));
7382 /* disallow renaming into or out of temp schemas */
7383 if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
7384 ereport(ERROR,
7385 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7386 errmsg("cannot move objects into or out of temporary schemas")));
7388 /* same for TOAST schema */
7389 if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
7390 ereport(ERROR,
7391 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7392 errmsg("cannot move objects into or out of TOAST schema")));
7394 /* OK, modify the pg_class row and pg_depend entry */
7395 classRel = heap_open(RelationRelationId, RowExclusiveLock);
7397 AlterRelationNamespaceInternal(classRel, relid, oldNspOid, nspOid, true);
7399 /* Fix the table's rowtype too */
7400 AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid, false, false);
7402 /* Fix other dependent stuff */
7403 if (rel->rd_rel->relkind == RELKIND_RELATION)
7405 AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid);
7406 AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid, newschema);
7407 AlterConstraintNamespaces(relid, oldNspOid, nspOid, false);
7410 heap_close(classRel, RowExclusiveLock);
7412 /* close rel, but keep lock until commit */
7413 relation_close(rel, NoLock);
7417 * The guts of relocating a relation to another namespace: fix the pg_class
7418 * entry, and the pg_depend entry if any. Caller must already have
7419 * opened and write-locked pg_class.
7421 void
7422 AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
7423 Oid oldNspOid, Oid newNspOid,
7424 bool hasDependEntry)
7426 HeapTuple classTup;
7427 Form_pg_class classForm;
7429 classTup = SearchSysCacheCopy(RELOID,
7430 ObjectIdGetDatum(relOid),
7431 0, 0, 0);
7432 if (!HeapTupleIsValid(classTup))
7433 elog(ERROR, "cache lookup failed for relation %u", relOid);
7434 classForm = (Form_pg_class) GETSTRUCT(classTup);
7436 Assert(classForm->relnamespace == oldNspOid);
7438 /* check for duplicate name (more friendly than unique-index failure) */
7439 if (get_relname_relid(NameStr(classForm->relname),
7440 newNspOid) != InvalidOid)
7441 ereport(ERROR,
7442 (errcode(ERRCODE_DUPLICATE_TABLE),
7443 errmsg("relation \"%s\" already exists in schema \"%s\"",
7444 NameStr(classForm->relname),
7445 get_namespace_name(newNspOid))));
7447 /* classTup is a copy, so OK to scribble on */
7448 classForm->relnamespace = newNspOid;
7450 simple_heap_update(classRel, &classTup->t_self, classTup);
7451 CatalogUpdateIndexes(classRel, classTup);
7453 /* Update dependency on schema if caller said so */
7454 if (hasDependEntry &&
7455 changeDependencyFor(RelationRelationId, relOid,
7456 NamespaceRelationId, oldNspOid, newNspOid) != 1)
7457 elog(ERROR, "failed to change schema dependency for relation \"%s\"",
7458 NameStr(classForm->relname));
7460 heap_freetuple(classTup);
7464 * Move all indexes for the specified relation to another namespace.
7466 * Note: we assume adequate permission checking was done by the caller,
7467 * and that the caller has a suitable lock on the owning relation.
7469 static void
7470 AlterIndexNamespaces(Relation classRel, Relation rel,
7471 Oid oldNspOid, Oid newNspOid)
7473 List *indexList;
7474 ListCell *l;
7476 indexList = RelationGetIndexList(rel);
7478 foreach(l, indexList)
7480 Oid indexOid = lfirst_oid(l);
7483 * Note: currently, the index will not have its own dependency on the
7484 * namespace, so we don't need to do changeDependencyFor(). There's no
7485 * rowtype in pg_type, either.
7487 AlterRelationNamespaceInternal(classRel, indexOid,
7488 oldNspOid, newNspOid,
7489 false);
7492 list_free(indexList);
7496 * Move all SERIAL-column sequences of the specified relation to another
7497 * namespace.
7499 * Note: we assume adequate permission checking was done by the caller,
7500 * and that the caller has a suitable lock on the owning relation.
7502 static void
7503 AlterSeqNamespaces(Relation classRel, Relation rel,
7504 Oid oldNspOid, Oid newNspOid, const char *newNspName)
7506 Relation depRel;
7507 SysScanDesc scan;
7508 ScanKeyData key[2];
7509 HeapTuple tup;
7512 * SERIAL sequences are those having an auto dependency on one of the
7513 * table's columns (we don't care *which* column, exactly).
7515 depRel = heap_open(DependRelationId, AccessShareLock);
7517 ScanKeyInit(&key[0],
7518 Anum_pg_depend_refclassid,
7519 BTEqualStrategyNumber, F_OIDEQ,
7520 ObjectIdGetDatum(RelationRelationId));
7521 ScanKeyInit(&key[1],
7522 Anum_pg_depend_refobjid,
7523 BTEqualStrategyNumber, F_OIDEQ,
7524 ObjectIdGetDatum(RelationGetRelid(rel)));
7525 /* we leave refobjsubid unspecified */
7527 scan = systable_beginscan(depRel, DependReferenceIndexId, true,
7528 SnapshotNow, 2, key);
7530 while (HeapTupleIsValid(tup = systable_getnext(scan)))
7532 Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
7533 Relation seqRel;
7535 /* skip dependencies other than auto dependencies on columns */
7536 if (depForm->refobjsubid == 0 ||
7537 depForm->classid != RelationRelationId ||
7538 depForm->objsubid != 0 ||
7539 depForm->deptype != DEPENDENCY_AUTO)
7540 continue;
7542 /* Use relation_open just in case it's an index */
7543 seqRel = relation_open(depForm->objid, AccessExclusiveLock);
7545 /* skip non-sequence relations */
7546 if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
7548 /* No need to keep the lock */
7549 relation_close(seqRel, AccessExclusiveLock);
7550 continue;
7553 /* Fix the pg_class and pg_depend entries */
7554 AlterRelationNamespaceInternal(classRel, depForm->objid,
7555 oldNspOid, newNspOid,
7556 true);
7559 * Sequences have entries in pg_type. We need to be careful to move
7560 * them to the new namespace, too.
7562 AlterTypeNamespaceInternal(RelationGetForm(seqRel)->reltype,
7563 newNspOid, false, false);
7565 /* Now we can close it. Keep the lock till end of transaction. */
7566 relation_close(seqRel, NoLock);
7569 systable_endscan(scan);
7571 relation_close(depRel, AccessShareLock);
7576 * This code supports
7577 * CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
7579 * Because we only support this for TEMP tables, it's sufficient to remember
7580 * the state in a backend-local data structure.
7584 * Register a newly-created relation's ON COMMIT action.
7586 void
7587 register_on_commit_action(Oid relid, OnCommitAction action)
7589 OnCommitItem *oc;
7590 MemoryContext oldcxt;
7593 * We needn't bother registering the relation unless there is an ON COMMIT
7594 * action we need to take.
7596 if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
7597 return;
7599 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
7601 oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
7602 oc->relid = relid;
7603 oc->oncommit = action;
7604 oc->creating_subid = GetCurrentSubTransactionId();
7605 oc->deleting_subid = InvalidSubTransactionId;
7607 on_commits = lcons(oc, on_commits);
7609 MemoryContextSwitchTo(oldcxt);
7613 * Unregister any ON COMMIT action when a relation is deleted.
7615 * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
7617 void
7618 remove_on_commit_action(Oid relid)
7620 ListCell *l;
7622 foreach(l, on_commits)
7624 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
7626 if (oc->relid == relid)
7628 oc->deleting_subid = GetCurrentSubTransactionId();
7629 break;
7635 * Perform ON COMMIT actions.
7637 * This is invoked just before actually committing, since it's possible
7638 * to encounter errors.
7640 void
7641 PreCommit_on_commit_actions(void)
7643 ListCell *l;
7644 List *oids_to_truncate = NIL;
7646 foreach(l, on_commits)
7648 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
7650 /* Ignore entry if already dropped in this xact */
7651 if (oc->deleting_subid != InvalidSubTransactionId)
7652 continue;
7654 switch (oc->oncommit)
7656 case ONCOMMIT_NOOP:
7657 case ONCOMMIT_PRESERVE_ROWS:
7658 /* Do nothing (there shouldn't be such entries, actually) */
7659 break;
7660 case ONCOMMIT_DELETE_ROWS:
7661 oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
7662 break;
7663 case ONCOMMIT_DROP:
7665 ObjectAddress object;
7667 object.classId = RelationRelationId;
7668 object.objectId = oc->relid;
7669 object.objectSubId = 0;
7670 performDeletion(&object, DROP_CASCADE);
7673 * Note that table deletion will call
7674 * remove_on_commit_action, so the entry should get marked
7675 * as deleted.
7677 Assert(oc->deleting_subid != InvalidSubTransactionId);
7678 break;
7682 if (oids_to_truncate != NIL)
7684 heap_truncate(oids_to_truncate);
7685 CommandCounterIncrement(); /* XXX needed? */
7690 * Post-commit or post-abort cleanup for ON COMMIT management.
7692 * All we do here is remove no-longer-needed OnCommitItem entries.
7694 * During commit, remove entries that were deleted during this transaction;
7695 * during abort, remove those created during this transaction.
7697 void
7698 AtEOXact_on_commit_actions(bool isCommit)
7700 ListCell *cur_item;
7701 ListCell *prev_item;
7703 prev_item = NULL;
7704 cur_item = list_head(on_commits);
7706 while (cur_item != NULL)
7708 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
7710 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
7711 oc->creating_subid != InvalidSubTransactionId)
7713 /* cur_item must be removed */
7714 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
7715 pfree(oc);
7716 if (prev_item)
7717 cur_item = lnext(prev_item);
7718 else
7719 cur_item = list_head(on_commits);
7721 else
7723 /* cur_item must be preserved */
7724 oc->creating_subid = InvalidSubTransactionId;
7725 oc->deleting_subid = InvalidSubTransactionId;
7726 prev_item = cur_item;
7727 cur_item = lnext(prev_item);
7733 * Post-subcommit or post-subabort cleanup for ON COMMIT management.
7735 * During subabort, we can immediately remove entries created during this
7736 * subtransaction. During subcommit, just relabel entries marked during
7737 * this subtransaction as being the parent's responsibility.
7739 void
7740 AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
7741 SubTransactionId parentSubid)
7743 ListCell *cur_item;
7744 ListCell *prev_item;
7746 prev_item = NULL;
7747 cur_item = list_head(on_commits);
7749 while (cur_item != NULL)
7751 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
7753 if (!isCommit && oc->creating_subid == mySubid)
7755 /* cur_item must be removed */
7756 on_commits = list_delete_cell(on_commits, cur_item, prev_item);
7757 pfree(oc);
7758 if (prev_item)
7759 cur_item = lnext(prev_item);
7760 else
7761 cur_item = list_head(on_commits);
7763 else
7765 /* cur_item must be preserved */
7766 if (oc->creating_subid == mySubid)
7767 oc->creating_subid = parentSubid;
7768 if (oc->deleting_subid == mySubid)
7769 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
7770 prev_item = cur_item;
7771 cur_item = lnext(prev_item);