1 /*-------------------------------------------------------------------------
4 * Commands for creating and altering table structures and settings
6 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
13 *-------------------------------------------------------------------------
17 #include "access/genam.h"
18 #include "access/heapam.h"
19 #include "access/reloptions.h"
20 #include "access/relscan.h"
21 #include "access/sysattr.h"
22 #include "access/xact.h"
23 #include "catalog/catalog.h"
24 #include "catalog/dependency.h"
25 #include "catalog/heap.h"
26 #include "catalog/index.h"
27 #include "catalog/indexing.h"
28 #include "catalog/namespace.h"
29 #include "catalog/pg_constraint.h"
30 #include "catalog/pg_depend.h"
31 #include "catalog/pg_inherits.h"
32 #include "catalog/pg_inherits_fn.h"
33 #include "catalog/pg_namespace.h"
34 #include "catalog/pg_opclass.h"
35 #include "catalog/pg_tablespace.h"
36 #include "catalog/pg_trigger.h"
37 #include "catalog/pg_type.h"
38 #include "catalog/pg_type_fn.h"
39 #include "catalog/storage.h"
40 #include "catalog/toasting.h"
41 #include "commands/cluster.h"
42 #include "commands/defrem.h"
43 #include "commands/sequence.h"
44 #include "commands/tablecmds.h"
45 #include "commands/tablespace.h"
46 #include "commands/trigger.h"
47 #include "commands/typecmds.h"
48 #include "executor/executor.h"
49 #include "miscadmin.h"
50 #include "nodes/makefuncs.h"
51 #include "nodes/nodeFuncs.h"
52 #include "nodes/parsenodes.h"
53 #include "optimizer/clauses.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
;
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 bool new_changeoids
; /* T if we added/dropped the OID column */
141 Oid newTableSpace
; /* new tablespace; 0 means no change */
142 /* Objects to rebuild after completing ALTER TYPE operations */
143 List
*changedConstraintOids
; /* OIDs of constraints to rebuild */
144 List
*changedConstraintDefs
; /* string definitions of same */
145 List
*changedIndexOids
; /* OIDs of indexes to rebuild */
146 List
*changedIndexDefs
; /* string definitions of same */
149 /* Struct describing one new constraint to check in Phase 3 scan */
150 /* Note: new NOT NULL constraints are handled elsewhere */
151 typedef struct NewConstraint
153 char *name
; /* Constraint name, or NULL if none */
154 ConstrType contype
; /* CHECK or FOREIGN */
155 Oid refrelid
; /* PK rel, if FOREIGN */
156 Oid conid
; /* OID of pg_constraint entry, if FOREIGN */
157 Node
*qual
; /* Check expr or FkConstraint struct */
158 List
*qualstate
; /* Execution state for CHECK */
162 * Struct describing one new column value that needs to be computed during
163 * Phase 3 copy (this could be either a new column with a non-null default, or
164 * a column that we're changing the type of). Columns without such an entry
165 * are just copied from the old table during ATRewriteTable. Note that the
166 * expr is an expression over *old* table values.
168 typedef struct NewColumnValue
170 AttrNumber attnum
; /* which column */
171 Expr
*expr
; /* expression to compute */
172 ExprState
*exprstate
; /* execution state */
176 * Error-reporting support for RemoveRelations
178 struct dropmsgstrings
181 int nonexistent_code
;
182 const char *nonexistent_msg
;
183 const char *skipping_msg
;
184 const char *nota_msg
;
185 const char *drophint_msg
;
188 static const struct dropmsgstrings dropmsgstringarray
[] = {
190 ERRCODE_UNDEFINED_TABLE
,
191 gettext_noop("table \"%s\" does not exist"),
192 gettext_noop("table \"%s\" does not exist, skipping"),
193 gettext_noop("\"%s\" is not a table"),
194 gettext_noop("Use DROP TABLE to remove a table.")},
196 ERRCODE_UNDEFINED_TABLE
,
197 gettext_noop("sequence \"%s\" does not exist"),
198 gettext_noop("sequence \"%s\" does not exist, skipping"),
199 gettext_noop("\"%s\" is not a sequence"),
200 gettext_noop("Use DROP SEQUENCE to remove a sequence.")},
202 ERRCODE_UNDEFINED_TABLE
,
203 gettext_noop("view \"%s\" does not exist"),
204 gettext_noop("view \"%s\" does not exist, skipping"),
205 gettext_noop("\"%s\" is not a view"),
206 gettext_noop("Use DROP VIEW to remove a view.")},
208 ERRCODE_UNDEFINED_OBJECT
,
209 gettext_noop("index \"%s\" does not exist"),
210 gettext_noop("index \"%s\" does not exist, skipping"),
211 gettext_noop("\"%s\" is not an index"),
212 gettext_noop("Use DROP INDEX to remove an index.")},
213 {RELKIND_COMPOSITE_TYPE
,
214 ERRCODE_UNDEFINED_OBJECT
,
215 gettext_noop("type \"%s\" does not exist"),
216 gettext_noop("type \"%s\" does not exist, skipping"),
217 gettext_noop("\"%s\" is not a type"),
218 gettext_noop("Use DROP TYPE to remove a type.")},
219 {'\0', 0, NULL
, NULL
, NULL
, NULL
}
223 static void truncate_check_rel(Relation rel
);
224 static List
*MergeAttributes(List
*schema
, List
*supers
, bool istemp
,
225 List
**supOids
, List
**supconstr
, int *supOidCount
);
226 static bool MergeCheckConstraint(List
*constraints
, char *name
, Node
*expr
);
227 static bool change_varattnos_walker(Node
*node
, const AttrNumber
*newattno
);
228 static void MergeAttributesIntoExisting(Relation child_rel
, Relation parent_rel
);
229 static void MergeConstraintsIntoExisting(Relation child_rel
, Relation parent_rel
);
230 static void StoreCatalogInheritance(Oid relationId
, List
*supers
);
231 static void StoreCatalogInheritance1(Oid relationId
, Oid parentOid
,
232 int16 seqNumber
, Relation inhRelation
);
233 static int findAttrByName(const char *attributeName
, List
*schema
);
234 static void setRelhassubclassInRelation(Oid relationId
, bool relhassubclass
);
235 static void AlterIndexNamespaces(Relation classRel
, Relation rel
,
236 Oid oldNspOid
, Oid newNspOid
);
237 static void AlterSeqNamespaces(Relation classRel
, Relation rel
,
238 Oid oldNspOid
, Oid newNspOid
,
239 const char *newNspName
);
240 static int transformColumnNameList(Oid relId
, List
*colList
,
241 int16
*attnums
, Oid
*atttypids
);
242 static int transformFkeyGetPrimaryKey(Relation pkrel
, Oid
*indexOid
,
244 int16
*attnums
, Oid
*atttypids
,
246 static Oid
transformFkeyCheckAttrs(Relation pkrel
,
247 int numattrs
, int16
*attnums
,
249 static void checkFkeyPermissions(Relation rel
, int16
*attnums
, int natts
);
250 static void validateForeignKeyConstraint(FkConstraint
*fkconstraint
,
251 Relation rel
, Relation pkrel
, Oid constraintOid
);
252 static void createForeignKeyTriggers(Relation rel
, FkConstraint
*fkconstraint
,
254 static void ATController(Relation rel
, List
*cmds
, bool recurse
);
255 static void ATPrepCmd(List
**wqueue
, Relation rel
, AlterTableCmd
*cmd
,
256 bool recurse
, bool recursing
);
257 static void ATRewriteCatalogs(List
**wqueue
);
258 static void ATExecCmd(List
**wqueue
, AlteredTableInfo
*tab
, Relation rel
,
260 static void ATRewriteTables(List
**wqueue
);
261 static void ATRewriteTable(AlteredTableInfo
*tab
, Oid OIDNewHeap
);
262 static AlteredTableInfo
*ATGetQueueEntry(List
**wqueue
, Relation rel
);
263 static void ATSimplePermissions(Relation rel
, bool allowView
);
264 static void ATSimplePermissionsRelationOrIndex(Relation rel
);
265 static void ATSimpleRecursion(List
**wqueue
, Relation rel
,
266 AlterTableCmd
*cmd
, bool recurse
);
267 static void ATOneLevelRecursion(List
**wqueue
, Relation rel
,
269 static void ATPrepAddColumn(List
**wqueue
, Relation rel
, bool recurse
,
271 static void ATExecAddColumn(AlteredTableInfo
*tab
, Relation rel
,
272 ColumnDef
*colDef
, bool isOid
);
273 static void add_column_datatype_dependency(Oid relid
, int32 attnum
, Oid typid
);
274 static void ATPrepAddOids(List
**wqueue
, Relation rel
, bool recurse
,
276 static void ATExecDropNotNull(Relation rel
, const char *colName
);
277 static void ATExecSetNotNull(AlteredTableInfo
*tab
, Relation rel
,
278 const char *colName
);
279 static void ATExecColumnDefault(Relation rel
, const char *colName
,
281 static void ATPrepSetStatistics(Relation rel
, const char *colName
,
283 static void ATExecSetStatistics(Relation rel
, const char *colName
,
285 static void ATExecSetStorage(Relation rel
, const char *colName
,
287 static void ATExecDropColumn(List
**wqueue
, Relation rel
, const char *colName
,
288 DropBehavior behavior
,
289 bool recurse
, bool recursing
);
290 static void ATExecAddIndex(AlteredTableInfo
*tab
, Relation rel
,
291 IndexStmt
*stmt
, bool is_rebuild
);
292 static void ATExecAddConstraint(List
**wqueue
,
293 AlteredTableInfo
*tab
, Relation rel
,
294 Node
*newConstraint
, bool recurse
);
295 static void ATAddCheckConstraint(List
**wqueue
,
296 AlteredTableInfo
*tab
, Relation rel
,
298 bool recurse
, bool recursing
);
299 static void ATAddForeignKeyConstraint(AlteredTableInfo
*tab
, Relation rel
,
300 FkConstraint
*fkconstraint
);
301 static void ATExecDropConstraint(Relation rel
, const char *constrName
,
302 DropBehavior behavior
,
303 bool recurse
, bool recursing
);
304 static void ATPrepAlterColumnType(List
**wqueue
,
305 AlteredTableInfo
*tab
, Relation rel
,
306 bool recurse
, bool recursing
,
308 static void ATExecAlterColumnType(AlteredTableInfo
*tab
, Relation rel
,
309 const char *colName
, TypeName
*typename
);
310 static void ATPostAlterTypeCleanup(List
**wqueue
, AlteredTableInfo
*tab
);
311 static void ATPostAlterTypeParse(char *cmd
, List
**wqueue
);
312 static void change_owner_recurse_to_sequences(Oid relationOid
,
314 static void ATExecClusterOn(Relation rel
, const char *indexName
);
315 static void ATExecDropCluster(Relation rel
);
316 static void ATPrepSetTableSpace(AlteredTableInfo
*tab
, Relation rel
,
317 char *tablespacename
);
318 static void ATExecSetTableSpace(Oid tableOid
, Oid newTableSpace
);
319 static void ATExecSetRelOptions(Relation rel
, List
*defList
, bool isReset
);
320 static void ATExecEnableDisableTrigger(Relation rel
, char *trigname
,
321 char fires_when
, bool skip_system
);
322 static void ATExecEnableDisableRule(Relation rel
, char *rulename
,
324 static void ATExecAddInherit(Relation rel
, RangeVar
*parent
);
325 static void ATExecDropInherit(Relation rel
, RangeVar
*parent
);
326 static void copy_relation_data(SMgrRelation rel
, SMgrRelation dst
,
327 ForkNumber forkNum
, bool istemp
);
330 /* ----------------------------------------------------------------
332 * Creates a new relation.
334 * If successful, returns the OID of the new relation.
335 * ----------------------------------------------------------------
338 DefineRelation(CreateStmt
*stmt
, char relkind
)
340 char relname
[NAMEDATALEN
];
342 List
*schema
= stmt
->tableElts
;
346 TupleDesc descriptor
;
348 List
*old_constraints
;
352 List
*cookedDefaults
;
356 static char *validnsps
[] = HEAP_RELOPT_NAMESPACES
;
359 * Truncate relname to appropriate length (probably a waste of time, as
360 * parser should have done this already).
362 StrNCpy(relname
, stmt
->relation
->relname
, NAMEDATALEN
);
365 * Check consistency of arguments
367 if (stmt
->oncommit
!= ONCOMMIT_NOOP
&& !stmt
->relation
->istemp
)
369 (errcode(ERRCODE_INVALID_TABLE_DEFINITION
),
370 errmsg("ON COMMIT can only be used on temporary tables")));
373 * Look up the namespace in which we are supposed to create the relation.
374 * Check we have permission to create there. Skip check if bootstrapping,
375 * since permissions machinery may not be working yet.
377 namespaceId
= RangeVarGetCreationNamespace(stmt
->relation
);
379 if (!IsBootstrapProcessingMode())
383 aclresult
= pg_namespace_aclcheck(namespaceId
, GetUserId(),
385 if (aclresult
!= ACLCHECK_OK
)
386 aclcheck_error(aclresult
, ACL_KIND_NAMESPACE
,
387 get_namespace_name(namespaceId
));
391 * Select tablespace to use. If not specified, use default tablespace
392 * (which may in turn default to database's default).
394 if (stmt
->tablespacename
)
396 tablespaceId
= get_tablespace_oid(stmt
->tablespacename
);
397 if (!OidIsValid(tablespaceId
))
399 (errcode(ERRCODE_UNDEFINED_OBJECT
),
400 errmsg("tablespace \"%s\" does not exist",
401 stmt
->tablespacename
)));
405 tablespaceId
= GetDefaultTablespace(stmt
->relation
->istemp
);
406 /* note InvalidOid is OK in this case */
409 /* Check permissions except when using database's default */
410 if (OidIsValid(tablespaceId
) && tablespaceId
!= MyDatabaseTableSpace
)
414 aclresult
= pg_tablespace_aclcheck(tablespaceId
, GetUserId(),
416 if (aclresult
!= ACLCHECK_OK
)
417 aclcheck_error(aclresult
, ACL_KIND_TABLESPACE
,
418 get_tablespace_name(tablespaceId
));
422 * Parse and validate reloptions, if any.
424 reloptions
= transformRelOptions((Datum
) 0, stmt
->options
, NULL
, validnsps
,
427 (void) heap_reloptions(relkind
, reloptions
, true);
430 * Look up inheritance ancestors and generate relation schema, including
431 * inherited attributes.
433 schema
= MergeAttributes(schema
, stmt
->inhRelations
,
434 stmt
->relation
->istemp
,
435 &inheritOids
, &old_constraints
, &parentOidCount
);
438 * Create a tuple descriptor from the relation schema. Note that this
439 * deals with column names, types, and NOT NULL constraints, but not
440 * default values or CHECK constraints; we handle those below.
442 descriptor
= BuildDescForRelation(schema
);
444 localHasOids
= interpretOidsOption(stmt
->options
);
445 descriptor
->tdhasoid
= (localHasOids
|| parentOidCount
> 0);
448 * Find columns with default values and prepare for insertion of the
449 * defaults. Pre-cooked (that is, inherited) defaults go into a list of
450 * CookedConstraint structs that we'll pass to heap_create_with_catalog,
451 * while raw defaults go into a list of RawColumnDefault structs that will
452 * be processed by AddRelationNewConstraints. (We can't deal with raw
453 * expressions until we can do transformExpr.)
455 * We can set the atthasdef flags now in the tuple descriptor; this just
456 * saves StoreAttrDefault from having to do an immediate update of the
460 cookedDefaults
= NIL
;
463 foreach(listptr
, schema
)
465 ColumnDef
*colDef
= lfirst(listptr
);
469 if (colDef
->raw_default
!= NULL
)
471 RawColumnDefault
*rawEnt
;
473 Assert(colDef
->cooked_default
== NULL
);
475 rawEnt
= (RawColumnDefault
*) palloc(sizeof(RawColumnDefault
));
476 rawEnt
->attnum
= attnum
;
477 rawEnt
->raw_default
= colDef
->raw_default
;
478 rawDefaults
= lappend(rawDefaults
, rawEnt
);
479 descriptor
->attrs
[attnum
- 1]->atthasdef
= true;
481 else if (colDef
->cooked_default
!= NULL
)
483 CookedConstraint
*cooked
;
485 cooked
= (CookedConstraint
*) palloc(sizeof(CookedConstraint
));
486 cooked
->contype
= CONSTR_DEFAULT
;
488 cooked
->attnum
= attnum
;
489 cooked
->expr
= stringToNode(colDef
->cooked_default
);
490 cooked
->is_local
= true; /* not used for defaults */
491 cooked
->inhcount
= 0; /* ditto */
492 cookedDefaults
= lappend(cookedDefaults
, cooked
);
493 descriptor
->attrs
[attnum
- 1]->atthasdef
= true;
498 * Create the relation. Inherited defaults and constraints are passed in
499 * for immediate handling --- since they don't need parsing, they can be
500 * stored immediately.
502 relationId
= heap_create_with_catalog(relname
,
508 list_concat(cookedDefaults
,
516 allowSystemTableMods
);
518 StoreCatalogInheritance(relationId
, inheritOids
);
521 * We must bump the command counter to make the newly-created relation
522 * tuple visible for opening.
524 CommandCounterIncrement();
527 * Open the new relation and acquire exclusive lock on it. This isn't
528 * really necessary for locking out other backends (since they can't see
529 * the new rel anyway until we commit), but it keeps the lock manager from
530 * complaining about deadlock risks.
532 rel
= relation_open(relationId
, AccessExclusiveLock
);
535 * Now add any newly specified column default values and CHECK constraints
536 * to the new relation. These are passed to us in the form of raw
537 * parsetrees; we need to transform them to executable expression trees
538 * before they can be added. The most convenient way to do that is to
539 * apply the parser's transformExpr routine, but transformExpr doesn't
540 * work unless we have a pre-existing relation. So, the transformation has
541 * to be postponed to this final step of CREATE TABLE.
543 if (rawDefaults
|| stmt
->constraints
)
544 AddRelationNewConstraints(rel
, rawDefaults
, stmt
->constraints
,
548 * Clean up. We keep lock on new relation (although it shouldn't be
549 * visible to anyone else anyway, until commit).
551 relation_close(rel
, NoLock
);
557 * Emit the right error or warning message for a "DROP" command issued on a
558 * non-existent relation
561 DropErrorMsgNonExistent(const char *relname
, char rightkind
, bool missing_ok
)
563 const struct dropmsgstrings
*rentry
;
565 for (rentry
= dropmsgstringarray
; rentry
->kind
!= '\0'; rentry
++)
567 if (rentry
->kind
== rightkind
)
572 (errcode(rentry
->nonexistent_code
),
573 errmsg(rentry
->nonexistent_msg
, relname
)));
577 ereport(NOTICE
, (errmsg(rentry
->skipping_msg
, relname
)));
583 Assert(rentry
->kind
!= '\0'); /* Should be impossible */
587 * Emit the right error message for a "DROP" command issued on a
588 * relation of the wrong type
591 DropErrorMsgWrongType(const char *relname
, char wrongkind
, char rightkind
)
593 const struct dropmsgstrings
*rentry
;
594 const struct dropmsgstrings
*wentry
;
596 for (rentry
= dropmsgstringarray
; rentry
->kind
!= '\0'; rentry
++)
597 if (rentry
->kind
== rightkind
)
599 Assert(rentry
->kind
!= '\0');
601 for (wentry
= dropmsgstringarray
; wentry
->kind
!= '\0'; wentry
++)
602 if (wentry
->kind
== wrongkind
)
604 /* wrongkind could be something we don't have in our table... */
607 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
608 errmsg(rentry
->nota_msg
, relname
),
609 (wentry
->kind
!= '\0') ? errhint("%s", _(wentry
->drophint_msg
)) : 0));
614 * Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW
617 RemoveRelations(DropStmt
*drop
)
619 ObjectAddresses
*objects
;
624 * First we identify all the relations, then we delete them in a single
625 * performMultipleDeletions() call. This is to avoid unwanted DROP
626 * RESTRICT errors if one of the relations depends on another.
629 /* Determine required relkind */
630 switch (drop
->removeType
)
633 relkind
= RELKIND_RELATION
;
637 relkind
= RELKIND_INDEX
;
640 case OBJECT_SEQUENCE
:
641 relkind
= RELKIND_SEQUENCE
;
645 relkind
= RELKIND_VIEW
;
649 elog(ERROR
, "unrecognized drop object type: %d",
650 (int) drop
->removeType
);
651 relkind
= 0; /* keep compiler quiet */
655 /* Lock and validate each relation; build a list of object addresses */
656 objects
= new_object_addresses();
658 foreach(cell
, drop
->objects
)
660 RangeVar
*rel
= makeRangeVarFromNameList((List
*) lfirst(cell
));
663 Form_pg_class classform
;
667 * These next few steps are a great deal like relation_openrv, but we
668 * don't bother building a relcache entry since we don't need it.
670 * Check for shared-cache-inval messages before trying to access the
671 * relation. This is needed to cover the case where the name
672 * identifies a rel that has been dropped and recreated since the
673 * start of our transaction: if we don't flush the old syscache entry,
674 * then we'll latch onto that entry and suffer an error later.
676 AcceptInvalidationMessages();
678 /* Look up the appropriate relation using namespace search */
679 relOid
= RangeVarGetRelid(rel
, true);
682 if (!OidIsValid(relOid
))
684 DropErrorMsgNonExistent(rel
->relname
, relkind
, drop
->missing_ok
);
689 * In DROP INDEX, attempt to acquire lock on the parent table before
690 * locking the index. index_drop() will need this anyway, and since
691 * regular queries lock tables before their indexes, we risk deadlock
692 * if we do it the other way around. No error if we don't find a
693 * pg_index entry, though --- that most likely means it isn't an
694 * index, and we'll fail below.
696 if (relkind
== RELKIND_INDEX
)
698 tuple
= SearchSysCache(INDEXRELID
,
699 ObjectIdGetDatum(relOid
),
701 if (HeapTupleIsValid(tuple
))
703 Form_pg_index index
= (Form_pg_index
) GETSTRUCT(tuple
);
705 LockRelationOid(index
->indrelid
, AccessExclusiveLock
);
706 ReleaseSysCache(tuple
);
710 /* Get the lock before trying to fetch the syscache entry */
711 LockRelationOid(relOid
, AccessExclusiveLock
);
713 tuple
= SearchSysCache(RELOID
,
714 ObjectIdGetDatum(relOid
),
716 if (!HeapTupleIsValid(tuple
))
717 elog(ERROR
, "cache lookup failed for relation %u", relOid
);
718 classform
= (Form_pg_class
) GETSTRUCT(tuple
);
720 if (classform
->relkind
!= relkind
)
721 DropErrorMsgWrongType(rel
->relname
, classform
->relkind
, relkind
);
723 /* Allow DROP to either table owner or schema owner */
724 if (!pg_class_ownercheck(relOid
, GetUserId()) &&
725 !pg_namespace_ownercheck(classform
->relnamespace
, GetUserId()))
726 aclcheck_error(ACLCHECK_NOT_OWNER
, ACL_KIND_CLASS
,
729 if (!allowSystemTableMods
&& IsSystemClass(classform
))
731 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE
),
732 errmsg("permission denied: \"%s\" is a system catalog",
735 /* OK, we're ready to delete this one */
736 obj
.classId
= RelationRelationId
;
737 obj
.objectId
= relOid
;
740 add_exact_object_address(&obj
, objects
);
742 ReleaseSysCache(tuple
);
745 performMultipleDeletions(objects
, drop
->behavior
);
747 free_object_addresses(objects
);
752 * Executes a TRUNCATE command.
754 * This is a multi-relation truncate. We first open and grab exclusive
755 * lock on all relations involved, checking permissions and otherwise
756 * verifying that the relation is OK for truncation. In CASCADE mode,
757 * relations having FK references to the targeted relations are automatically
758 * added to the group; in RESTRICT mode, we check that all FK references are
759 * internal to the group that's being truncated. Finally all the relations
760 * are truncated and reindexed.
763 ExecuteTruncate(TruncateStmt
*stmt
)
767 List
*seq_relids
= NIL
;
769 ResultRelInfo
*resultRelInfos
;
770 ResultRelInfo
*resultRelInfo
;
774 * Open, exclusive-lock, and check all the explicitly-specified relations
776 foreach(cell
, stmt
->relations
)
778 RangeVar
*rv
= lfirst(cell
);
780 bool recurse
= interpretInhOption(rv
->inhOpt
);
783 rel
= heap_openrv(rv
, AccessExclusiveLock
);
784 myrelid
= RelationGetRelid(rel
);
785 /* don't throw error for "TRUNCATE foo, foo" */
786 if (list_member_oid(relids
, myrelid
))
788 heap_close(rel
, AccessExclusiveLock
);
791 truncate_check_rel(rel
);
792 rels
= lappend(rels
, rel
);
793 relids
= lappend_oid(relids
, myrelid
);
800 children
= find_all_inheritors(myrelid
, AccessExclusiveLock
);
802 foreach(child
, children
)
804 Oid childrelid
= lfirst_oid(child
);
806 if (list_member_oid(relids
, childrelid
))
809 /* find_all_inheritors already got lock */
810 rel
= heap_open(childrelid
, NoLock
);
811 truncate_check_rel(rel
);
812 rels
= lappend(rels
, rel
);
813 relids
= lappend_oid(relids
, childrelid
);
819 * In CASCADE mode, suck in all referencing relations as well. This
820 * requires multiple iterations to find indirectly-dependent relations. At
821 * each phase, we need to exclusive-lock new rels before looking for their
822 * dependencies, else we might miss something. Also, we check each rel as
823 * soon as we open it, to avoid a faux pas such as holding lock for a long
824 * time on a rel we have no permissions for.
826 if (stmt
->behavior
== DROP_CASCADE
)
832 newrelids
= heap_truncate_find_FKs(relids
);
833 if (newrelids
== NIL
)
834 break; /* nothing else to add */
836 foreach(cell
, newrelids
)
838 Oid relid
= lfirst_oid(cell
);
841 rel
= heap_open(relid
, AccessExclusiveLock
);
843 (errmsg("truncate cascades to table \"%s\"",
844 RelationGetRelationName(rel
))));
845 truncate_check_rel(rel
);
846 rels
= lappend(rels
, rel
);
847 relids
= lappend_oid(relids
, relid
);
853 * Check foreign key references. In CASCADE mode, this should be
854 * unnecessary since we just pulled in all the references; but as a
855 * cross-check, do it anyway if in an Assert-enabled build.
857 #ifdef USE_ASSERT_CHECKING
858 heap_truncate_check_FKs(rels
, false);
860 if (stmt
->behavior
== DROP_RESTRICT
)
861 heap_truncate_check_FKs(rels
, false);
865 * If we are asked to restart sequences, find all the sequences, lock them
866 * (we only need AccessShareLock because that's all that ALTER SEQUENCE
867 * takes), and check permissions. We want to do this early since it's
868 * pointless to do all the truncation work only to fail on sequence
871 if (stmt
->restart_seqs
)
875 Relation rel
= (Relation
) lfirst(cell
);
876 List
*seqlist
= getOwnedSequences(RelationGetRelid(rel
));
879 foreach(seqcell
, seqlist
)
881 Oid seq_relid
= lfirst_oid(seqcell
);
884 seq_rel
= relation_open(seq_relid
, AccessShareLock
);
886 /* This check must match AlterSequence! */
887 if (!pg_class_ownercheck(seq_relid
, GetUserId()))
888 aclcheck_error(ACLCHECK_NOT_OWNER
, ACL_KIND_CLASS
,
889 RelationGetRelationName(seq_rel
));
891 seq_relids
= lappend_oid(seq_relids
, seq_relid
);
893 relation_close(seq_rel
, NoLock
);
898 /* Prepare to catch AFTER triggers. */
899 AfterTriggerBeginQuery();
902 * To fire triggers, we'll need an EState as well as a ResultRelInfo for
905 estate
= CreateExecutorState();
906 resultRelInfos
= (ResultRelInfo
*)
907 palloc(list_length(rels
) * sizeof(ResultRelInfo
));
908 resultRelInfo
= resultRelInfos
;
911 Relation rel
= (Relation
) lfirst(cell
);
913 InitResultRelInfo(resultRelInfo
,
915 0, /* dummy rangetable index */
916 CMD_DELETE
, /* don't need any index info */
920 estate
->es_result_relations
= resultRelInfos
;
921 estate
->es_num_result_relations
= list_length(rels
);
924 * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
925 * truncating (this is because one of them might throw an error). Also, if
926 * we were to allow them to prevent statement execution, that would need
927 * to be handled here.
929 resultRelInfo
= resultRelInfos
;
932 estate
->es_result_relation_info
= resultRelInfo
;
933 ExecBSTruncateTriggers(estate
, resultRelInfo
);
938 * OK, truncate each table.
942 Relation rel
= (Relation
) lfirst(cell
);
947 * Create a new empty storage file for the relation, and assign it as
948 * the relfilenode value. The old storage file is scheduled for
949 * deletion at commit.
951 setNewRelfilenode(rel
, RecentXmin
);
953 heap_relid
= RelationGetRelid(rel
);
954 toast_relid
= rel
->rd_rel
->reltoastrelid
;
957 * The same for the toast table, if any.
959 if (OidIsValid(toast_relid
))
961 rel
= relation_open(toast_relid
, AccessExclusiveLock
);
962 setNewRelfilenode(rel
, RecentXmin
);
963 heap_close(rel
, NoLock
);
967 * Reconstruct the indexes to match, and we're done.
969 reindex_relation(heap_relid
, true);
973 * Process all AFTER STATEMENT TRUNCATE triggers.
975 resultRelInfo
= resultRelInfos
;
978 estate
->es_result_relation_info
= resultRelInfo
;
979 ExecASTruncateTriggers(estate
, resultRelInfo
);
983 /* Handle queued AFTER triggers */
984 AfterTriggerEndQuery(estate
);
986 /* We can clean up the EState now */
987 FreeExecutorState(estate
);
989 /* And close the rels (can't do this while EState still holds refs) */
992 Relation rel
= (Relation
) lfirst(cell
);
994 heap_close(rel
, NoLock
);
998 * Lastly, restart any owned sequences if we were asked to. This is done
999 * last because it's nontransactional: restarts will not roll back if we
1000 * abort later. Hence it's important to postpone them as long as
1001 * possible. (This is also a big reason why we locked and
1002 * permission-checked the sequences beforehand.)
1004 if (stmt
->restart_seqs
)
1006 List
*options
= list_make1(makeDefElem("restart", NULL
));
1008 foreach(cell
, seq_relids
)
1010 Oid seq_relid
= lfirst_oid(cell
);
1012 AlterSequenceInternal(seq_relid
, options
);
1018 * Check that a given rel is safe to truncate. Subroutine for ExecuteTruncate
1021 truncate_check_rel(Relation rel
)
1023 AclResult aclresult
;
1025 /* Only allow truncate on regular tables */
1026 if (rel
->rd_rel
->relkind
!= RELKIND_RELATION
)
1028 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
1029 errmsg("\"%s\" is not a table",
1030 RelationGetRelationName(rel
))));
1032 /* Permissions checks */
1033 aclresult
= pg_class_aclcheck(RelationGetRelid(rel
), GetUserId(),
1035 if (aclresult
!= ACLCHECK_OK
)
1036 aclcheck_error(aclresult
, ACL_KIND_CLASS
,
1037 RelationGetRelationName(rel
));
1039 if (!allowSystemTableMods
&& IsSystemRelation(rel
))
1041 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE
),
1042 errmsg("permission denied: \"%s\" is a system catalog",
1043 RelationGetRelationName(rel
))));
1046 * We can never allow truncation of shared or nailed-in-cache relations,
1047 * because we can't support changing their relfilenode values.
1049 if (rel
->rd_rel
->relisshared
|| rel
->rd_isnailed
)
1051 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
1052 errmsg("cannot truncate system relation \"%s\"",
1053 RelationGetRelationName(rel
))));
1056 * Don't allow truncate on temp tables of other backends ... their local
1057 * buffer manager is not going to cope.
1059 if (RELATION_IS_OTHER_TEMP(rel
))
1061 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
1062 errmsg("cannot truncate temporary tables of other sessions")));
1065 * Also check for active uses of the relation in the current transaction,
1066 * including open scans and pending AFTER trigger events.
1068 CheckTableNotInUse(rel
, "TRUNCATE");
1073 * Returns new schema given initial schema and superclasses.
1076 * 'schema' is the column/attribute definition for the table. (It's a list
1077 * of ColumnDef's.) It is destructively changed.
1078 * 'supers' is a list of names (as RangeVar nodes) of parent relations.
1079 * 'istemp' is TRUE if we are creating a temp relation.
1082 * 'supOids' receives a list of the OIDs of the parent relations.
1083 * 'supconstr' receives a list of constraints belonging to the parents,
1084 * updated as necessary to be valid for the child.
1085 * 'supOidCount' is set to the number of parents that have OID columns.
1088 * Completed schema list.
1091 * The order in which the attributes are inherited is very important.
1092 * Intuitively, the inherited attributes should come first. If a table
1093 * inherits from multiple parents, the order of those attributes are
1094 * according to the order of the parents specified in CREATE TABLE.
1096 * Here's an example:
1098 * create table person (name text, age int4, location point);
1099 * create table emp (salary int4, manager text) inherits(person);
1100 * create table student (gpa float8) inherits (person);
1101 * create table stud_emp (percent int4) inherits (emp, student);
1103 * The order of the attributes of stud_emp is:
1105 * person {1:name, 2:age, 3:location}
1107 * {6:gpa} student emp {4:salary, 5:manager}
1109 * stud_emp {7:percent}
1111 * If the same attribute name appears multiple times, then it appears
1112 * in the result table in the proper location for its first appearance.
1114 * Constraints (including NOT NULL constraints) for the child table
1115 * are the union of all relevant constraints, from both the child schema
1116 * and parent tables.
1118 * The default value for a child column is defined as:
1119 * (1) If the child schema specifies a default, that value is used.
1120 * (2) If neither the child nor any parent specifies a default, then
1121 * the column will not have a default.
1122 * (3) If conflicting defaults are inherited from different parents
1123 * (and not overridden by the child), an error is raised.
1124 * (4) Otherwise the inherited default is used.
1125 * Rule (3) is new in Postgres 7.1; in earlier releases you got a
1126 * rather arbitrary choice of which parent default to use.
1130 MergeAttributes(List
*schema
, List
*supers
, bool istemp
,
1131 List
**supOids
, List
**supconstr
, int *supOidCount
)
1134 List
*inhSchema
= NIL
;
1135 List
*parentOids
= NIL
;
1136 List
*constraints
= NIL
;
1137 int parentsWithOids
= 0;
1138 bool have_bogus_defaults
= false;
1139 char *bogus_marker
= "Bogus!"; /* marks conflicting defaults */
1143 * Check for and reject tables with too many columns. We perform this
1144 * check relatively early for two reasons: (a) we don't run the risk of
1145 * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
1146 * okay if we're processing <= 1600 columns, but could take minutes to
1147 * execute if the user attempts to create a table with hundreds of
1148 * thousands of columns.
1150 * Note that we also need to check that any we do not exceed this figure
1151 * after including columns from inherited relations.
1153 if (list_length(schema
) > MaxHeapAttributeNumber
)
1155 (errcode(ERRCODE_TOO_MANY_COLUMNS
),
1156 errmsg("tables can have at most %d columns",
1157 MaxHeapAttributeNumber
)));
1160 * Check for duplicate names in the explicit list of attributes.
1162 * Although we might consider merging such entries in the same way that we
1163 * handle name conflicts for inherited attributes, it seems to make more
1164 * sense to assume such conflicts are errors.
1166 foreach(entry
, schema
)
1168 ColumnDef
*coldef
= lfirst(entry
);
1171 for_each_cell(rest
, lnext(entry
))
1173 ColumnDef
*restdef
= lfirst(rest
);
1175 if (strcmp(coldef
->colname
, restdef
->colname
) == 0)
1177 (errcode(ERRCODE_DUPLICATE_COLUMN
),
1178 errmsg("column \"%s\" specified more than once",
1184 * Scan the parents left-to-right, and merge their attributes to form a
1185 * list of inherited attributes (inhSchema). Also check to see if we need
1186 * to inherit an OID column.
1189 foreach(entry
, supers
)
1191 RangeVar
*parent
= (RangeVar
*) lfirst(entry
);
1193 TupleDesc tupleDesc
;
1194 TupleConstr
*constr
;
1195 AttrNumber
*newattno
;
1196 AttrNumber parent_attno
;
1198 relation
= heap_openrv(parent
, AccessShareLock
);
1200 if (relation
->rd_rel
->relkind
!= RELKIND_RELATION
)
1202 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
1203 errmsg("inherited relation \"%s\" is not a table",
1205 /* Permanent rels cannot inherit from temporary ones */
1206 if (!istemp
&& relation
->rd_istemp
)
1208 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
1209 errmsg("cannot inherit from temporary relation \"%s\"",
1213 * We should have an UNDER permission flag for this, but for now,
1214 * demand that creator of a child table own the parent.
1216 if (!pg_class_ownercheck(RelationGetRelid(relation
), GetUserId()))
1217 aclcheck_error(ACLCHECK_NOT_OWNER
, ACL_KIND_CLASS
,
1218 RelationGetRelationName(relation
));
1221 * Reject duplications in the list of parents.
1223 if (list_member_oid(parentOids
, RelationGetRelid(relation
)))
1225 (errcode(ERRCODE_DUPLICATE_TABLE
),
1226 errmsg("relation \"%s\" would be inherited from more than once",
1229 parentOids
= lappend_oid(parentOids
, RelationGetRelid(relation
));
1231 if (relation
->rd_rel
->relhasoids
)
1234 tupleDesc
= RelationGetDescr(relation
);
1235 constr
= tupleDesc
->constr
;
1238 * newattno[] will contain the child-table attribute numbers for the
1239 * attributes of this parent table. (They are not the same for
1240 * parents after the first one, nor if we have dropped columns.)
1242 newattno
= (AttrNumber
*)
1243 palloc(tupleDesc
->natts
* sizeof(AttrNumber
));
1245 for (parent_attno
= 1; parent_attno
<= tupleDesc
->natts
;
1248 Form_pg_attribute attribute
= tupleDesc
->attrs
[parent_attno
- 1];
1249 char *attributeName
= NameStr(attribute
->attname
);
1254 * Ignore dropped columns in the parent.
1256 if (attribute
->attisdropped
)
1259 * change_varattnos_of_a_node asserts that this is greater
1260 * than zero, so if anything tries to use it, we should find
1263 newattno
[parent_attno
- 1] = 0;
1268 * Does it conflict with some previously inherited column?
1270 exist_attno
= findAttrByName(attributeName
, inhSchema
);
1271 if (exist_attno
> 0)
1277 * Yes, try to merge the two column definitions. They must
1278 * have the same type and typmod.
1281 (errmsg("merging multiple inherited definitions of column \"%s\"",
1283 def
= (ColumnDef
*) list_nth(inhSchema
, exist_attno
- 1);
1284 defTypeId
= typenameTypeId(NULL
, def
->typename
, &deftypmod
);
1285 if (defTypeId
!= attribute
->atttypid
||
1286 deftypmod
!= attribute
->atttypmod
)
1288 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1289 errmsg("inherited column \"%s\" has a type conflict",
1291 errdetail("%s versus %s",
1292 TypeNameToString(def
->typename
),
1293 format_type_be(attribute
->atttypid
))));
1295 /* Merge of NOT NULL constraints = OR 'em together */
1296 def
->is_not_null
|= attribute
->attnotnull
;
1297 /* Default and other constraints are handled below */
1298 newattno
[parent_attno
- 1] = exist_attno
;
1303 * No, create a new inherited column
1305 def
= makeNode(ColumnDef
);
1306 def
->colname
= pstrdup(attributeName
);
1307 def
->typename
= makeTypeNameFromOid(attribute
->atttypid
,
1308 attribute
->atttypmod
);
1310 def
->is_local
= false;
1311 def
->is_not_null
= attribute
->attnotnull
;
1312 def
->raw_default
= NULL
;
1313 def
->cooked_default
= NULL
;
1314 def
->constraints
= NIL
;
1315 inhSchema
= lappend(inhSchema
, def
);
1316 newattno
[parent_attno
- 1] = ++child_attno
;
1320 * Copy default if any
1322 if (attribute
->atthasdef
)
1324 char *this_default
= NULL
;
1325 AttrDefault
*attrdef
;
1328 /* Find default in constraint structure */
1329 Assert(constr
!= NULL
);
1330 attrdef
= constr
->defval
;
1331 for (i
= 0; i
< constr
->num_defval
; i
++)
1333 if (attrdef
[i
].adnum
== parent_attno
)
1335 this_default
= attrdef
[i
].adbin
;
1339 Assert(this_default
!= NULL
);
1342 * If default expr could contain any vars, we'd need to fix
1343 * 'em, but it can't; so default is ready to apply to child.
1345 * If we already had a default from some prior parent, check
1346 * to see if they are the same. If so, no problem; if not,
1347 * mark the column as having a bogus default. Below, we will
1348 * complain if the bogus default isn't overridden by the child
1351 Assert(def
->raw_default
== NULL
);
1352 if (def
->cooked_default
== NULL
)
1353 def
->cooked_default
= pstrdup(this_default
);
1354 else if (strcmp(def
->cooked_default
, this_default
) != 0)
1356 def
->cooked_default
= bogus_marker
;
1357 have_bogus_defaults
= true;
1363 * Now copy the CHECK constraints of this parent, adjusting attnos
1364 * using the completed newattno[] map. Identically named constraints
1365 * are merged if possible, else we throw error.
1367 if (constr
&& constr
->num_check
> 0)
1369 ConstrCheck
*check
= constr
->check
;
1372 for (i
= 0; i
< constr
->num_check
; i
++)
1374 char *name
= check
[i
].ccname
;
1377 /* adjust varattnos of ccbin here */
1378 expr
= stringToNode(check
[i
].ccbin
);
1379 change_varattnos_of_a_node(expr
, newattno
);
1381 /* check for duplicate */
1382 if (!MergeCheckConstraint(constraints
, name
, expr
))
1384 /* nope, this is a new one */
1385 CookedConstraint
*cooked
;
1387 cooked
= (CookedConstraint
*) palloc(sizeof(CookedConstraint
));
1388 cooked
->contype
= CONSTR_CHECK
;
1389 cooked
->name
= pstrdup(name
);
1390 cooked
->attnum
= 0; /* not used for constraints */
1391 cooked
->expr
= expr
;
1392 cooked
->is_local
= false;
1393 cooked
->inhcount
= 1;
1394 constraints
= lappend(constraints
, cooked
);
1402 * Close the parent rel, but keep our AccessShareLock on it until xact
1403 * commit. That will prevent someone else from deleting or ALTERing
1404 * the parent before the child is committed.
1406 heap_close(relation
, NoLock
);
1410 * If we had no inherited attributes, the result schema is just the
1411 * explicitly declared columns. Otherwise, we need to merge the declared
1412 * columns into the inherited schema list.
1414 if (inhSchema
!= NIL
)
1416 foreach(entry
, schema
)
1418 ColumnDef
*newdef
= lfirst(entry
);
1419 char *attributeName
= newdef
->colname
;
1423 * Does it conflict with some previously inherited column?
1425 exist_attno
= findAttrByName(attributeName
, inhSchema
);
1426 if (exist_attno
> 0)
1435 * Yes, try to merge the two column definitions. They must
1436 * have the same type and typmod.
1439 (errmsg("merging column \"%s\" with inherited definition",
1441 def
= (ColumnDef
*) list_nth(inhSchema
, exist_attno
- 1);
1442 defTypeId
= typenameTypeId(NULL
, def
->typename
, &deftypmod
);
1443 newTypeId
= typenameTypeId(NULL
, newdef
->typename
, &newtypmod
);
1444 if (defTypeId
!= newTypeId
|| deftypmod
!= newtypmod
)
1446 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1447 errmsg("column \"%s\" has a type conflict",
1449 errdetail("%s versus %s",
1450 TypeNameToString(def
->typename
),
1451 TypeNameToString(newdef
->typename
))));
1452 /* Mark the column as locally defined */
1453 def
->is_local
= true;
1454 /* Merge of NOT NULL constraints = OR 'em together */
1455 def
->is_not_null
|= newdef
->is_not_null
;
1456 /* If new def has a default, override previous default */
1457 if (newdef
->raw_default
!= NULL
)
1459 def
->raw_default
= newdef
->raw_default
;
1460 def
->cooked_default
= newdef
->cooked_default
;
1466 * No, attach new column to result schema
1468 inhSchema
= lappend(inhSchema
, newdef
);
1475 * Check that we haven't exceeded the legal # of columns after merging
1476 * in inherited columns.
1478 if (list_length(schema
) > MaxHeapAttributeNumber
)
1480 (errcode(ERRCODE_TOO_MANY_COLUMNS
),
1481 errmsg("tables can have at most %d columns",
1482 MaxHeapAttributeNumber
)));
1486 * If we found any conflicting parent default values, check to make sure
1487 * they were overridden by the child.
1489 if (have_bogus_defaults
)
1491 foreach(entry
, schema
)
1493 ColumnDef
*def
= lfirst(entry
);
1495 if (def
->cooked_default
== bogus_marker
)
1497 (errcode(ERRCODE_INVALID_COLUMN_DEFINITION
),
1498 errmsg("column \"%s\" inherits conflicting default values",
1500 errhint("To resolve the conflict, specify a default explicitly.")));
1504 *supOids
= parentOids
;
1505 *supconstr
= constraints
;
1506 *supOidCount
= parentsWithOids
;
1512 * MergeCheckConstraint
1513 * Try to merge an inherited CHECK constraint with previous ones
1515 * If we inherit identically-named constraints from multiple parents, we must
1516 * merge them, or throw an error if they don't have identical definitions.
1518 * constraints is a list of CookedConstraint structs for previous constraints.
1520 * Returns TRUE if merged (constraint is a duplicate), or FALSE if it's
1521 * got a so-far-unique name, or throws error if conflict.
1524 MergeCheckConstraint(List
*constraints
, char *name
, Node
*expr
)
1528 foreach(lc
, constraints
)
1530 CookedConstraint
*ccon
= (CookedConstraint
*) lfirst(lc
);
1532 Assert(ccon
->contype
== CONSTR_CHECK
);
1534 /* Non-matching names never conflict */
1535 if (strcmp(ccon
->name
, name
) != 0)
1538 if (equal(expr
, ccon
->expr
))
1546 (errcode(ERRCODE_DUPLICATE_OBJECT
),
1547 errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
1556 * Replace varattno values in an expression tree according to the given
1557 * map array, that is, varattno N is replaced by newattno[N-1]. It is
1558 * caller's responsibility to ensure that the array is long enough to
1559 * define values for all user varattnos present in the tree. System column
1560 * attnos remain unchanged.
1562 * Note that the passed node tree is modified in-place!
1565 change_varattnos_of_a_node(Node
*node
, const AttrNumber
*newattno
)
1567 /* no setup needed, so away we go */
1568 (void) change_varattnos_walker(node
, newattno
);
1572 change_varattnos_walker(Node
*node
, const AttrNumber
*newattno
)
1578 Var
*var
= (Var
*) node
;
1580 if (var
->varlevelsup
== 0 && var
->varno
== 1 &&
1584 * ??? the following may be a problem when the node is multiply
1585 * referenced though stringToNode() doesn't create such a node
1588 Assert(newattno
[var
->varattno
- 1] > 0);
1589 var
->varattno
= var
->varoattno
= newattno
[var
->varattno
- 1];
1593 return expression_tree_walker(node
, change_varattnos_walker
,
1598 * Generate a map for change_varattnos_of_a_node from old and new TupleDesc's,
1599 * matching according to column name.
1602 varattnos_map(TupleDesc old
, TupleDesc
new)
1608 attmap
= (AttrNumber
*) palloc0(sizeof(AttrNumber
) * old
->natts
);
1609 for (i
= 1; i
<= old
->natts
; i
++)
1611 if (old
->attrs
[i
- 1]->attisdropped
)
1612 continue; /* leave the entry as zero */
1614 for (j
= 1; j
<= new->natts
; j
++)
1616 if (strcmp(NameStr(old
->attrs
[i
- 1]->attname
),
1617 NameStr(new->attrs
[j
- 1]->attname
)) == 0)
1628 * Generate a map for change_varattnos_of_a_node from a TupleDesc and a list
1632 varattnos_map_schema(TupleDesc old
, List
*schema
)
1637 attmap
= (AttrNumber
*) palloc0(sizeof(AttrNumber
) * old
->natts
);
1638 for (i
= 1; i
<= old
->natts
; i
++)
1640 if (old
->attrs
[i
- 1]->attisdropped
)
1641 continue; /* leave the entry as zero */
1643 attmap
[i
- 1] = findAttrByName(NameStr(old
->attrs
[i
- 1]->attname
),
1651 * StoreCatalogInheritance
1652 * Updates the system catalogs with proper inheritance information.
1654 * supers is a list of the OIDs of the new relation's direct ancestors.
1657 StoreCatalogInheritance(Oid relationId
, List
*supers
)
1666 AssertArg(OidIsValid(relationId
));
1672 * Store INHERITS information in pg_inherits using direct ancestors only.
1673 * Also enter dependencies on the direct ancestors, and make sure they are
1674 * marked with relhassubclass = true.
1676 * (Once upon a time, both direct and indirect ancestors were found here
1677 * and then entered into pg_ipl. Since that catalog doesn't exist
1678 * anymore, there's no need to look for indirect ancestors.)
1680 relation
= heap_open(InheritsRelationId
, RowExclusiveLock
);
1683 foreach(entry
, supers
)
1685 Oid parentOid
= lfirst_oid(entry
);
1687 StoreCatalogInheritance1(relationId
, parentOid
, seqNumber
, relation
);
1691 heap_close(relation
, RowExclusiveLock
);
1695 * Make catalog entries showing relationId as being an inheritance child
1696 * of parentOid. inhRelation is the already-opened pg_inherits catalog.
1699 StoreCatalogInheritance1(Oid relationId
, Oid parentOid
,
1700 int16 seqNumber
, Relation inhRelation
)
1702 TupleDesc desc
= RelationGetDescr(inhRelation
);
1703 Datum datum
[Natts_pg_inherits
];
1704 bool nullarr
[Natts_pg_inherits
];
1705 ObjectAddress childobject
,
1710 * Make the pg_inherits entry
1712 datum
[0] = ObjectIdGetDatum(relationId
); /* inhrelid */
1713 datum
[1] = ObjectIdGetDatum(parentOid
); /* inhparent */
1714 datum
[2] = Int16GetDatum(seqNumber
); /* inhseqno */
1720 tuple
= heap_form_tuple(desc
, datum
, nullarr
);
1722 simple_heap_insert(inhRelation
, tuple
);
1724 CatalogUpdateIndexes(inhRelation
, tuple
);
1726 heap_freetuple(tuple
);
1729 * Store a dependency too
1731 parentobject
.classId
= RelationRelationId
;
1732 parentobject
.objectId
= parentOid
;
1733 parentobject
.objectSubId
= 0;
1734 childobject
.classId
= RelationRelationId
;
1735 childobject
.objectId
= relationId
;
1736 childobject
.objectSubId
= 0;
1738 recordDependencyOn(&childobject
, &parentobject
, DEPENDENCY_NORMAL
);
1741 * Mark the parent as having subclasses.
1743 setRelhassubclassInRelation(parentOid
, true);
1747 * Look for an existing schema entry with the given name.
1749 * Returns the index (starting with 1) if attribute already exists in schema,
1753 findAttrByName(const char *attributeName
, List
*schema
)
1760 ColumnDef
*def
= lfirst(s
);
1762 if (strcmp(attributeName
, def
->colname
) == 0)
1771 * Update a relation's pg_class.relhassubclass entry to the given value
1774 setRelhassubclassInRelation(Oid relationId
, bool relhassubclass
)
1776 Relation relationRelation
;
1778 Form_pg_class classtuple
;
1781 * Fetch a modifiable copy of the tuple, modify it, update pg_class.
1783 * If the tuple already has the right relhassubclass setting, we don't
1784 * need to update it, but we still need to issue an SI inval message.
1786 relationRelation
= heap_open(RelationRelationId
, RowExclusiveLock
);
1787 tuple
= SearchSysCacheCopy(RELOID
,
1788 ObjectIdGetDatum(relationId
),
1790 if (!HeapTupleIsValid(tuple
))
1791 elog(ERROR
, "cache lookup failed for relation %u", relationId
);
1792 classtuple
= (Form_pg_class
) GETSTRUCT(tuple
);
1794 if (classtuple
->relhassubclass
!= relhassubclass
)
1796 classtuple
->relhassubclass
= relhassubclass
;
1797 simple_heap_update(relationRelation
, &tuple
->t_self
, tuple
);
1799 /* keep the catalog indexes up to date */
1800 CatalogUpdateIndexes(relationRelation
, tuple
);
1804 /* no need to change tuple, but force relcache rebuild anyway */
1805 CacheInvalidateRelcacheByTuple(tuple
);
1808 heap_freetuple(tuple
);
1809 heap_close(relationRelation
, RowExclusiveLock
);
1814 * renameatt - changes the name of a attribute in a relation
1816 * Attname attribute is changed in attribute catalog.
1817 * No record of the previous attname is kept (correct?).
1819 * get proper relrelation from relation catalog (if not arg)
1820 * scan attribute catalog
1821 * for name conflict (within rel)
1822 * for original attribute (if not arg)
1823 * modify attname in attribute tuple
1824 * insert modified attribute in attribute catalog
1825 * delete original attribute from attribute catalog
1828 renameatt(Oid myrelid
,
1829 const char *oldattname
,
1830 const char *newattname
,
1834 Relation targetrelation
;
1835 Relation attrelation
;
1837 Form_pg_attribute attform
;
1840 ListCell
*indexoidscan
;
1843 * Grab an exclusive lock on the target table, which we will NOT release
1844 * until end of transaction.
1846 targetrelation
= relation_open(myrelid
, AccessExclusiveLock
);
1849 * permissions checking. this would normally be done in utility.c, but
1850 * this particular routine is recursive.
1852 * normally, only the owner of a class can change its schema.
1854 if (!pg_class_ownercheck(myrelid
, GetUserId()))
1855 aclcheck_error(ACLCHECK_NOT_OWNER
, ACL_KIND_CLASS
,
1856 RelationGetRelationName(targetrelation
));
1857 if (!allowSystemTableMods
&& IsSystemRelation(targetrelation
))
1859 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE
),
1860 errmsg("permission denied: \"%s\" is a system catalog",
1861 RelationGetRelationName(targetrelation
))));
1864 * if the 'recurse' flag is set then we are supposed to rename this
1865 * attribute in all classes that inherit from 'relname' (as well as in
1868 * any permissions or problems with duplicate attributes will cause the
1869 * whole transaction to abort, which is what we want -- all or nothing.
1876 children
= find_all_inheritors(myrelid
, AccessExclusiveLock
);
1879 * find_all_inheritors does the recursive search of the inheritance
1880 * hierarchy, so all we have to do is process all of the relids in the
1881 * list that it returns.
1883 foreach(child
, children
)
1885 Oid childrelid
= lfirst_oid(child
);
1887 if (childrelid
== myrelid
)
1889 /* note we need not recurse again */
1890 renameatt(childrelid
, oldattname
, newattname
, false, true);
1896 * If we are told not to recurse, there had better not be any child
1897 * tables; else the rename would put them out of step.
1900 find_inheritance_children(myrelid
, NoLock
) != NIL
)
1902 (errcode(ERRCODE_INVALID_TABLE_DEFINITION
),
1903 errmsg("inherited column \"%s\" must be renamed in child tables too",
1907 attrelation
= heap_open(AttributeRelationId
, RowExclusiveLock
);
1909 atttup
= SearchSysCacheCopyAttName(myrelid
, oldattname
);
1910 if (!HeapTupleIsValid(atttup
))
1912 (errcode(ERRCODE_UNDEFINED_COLUMN
),
1913 errmsg("column \"%s\" does not exist",
1915 attform
= (Form_pg_attribute
) GETSTRUCT(atttup
);
1917 attnum
= attform
->attnum
;
1920 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
1921 errmsg("cannot rename system column \"%s\"",
1925 * if the attribute is inherited, forbid the renaming, unless we are
1926 * already inside a recursive rename.
1928 if (attform
->attinhcount
> 0 && !recursing
)
1930 (errcode(ERRCODE_INVALID_TABLE_DEFINITION
),
1931 errmsg("cannot rename inherited column \"%s\"",
1934 /* should not already exist */
1935 /* this test is deliberately not attisdropped-aware */
1936 if (SearchSysCacheExists(ATTNAME
,
1937 ObjectIdGetDatum(myrelid
),
1938 PointerGetDatum(newattname
),
1941 (errcode(ERRCODE_DUPLICATE_COLUMN
),
1942 errmsg("column \"%s\" of relation \"%s\" already exists",
1943 newattname
, RelationGetRelationName(targetrelation
))));
1945 namestrcpy(&(attform
->attname
), newattname
);
1947 simple_heap_update(attrelation
, &atttup
->t_self
, atttup
);
1949 /* keep system catalog indexes current */
1950 CatalogUpdateIndexes(attrelation
, atttup
);
1952 heap_freetuple(atttup
);
1955 * Update column names of indexes that refer to the column being renamed.
1957 indexoidlist
= RelationGetIndexList(targetrelation
);
1959 foreach(indexoidscan
, indexoidlist
)
1961 Oid indexoid
= lfirst_oid(indexoidscan
);
1963 Form_pg_index indexform
;
1967 * Scan through index columns to see if there's any simple index
1968 * entries for this attribute. We ignore expressional entries.
1970 indextup
= SearchSysCache(INDEXRELID
,
1971 ObjectIdGetDatum(indexoid
),
1973 if (!HeapTupleIsValid(indextup
))
1974 elog(ERROR
, "cache lookup failed for index %u", indexoid
);
1975 indexform
= (Form_pg_index
) GETSTRUCT(indextup
);
1977 for (i
= 0; i
< indexform
->indnatts
; i
++)
1979 if (attnum
!= indexform
->indkey
.values
[i
])
1983 * Found one, rename it.
1985 atttup
= SearchSysCacheCopy(ATTNUM
,
1986 ObjectIdGetDatum(indexoid
),
1987 Int16GetDatum(i
+ 1),
1989 if (!HeapTupleIsValid(atttup
))
1990 continue; /* should we raise an error? */
1993 * Update the (copied) attribute tuple.
1995 namestrcpy(&(((Form_pg_attribute
) GETSTRUCT(atttup
))->attname
),
1998 simple_heap_update(attrelation
, &atttup
->t_self
, atttup
);
2000 /* keep system catalog indexes current */
2001 CatalogUpdateIndexes(attrelation
, atttup
);
2003 heap_freetuple(atttup
);
2006 ReleaseSysCache(indextup
);
2009 list_free(indexoidlist
);
2011 heap_close(attrelation
, RowExclusiveLock
);
2013 relation_close(targetrelation
, NoLock
); /* close rel but keep lock */
2018 * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW RENAME
2020 * Caller has already done permissions checks.
2023 RenameRelation(Oid myrelid
, const char *newrelname
, ObjectType reltype
)
2025 Relation targetrelation
;
2030 * Grab an exclusive lock on the target table, index, sequence or view,
2031 * which we will NOT release until end of transaction.
2033 targetrelation
= relation_open(myrelid
, AccessExclusiveLock
);
2035 namespaceId
= RelationGetNamespace(targetrelation
);
2036 relkind
= targetrelation
->rd_rel
->relkind
;
2039 * For compatibility with prior releases, we don't complain if ALTER TABLE
2040 * or ALTER INDEX is used to rename a sequence or view.
2042 if (reltype
== OBJECT_SEQUENCE
&& relkind
!= RELKIND_SEQUENCE
)
2044 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
2045 errmsg("\"%s\" is not a sequence",
2046 RelationGetRelationName(targetrelation
))));
2048 if (reltype
== OBJECT_VIEW
&& relkind
!= RELKIND_VIEW
)
2050 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
2051 errmsg("\"%s\" is not a view",
2052 RelationGetRelationName(targetrelation
))));
2055 * Don't allow ALTER TABLE on composite types. We want people to use ALTER
2058 if (relkind
== RELKIND_COMPOSITE_TYPE
)
2060 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
2061 errmsg("\"%s\" is a composite type",
2062 RelationGetRelationName(targetrelation
)),
2063 errhint("Use ALTER TYPE instead.")));
2066 RenameRelationInternal(myrelid
, newrelname
, namespaceId
);
2069 * Close rel, but keep exclusive lock!
2071 relation_close(targetrelation
, NoLock
);
2075 * RenameRelationInternal - change the name of a relation
2077 * XXX - When renaming sequences, we don't bother to modify the
2078 * sequence name that is stored within the sequence itself
2079 * (this would cause problems with MVCC). In the future,
2080 * the sequence name should probably be removed from the
2081 * sequence, AFAIK there's no need for it to be there.
2084 RenameRelationInternal(Oid myrelid
, const char *newrelname
, Oid namespaceId
)
2086 Relation targetrelation
;
2087 Relation relrelation
; /* for RELATION relation */
2089 Form_pg_class relform
;
2092 * Grab an exclusive lock on the target table, index, sequence or view,
2093 * which we will NOT release until end of transaction.
2095 targetrelation
= relation_open(myrelid
, AccessExclusiveLock
);
2098 * Find relation's pg_class tuple, and make sure newrelname isn't in use.
2100 relrelation
= heap_open(RelationRelationId
, RowExclusiveLock
);
2102 reltup
= SearchSysCacheCopy(RELOID
,
2103 ObjectIdGetDatum(myrelid
),
2105 if (!HeapTupleIsValid(reltup
)) /* shouldn't happen */
2106 elog(ERROR
, "cache lookup failed for relation %u", myrelid
);
2107 relform
= (Form_pg_class
) GETSTRUCT(reltup
);
2109 if (get_relname_relid(newrelname
, namespaceId
) != InvalidOid
)
2111 (errcode(ERRCODE_DUPLICATE_TABLE
),
2112 errmsg("relation \"%s\" already exists",
2116 * Update pg_class tuple with new relname. (Scribbling on reltup is OK
2117 * because it's a copy...)
2119 namestrcpy(&(relform
->relname
), newrelname
);
2121 simple_heap_update(relrelation
, &reltup
->t_self
, reltup
);
2123 /* keep the system catalog indexes current */
2124 CatalogUpdateIndexes(relrelation
, reltup
);
2126 heap_freetuple(reltup
);
2127 heap_close(relrelation
, RowExclusiveLock
);
2130 * Also rename the associated type, if any.
2132 if (OidIsValid(targetrelation
->rd_rel
->reltype
))
2133 RenameTypeInternal(targetrelation
->rd_rel
->reltype
,
2134 newrelname
, namespaceId
);
2137 * Also rename the associated constraint, if any.
2139 if (targetrelation
->rd_rel
->relkind
== RELKIND_INDEX
)
2141 Oid constraintId
= get_index_constraint(myrelid
);
2143 if (OidIsValid(constraintId
))
2144 RenameConstraintById(constraintId
, newrelname
);
2148 * Close rel, but keep exclusive lock!
2150 relation_close(targetrelation
, NoLock
);
2154 * Disallow ALTER TABLE (and similar commands) when the current backend has
2155 * any open reference to the target table besides the one just acquired by
2156 * the calling command; this implies there's an open cursor or active plan.
2157 * We need this check because our AccessExclusiveLock doesn't protect us
2158 * against stomping on our own foot, only other people's feet!
2160 * For ALTER TABLE, the only case known to cause serious trouble is ALTER
2161 * COLUMN TYPE, and some changes are obviously pretty benign, so this could
2162 * possibly be relaxed to only error out for certain types of alterations.
2163 * But the use-case for allowing any of these things is not obvious, so we
2164 * won't work hard at it for now.
2166 * We also reject these commands if there are any pending AFTER trigger events
2167 * for the rel. This is certainly necessary for the rewriting variants of
2168 * ALTER TABLE, because they don't preserve tuple TIDs and so the pending
2169 * events would try to fetch the wrong tuples. It might be overly cautious
2170 * in other cases, but again it seems better to err on the side of paranoia.
2172 * REINDEX calls this with "rel" referencing the index to be rebuilt; here
2173 * we are worried about active indexscans on the index. The trigger-event
2174 * check can be skipped, since we are doing no damage to the parent table.
2176 * The statement name (eg, "ALTER TABLE") is passed for use in error messages.
2179 CheckTableNotInUse(Relation rel
, const char *stmt
)
2181 int expected_refcnt
;
2183 expected_refcnt
= rel
->rd_isnailed
? 2 : 1;
2184 if (rel
->rd_refcnt
!= expected_refcnt
)
2186 (errcode(ERRCODE_OBJECT_IN_USE
),
2187 /* translator: first %s is a SQL command, eg ALTER TABLE */
2188 errmsg("cannot %s \"%s\" because "
2189 "it is being used by active queries in this session",
2190 stmt
, RelationGetRelationName(rel
))));
2192 if (rel
->rd_rel
->relkind
!= RELKIND_INDEX
&&
2193 AfterTriggerPendingOnRel(RelationGetRelid(rel
)))
2195 (errcode(ERRCODE_OBJECT_IN_USE
),
2196 /* translator: first %s is a SQL command, eg ALTER TABLE */
2197 errmsg("cannot %s \"%s\" because "
2198 "it has pending trigger events",
2199 stmt
, RelationGetRelationName(rel
))));
2204 * Execute ALTER TABLE, which can be a list of subcommands
2206 * ALTER TABLE is performed in three phases:
2207 * 1. Examine subcommands and perform pre-transformation checking.
2208 * 2. Update system catalogs.
2209 * 3. Scan table(s) to check new constraints, and optionally recopy
2210 * the data into new table(s).
2211 * Phase 3 is not performed unless one or more of the subcommands requires
2212 * it. The intention of this design is to allow multiple independent
2213 * updates of the table schema to be performed with only one pass over the
2216 * ATPrepCmd performs phase 1. A "work queue" entry is created for
2217 * each table to be affected (there may be multiple affected tables if the
2218 * commands traverse a table inheritance hierarchy). Also we do preliminary
2219 * validation of the subcommands, including parse transformation of those
2220 * expressions that need to be evaluated with respect to the old table
2223 * ATRewriteCatalogs performs phase 2 for each affected table. (Note that
2224 * phases 2 and 3 normally do no explicit recursion, since phase 1 already
2225 * did it --- although some subcommands have to recurse in phase 2 instead.)
2226 * Certain subcommands need to be performed before others to avoid
2227 * unnecessary conflicts; for example, DROP COLUMN should come before
2228 * ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
2229 * lists, one for each logical "pass" of phase 2.
2231 * ATRewriteTables performs phase 3 for those tables that need it.
2233 * Thanks to the magic of MVCC, an error anywhere along the way rolls back
2234 * the whole operation; we don't have to do anything special to clean up.
2237 AlterTable(AlterTableStmt
*stmt
)
2239 Relation rel
= relation_openrv(stmt
->relation
, AccessExclusiveLock
);
2241 CheckTableNotInUse(rel
, "ALTER TABLE");
2243 /* Check relation type against type specified in the ALTER command */
2244 switch (stmt
->relkind
)
2249 * For mostly-historical reasons, we allow ALTER TABLE to apply to
2250 * all relation types.
2255 if (rel
->rd_rel
->relkind
!= RELKIND_INDEX
)
2257 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
2258 errmsg("\"%s\" is not an index",
2259 RelationGetRelationName(rel
))));
2262 case OBJECT_SEQUENCE
:
2263 if (rel
->rd_rel
->relkind
!= RELKIND_SEQUENCE
)
2265 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
2266 errmsg("\"%s\" is not a sequence",
2267 RelationGetRelationName(rel
))));
2271 if (rel
->rd_rel
->relkind
!= RELKIND_VIEW
)
2273 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
2274 errmsg("\"%s\" is not a view",
2275 RelationGetRelationName(rel
))));
2279 elog(ERROR
, "unrecognized object type: %d", (int) stmt
->relkind
);
2282 ATController(rel
, stmt
->cmds
, interpretInhOption(stmt
->relation
->inhOpt
));
2286 * AlterTableInternal
2288 * ALTER TABLE with target specified by OID
2290 * We do not reject if the relation is already open, because it's quite
2291 * likely that one or more layers of caller have it open. That means it
2292 * is unsafe to use this entry point for alterations that could break
2293 * existing query plans. On the assumption it's not used for such, we
2294 * don't have to reject pending AFTER triggers, either.
2297 AlterTableInternal(Oid relid
, List
*cmds
, bool recurse
)
2299 Relation rel
= relation_open(relid
, AccessExclusiveLock
);
2301 ATController(rel
, cmds
, recurse
);
2305 ATController(Relation rel
, List
*cmds
, bool recurse
)
2310 /* Phase 1: preliminary examination of commands, create work queue */
2313 AlterTableCmd
*cmd
= (AlterTableCmd
*) lfirst(lcmd
);
2315 ATPrepCmd(&wqueue
, rel
, cmd
, recurse
, false);
2318 /* Close the relation, but keep lock until commit */
2319 relation_close(rel
, NoLock
);
2321 /* Phase 2: update system catalogs */
2322 ATRewriteCatalogs(&wqueue
);
2324 /* Phase 3: scan/rewrite tables as needed */
2325 ATRewriteTables(&wqueue
);
2331 * Traffic cop for ALTER TABLE Phase 1 operations, including simple
2332 * recursion and permission checks.
2334 * Caller must have acquired AccessExclusiveLock on relation already.
2335 * This lock should be held until commit.
2338 ATPrepCmd(List
**wqueue
, Relation rel
, AlterTableCmd
*cmd
,
2339 bool recurse
, bool recursing
)
2341 AlteredTableInfo
*tab
;
2344 /* Find or create work queue entry for this table */
2345 tab
= ATGetQueueEntry(wqueue
, rel
);
2348 * Copy the original subcommand for each table. This avoids conflicts
2349 * when different child tables need to make different parse
2350 * transformations (for example, the same column may have different column
2351 * numbers in different children).
2353 cmd
= copyObject(cmd
);
2356 * Do permissions checking, recursion to child tables if needed, and any
2357 * additional phase-1 processing needed.
2359 switch (cmd
->subtype
)
2361 case AT_AddColumn
: /* ADD COLUMN */
2362 ATSimplePermissions(rel
, false);
2363 /* Performs own recursion */
2364 ATPrepAddColumn(wqueue
, rel
, recurse
, cmd
);
2365 pass
= AT_PASS_ADD_COL
;
2367 case AT_AddColumnToView
: /* add column via CREATE OR REPLACE
2369 ATSimplePermissions(rel
, true);
2370 /* Performs own recursion */
2371 ATPrepAddColumn(wqueue
, rel
, recurse
, cmd
);
2372 pass
= AT_PASS_ADD_COL
;
2374 case AT_ColumnDefault
: /* ALTER COLUMN DEFAULT */
2377 * We allow defaults on views so that INSERT into a view can have
2378 * default-ish behavior. This works because the rewriter
2379 * substitutes default values into INSERTs before it expands
2382 ATSimplePermissions(rel
, true);
2383 ATSimpleRecursion(wqueue
, rel
, cmd
, recurse
);
2384 /* No command-specific prep needed */
2385 pass
= cmd
->def
? AT_PASS_ADD_CONSTR
: AT_PASS_DROP
;
2387 case AT_DropNotNull
: /* ALTER COLUMN DROP NOT NULL */
2388 ATSimplePermissions(rel
, false);
2389 ATSimpleRecursion(wqueue
, rel
, cmd
, recurse
);
2390 /* No command-specific prep needed */
2391 pass
= AT_PASS_DROP
;
2393 case AT_SetNotNull
: /* ALTER COLUMN SET NOT NULL */
2394 ATSimplePermissions(rel
, false);
2395 ATSimpleRecursion(wqueue
, rel
, cmd
, recurse
);
2396 /* No command-specific prep needed */
2397 pass
= AT_PASS_ADD_CONSTR
;
2399 case AT_SetStatistics
: /* ALTER COLUMN STATISTICS */
2400 ATSimpleRecursion(wqueue
, rel
, cmd
, recurse
);
2401 /* Performs own permission checks */
2402 ATPrepSetStatistics(rel
, cmd
->name
, cmd
->def
);
2403 pass
= AT_PASS_COL_ATTRS
;
2405 case AT_SetStorage
: /* ALTER COLUMN STORAGE */
2406 ATSimplePermissions(rel
, false);
2407 ATSimpleRecursion(wqueue
, rel
, cmd
, recurse
);
2408 /* No command-specific prep needed */
2409 pass
= AT_PASS_COL_ATTRS
;
2411 case AT_DropColumn
: /* DROP COLUMN */
2412 ATSimplePermissions(rel
, false);
2413 /* Recursion occurs during execution phase */
2414 /* No command-specific prep needed except saving recurse flag */
2416 cmd
->subtype
= AT_DropColumnRecurse
;
2417 pass
= AT_PASS_DROP
;
2419 case AT_AddIndex
: /* ADD INDEX */
2420 ATSimplePermissions(rel
, false);
2421 /* This command never recurses */
2422 /* No command-specific prep needed */
2423 pass
= AT_PASS_ADD_INDEX
;
2425 case AT_AddConstraint
: /* ADD CONSTRAINT */
2426 ATSimplePermissions(rel
, false);
2427 /* Recursion occurs during execution phase */
2428 /* No command-specific prep needed except saving recurse flag */
2430 cmd
->subtype
= AT_AddConstraintRecurse
;
2431 pass
= AT_PASS_ADD_CONSTR
;
2433 case AT_DropConstraint
: /* DROP CONSTRAINT */
2434 ATSimplePermissions(rel
, false);
2435 /* Recursion occurs during execution phase */
2436 /* No command-specific prep needed except saving recurse flag */
2438 cmd
->subtype
= AT_DropConstraintRecurse
;
2439 pass
= AT_PASS_DROP
;
2441 case AT_AlterColumnType
: /* ALTER COLUMN TYPE */
2442 ATSimplePermissions(rel
, false);
2443 /* Performs own recursion */
2444 ATPrepAlterColumnType(wqueue
, tab
, rel
, recurse
, recursing
, cmd
);
2445 pass
= AT_PASS_ALTER_TYPE
;
2447 case AT_ChangeOwner
: /* ALTER OWNER */
2448 /* This command never recurses */
2449 /* No command-specific prep needed */
2450 pass
= AT_PASS_MISC
;
2452 case AT_ClusterOn
: /* CLUSTER ON */
2453 case AT_DropCluster
: /* SET WITHOUT CLUSTER */
2454 ATSimplePermissions(rel
, false);
2455 /* These commands never recurse */
2456 /* No command-specific prep needed */
2457 pass
= AT_PASS_MISC
;
2459 case AT_AddOids
: /* SET WITH OIDS */
2460 ATSimplePermissions(rel
, false);
2461 /* Performs own recursion */
2462 if (!rel
->rd_rel
->relhasoids
|| recursing
)
2463 ATPrepAddOids(wqueue
, rel
, recurse
, cmd
);
2464 pass
= AT_PASS_ADD_COL
;
2466 case AT_DropOids
: /* SET WITHOUT OIDS */
2467 ATSimplePermissions(rel
, false);
2468 /* Performs own recursion */
2469 if (rel
->rd_rel
->relhasoids
)
2471 AlterTableCmd
*dropCmd
= makeNode(AlterTableCmd
);
2473 dropCmd
->subtype
= AT_DropColumn
;
2474 dropCmd
->name
= pstrdup("oid");
2475 dropCmd
->behavior
= cmd
->behavior
;
2476 ATPrepCmd(wqueue
, rel
, dropCmd
, recurse
, false);
2478 pass
= AT_PASS_DROP
;
2480 case AT_SetTableSpace
: /* SET TABLESPACE */
2481 ATSimplePermissionsRelationOrIndex(rel
);
2482 /* This command never recurses */
2483 ATPrepSetTableSpace(tab
, rel
, cmd
->name
);
2484 pass
= AT_PASS_MISC
; /* doesn't actually matter */
2486 case AT_SetRelOptions
: /* SET (...) */
2487 case AT_ResetRelOptions
: /* RESET (...) */
2488 ATSimplePermissionsRelationOrIndex(rel
);
2489 /* This command never recurses */
2490 /* No command-specific prep needed */
2491 pass
= AT_PASS_MISC
;
2493 case AT_EnableTrig
: /* ENABLE TRIGGER variants */
2494 case AT_EnableAlwaysTrig
:
2495 case AT_EnableReplicaTrig
:
2496 case AT_EnableTrigAll
:
2497 case AT_EnableTrigUser
:
2498 case AT_DisableTrig
: /* DISABLE TRIGGER variants */
2499 case AT_DisableTrigAll
:
2500 case AT_DisableTrigUser
:
2501 case AT_EnableRule
: /* ENABLE/DISABLE RULE variants */
2502 case AT_EnableAlwaysRule
:
2503 case AT_EnableReplicaRule
:
2504 case AT_DisableRule
:
2505 case AT_AddInherit
: /* INHERIT / NO INHERIT */
2506 case AT_DropInherit
:
2507 ATSimplePermissions(rel
, false);
2508 /* These commands never recurse */
2509 /* No command-specific prep needed */
2510 pass
= AT_PASS_MISC
;
2513 elog(ERROR
, "unrecognized alter table type: %d",
2514 (int) cmd
->subtype
);
2515 pass
= 0; /* keep compiler quiet */
2519 /* Add the subcommand to the appropriate list for phase 2 */
2520 tab
->subcmds
[pass
] = lappend(tab
->subcmds
[pass
], cmd
);
2526 * Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
2527 * dispatched in a "safe" execution order (designed to avoid unnecessary
2531 ATRewriteCatalogs(List
**wqueue
)
2537 * We process all the tables "in parallel", one pass at a time. This is
2538 * needed because we may have to propagate work from one table to another
2539 * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
2540 * re-adding of the foreign key constraint to the other table). Work can
2541 * only be propagated into later passes, however.
2543 for (pass
= 0; pass
< AT_NUM_PASSES
; pass
++)
2545 /* Go through each table that needs to be processed */
2546 foreach(ltab
, *wqueue
)
2548 AlteredTableInfo
*tab
= (AlteredTableInfo
*) lfirst(ltab
);
2549 List
*subcmds
= tab
->subcmds
[pass
];
2557 * Exclusive lock was obtained by phase 1, needn't get it again
2559 rel
= relation_open(tab
->relid
, NoLock
);
2561 foreach(lcmd
, subcmds
)
2562 ATExecCmd(wqueue
, tab
, rel
, (AlterTableCmd
*) lfirst(lcmd
));
2565 * After the ALTER TYPE pass, do cleanup work (this is not done in
2566 * ATExecAlterColumnType since it should be done only once if
2567 * multiple columns of a table are altered).
2569 if (pass
== AT_PASS_ALTER_TYPE
)
2570 ATPostAlterTypeCleanup(wqueue
, tab
);
2572 relation_close(rel
, NoLock
);
2577 * Check to see if a toast table must be added, if we executed any
2578 * subcommands that might have added a column or changed column storage.
2580 foreach(ltab
, *wqueue
)
2582 AlteredTableInfo
*tab
= (AlteredTableInfo
*) lfirst(ltab
);
2584 if (tab
->relkind
== RELKIND_RELATION
&&
2585 (tab
->subcmds
[AT_PASS_ADD_COL
] ||
2586 tab
->subcmds
[AT_PASS_ALTER_TYPE
] ||
2587 tab
->subcmds
[AT_PASS_COL_ATTRS
]))
2588 AlterTableCreateToastTable(tab
->relid
, InvalidOid
,
2594 * ATExecCmd: dispatch a subcommand to appropriate execution routine
2597 ATExecCmd(List
**wqueue
, AlteredTableInfo
*tab
, Relation rel
,
2600 switch (cmd
->subtype
)
2602 case AT_AddColumn
: /* ADD COLUMN */
2603 case AT_AddColumnToView
: /* add column via CREATE OR REPLACE
2605 ATExecAddColumn(tab
, rel
, (ColumnDef
*) cmd
->def
, false);
2607 case AT_ColumnDefault
: /* ALTER COLUMN DEFAULT */
2608 ATExecColumnDefault(rel
, cmd
->name
, cmd
->def
);
2610 case AT_DropNotNull
: /* ALTER COLUMN DROP NOT NULL */
2611 ATExecDropNotNull(rel
, cmd
->name
);
2613 case AT_SetNotNull
: /* ALTER COLUMN SET NOT NULL */
2614 ATExecSetNotNull(tab
, rel
, cmd
->name
);
2616 case AT_SetStatistics
: /* ALTER COLUMN STATISTICS */
2617 ATExecSetStatistics(rel
, cmd
->name
, cmd
->def
);
2619 case AT_SetStorage
: /* ALTER COLUMN STORAGE */
2620 ATExecSetStorage(rel
, cmd
->name
, cmd
->def
);
2622 case AT_DropColumn
: /* DROP COLUMN */
2623 ATExecDropColumn(wqueue
, rel
, cmd
->name
,
2624 cmd
->behavior
, false, false);
2626 case AT_DropColumnRecurse
: /* DROP COLUMN with recursion */
2627 ATExecDropColumn(wqueue
, rel
, cmd
->name
,
2628 cmd
->behavior
, true, false);
2630 case AT_AddIndex
: /* ADD INDEX */
2631 ATExecAddIndex(tab
, rel
, (IndexStmt
*) cmd
->def
, false);
2633 case AT_ReAddIndex
: /* ADD INDEX */
2634 ATExecAddIndex(tab
, rel
, (IndexStmt
*) cmd
->def
, true);
2636 case AT_AddConstraint
: /* ADD CONSTRAINT */
2637 ATExecAddConstraint(wqueue
, tab
, rel
, cmd
->def
, false);
2639 case AT_AddConstraintRecurse
: /* ADD CONSTRAINT with recursion */
2640 ATExecAddConstraint(wqueue
, tab
, rel
, cmd
->def
, true);
2642 case AT_DropConstraint
: /* DROP CONSTRAINT */
2643 ATExecDropConstraint(rel
, cmd
->name
, cmd
->behavior
, false, false);
2645 case AT_DropConstraintRecurse
: /* DROP CONSTRAINT with recursion */
2646 ATExecDropConstraint(rel
, cmd
->name
, cmd
->behavior
, true, false);
2648 case AT_AlterColumnType
: /* ALTER COLUMN TYPE */
2649 ATExecAlterColumnType(tab
, rel
, cmd
->name
, (TypeName
*) cmd
->def
);
2651 case AT_ChangeOwner
: /* ALTER OWNER */
2652 ATExecChangeOwner(RelationGetRelid(rel
),
2653 get_roleid_checked(cmd
->name
),
2656 case AT_ClusterOn
: /* CLUSTER ON */
2657 ATExecClusterOn(rel
, cmd
->name
);
2659 case AT_DropCluster
: /* SET WITHOUT CLUSTER */
2660 ATExecDropCluster(rel
);
2662 case AT_AddOids
: /* SET WITH OIDS */
2663 /* Use the ADD COLUMN code, unless prep decided to do nothing */
2664 if (cmd
->def
!= NULL
)
2665 ATExecAddColumn(tab
, rel
, (ColumnDef
*) cmd
->def
, true);
2667 case AT_DropOids
: /* SET WITHOUT OIDS */
2670 * Nothing to do here; we'll have generated a DropColumn
2671 * subcommand to do the real work
2674 case AT_SetTableSpace
: /* SET TABLESPACE */
2677 * Nothing to do here; Phase 3 does the work
2680 case AT_SetRelOptions
: /* SET (...) */
2681 ATExecSetRelOptions(rel
, (List
*) cmd
->def
, false);
2683 case AT_ResetRelOptions
: /* RESET (...) */
2684 ATExecSetRelOptions(rel
, (List
*) cmd
->def
, true);
2687 case AT_EnableTrig
: /* ENABLE TRIGGER name */
2688 ATExecEnableDisableTrigger(rel
, cmd
->name
,
2689 TRIGGER_FIRES_ON_ORIGIN
, false);
2691 case AT_EnableAlwaysTrig
: /* ENABLE ALWAYS TRIGGER name */
2692 ATExecEnableDisableTrigger(rel
, cmd
->name
,
2693 TRIGGER_FIRES_ALWAYS
, false);
2695 case AT_EnableReplicaTrig
: /* ENABLE REPLICA TRIGGER name */
2696 ATExecEnableDisableTrigger(rel
, cmd
->name
,
2697 TRIGGER_FIRES_ON_REPLICA
, false);
2699 case AT_DisableTrig
: /* DISABLE TRIGGER name */
2700 ATExecEnableDisableTrigger(rel
, cmd
->name
,
2701 TRIGGER_DISABLED
, false);
2703 case AT_EnableTrigAll
: /* ENABLE TRIGGER ALL */
2704 ATExecEnableDisableTrigger(rel
, NULL
,
2705 TRIGGER_FIRES_ON_ORIGIN
, false);
2707 case AT_DisableTrigAll
: /* DISABLE TRIGGER ALL */
2708 ATExecEnableDisableTrigger(rel
, NULL
,
2709 TRIGGER_DISABLED
, false);
2711 case AT_EnableTrigUser
: /* ENABLE TRIGGER USER */
2712 ATExecEnableDisableTrigger(rel
, NULL
,
2713 TRIGGER_FIRES_ON_ORIGIN
, true);
2715 case AT_DisableTrigUser
: /* DISABLE TRIGGER USER */
2716 ATExecEnableDisableTrigger(rel
, NULL
,
2717 TRIGGER_DISABLED
, true);
2720 case AT_EnableRule
: /* ENABLE RULE name */
2721 ATExecEnableDisableRule(rel
, cmd
->name
,
2722 RULE_FIRES_ON_ORIGIN
);
2724 case AT_EnableAlwaysRule
: /* ENABLE ALWAYS RULE name */
2725 ATExecEnableDisableRule(rel
, cmd
->name
,
2728 case AT_EnableReplicaRule
: /* ENABLE REPLICA RULE name */
2729 ATExecEnableDisableRule(rel
, cmd
->name
,
2730 RULE_FIRES_ON_REPLICA
);
2732 case AT_DisableRule
: /* DISABLE RULE name */
2733 ATExecEnableDisableRule(rel
, cmd
->name
,
2738 ATExecAddInherit(rel
, (RangeVar
*) cmd
->def
);
2740 case AT_DropInherit
:
2741 ATExecDropInherit(rel
, (RangeVar
*) cmd
->def
);
2744 elog(ERROR
, "unrecognized alter table type: %d",
2745 (int) cmd
->subtype
);
2750 * Bump the command counter to ensure the next subcommand in the sequence
2751 * can see the changes so far
2753 CommandCounterIncrement();
2757 * ATRewriteTables: ALTER TABLE phase 3
2760 ATRewriteTables(List
**wqueue
)
2764 /* Go through each table that needs to be checked or rewritten */
2765 foreach(ltab
, *wqueue
)
2767 AlteredTableInfo
*tab
= (AlteredTableInfo
*) lfirst(ltab
);
2770 * We only need to rewrite the table if at least one column needs to
2771 * be recomputed, or we are adding/removing the OID column.
2773 if (tab
->newvals
!= NIL
|| tab
->new_changeoids
)
2775 /* Build a temporary relation and copy data */
2777 char NewHeapName
[NAMEDATALEN
];
2780 ObjectAddress object
;
2782 OldHeap
= heap_open(tab
->relid
, NoLock
);
2785 * We can never allow rewriting of shared or nailed-in-cache
2786 * relations, because we can't support changing their relfilenode
2789 if (OldHeap
->rd_rel
->relisshared
|| OldHeap
->rd_isnailed
)
2791 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2792 errmsg("cannot rewrite system relation \"%s\"",
2793 RelationGetRelationName(OldHeap
))));
2796 * Don't allow rewrite on temp tables of other backends ... their
2797 * local buffer manager is not going to cope.
2799 if (RELATION_IS_OTHER_TEMP(OldHeap
))
2801 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2802 errmsg("cannot rewrite temporary tables of other sessions")));
2805 * Select destination tablespace (same as original unless user
2806 * requested a change)
2808 if (tab
->newTableSpace
)
2809 NewTableSpace
= tab
->newTableSpace
;
2811 NewTableSpace
= OldHeap
->rd_rel
->reltablespace
;
2813 heap_close(OldHeap
, NoLock
);
2816 * Create the new heap, using a temporary name in the same
2817 * namespace as the existing table. NOTE: there is some risk of
2818 * collision with user relnames. Working around this seems more
2819 * trouble than it's worth; in particular, we can't create the new
2820 * heap in a different namespace from the old, or we will have
2821 * problems with the TEMP status of temp tables.
2823 snprintf(NewHeapName
, sizeof(NewHeapName
),
2824 "pg_temp_%u", tab
->relid
);
2826 OIDNewHeap
= make_new_heap(tab
->relid
, NewHeapName
, NewTableSpace
);
2829 * Copy the heap data into the new table with the desired
2830 * modifications, and test the current data within the table
2831 * against new constraints generated by ALTER TABLE commands.
2833 ATRewriteTable(tab
, OIDNewHeap
);
2836 * Swap the physical files of the old and new heaps. Since we are
2837 * generating a new heap, we can use RecentXmin for the table's
2838 * new relfrozenxid because we rewrote all the tuples on
2839 * ATRewriteTable, so no older Xid remains on the table.
2841 swap_relation_files(tab
->relid
, OIDNewHeap
, RecentXmin
);
2843 CommandCounterIncrement();
2845 /* Destroy new heap with old filenode */
2846 object
.classId
= RelationRelationId
;
2847 object
.objectId
= OIDNewHeap
;
2848 object
.objectSubId
= 0;
2851 * The new relation is local to our transaction and we know
2852 * nothing depends on it, so DROP_RESTRICT should be OK.
2854 performDeletion(&object
, DROP_RESTRICT
);
2855 /* performDeletion does CommandCounterIncrement at end */
2858 * Rebuild each index on the relation (but not the toast table,
2859 * which is all-new anyway). We do not need
2860 * CommandCounterIncrement() because reindex_relation does it.
2862 reindex_relation(tab
->relid
, false);
2867 * Test the current data within the table against new constraints
2868 * generated by ALTER TABLE commands, but don't rebuild data.
2870 if (tab
->constraints
!= NIL
|| tab
->new_notnull
)
2871 ATRewriteTable(tab
, InvalidOid
);
2874 * If we had SET TABLESPACE but no reason to reconstruct tuples,
2875 * just do a block-by-block copy.
2877 if (tab
->newTableSpace
)
2878 ATExecSetTableSpace(tab
->relid
, tab
->newTableSpace
);
2883 * Foreign key constraints are checked in a final pass, since (a) it's
2884 * generally best to examine each one separately, and (b) it's at least
2885 * theoretically possible that we have changed both relations of the
2886 * foreign key, and we'd better have finished both rewrites before we try
2887 * to read the tables.
2889 foreach(ltab
, *wqueue
)
2891 AlteredTableInfo
*tab
= (AlteredTableInfo
*) lfirst(ltab
);
2892 Relation rel
= NULL
;
2895 foreach(lcon
, tab
->constraints
)
2897 NewConstraint
*con
= lfirst(lcon
);
2899 if (con
->contype
== CONSTR_FOREIGN
)
2901 FkConstraint
*fkconstraint
= (FkConstraint
*) con
->qual
;
2906 /* Long since locked, no need for another */
2907 rel
= heap_open(tab
->relid
, NoLock
);
2910 refrel
= heap_open(con
->refrelid
, RowShareLock
);
2912 validateForeignKeyConstraint(fkconstraint
, rel
, refrel
,
2915 heap_close(refrel
, NoLock
);
2920 heap_close(rel
, NoLock
);
2925 * ATRewriteTable: scan or rewrite one table
2927 * OIDNewHeap is InvalidOid if we don't need to rewrite
2930 ATRewriteTable(AlteredTableInfo
*tab
, Oid OIDNewHeap
)
2934 TupleDesc oldTupDesc
;
2935 TupleDesc newTupDesc
;
2936 bool needscan
= false;
2937 List
*notnull_attrs
;
2943 * Open the relation(s). We have surely already locked the existing
2946 oldrel
= heap_open(tab
->relid
, NoLock
);
2947 oldTupDesc
= tab
->oldDesc
;
2948 newTupDesc
= RelationGetDescr(oldrel
); /* includes all mods */
2950 if (OidIsValid(OIDNewHeap
))
2951 newrel
= heap_open(OIDNewHeap
, AccessExclusiveLock
);
2956 * If we need to rewrite the table, the operation has to be propagated to
2957 * tables that use this table's rowtype as a column type.
2959 * (Eventually this will probably become true for scans as well, but at
2960 * the moment a composite type does not enforce any constraints, so it's
2961 * not necessary/appropriate to enforce them just during ALTER.)
2964 find_composite_type_dependencies(oldrel
->rd_rel
->reltype
,
2965 RelationGetRelationName(oldrel
),
2969 * Generate the constraint and default execution states
2972 estate
= CreateExecutorState();
2974 /* Build the needed expression execution states */
2975 foreach(l
, tab
->constraints
)
2977 NewConstraint
*con
= lfirst(l
);
2979 switch (con
->contype
)
2983 con
->qualstate
= (List
*)
2984 ExecPrepareExpr((Expr
*) con
->qual
, estate
);
2986 case CONSTR_FOREIGN
:
2987 /* Nothing to do here */
2990 elog(ERROR
, "unrecognized constraint type: %d",
2991 (int) con
->contype
);
2995 foreach(l
, tab
->newvals
)
2997 NewColumnValue
*ex
= lfirst(l
);
2999 ex
->exprstate
= ExecPrepareExpr((Expr
*) ex
->expr
, estate
);
3002 notnull_attrs
= NIL
;
3003 if (newrel
|| tab
->new_notnull
)
3006 * If we are rebuilding the tuples OR if we added any new NOT NULL
3007 * constraints, check all not-null constraints. This is a bit of
3008 * overkill but it minimizes risk of bugs, and heap_attisnull is a
3009 * pretty cheap test anyway.
3011 for (i
= 0; i
< newTupDesc
->natts
; i
++)
3013 if (newTupDesc
->attrs
[i
]->attnotnull
&&
3014 !newTupDesc
->attrs
[i
]->attisdropped
)
3015 notnull_attrs
= lappend_int(notnull_attrs
, i
);
3021 if (newrel
|| needscan
)
3023 ExprContext
*econtext
;
3026 TupleTableSlot
*oldslot
;
3027 TupleTableSlot
*newslot
;
3030 MemoryContext oldCxt
;
3031 List
*dropped_attrs
= NIL
;
3034 econtext
= GetPerTupleExprContext(estate
);
3037 * Make tuple slots for old and new tuples. Note that even when the
3038 * tuples are the same, the tupDescs might not be (consider ADD COLUMN
3039 * without a default).
3041 oldslot
= MakeSingleTupleTableSlot(oldTupDesc
);
3042 newslot
= MakeSingleTupleTableSlot(newTupDesc
);
3044 /* Preallocate values/isnull arrays */
3045 i
= Max(newTupDesc
->natts
, oldTupDesc
->natts
);
3046 values
= (Datum
*) palloc(i
* sizeof(Datum
));
3047 isnull
= (bool *) palloc(i
* sizeof(bool));
3048 memset(values
, 0, i
* sizeof(Datum
));
3049 memset(isnull
, true, i
* sizeof(bool));
3052 * Any attributes that are dropped according to the new tuple
3053 * descriptor can be set to NULL. We precompute the list of dropped
3054 * attributes to avoid needing to do so in the per-tuple loop.
3056 for (i
= 0; i
< newTupDesc
->natts
; i
++)
3058 if (newTupDesc
->attrs
[i
]->attisdropped
)
3059 dropped_attrs
= lappend_int(dropped_attrs
, i
);
3063 * Scan through the rows, generating a new row if needed and then
3064 * checking all the constraints.
3066 scan
= heap_beginscan(oldrel
, SnapshotNow
, 0, NULL
);
3069 * Switch to per-tuple memory context and reset it for each tuple
3070 * produced, so we don't leak memory.
3072 oldCxt
= MemoryContextSwitchTo(GetPerTupleMemoryContext(estate
));
3074 while ((tuple
= heap_getnext(scan
, ForwardScanDirection
)) != NULL
)
3078 Oid tupOid
= InvalidOid
;
3080 /* Extract data from old tuple */
3081 heap_deform_tuple(tuple
, oldTupDesc
, values
, isnull
);
3082 if (oldTupDesc
->tdhasoid
)
3083 tupOid
= HeapTupleGetOid(tuple
);
3085 /* Set dropped attributes to null in new tuple */
3086 foreach(lc
, dropped_attrs
)
3087 isnull
[lfirst_int(lc
)] = true;
3090 * Process supplied expressions to replace selected columns.
3091 * Expression inputs come from the old tuple.
3093 ExecStoreTuple(tuple
, oldslot
, InvalidBuffer
, false);
3094 econtext
->ecxt_scantuple
= oldslot
;
3096 foreach(l
, tab
->newvals
)
3098 NewColumnValue
*ex
= lfirst(l
);
3100 values
[ex
->attnum
- 1] = ExecEvalExpr(ex
->exprstate
,
3102 &isnull
[ex
->attnum
- 1],
3107 * Form the new tuple. Note that we don't explicitly pfree it,
3108 * since the per-tuple memory context will be reset shortly.
3110 tuple
= heap_form_tuple(newTupDesc
, values
, isnull
);
3112 /* Preserve OID, if any */
3113 if (newTupDesc
->tdhasoid
)
3114 HeapTupleSetOid(tuple
, tupOid
);
3117 /* Now check any constraints on the possibly-changed tuple */
3118 ExecStoreTuple(tuple
, newslot
, InvalidBuffer
, false);
3119 econtext
->ecxt_scantuple
= newslot
;
3121 foreach(l
, notnull_attrs
)
3123 int attn
= lfirst_int(l
);
3125 if (heap_attisnull(tuple
, attn
+ 1))
3127 (errcode(ERRCODE_NOT_NULL_VIOLATION
),
3128 errmsg("column \"%s\" contains null values",
3129 NameStr(newTupDesc
->attrs
[attn
]->attname
))));
3132 foreach(l
, tab
->constraints
)
3134 NewConstraint
*con
= lfirst(l
);
3136 switch (con
->contype
)
3139 if (!ExecQual(con
->qualstate
, econtext
, true))
3141 (errcode(ERRCODE_CHECK_VIOLATION
),
3142 errmsg("check constraint \"%s\" is violated by some row",
3145 case CONSTR_FOREIGN
:
3146 /* Nothing to do here */
3149 elog(ERROR
, "unrecognized constraint type: %d",
3150 (int) con
->contype
);
3154 /* Write the tuple out to the new relation */
3156 simple_heap_insert(newrel
, tuple
);
3158 ResetExprContext(econtext
);
3160 CHECK_FOR_INTERRUPTS();
3163 MemoryContextSwitchTo(oldCxt
);
3166 ExecDropSingleTupleTableSlot(oldslot
);
3167 ExecDropSingleTupleTableSlot(newslot
);
3170 FreeExecutorState(estate
);
3172 heap_close(oldrel
, NoLock
);
3174 heap_close(newrel
, NoLock
);
3178 * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
3180 static AlteredTableInfo
*
3181 ATGetQueueEntry(List
**wqueue
, Relation rel
)
3183 Oid relid
= RelationGetRelid(rel
);
3184 AlteredTableInfo
*tab
;
3187 foreach(ltab
, *wqueue
)
3189 tab
= (AlteredTableInfo
*) lfirst(ltab
);
3190 if (tab
->relid
== relid
)
3195 * Not there, so add it. Note that we make a copy of the relation's
3196 * existing descriptor before anything interesting can happen to it.
3198 tab
= (AlteredTableInfo
*) palloc0(sizeof(AlteredTableInfo
));
3200 tab
->relkind
= rel
->rd_rel
->relkind
;
3201 tab
->oldDesc
= CreateTupleDescCopy(RelationGetDescr(rel
));
3203 *wqueue
= lappend(*wqueue
, tab
);
3209 * ATSimplePermissions
3211 * - Ensure that it is a relation (or possibly a view)
3212 * - Ensure this user is the owner
3213 * - Ensure that it is not a system table
3216 ATSimplePermissions(Relation rel
, bool allowView
)
3218 if (rel
->rd_rel
->relkind
!= RELKIND_RELATION
)
3222 if (rel
->rd_rel
->relkind
!= RELKIND_VIEW
)
3224 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
3225 errmsg("\"%s\" is not a table or view",
3226 RelationGetRelationName(rel
))));
3230 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
3231 errmsg("\"%s\" is not a table",
3232 RelationGetRelationName(rel
))));
3235 /* Permissions checks */
3236 if (!pg_class_ownercheck(RelationGetRelid(rel
), GetUserId()))
3237 aclcheck_error(ACLCHECK_NOT_OWNER
, ACL_KIND_CLASS
,
3238 RelationGetRelationName(rel
));
3240 if (!allowSystemTableMods
&& IsSystemRelation(rel
))
3242 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE
),
3243 errmsg("permission denied: \"%s\" is a system catalog",
3244 RelationGetRelationName(rel
))));
3248 * ATSimplePermissionsRelationOrIndex
3250 * - Ensure that it is a relation or an index
3251 * - Ensure this user is the owner
3252 * - Ensure that it is not a system table
3255 ATSimplePermissionsRelationOrIndex(Relation rel
)
3257 if (rel
->rd_rel
->relkind
!= RELKIND_RELATION
&&
3258 rel
->rd_rel
->relkind
!= RELKIND_INDEX
)
3260 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
3261 errmsg("\"%s\" is not a table or index",
3262 RelationGetRelationName(rel
))));
3264 /* Permissions checks */
3265 if (!pg_class_ownercheck(RelationGetRelid(rel
), GetUserId()))
3266 aclcheck_error(ACLCHECK_NOT_OWNER
, ACL_KIND_CLASS
,
3267 RelationGetRelationName(rel
));
3269 if (!allowSystemTableMods
&& IsSystemRelation(rel
))
3271 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE
),
3272 errmsg("permission denied: \"%s\" is a system catalog",
3273 RelationGetRelationName(rel
))));
3279 * Simple table recursion sufficient for most ALTER TABLE operations.
3280 * All direct and indirect children are processed in an unspecified order.
3281 * Note that if a child inherits from the original table via multiple
3282 * inheritance paths, it will be visited just once.
3285 ATSimpleRecursion(List
**wqueue
, Relation rel
,
3286 AlterTableCmd
*cmd
, bool recurse
)
3289 * Propagate to children if desired. Non-table relations never have
3290 * children, so no need to search in that case.
3292 if (recurse
&& rel
->rd_rel
->relkind
== RELKIND_RELATION
)
3294 Oid relid
= RelationGetRelid(rel
);
3298 children
= find_all_inheritors(relid
, AccessExclusiveLock
);
3301 * find_all_inheritors does the recursive search of the inheritance
3302 * hierarchy, so all we have to do is process all of the relids in the
3303 * list that it returns.
3305 foreach(child
, children
)
3307 Oid childrelid
= lfirst_oid(child
);
3310 if (childrelid
== relid
)
3312 /* find_all_inheritors already got lock */
3313 childrel
= relation_open(childrelid
, NoLock
);
3314 CheckTableNotInUse(childrel
, "ALTER TABLE");
3315 ATPrepCmd(wqueue
, childrel
, cmd
, false, true);
3316 relation_close(childrel
, NoLock
);
3322 * ATOneLevelRecursion
3324 * Here, we visit only direct inheritance children. It is expected that
3325 * the command's prep routine will recurse again to find indirect children.
3326 * When using this technique, a multiply-inheriting child will be visited
3330 ATOneLevelRecursion(List
**wqueue
, Relation rel
,
3333 Oid relid
= RelationGetRelid(rel
);
3337 children
= find_inheritance_children(relid
, AccessExclusiveLock
);
3339 foreach(child
, children
)
3341 Oid childrelid
= lfirst_oid(child
);
3344 /* find_inheritance_children already got lock */
3345 childrel
= relation_open(childrelid
, NoLock
);
3346 CheckTableNotInUse(childrel
, "ALTER TABLE");
3347 ATPrepCmd(wqueue
, childrel
, cmd
, true, true);
3348 relation_close(childrel
, NoLock
);
3354 * find_composite_type_dependencies
3356 * Check to see if a composite type is being used as a column in some
3357 * other table (possibly nested several levels deep in composite types!).
3358 * Eventually, we'd like to propagate the check or rewrite operation
3359 * into other such tables, but for now, just error out if we find any.
3361 * Caller should provide either a table name or a type name (not both) to
3362 * report in the error message, if any.
3364 * We assume that functions and views depending on the type are not reasons
3365 * to reject the ALTER. (How safe is this really?)
3368 find_composite_type_dependencies(Oid typeOid
,
3369 const char *origTblName
,
3370 const char *origTypeName
)
3374 SysScanDesc depScan
;
3379 * We scan pg_depend to find those things that depend on the rowtype. (We
3380 * assume we can ignore refobjsubid for a rowtype.)
3382 depRel
= heap_open(DependRelationId
, AccessShareLock
);
3384 ScanKeyInit(&key
[0],
3385 Anum_pg_depend_refclassid
,
3386 BTEqualStrategyNumber
, F_OIDEQ
,
3387 ObjectIdGetDatum(TypeRelationId
));
3388 ScanKeyInit(&key
[1],
3389 Anum_pg_depend_refobjid
,
3390 BTEqualStrategyNumber
, F_OIDEQ
,
3391 ObjectIdGetDatum(typeOid
));
3393 depScan
= systable_beginscan(depRel
, DependReferenceIndexId
, true,
3394 SnapshotNow
, 2, key
);
3396 while (HeapTupleIsValid(depTup
= systable_getnext(depScan
)))
3398 Form_pg_depend pg_depend
= (Form_pg_depend
) GETSTRUCT(depTup
);
3400 Form_pg_attribute att
;
3402 /* Ignore dependees that aren't user columns of relations */
3403 /* (we assume system columns are never of rowtypes) */
3404 if (pg_depend
->classid
!= RelationRelationId
||
3405 pg_depend
->objsubid
<= 0)
3408 rel
= relation_open(pg_depend
->objid
, AccessShareLock
);
3409 att
= rel
->rd_att
->attrs
[pg_depend
->objsubid
- 1];
3411 if (rel
->rd_rel
->relkind
== RELKIND_RELATION
)
3415 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
3416 errmsg("cannot alter table \"%s\" because column \"%s\".\"%s\" uses its rowtype",
3418 RelationGetRelationName(rel
),
3419 NameStr(att
->attname
))));
3422 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
3423 errmsg("cannot alter type \"%s\" because column \"%s\".\"%s\" uses it",
3425 RelationGetRelationName(rel
),
3426 NameStr(att
->attname
))));
3428 else if (OidIsValid(rel
->rd_rel
->reltype
))
3431 * A view or composite type itself isn't a problem, but we must
3432 * recursively check for indirect dependencies via its rowtype.
3434 find_composite_type_dependencies(rel
->rd_rel
->reltype
,
3435 origTblName
, origTypeName
);
3438 relation_close(rel
, AccessShareLock
);
3441 systable_endscan(depScan
);
3443 relation_close(depRel
, AccessShareLock
);
3446 * If there's an array type for the rowtype, must check for uses of it,
3449 arrayOid
= get_array_type(typeOid
);
3450 if (OidIsValid(arrayOid
))
3451 find_composite_type_dependencies(arrayOid
, origTblName
, origTypeName
);
3456 * ALTER TABLE ADD COLUMN
3458 * Adds an additional attribute to a relation making the assumption that
3459 * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
3460 * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
3464 ATPrepAddColumn(List
**wqueue
, Relation rel
, bool recurse
,
3468 * Recurse to add the column to child classes, if requested.
3470 * We must recurse one level at a time, so that multiply-inheriting
3471 * children are visited the right number of times and end up with the
3472 * right attinhcount.
3476 AlterTableCmd
*childCmd
= copyObject(cmd
);
3477 ColumnDef
*colDefChild
= (ColumnDef
*) childCmd
->def
;
3479 /* Child should see column as singly inherited */
3480 colDefChild
->inhcount
= 1;
3481 colDefChild
->is_local
= false;
3483 ATOneLevelRecursion(wqueue
, rel
, childCmd
);
3488 * If we are told not to recurse, there had better not be any child
3489 * tables; else the addition would put them out of step.
3491 if (find_inheritance_children(RelationGetRelid(rel
), NoLock
) != NIL
)
3493 (errcode(ERRCODE_INVALID_TABLE_DEFINITION
),
3494 errmsg("column must be added to child tables too")));
3499 ATExecAddColumn(AlteredTableInfo
*tab
, Relation rel
,
3500 ColumnDef
*colDef
, bool isOid
)
3502 Oid myrelid
= RelationGetRelid(rel
);
3506 FormData_pg_attribute attribute
;
3509 HeapTuple typeTuple
;
3515 attrdesc
= heap_open(AttributeRelationId
, RowExclusiveLock
);
3518 * Are we adding the column to a recursion child? If so, check whether to
3519 * merge with an existing definition for the column.
3521 if (colDef
->inhcount
> 0)
3525 /* Does child already have a column by this name? */
3526 tuple
= SearchSysCacheCopyAttName(myrelid
, colDef
->colname
);
3527 if (HeapTupleIsValid(tuple
))
3529 Form_pg_attribute childatt
= (Form_pg_attribute
) GETSTRUCT(tuple
);
3533 /* Child column must match by type */
3534 ctypeId
= typenameTypeId(NULL
, colDef
->typename
, &ctypmod
);
3535 if (ctypeId
!= childatt
->atttypid
||
3536 ctypmod
!= childatt
->atttypmod
)
3538 (errcode(ERRCODE_DATATYPE_MISMATCH
),
3539 errmsg("child table \"%s\" has different type for column \"%s\"",
3540 RelationGetRelationName(rel
), colDef
->colname
)));
3542 /* If it's OID, child column must actually be OID */
3543 if (isOid
&& childatt
->attnum
!= ObjectIdAttributeNumber
)
3545 (errcode(ERRCODE_DATATYPE_MISMATCH
),
3546 errmsg("child table \"%s\" has a conflicting \"%s\" column",
3547 RelationGetRelationName(rel
), colDef
->colname
)));
3549 /* Bump the existing child att's inhcount */
3550 childatt
->attinhcount
++;
3551 simple_heap_update(attrdesc
, &tuple
->t_self
, tuple
);
3552 CatalogUpdateIndexes(attrdesc
, tuple
);
3554 heap_freetuple(tuple
);
3556 /* Inform the user about the merge */
3558 (errmsg("merging definition of column \"%s\" for child \"%s\"",
3559 colDef
->colname
, RelationGetRelationName(rel
))));
3561 heap_close(attrdesc
, RowExclusiveLock
);
3566 pgclass
= heap_open(RelationRelationId
, RowExclusiveLock
);
3568 reltup
= SearchSysCacheCopy(RELOID
,
3569 ObjectIdGetDatum(myrelid
),
3571 if (!HeapTupleIsValid(reltup
))
3572 elog(ERROR
, "cache lookup failed for relation %u", myrelid
);
3573 relkind
= ((Form_pg_class
) GETSTRUCT(reltup
))->relkind
;
3576 * this test is deliberately not attisdropped-aware, since if one tries to
3577 * add a column matching a dropped column name, it's gonna fail anyway.
3579 if (SearchSysCacheExists(ATTNAME
,
3580 ObjectIdGetDatum(myrelid
),
3581 PointerGetDatum(colDef
->colname
),
3584 (errcode(ERRCODE_DUPLICATE_COLUMN
),
3585 errmsg("column \"%s\" of relation \"%s\" already exists",
3586 colDef
->colname
, RelationGetRelationName(rel
))));
3588 /* Determine the new attribute's number */
3590 newattnum
= ObjectIdAttributeNumber
;
3593 newattnum
= ((Form_pg_class
) GETSTRUCT(reltup
))->relnatts
+ 1;
3594 if (newattnum
> MaxHeapAttributeNumber
)
3596 (errcode(ERRCODE_TOO_MANY_COLUMNS
),
3597 errmsg("tables can have at most %d columns",
3598 MaxHeapAttributeNumber
)));
3601 typeTuple
= typenameType(NULL
, colDef
->typename
, &typmod
);
3602 tform
= (Form_pg_type
) GETSTRUCT(typeTuple
);
3603 typeOid
= HeapTupleGetOid(typeTuple
);
3605 /* make sure datatype is legal for a column */
3606 CheckAttributeType(colDef
->colname
, typeOid
);
3608 /* construct new attribute's pg_attribute entry */
3609 attribute
.attrelid
= myrelid
;
3610 namestrcpy(&(attribute
.attname
), colDef
->colname
);
3611 attribute
.atttypid
= typeOid
;
3612 attribute
.attstattarget
= (newattnum
> 0) ? -1 : 0;
3613 attribute
.attlen
= tform
->typlen
;
3614 attribute
.attcacheoff
= -1;
3615 attribute
.atttypmod
= typmod
;
3616 attribute
.attnum
= newattnum
;
3617 attribute
.attbyval
= tform
->typbyval
;
3618 attribute
.attndims
= list_length(colDef
->typename
->arrayBounds
);
3619 attribute
.attstorage
= tform
->typstorage
;
3620 attribute
.attalign
= tform
->typalign
;
3621 attribute
.attnotnull
= colDef
->is_not_null
;
3622 attribute
.atthasdef
= false;
3623 attribute
.attisdropped
= false;
3624 attribute
.attislocal
= colDef
->is_local
;
3625 attribute
.attinhcount
= colDef
->inhcount
;
3626 /* attribute.attacl is handled by InsertPgAttributeTuple */
3628 ReleaseSysCache(typeTuple
);
3630 InsertPgAttributeTuple(attrdesc
, &attribute
, NULL
);
3632 heap_close(attrdesc
, RowExclusiveLock
);
3635 * Update pg_class tuple as appropriate
3638 ((Form_pg_class
) GETSTRUCT(reltup
))->relhasoids
= true;
3640 ((Form_pg_class
) GETSTRUCT(reltup
))->relnatts
= newattnum
;
3642 simple_heap_update(pgclass
, &reltup
->t_self
, reltup
);
3644 /* keep catalog indexes current */
3645 CatalogUpdateIndexes(pgclass
, reltup
);
3647 heap_freetuple(reltup
);
3649 heap_close(pgclass
, RowExclusiveLock
);
3651 /* Make the attribute's catalog entry visible */
3652 CommandCounterIncrement();
3655 * Store the DEFAULT, if any, in the catalogs
3657 if (colDef
->raw_default
)
3659 RawColumnDefault
*rawEnt
;
3661 rawEnt
= (RawColumnDefault
*) palloc(sizeof(RawColumnDefault
));
3662 rawEnt
->attnum
= attribute
.attnum
;
3663 rawEnt
->raw_default
= copyObject(colDef
->raw_default
);
3666 * This function is intended for CREATE TABLE, so it processes a
3667 * _list_ of defaults, but we just do one.
3669 AddRelationNewConstraints(rel
, list_make1(rawEnt
), NIL
, false, true);
3671 /* Make the additional catalog changes visible */
3672 CommandCounterIncrement();
3676 * Tell Phase 3 to fill in the default expression, if there is one.
3678 * If there is no default, Phase 3 doesn't have to do anything, because
3679 * that effectively means that the default is NULL. The heap tuple access
3680 * routines always check for attnum > # of attributes in tuple, and return
3681 * NULL if so, so without any modification of the tuple data we will get
3682 * the effect of NULL values in the new column.
3684 * An exception occurs when the new column is of a domain type: the domain
3685 * might have a NOT NULL constraint, or a check constraint that indirectly
3686 * rejects nulls. If there are any domain constraints then we construct
3687 * an explicit NULL default value that will be passed through
3688 * CoerceToDomain processing. (This is a tad inefficient, since it causes
3689 * rewriting the table which we really don't have to do, but the present
3690 * design of domain processing doesn't offer any simple way of checking
3691 * the constraints more directly.)
3693 * Note: we use build_column_default, and not just the cooked default
3694 * returned by AddRelationNewConstraints, so that the right thing happens
3695 * when a datatype's default applies.
3697 * We skip this step completely for views. For a view, we can only get
3698 * here from CREATE OR REPLACE VIEW, which historically doesn't set up
3699 * defaults, not even for domain-typed columns. And in any case we
3700 * mustn't invoke Phase 3 on a view, since it has no storage.
3702 if (relkind
!= RELKIND_VIEW
&& attribute
.attnum
> 0)
3704 defval
= (Expr
*) build_column_default(rel
, attribute
.attnum
);
3706 if (!defval
&& GetDomainConstraints(typeOid
) != NIL
)
3711 baseTypeMod
= typmod
;
3712 baseTypeId
= getBaseTypeAndTypmod(typeOid
, &baseTypeMod
);
3713 defval
= (Expr
*) makeNullConst(baseTypeId
, baseTypeMod
);
3714 defval
= (Expr
*) coerce_to_target_type(NULL
,
3719 COERCION_ASSIGNMENT
,
3720 COERCE_IMPLICIT_CAST
,
3722 if (defval
== NULL
) /* should not happen */
3723 elog(ERROR
, "failed to coerce base type to domain");
3728 NewColumnValue
*newval
;
3730 newval
= (NewColumnValue
*) palloc0(sizeof(NewColumnValue
));
3731 newval
->attnum
= attribute
.attnum
;
3732 newval
->expr
= defval
;
3734 tab
->newvals
= lappend(tab
->newvals
, newval
);
3738 * If the new column is NOT NULL, tell Phase 3 it needs to test that.
3739 * (Note we don't do this for an OID column. OID will be marked not
3740 * null, but since it's filled specially, there's no need to test
3743 tab
->new_notnull
|= colDef
->is_not_null
;
3747 * If we are adding an OID column, we have to tell Phase 3 to rewrite the
3748 * table to fix that.
3751 tab
->new_changeoids
= true;
3754 * Add needed dependency entries for the new column.
3756 add_column_datatype_dependency(myrelid
, newattnum
, attribute
.atttypid
);
3760 * Install a column's dependency on its datatype.
3763 add_column_datatype_dependency(Oid relid
, int32 attnum
, Oid typid
)
3765 ObjectAddress myself
,
3768 myself
.classId
= RelationRelationId
;
3769 myself
.objectId
= relid
;
3770 myself
.objectSubId
= attnum
;
3771 referenced
.classId
= TypeRelationId
;
3772 referenced
.objectId
= typid
;
3773 referenced
.objectSubId
= 0;
3774 recordDependencyOn(&myself
, &referenced
, DEPENDENCY_NORMAL
);
3778 * ALTER TABLE SET WITH OIDS
3780 * Basically this is an ADD COLUMN for the special OID column. We have
3781 * to cons up a ColumnDef node because the ADD COLUMN code needs one.
3784 ATPrepAddOids(List
**wqueue
, Relation rel
, bool recurse
, AlterTableCmd
*cmd
)
3786 /* If we're recursing to a child table, the ColumnDef is already set up */
3787 if (cmd
->def
== NULL
)
3789 ColumnDef
*cdef
= makeNode(ColumnDef
);
3791 cdef
->colname
= pstrdup("oid");
3792 cdef
->typename
= makeTypeNameFromOid(OIDOID
, -1);
3794 cdef
->is_local
= true;
3795 cdef
->is_not_null
= true;
3796 cmd
->def
= (Node
*) cdef
;
3798 ATPrepAddColumn(wqueue
, rel
, recurse
, cmd
);
3802 * ALTER TABLE ALTER COLUMN DROP NOT NULL
3805 ATExecDropNotNull(Relation rel
, const char *colName
)
3811 ListCell
*indexoidscan
;
3814 * lookup the attribute
3816 attr_rel
= heap_open(AttributeRelationId
, RowExclusiveLock
);
3818 tuple
= SearchSysCacheCopyAttName(RelationGetRelid(rel
), colName
);
3820 if (!HeapTupleIsValid(tuple
))
3822 (errcode(ERRCODE_UNDEFINED_COLUMN
),
3823 errmsg("column \"%s\" of relation \"%s\" does not exist",
3824 colName
, RelationGetRelationName(rel
))));
3826 attnum
= ((Form_pg_attribute
) GETSTRUCT(tuple
))->attnum
;
3828 /* Prevent them from altering a system attribute */
3831 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
3832 errmsg("cannot alter system column \"%s\"",
3836 * Check that the attribute is not in a primary key
3839 /* Loop over all indexes on the relation */
3840 indexoidlist
= RelationGetIndexList(rel
);
3842 foreach(indexoidscan
, indexoidlist
)
3844 Oid indexoid
= lfirst_oid(indexoidscan
);
3845 HeapTuple indexTuple
;
3846 Form_pg_index indexStruct
;
3849 indexTuple
= SearchSysCache(INDEXRELID
,
3850 ObjectIdGetDatum(indexoid
),
3852 if (!HeapTupleIsValid(indexTuple
))
3853 elog(ERROR
, "cache lookup failed for index %u", indexoid
);
3854 indexStruct
= (Form_pg_index
) GETSTRUCT(indexTuple
);
3856 /* If the index is not a primary key, skip the check */
3857 if (indexStruct
->indisprimary
)
3860 * Loop over each attribute in the primary key and see if it
3861 * matches the to-be-altered attribute
3863 for (i
= 0; i
< indexStruct
->indnatts
; i
++)
3865 if (indexStruct
->indkey
.values
[i
] == attnum
)
3867 (errcode(ERRCODE_INVALID_TABLE_DEFINITION
),
3868 errmsg("column \"%s\" is in a primary key",
3873 ReleaseSysCache(indexTuple
);
3876 list_free(indexoidlist
);
3879 * Okay, actually perform the catalog change ... if needed
3881 if (((Form_pg_attribute
) GETSTRUCT(tuple
))->attnotnull
)
3883 ((Form_pg_attribute
) GETSTRUCT(tuple
))->attnotnull
= FALSE
;
3885 simple_heap_update(attr_rel
, &tuple
->t_self
, tuple
);
3887 /* keep the system catalog indexes current */
3888 CatalogUpdateIndexes(attr_rel
, tuple
);
3891 heap_close(attr_rel
, RowExclusiveLock
);
3895 * ALTER TABLE ALTER COLUMN SET NOT NULL
3898 ATExecSetNotNull(AlteredTableInfo
*tab
, Relation rel
,
3899 const char *colName
)
3906 * lookup the attribute
3908 attr_rel
= heap_open(AttributeRelationId
, RowExclusiveLock
);
3910 tuple
= SearchSysCacheCopyAttName(RelationGetRelid(rel
), colName
);
3912 if (!HeapTupleIsValid(tuple
))
3914 (errcode(ERRCODE_UNDEFINED_COLUMN
),
3915 errmsg("column \"%s\" of relation \"%s\" does not exist",
3916 colName
, RelationGetRelationName(rel
))));
3918 attnum
= ((Form_pg_attribute
) GETSTRUCT(tuple
))->attnum
;
3920 /* Prevent them from altering a system attribute */
3923 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
3924 errmsg("cannot alter system column \"%s\"",
3928 * Okay, actually perform the catalog change ... if needed
3930 if (!((Form_pg_attribute
) GETSTRUCT(tuple
))->attnotnull
)
3932 ((Form_pg_attribute
) GETSTRUCT(tuple
))->attnotnull
= TRUE
;
3934 simple_heap_update(attr_rel
, &tuple
->t_self
, tuple
);
3936 /* keep the system catalog indexes current */
3937 CatalogUpdateIndexes(attr_rel
, tuple
);
3939 /* Tell Phase 3 it needs to test the constraint */
3940 tab
->new_notnull
= true;
3943 heap_close(attr_rel
, RowExclusiveLock
);
3947 * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
3950 ATExecColumnDefault(Relation rel
, const char *colName
,
3956 * get the number of the attribute
3958 attnum
= get_attnum(RelationGetRelid(rel
), colName
);
3959 if (attnum
== InvalidAttrNumber
)
3961 (errcode(ERRCODE_UNDEFINED_COLUMN
),
3962 errmsg("column \"%s\" of relation \"%s\" does not exist",
3963 colName
, RelationGetRelationName(rel
))));
3965 /* Prevent them from altering a system attribute */
3968 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
3969 errmsg("cannot alter system column \"%s\"",
3973 * Remove any old default for the column. We use RESTRICT here for
3974 * safety, but at present we do not expect anything to depend on the
3977 RemoveAttrDefault(RelationGetRelid(rel
), attnum
, DROP_RESTRICT
, false);
3982 RawColumnDefault
*rawEnt
;
3984 rawEnt
= (RawColumnDefault
*) palloc(sizeof(RawColumnDefault
));
3985 rawEnt
->attnum
= attnum
;
3986 rawEnt
->raw_default
= newDefault
;
3989 * This function is intended for CREATE TABLE, so it processes a
3990 * _list_ of defaults, but we just do one.
3992 AddRelationNewConstraints(rel
, list_make1(rawEnt
), NIL
, false, true);
3997 * ALTER TABLE ALTER COLUMN SET STATISTICS
4000 ATPrepSetStatistics(Relation rel
, const char *colName
, Node
*flagValue
)
4003 * We do our own permission checking because (a) we want to allow SET
4004 * STATISTICS on indexes (for expressional index columns), and (b) we want
4005 * to allow SET STATISTICS on system catalogs without requiring
4006 * allowSystemTableMods to be turned on.
4008 if (rel
->rd_rel
->relkind
!= RELKIND_RELATION
&&
4009 rel
->rd_rel
->relkind
!= RELKIND_INDEX
)
4011 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
4012 errmsg("\"%s\" is not a table or index",
4013 RelationGetRelationName(rel
))));
4015 /* Permissions checks */
4016 if (!pg_class_ownercheck(RelationGetRelid(rel
), GetUserId()))
4017 aclcheck_error(ACLCHECK_NOT_OWNER
, ACL_KIND_CLASS
,
4018 RelationGetRelationName(rel
));
4022 ATExecSetStatistics(Relation rel
, const char *colName
, Node
*newValue
)
4025 Relation attrelation
;
4027 Form_pg_attribute attrtuple
;
4029 Assert(IsA(newValue
, Integer
));
4030 newtarget
= intVal(newValue
);
4033 * Limit target to a sane range
4038 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
4039 errmsg("statistics target %d is too low",
4042 else if (newtarget
> 10000)
4046 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
4047 errmsg("lowering statistics target to %d",
4051 attrelation
= heap_open(AttributeRelationId
, RowExclusiveLock
);
4053 tuple
= SearchSysCacheCopyAttName(RelationGetRelid(rel
), colName
);
4055 if (!HeapTupleIsValid(tuple
))
4057 (errcode(ERRCODE_UNDEFINED_COLUMN
),
4058 errmsg("column \"%s\" of relation \"%s\" does not exist",
4059 colName
, RelationGetRelationName(rel
))));
4060 attrtuple
= (Form_pg_attribute
) GETSTRUCT(tuple
);
4062 if (attrtuple
->attnum
<= 0)
4064 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
4065 errmsg("cannot alter system column \"%s\"",
4068 attrtuple
->attstattarget
= newtarget
;
4070 simple_heap_update(attrelation
, &tuple
->t_self
, tuple
);
4072 /* keep system catalog indexes current */
4073 CatalogUpdateIndexes(attrelation
, tuple
);
4075 heap_freetuple(tuple
);
4077 heap_close(attrelation
, RowExclusiveLock
);
4081 * ALTER TABLE ALTER COLUMN SET STORAGE
4084 ATExecSetStorage(Relation rel
, const char *colName
, Node
*newValue
)
4088 Relation attrelation
;
4090 Form_pg_attribute attrtuple
;
4092 Assert(IsA(newValue
, String
));
4093 storagemode
= strVal(newValue
);
4095 if (pg_strcasecmp(storagemode
, "plain") == 0)
4097 else if (pg_strcasecmp(storagemode
, "external") == 0)
4099 else if (pg_strcasecmp(storagemode
, "extended") == 0)
4101 else if (pg_strcasecmp(storagemode
, "main") == 0)
4106 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
4107 errmsg("invalid storage type \"%s\"",
4109 newstorage
= 0; /* keep compiler quiet */
4112 attrelation
= heap_open(AttributeRelationId
, RowExclusiveLock
);
4114 tuple
= SearchSysCacheCopyAttName(RelationGetRelid(rel
), colName
);
4116 if (!HeapTupleIsValid(tuple
))
4118 (errcode(ERRCODE_UNDEFINED_COLUMN
),
4119 errmsg("column \"%s\" of relation \"%s\" does not exist",
4120 colName
, RelationGetRelationName(rel
))));
4121 attrtuple
= (Form_pg_attribute
) GETSTRUCT(tuple
);
4123 if (attrtuple
->attnum
<= 0)
4125 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
4126 errmsg("cannot alter system column \"%s\"",
4130 * safety check: do not allow toasted storage modes unless column datatype
4133 if (newstorage
== 'p' || TypeIsToastable(attrtuple
->atttypid
))
4134 attrtuple
->attstorage
= newstorage
;
4137 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
4138 errmsg("column data type %s can only have storage PLAIN",
4139 format_type_be(attrtuple
->atttypid
))));
4141 simple_heap_update(attrelation
, &tuple
->t_self
, tuple
);
4143 /* keep system catalog indexes current */
4144 CatalogUpdateIndexes(attrelation
, tuple
);
4146 heap_freetuple(tuple
);
4148 heap_close(attrelation
, RowExclusiveLock
);
4153 * ALTER TABLE DROP COLUMN
4155 * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
4156 * because we have to decide at runtime whether to recurse or not depending
4157 * on whether attinhcount goes to zero or not. (We can't check this in a
4158 * static pre-pass because it won't handle multiple inheritance situations
4162 ATExecDropColumn(List
**wqueue
, Relation rel
, const char *colName
,
4163 DropBehavior behavior
,
4164 bool recurse
, bool recursing
)
4167 Form_pg_attribute targetatt
;
4170 ObjectAddress object
;
4172 /* At top level, permission check was done in ATPrepCmd, else do it */
4174 ATSimplePermissions(rel
, false);
4177 * get the number of the attribute
4179 tuple
= SearchSysCacheAttName(RelationGetRelid(rel
), colName
);
4180 if (!HeapTupleIsValid(tuple
))
4182 (errcode(ERRCODE_UNDEFINED_COLUMN
),
4183 errmsg("column \"%s\" of relation \"%s\" does not exist",
4184 colName
, RelationGetRelationName(rel
))));
4185 targetatt
= (Form_pg_attribute
) GETSTRUCT(tuple
);
4187 attnum
= targetatt
->attnum
;
4189 /* Can't drop a system attribute, except OID */
4190 if (attnum
<= 0 && attnum
!= ObjectIdAttributeNumber
)
4192 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
4193 errmsg("cannot drop system column \"%s\"",
4196 /* Don't drop inherited columns */
4197 if (targetatt
->attinhcount
> 0 && !recursing
)
4199 (errcode(ERRCODE_INVALID_TABLE_DEFINITION
),
4200 errmsg("cannot drop inherited column \"%s\"",
4203 ReleaseSysCache(tuple
);
4206 * Propagate to children as appropriate. Unlike most other ALTER
4207 * routines, we have to do this one level of recursion at a time; we can't
4208 * use find_all_inheritors to do it in one pass.
4210 children
= find_inheritance_children(RelationGetRelid(rel
),
4211 AccessExclusiveLock
);
4218 attr_rel
= heap_open(AttributeRelationId
, RowExclusiveLock
);
4219 foreach(child
, children
)
4221 Oid childrelid
= lfirst_oid(child
);
4223 Form_pg_attribute childatt
;
4225 /* find_inheritance_children already got lock */
4226 childrel
= heap_open(childrelid
, NoLock
);
4227 CheckTableNotInUse(childrel
, "ALTER TABLE");
4229 tuple
= SearchSysCacheCopyAttName(childrelid
, colName
);
4230 if (!HeapTupleIsValid(tuple
)) /* shouldn't happen */
4231 elog(ERROR
, "cache lookup failed for attribute \"%s\" of relation %u",
4232 colName
, childrelid
);
4233 childatt
= (Form_pg_attribute
) GETSTRUCT(tuple
);
4235 if (childatt
->attinhcount
<= 0) /* shouldn't happen */
4236 elog(ERROR
, "relation %u has non-inherited attribute \"%s\"",
4237 childrelid
, colName
);
4242 * If the child column has other definition sources, just
4243 * decrement its inheritance count; if not, recurse to delete
4246 if (childatt
->attinhcount
== 1 && !childatt
->attislocal
)
4248 /* Time to delete this child column, too */
4249 ATExecDropColumn(wqueue
, childrel
, colName
,
4250 behavior
, true, true);
4254 /* Child column must survive my deletion */
4255 childatt
->attinhcount
--;
4257 simple_heap_update(attr_rel
, &tuple
->t_self
, tuple
);
4259 /* keep the system catalog indexes current */
4260 CatalogUpdateIndexes(attr_rel
, tuple
);
4262 /* Make update visible */
4263 CommandCounterIncrement();
4269 * If we were told to drop ONLY in this table (no recursion),
4270 * we need to mark the inheritors' attributes as locally
4271 * defined rather than inherited.
4273 childatt
->attinhcount
--;
4274 childatt
->attislocal
= true;
4276 simple_heap_update(attr_rel
, &tuple
->t_self
, tuple
);
4278 /* keep the system catalog indexes current */
4279 CatalogUpdateIndexes(attr_rel
, tuple
);
4281 /* Make update visible */
4282 CommandCounterIncrement();
4285 heap_freetuple(tuple
);
4287 heap_close(childrel
, NoLock
);
4289 heap_close(attr_rel
, RowExclusiveLock
);
4293 * Perform the actual column deletion
4295 object
.classId
= RelationRelationId
;
4296 object
.objectId
= RelationGetRelid(rel
);
4297 object
.objectSubId
= attnum
;
4299 performDeletion(&object
, behavior
);
4302 * If we dropped the OID column, must adjust pg_class.relhasoids and tell
4303 * Phase 3 to physically get rid of the column.
4305 if (attnum
== ObjectIdAttributeNumber
)
4308 Form_pg_class tuple_class
;
4309 AlteredTableInfo
*tab
;
4311 class_rel
= heap_open(RelationRelationId
, RowExclusiveLock
);
4313 tuple
= SearchSysCacheCopy(RELOID
,
4314 ObjectIdGetDatum(RelationGetRelid(rel
)),
4316 if (!HeapTupleIsValid(tuple
))
4317 elog(ERROR
, "cache lookup failed for relation %u",
4318 RelationGetRelid(rel
));
4319 tuple_class
= (Form_pg_class
) GETSTRUCT(tuple
);
4321 tuple_class
->relhasoids
= false;
4322 simple_heap_update(class_rel
, &tuple
->t_self
, tuple
);
4324 /* Keep the catalog indexes up to date */
4325 CatalogUpdateIndexes(class_rel
, tuple
);
4327 heap_close(class_rel
, RowExclusiveLock
);
4329 /* Find or create work queue entry for this table */
4330 tab
= ATGetQueueEntry(wqueue
, rel
);
4332 /* Tell Phase 3 to physically remove the OID column */
4333 tab
->new_changeoids
= true;
4338 * ALTER TABLE ADD INDEX
4340 * There is no such command in the grammar, but parse_utilcmd.c converts
4341 * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands. This lets
4342 * us schedule creation of the index at the appropriate time during ALTER.
4345 ATExecAddIndex(AlteredTableInfo
*tab
, Relation rel
,
4346 IndexStmt
*stmt
, bool is_rebuild
)
4352 Assert(IsA(stmt
, IndexStmt
));
4354 /* suppress schema rights check when rebuilding existing index */
4355 check_rights
= !is_rebuild
;
4356 /* skip index build if phase 3 will have to rewrite table anyway */
4357 skip_build
= (tab
->newvals
!= NIL
);
4358 /* suppress notices when rebuilding existing index */
4361 /* The IndexStmt has already been through transformIndexStmt */
4363 DefineIndex(stmt
->relation
, /* relation */
4364 stmt
->idxname
, /* index name */
4365 InvalidOid
, /* no predefined OID */
4366 stmt
->accessMethod
, /* am name */
4368 stmt
->indexParams
, /* parameters */
4369 (Expr
*) stmt
->whereClause
,
4374 true, /* is_alter_table */
4382 * ALTER TABLE ADD CONSTRAINT
4385 ATExecAddConstraint(List
**wqueue
, AlteredTableInfo
*tab
, Relation rel
,
4386 Node
*newConstraint
, bool recurse
)
4388 switch (nodeTag(newConstraint
))
4392 Constraint
*constr
= (Constraint
*) newConstraint
;
4395 * Currently, we only expect to see CONSTR_CHECK nodes
4396 * arriving here (see the preprocessing done in
4397 * parse_utilcmd.c). Use a switch anyway to make it easier to
4398 * add more code later.
4400 switch (constr
->contype
)
4403 ATAddCheckConstraint(wqueue
, tab
, rel
,
4404 constr
, recurse
, false);
4407 elog(ERROR
, "unrecognized constraint type: %d",
4408 (int) constr
->contype
);
4412 case T_FkConstraint
:
4414 FkConstraint
*fkconstraint
= (FkConstraint
*) newConstraint
;
4417 * Note that we currently never recurse for FK constraints, so
4418 * the "recurse" flag is silently ignored.
4420 * Assign or validate constraint name
4422 if (fkconstraint
->constr_name
)
4424 if (ConstraintNameIsUsed(CONSTRAINT_RELATION
,
4425 RelationGetRelid(rel
),
4426 RelationGetNamespace(rel
),
4427 fkconstraint
->constr_name
))
4429 (errcode(ERRCODE_DUPLICATE_OBJECT
),
4430 errmsg("constraint \"%s\" for relation \"%s\" already exists",
4431 fkconstraint
->constr_name
,
4432 RelationGetRelationName(rel
))));
4435 fkconstraint
->constr_name
=
4436 ChooseConstraintName(RelationGetRelationName(rel
),
4437 strVal(linitial(fkconstraint
->fk_attrs
)),
4439 RelationGetNamespace(rel
),
4442 ATAddForeignKeyConstraint(tab
, rel
, fkconstraint
);
4447 elog(ERROR
, "unrecognized node type: %d",
4448 (int) nodeTag(newConstraint
));
4453 * Add a check constraint to a single table and its children
4455 * Subroutine for ATExecAddConstraint.
4457 * We must recurse to child tables during execution, rather than using
4458 * ALTER TABLE's normal prep-time recursion. The reason is that all the
4459 * constraints *must* be given the same name, else they won't be seen as
4460 * related later. If the user didn't explicitly specify a name, then
4461 * AddRelationNewConstraints would normally assign different names to the
4462 * child constraints. To fix that, we must capture the name assigned at
4463 * the parent table and pass that down.
4466 ATAddCheckConstraint(List
**wqueue
, AlteredTableInfo
*tab
, Relation rel
,
4467 Constraint
*constr
, bool recurse
, bool recursing
)
4474 /* At top level, permission check was done in ATPrepCmd, else do it */
4476 ATSimplePermissions(rel
, false);
4479 * Call AddRelationNewConstraints to do the work, making sure it works on
4480 * a copy of the Constraint so transformExpr can't modify the original. It
4481 * returns a list of cooked constraints.
4483 * If the constraint ends up getting merged with a pre-existing one, it's
4484 * omitted from the returned list, which is what we want: we do not need
4485 * to do any validation work. That can only happen at child tables,
4486 * though, since we disallow merging at the top level.
4488 newcons
= AddRelationNewConstraints(rel
, NIL
,
4489 list_make1(copyObject(constr
)),
4490 recursing
, !recursing
);
4492 /* Add each constraint to Phase 3's queue */
4493 foreach(lcon
, newcons
)
4495 CookedConstraint
*ccon
= (CookedConstraint
*) lfirst(lcon
);
4496 NewConstraint
*newcon
;
4498 newcon
= (NewConstraint
*) palloc0(sizeof(NewConstraint
));
4499 newcon
->name
= ccon
->name
;
4500 newcon
->contype
= ccon
->contype
;
4501 /* ExecQual wants implicit-AND format */
4502 newcon
->qual
= (Node
*) make_ands_implicit((Expr
*) ccon
->expr
);
4504 tab
->constraints
= lappend(tab
->constraints
, newcon
);
4506 /* Save the actually assigned name if it was defaulted */
4507 if (constr
->name
== NULL
)
4508 constr
->name
= ccon
->name
;
4511 /* At this point we must have a locked-down name to use */
4512 Assert(constr
->name
!= NULL
);
4514 /* Advance command counter in case same table is visited multiple times */
4515 CommandCounterIncrement();
4518 * Propagate to children as appropriate. Unlike most other ALTER
4519 * routines, we have to do this one level of recursion at a time; we can't
4520 * use find_all_inheritors to do it in one pass.
4522 children
= find_inheritance_children(RelationGetRelid(rel
),
4523 AccessExclusiveLock
);
4526 * If we are told not to recurse, there had better not be any child
4527 * tables; else the addition would put them out of step.
4529 if (children
&& !recurse
)
4531 (errcode(ERRCODE_INVALID_TABLE_DEFINITION
),
4532 errmsg("constraint must be added to child tables too")));
4534 foreach(child
, children
)
4536 Oid childrelid
= lfirst_oid(child
);
4538 AlteredTableInfo
*childtab
;
4540 /* find_inheritance_children already got lock */
4541 childrel
= heap_open(childrelid
, NoLock
);
4542 CheckTableNotInUse(childrel
, "ALTER TABLE");
4544 /* Find or create work queue entry for this table */
4545 childtab
= ATGetQueueEntry(wqueue
, childrel
);
4547 /* Recurse to child */
4548 ATAddCheckConstraint(wqueue
, childtab
, childrel
,
4549 constr
, recurse
, true);
4551 heap_close(childrel
, NoLock
);
4556 * Add a foreign-key constraint to a single table
4558 * Subroutine for ATExecAddConstraint. Must already hold exclusive
4559 * lock on the rel, and have done appropriate validity checks for it.
4560 * We do permissions checks here, however.
4563 ATAddForeignKeyConstraint(AlteredTableInfo
*tab
, Relation rel
,
4564 FkConstraint
*fkconstraint
)
4567 int16 pkattnum
[INDEX_MAX_KEYS
];
4568 int16 fkattnum
[INDEX_MAX_KEYS
];
4569 Oid pktypoid
[INDEX_MAX_KEYS
];
4570 Oid fktypoid
[INDEX_MAX_KEYS
];
4571 Oid opclasses
[INDEX_MAX_KEYS
];
4572 Oid pfeqoperators
[INDEX_MAX_KEYS
];
4573 Oid ppeqoperators
[INDEX_MAX_KEYS
];
4574 Oid ffeqoperators
[INDEX_MAX_KEYS
];
4582 * Grab an exclusive lock on the pk table, so that someone doesn't delete
4583 * rows out from under us. (Although a lesser lock would do for that
4584 * purpose, we'll need exclusive lock anyway to add triggers to the pk
4585 * table; trying to start with a lesser lock will just create a risk of
4588 pkrel
= heap_openrv(fkconstraint
->pktable
, AccessExclusiveLock
);
4591 * Validity checks (permission checks wait till we have the column
4594 if (pkrel
->rd_rel
->relkind
!= RELKIND_RELATION
)
4596 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
4597 errmsg("referenced relation \"%s\" is not a table",
4598 RelationGetRelationName(pkrel
))));
4600 if (!allowSystemTableMods
&& IsSystemRelation(pkrel
))
4602 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE
),
4603 errmsg("permission denied: \"%s\" is a system catalog",
4604 RelationGetRelationName(pkrel
))));
4607 * Disallow reference from permanent table to temp table or vice versa.
4608 * (The ban on perm->temp is for fairly obvious reasons. The ban on
4609 * temp->perm is because other backends might need to run the RI triggers
4610 * on the perm table, but they can't reliably see tuples the owning
4611 * backend has created in the temp table, because non-shared buffers are
4612 * used for temp tables.)
4614 if (pkrel
->rd_istemp
)
4616 if (!rel
->rd_istemp
)
4618 (errcode(ERRCODE_INVALID_TABLE_DEFINITION
),
4619 errmsg("cannot reference temporary table from permanent table constraint")));
4625 (errcode(ERRCODE_INVALID_TABLE_DEFINITION
),
4626 errmsg("cannot reference permanent table from temporary table constraint")));
4630 * Look up the referencing attributes to make sure they exist, and record
4631 * their attnums and type OIDs.
4633 MemSet(pkattnum
, 0, sizeof(pkattnum
));
4634 MemSet(fkattnum
, 0, sizeof(fkattnum
));
4635 MemSet(pktypoid
, 0, sizeof(pktypoid
));
4636 MemSet(fktypoid
, 0, sizeof(fktypoid
));
4637 MemSet(opclasses
, 0, sizeof(opclasses
));
4638 MemSet(pfeqoperators
, 0, sizeof(pfeqoperators
));
4639 MemSet(ppeqoperators
, 0, sizeof(ppeqoperators
));
4640 MemSet(ffeqoperators
, 0, sizeof(ffeqoperators
));
4642 numfks
= transformColumnNameList(RelationGetRelid(rel
),
4643 fkconstraint
->fk_attrs
,
4644 fkattnum
, fktypoid
);
4647 * If the attribute list for the referenced table was omitted, lookup the
4648 * definition of the primary key and use it. Otherwise, validate the
4649 * supplied attribute list. In either case, discover the index OID and
4650 * index opclasses, and the attnums and type OIDs of the attributes.
4652 if (fkconstraint
->pk_attrs
== NIL
)
4654 numpks
= transformFkeyGetPrimaryKey(pkrel
, &indexOid
,
4655 &fkconstraint
->pk_attrs
,
4661 numpks
= transformColumnNameList(RelationGetRelid(pkrel
),
4662 fkconstraint
->pk_attrs
,
4663 pkattnum
, pktypoid
);
4664 /* Look for an index matching the column list */
4665 indexOid
= transformFkeyCheckAttrs(pkrel
, numpks
, pkattnum
,
4670 * Now we can check permissions.
4672 checkFkeyPermissions(pkrel
, pkattnum
, numpks
);
4673 checkFkeyPermissions(rel
, fkattnum
, numfks
);
4676 * Look up the equality operators to use in the constraint.
4678 * Note that we have to be careful about the difference between the actual
4679 * PK column type and the opclass' declared input type, which might be
4680 * only binary-compatible with it. The declared opcintype is the right
4681 * thing to probe pg_amop with.
4683 if (numfks
!= numpks
)
4685 (errcode(ERRCODE_INVALID_FOREIGN_KEY
),
4686 errmsg("number of referencing and referenced columns for foreign key disagree")));
4688 for (i
= 0; i
< numpks
; i
++)
4690 Oid pktype
= pktypoid
[i
];
4691 Oid fktype
= fktypoid
[i
];
4694 Form_pg_opclass cla_tup
;
4703 /* We need several fields out of the pg_opclass entry */
4704 cla_ht
= SearchSysCache(CLAOID
,
4705 ObjectIdGetDatum(opclasses
[i
]),
4707 if (!HeapTupleIsValid(cla_ht
))
4708 elog(ERROR
, "cache lookup failed for opclass %u", opclasses
[i
]);
4709 cla_tup
= (Form_pg_opclass
) GETSTRUCT(cla_ht
);
4710 amid
= cla_tup
->opcmethod
;
4711 opfamily
= cla_tup
->opcfamily
;
4712 opcintype
= cla_tup
->opcintype
;
4713 ReleaseSysCache(cla_ht
);
4716 * Check it's a btree; currently this can never fail since no other
4717 * index AMs support unique indexes. If we ever did have other types
4718 * of unique indexes, we'd need a way to determine which operator
4719 * strategy number is equality. (Is it reasonable to insist that
4720 * every such index AM use btree's number for equality?)
4722 if (amid
!= BTREE_AM_OID
)
4723 elog(ERROR
, "only b-tree indexes are supported for foreign keys");
4724 eqstrategy
= BTEqualStrategyNumber
;
4727 * There had better be a primary equality operator for the index.
4728 * We'll use it for PK = PK comparisons.
4730 ppeqop
= get_opfamily_member(opfamily
, opcintype
, opcintype
,
4733 if (!OidIsValid(ppeqop
))
4734 elog(ERROR
, "missing operator %d(%u,%u) in opfamily %u",
4735 eqstrategy
, opcintype
, opcintype
, opfamily
);
4738 * Are there equality operators that take exactly the FK type? Assume
4739 * we should look through any domain here.
4741 fktyped
= getBaseType(fktype
);
4743 pfeqop
= get_opfamily_member(opfamily
, opcintype
, fktyped
,
4745 if (OidIsValid(pfeqop
))
4746 ffeqop
= get_opfamily_member(opfamily
, fktyped
, fktyped
,
4749 ffeqop
= InvalidOid
; /* keep compiler quiet */
4751 if (!(OidIsValid(pfeqop
) && OidIsValid(ffeqop
)))
4754 * Otherwise, look for an implicit cast from the FK type to the
4755 * opcintype, and if found, use the primary equality operator.
4756 * This is a bit tricky because opcintype might be a polymorphic
4757 * type such as ANYARRAY or ANYENUM; so what we have to test is
4758 * whether the two actual column types can be concurrently cast to
4759 * that type. (Otherwise, we'd fail to reject combinations such
4760 * as int[] and point[].)
4762 Oid input_typeids
[2];
4763 Oid target_typeids
[2];
4765 input_typeids
[0] = pktype
;
4766 input_typeids
[1] = fktype
;
4767 target_typeids
[0] = opcintype
;
4768 target_typeids
[1] = opcintype
;
4769 if (can_coerce_type(2, input_typeids
, target_typeids
,
4771 pfeqop
= ffeqop
= ppeqop
;
4774 if (!(OidIsValid(pfeqop
) && OidIsValid(ffeqop
)))
4776 (errcode(ERRCODE_DATATYPE_MISMATCH
),
4777 errmsg("foreign key constraint \"%s\" "
4778 "cannot be implemented",
4779 fkconstraint
->constr_name
),
4780 errdetail("Key columns \"%s\" and \"%s\" "
4781 "are of incompatible types: %s and %s.",
4782 strVal(list_nth(fkconstraint
->fk_attrs
, i
)),
4783 strVal(list_nth(fkconstraint
->pk_attrs
, i
)),
4784 format_type_be(fktype
),
4785 format_type_be(pktype
))));
4787 pfeqoperators
[i
] = pfeqop
;
4788 ppeqoperators
[i
] = ppeqop
;
4789 ffeqoperators
[i
] = ffeqop
;
4793 * Record the FK constraint in pg_constraint.
4795 constrOid
= CreateConstraintEntry(fkconstraint
->constr_name
,
4796 RelationGetNamespace(rel
),
4798 fkconstraint
->deferrable
,
4799 fkconstraint
->initdeferred
,
4800 RelationGetRelid(rel
),
4803 InvalidOid
, /* not a domain
4805 RelationGetRelid(pkrel
),
4811 fkconstraint
->fk_upd_action
,
4812 fkconstraint
->fk_del_action
,
4813 fkconstraint
->fk_matchtype
,
4815 NULL
, /* no check constraint */
4822 * Create the triggers that will enforce the constraint.
4824 createForeignKeyTriggers(rel
, fkconstraint
, constrOid
);
4827 * Tell Phase 3 to check that the constraint is satisfied by existing rows
4828 * (we can skip this during table creation).
4830 if (!fkconstraint
->skip_validation
)
4832 NewConstraint
*newcon
;
4834 newcon
= (NewConstraint
*) palloc0(sizeof(NewConstraint
));
4835 newcon
->name
= fkconstraint
->constr_name
;
4836 newcon
->contype
= CONSTR_FOREIGN
;
4837 newcon
->refrelid
= RelationGetRelid(pkrel
);
4838 newcon
->conid
= constrOid
;
4839 newcon
->qual
= (Node
*) fkconstraint
;
4841 tab
->constraints
= lappend(tab
->constraints
, newcon
);
4845 * Close pk table, but keep lock until we've committed.
4847 heap_close(pkrel
, NoLock
);
4852 * transformColumnNameList - transform list of column names
4854 * Lookup each name and return its attnum and type OID
4857 transformColumnNameList(Oid relId
, List
*colList
,
4858 int16
*attnums
, Oid
*atttypids
)
4866 char *attname
= strVal(lfirst(l
));
4869 atttuple
= SearchSysCacheAttName(relId
, attname
);
4870 if (!HeapTupleIsValid(atttuple
))
4872 (errcode(ERRCODE_UNDEFINED_COLUMN
),
4873 errmsg("column \"%s\" referenced in foreign key constraint does not exist",
4875 if (attnum
>= INDEX_MAX_KEYS
)
4877 (errcode(ERRCODE_TOO_MANY_COLUMNS
),
4878 errmsg("cannot have more than %d keys in a foreign key",
4880 attnums
[attnum
] = ((Form_pg_attribute
) GETSTRUCT(atttuple
))->attnum
;
4881 atttypids
[attnum
] = ((Form_pg_attribute
) GETSTRUCT(atttuple
))->atttypid
;
4882 ReleaseSysCache(atttuple
);
4890 * transformFkeyGetPrimaryKey -
4892 * Look up the names, attnums, and types of the primary key attributes
4893 * for the pkrel. Also return the index OID and index opclasses of the
4894 * index supporting the primary key.
4896 * All parameters except pkrel are output parameters. Also, the function
4897 * return value is the number of attributes in the primary key.
4899 * Used when the column list in the REFERENCES specification is omitted.
4902 transformFkeyGetPrimaryKey(Relation pkrel
, Oid
*indexOid
,
4904 int16
*attnums
, Oid
*atttypids
,
4908 ListCell
*indexoidscan
;
4909 HeapTuple indexTuple
= NULL
;
4910 Form_pg_index indexStruct
= NULL
;
4911 Datum indclassDatum
;
4913 oidvector
*indclass
;
4917 * Get the list of index OIDs for the table from the relcache, and look up
4918 * each one in the pg_index syscache until we find one marked primary key
4919 * (hopefully there isn't more than one such).
4921 *indexOid
= InvalidOid
;
4923 indexoidlist
= RelationGetIndexList(pkrel
);
4925 foreach(indexoidscan
, indexoidlist
)
4927 Oid indexoid
= lfirst_oid(indexoidscan
);
4929 indexTuple
= SearchSysCache(INDEXRELID
,
4930 ObjectIdGetDatum(indexoid
),
4932 if (!HeapTupleIsValid(indexTuple
))
4933 elog(ERROR
, "cache lookup failed for index %u", indexoid
);
4934 indexStruct
= (Form_pg_index
) GETSTRUCT(indexTuple
);
4935 if (indexStruct
->indisprimary
)
4937 *indexOid
= indexoid
;
4940 ReleaseSysCache(indexTuple
);
4943 list_free(indexoidlist
);
4946 * Check that we found it
4948 if (!OidIsValid(*indexOid
))
4950 (errcode(ERRCODE_UNDEFINED_OBJECT
),
4951 errmsg("there is no primary key for referenced table \"%s\"",
4952 RelationGetRelationName(pkrel
))));
4954 /* Must get indclass the hard way */
4955 indclassDatum
= SysCacheGetAttr(INDEXRELID
, indexTuple
,
4956 Anum_pg_index_indclass
, &isnull
);
4958 indclass
= (oidvector
*) DatumGetPointer(indclassDatum
);
4961 * Now build the list of PK attributes from the indkey definition (we
4962 * assume a primary key cannot have expressional elements)
4965 for (i
= 0; i
< indexStruct
->indnatts
; i
++)
4967 int pkattno
= indexStruct
->indkey
.values
[i
];
4969 attnums
[i
] = pkattno
;
4970 atttypids
[i
] = attnumTypeId(pkrel
, pkattno
);
4971 opclasses
[i
] = indclass
->values
[i
];
4972 *attnamelist
= lappend(*attnamelist
,
4973 makeString(pstrdup(NameStr(*attnumAttName(pkrel
, pkattno
)))));
4976 ReleaseSysCache(indexTuple
);
4982 * transformFkeyCheckAttrs -
4984 * Make sure that the attributes of a referenced table belong to a unique
4985 * (or primary key) constraint. Return the OID of the index supporting
4986 * the constraint, as well as the opclasses associated with the index
4990 transformFkeyCheckAttrs(Relation pkrel
,
4991 int numattrs
, int16
*attnums
,
4992 Oid
*opclasses
) /* output parameter */
4994 Oid indexoid
= InvalidOid
;
4997 ListCell
*indexoidscan
;
5000 * Get the list of index OIDs for the table from the relcache, and look up
5001 * each one in the pg_index syscache, and match unique indexes to the list
5002 * of attnums we are given.
5004 indexoidlist
= RelationGetIndexList(pkrel
);
5006 foreach(indexoidscan
, indexoidlist
)
5008 HeapTuple indexTuple
;
5009 Form_pg_index indexStruct
;
5013 indexoid
= lfirst_oid(indexoidscan
);
5014 indexTuple
= SearchSysCache(INDEXRELID
,
5015 ObjectIdGetDatum(indexoid
),
5017 if (!HeapTupleIsValid(indexTuple
))
5018 elog(ERROR
, "cache lookup failed for index %u", indexoid
);
5019 indexStruct
= (Form_pg_index
) GETSTRUCT(indexTuple
);
5022 * Must have the right number of columns; must be unique and not a
5023 * partial index; forget it if there are any expressions, too
5025 if (indexStruct
->indnatts
== numattrs
&&
5026 indexStruct
->indisunique
&&
5027 heap_attisnull(indexTuple
, Anum_pg_index_indpred
) &&
5028 heap_attisnull(indexTuple
, Anum_pg_index_indexprs
))
5030 /* Must get indclass the hard way */
5031 Datum indclassDatum
;
5033 oidvector
*indclass
;
5035 indclassDatum
= SysCacheGetAttr(INDEXRELID
, indexTuple
,
5036 Anum_pg_index_indclass
, &isnull
);
5038 indclass
= (oidvector
*) DatumGetPointer(indclassDatum
);
5041 * The given attnum list may match the index columns in any order.
5042 * Check that each list is a subset of the other.
5044 for (i
= 0; i
< numattrs
; i
++)
5047 for (j
= 0; j
< numattrs
; j
++)
5049 if (attnums
[i
] == indexStruct
->indkey
.values
[j
])
5060 for (i
= 0; i
< numattrs
; i
++)
5063 for (j
= 0; j
< numattrs
; j
++)
5065 if (attnums
[j
] == indexStruct
->indkey
.values
[i
])
5067 opclasses
[j
] = indclass
->values
[i
];
5077 ReleaseSysCache(indexTuple
);
5084 (errcode(ERRCODE_INVALID_FOREIGN_KEY
),
5085 errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
5086 RelationGetRelationName(pkrel
))));
5088 list_free(indexoidlist
);
5093 /* Permissions checks for ADD FOREIGN KEY */
5095 checkFkeyPermissions(Relation rel
, int16
*attnums
, int natts
)
5097 Oid roleid
= GetUserId();
5098 AclResult aclresult
;
5101 /* Okay if we have relation-level REFERENCES permission */
5102 aclresult
= pg_class_aclcheck(RelationGetRelid(rel
), roleid
,
5104 if (aclresult
== ACLCHECK_OK
)
5106 /* Else we must have REFERENCES on each column */
5107 for (i
= 0; i
< natts
; i
++)
5109 aclresult
= pg_attribute_aclcheck(RelationGetRelid(rel
), attnums
[i
],
5110 roleid
, ACL_REFERENCES
);
5111 if (aclresult
!= ACLCHECK_OK
)
5112 aclcheck_error(aclresult
, ACL_KIND_CLASS
,
5113 RelationGetRelationName(rel
));
5118 * Scan the existing rows in a table to verify they meet a proposed FK
5121 * Caller must have opened and locked both relations.
5124 validateForeignKeyConstraint(FkConstraint
*fkconstraint
,
5134 * Build a trigger call structure; we'll need it either way.
5136 MemSet(&trig
, 0, sizeof(trig
));
5137 trig
.tgoid
= InvalidOid
;
5138 trig
.tgname
= fkconstraint
->constr_name
;
5139 trig
.tgenabled
= TRIGGER_FIRES_ON_ORIGIN
;
5140 trig
.tgisconstraint
= TRUE
;
5141 trig
.tgconstrrelid
= RelationGetRelid(pkrel
);
5142 trig
.tgconstraint
= constraintOid
;
5143 trig
.tgdeferrable
= FALSE
;
5144 trig
.tginitdeferred
= FALSE
;
5145 /* we needn't fill in tgargs */
5148 * See if we can do it with a single LEFT JOIN query. A FALSE result
5149 * indicates we must proceed with the fire-the-trigger method.
5151 if (RI_Initial_Check(&trig
, rel
, pkrel
))
5155 * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
5156 * if that tuple had just been inserted. If any of those fail, it should
5157 * ereport(ERROR) and that's that.
5159 scan
= heap_beginscan(rel
, SnapshotNow
, 0, NULL
);
5161 while ((tuple
= heap_getnext(scan
, ForwardScanDirection
)) != NULL
)
5163 FunctionCallInfoData fcinfo
;
5164 TriggerData trigdata
;
5167 * Make a call to the trigger function
5169 * No parameters are passed, but we do set a context
5171 MemSet(&fcinfo
, 0, sizeof(fcinfo
));
5174 * We assume RI_FKey_check_ins won't look at flinfo...
5176 trigdata
.type
= T_TriggerData
;
5177 trigdata
.tg_event
= TRIGGER_EVENT_INSERT
| TRIGGER_EVENT_ROW
;
5178 trigdata
.tg_relation
= rel
;
5179 trigdata
.tg_trigtuple
= tuple
;
5180 trigdata
.tg_newtuple
= NULL
;
5181 trigdata
.tg_trigger
= &trig
;
5182 trigdata
.tg_trigtuplebuf
= scan
->rs_cbuf
;
5183 trigdata
.tg_newtuplebuf
= InvalidBuffer
;
5185 fcinfo
.context
= (Node
*) &trigdata
;
5187 RI_FKey_check_ins(&fcinfo
);
5194 CreateFKCheckTrigger(RangeVar
*myRel
, FkConstraint
*fkconstraint
,
5195 Oid constraintOid
, bool on_insert
)
5197 CreateTrigStmt
*fk_trigger
;
5199 fk_trigger
= makeNode(CreateTrigStmt
);
5200 fk_trigger
->trigname
= fkconstraint
->constr_name
;
5201 fk_trigger
->relation
= myRel
;
5202 fk_trigger
->before
= false;
5203 fk_trigger
->row
= true;
5205 /* Either ON INSERT or ON UPDATE */
5208 fk_trigger
->funcname
= SystemFuncName("RI_FKey_check_ins");
5209 fk_trigger
->events
= TRIGGER_TYPE_INSERT
;
5213 fk_trigger
->funcname
= SystemFuncName("RI_FKey_check_upd");
5214 fk_trigger
->events
= TRIGGER_TYPE_UPDATE
;
5217 fk_trigger
->isconstraint
= true;
5218 fk_trigger
->deferrable
= fkconstraint
->deferrable
;
5219 fk_trigger
->initdeferred
= fkconstraint
->initdeferred
;
5220 fk_trigger
->constrrel
= fkconstraint
->pktable
;
5221 fk_trigger
->args
= NIL
;
5223 (void) CreateTrigger(fk_trigger
, constraintOid
, false);
5225 /* Make changes-so-far visible */
5226 CommandCounterIncrement();
5230 * Create the triggers that implement an FK constraint.
5233 createForeignKeyTriggers(Relation rel
, FkConstraint
*fkconstraint
,
5237 CreateTrigStmt
*fk_trigger
;
5240 * Reconstruct a RangeVar for my relation (not passed in, unfortunately).
5242 myRel
= makeRangeVar(get_namespace_name(RelationGetNamespace(rel
)),
5243 pstrdup(RelationGetRelationName(rel
)),
5246 /* Make changes-so-far visible */
5247 CommandCounterIncrement();
5250 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the CHECK
5251 * action for both INSERTs and UPDATEs on the referencing table.
5253 CreateFKCheckTrigger(myRel
, fkconstraint
, constraintOid
, true);
5254 CreateFKCheckTrigger(myRel
, fkconstraint
, constraintOid
, false);
5257 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
5258 * DELETE action on the referenced table.
5260 fk_trigger
= makeNode(CreateTrigStmt
);
5261 fk_trigger
->trigname
= fkconstraint
->constr_name
;
5262 fk_trigger
->relation
= fkconstraint
->pktable
;
5263 fk_trigger
->before
= false;
5264 fk_trigger
->row
= true;
5265 fk_trigger
->events
= TRIGGER_TYPE_DELETE
;
5266 fk_trigger
->isconstraint
= true;
5267 fk_trigger
->constrrel
= myRel
;
5268 switch (fkconstraint
->fk_del_action
)
5270 case FKCONSTR_ACTION_NOACTION
:
5271 fk_trigger
->deferrable
= fkconstraint
->deferrable
;
5272 fk_trigger
->initdeferred
= fkconstraint
->initdeferred
;
5273 fk_trigger
->funcname
= SystemFuncName("RI_FKey_noaction_del");
5275 case FKCONSTR_ACTION_RESTRICT
:
5276 fk_trigger
->deferrable
= false;
5277 fk_trigger
->initdeferred
= false;
5278 fk_trigger
->funcname
= SystemFuncName("RI_FKey_restrict_del");
5280 case FKCONSTR_ACTION_CASCADE
:
5281 fk_trigger
->deferrable
= false;
5282 fk_trigger
->initdeferred
= false;
5283 fk_trigger
->funcname
= SystemFuncName("RI_FKey_cascade_del");
5285 case FKCONSTR_ACTION_SETNULL
:
5286 fk_trigger
->deferrable
= false;
5287 fk_trigger
->initdeferred
= false;
5288 fk_trigger
->funcname
= SystemFuncName("RI_FKey_setnull_del");
5290 case FKCONSTR_ACTION_SETDEFAULT
:
5291 fk_trigger
->deferrable
= false;
5292 fk_trigger
->initdeferred
= false;
5293 fk_trigger
->funcname
= SystemFuncName("RI_FKey_setdefault_del");
5296 elog(ERROR
, "unrecognized FK action type: %d",
5297 (int) fkconstraint
->fk_del_action
);
5300 fk_trigger
->args
= NIL
;
5302 (void) CreateTrigger(fk_trigger
, constraintOid
, false);
5304 /* Make changes-so-far visible */
5305 CommandCounterIncrement();
5308 * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
5309 * UPDATE action on the referenced table.
5311 fk_trigger
= makeNode(CreateTrigStmt
);
5312 fk_trigger
->trigname
= fkconstraint
->constr_name
;
5313 fk_trigger
->relation
= fkconstraint
->pktable
;
5314 fk_trigger
->before
= false;
5315 fk_trigger
->row
= true;
5316 fk_trigger
->events
= TRIGGER_TYPE_UPDATE
;
5317 fk_trigger
->isconstraint
= true;
5318 fk_trigger
->constrrel
= myRel
;
5319 switch (fkconstraint
->fk_upd_action
)
5321 case FKCONSTR_ACTION_NOACTION
:
5322 fk_trigger
->deferrable
= fkconstraint
->deferrable
;
5323 fk_trigger
->initdeferred
= fkconstraint
->initdeferred
;
5324 fk_trigger
->funcname
= SystemFuncName("RI_FKey_noaction_upd");
5326 case FKCONSTR_ACTION_RESTRICT
:
5327 fk_trigger
->deferrable
= false;
5328 fk_trigger
->initdeferred
= false;
5329 fk_trigger
->funcname
= SystemFuncName("RI_FKey_restrict_upd");
5331 case FKCONSTR_ACTION_CASCADE
:
5332 fk_trigger
->deferrable
= false;
5333 fk_trigger
->initdeferred
= false;
5334 fk_trigger
->funcname
= SystemFuncName("RI_FKey_cascade_upd");
5336 case FKCONSTR_ACTION_SETNULL
:
5337 fk_trigger
->deferrable
= false;
5338 fk_trigger
->initdeferred
= false;
5339 fk_trigger
->funcname
= SystemFuncName("RI_FKey_setnull_upd");
5341 case FKCONSTR_ACTION_SETDEFAULT
:
5342 fk_trigger
->deferrable
= false;
5343 fk_trigger
->initdeferred
= false;
5344 fk_trigger
->funcname
= SystemFuncName("RI_FKey_setdefault_upd");
5347 elog(ERROR
, "unrecognized FK action type: %d",
5348 (int) fkconstraint
->fk_upd_action
);
5351 fk_trigger
->args
= NIL
;
5353 (void) CreateTrigger(fk_trigger
, constraintOid
, false);
5357 * ALTER TABLE DROP CONSTRAINT
5359 * Like DROP COLUMN, we can't use the normal ALTER TABLE recursion mechanism.
5362 ATExecDropConstraint(Relation rel
, const char *constrName
,
5363 DropBehavior behavior
,
5364 bool recurse
, bool recursing
)
5369 Form_pg_constraint con
;
5374 bool is_check_constraint
= false;
5376 /* At top level, permission check was done in ATPrepCmd, else do it */
5378 ATSimplePermissions(rel
, false);
5380 conrel
= heap_open(ConstraintRelationId
, RowExclusiveLock
);
5383 * Find and drop the target constraint
5386 Anum_pg_constraint_conrelid
,
5387 BTEqualStrategyNumber
, F_OIDEQ
,
5388 ObjectIdGetDatum(RelationGetRelid(rel
)));
5389 scan
= systable_beginscan(conrel
, ConstraintRelidIndexId
,
5390 true, SnapshotNow
, 1, &key
);
5392 while (HeapTupleIsValid(tuple
= systable_getnext(scan
)))
5394 ObjectAddress conobj
;
5396 con
= (Form_pg_constraint
) GETSTRUCT(tuple
);
5398 if (strcmp(NameStr(con
->conname
), constrName
) != 0)
5401 /* Don't drop inherited constraints */
5402 if (con
->coninhcount
> 0 && !recursing
)
5404 (errcode(ERRCODE_INVALID_TABLE_DEFINITION
),
5405 errmsg("cannot drop inherited constraint \"%s\" of relation \"%s\"",
5406 constrName
, RelationGetRelationName(rel
))));
5408 /* Right now only CHECK constraints can be inherited */
5409 if (con
->contype
== CONSTRAINT_CHECK
)
5410 is_check_constraint
= true;
5413 * Perform the actual constraint deletion
5415 conobj
.classId
= ConstraintRelationId
;
5416 conobj
.objectId
= HeapTupleGetOid(tuple
);
5417 conobj
.objectSubId
= 0;
5419 performDeletion(&conobj
, behavior
);
5424 systable_endscan(scan
);
5428 (errcode(ERRCODE_UNDEFINED_OBJECT
),
5429 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
5430 constrName
, RelationGetRelationName(rel
))));
5433 * Propagate to children as appropriate. Unlike most other ALTER
5434 * routines, we have to do this one level of recursion at a time; we can't
5435 * use find_all_inheritors to do it in one pass.
5437 if (is_check_constraint
)
5438 children
= find_inheritance_children(RelationGetRelid(rel
),
5439 AccessExclusiveLock
);
5443 foreach(child
, children
)
5445 Oid childrelid
= lfirst_oid(child
);
5448 /* find_inheritance_children already got lock */
5449 childrel
= heap_open(childrelid
, NoLock
);
5450 CheckTableNotInUse(childrel
, "ALTER TABLE");
5453 Anum_pg_constraint_conrelid
,
5454 BTEqualStrategyNumber
, F_OIDEQ
,
5455 ObjectIdGetDatum(childrelid
));
5456 scan
= systable_beginscan(conrel
, ConstraintRelidIndexId
,
5457 true, SnapshotNow
, 1, &key
);
5461 while (HeapTupleIsValid(tuple
= systable_getnext(scan
)))
5463 HeapTuple copy_tuple
;
5465 con
= (Form_pg_constraint
) GETSTRUCT(tuple
);
5467 /* Right now only CHECK constraints can be inherited */
5468 if (con
->contype
!= CONSTRAINT_CHECK
)
5471 if (strcmp(NameStr(con
->conname
), constrName
) != 0)
5476 if (con
->coninhcount
<= 0) /* shouldn't happen */
5477 elog(ERROR
, "relation %u has non-inherited constraint \"%s\"",
5478 childrelid
, constrName
);
5480 copy_tuple
= heap_copytuple(tuple
);
5481 con
= (Form_pg_constraint
) GETSTRUCT(copy_tuple
);
5486 * If the child constraint has other definition sources, just
5487 * decrement its inheritance count; if not, recurse to delete
5490 if (con
->coninhcount
== 1 && !con
->conislocal
)
5492 /* Time to delete this child constraint, too */
5493 ATExecDropConstraint(childrel
, constrName
, behavior
,
5498 /* Child constraint must survive my deletion */
5500 simple_heap_update(conrel
, ©_tuple
->t_self
, copy_tuple
);
5501 CatalogUpdateIndexes(conrel
, copy_tuple
);
5503 /* Make update visible */
5504 CommandCounterIncrement();
5510 * If we were told to drop ONLY in this table (no recursion),
5511 * we need to mark the inheritors' constraints as locally
5512 * defined rather than inherited.
5515 con
->conislocal
= true;
5517 simple_heap_update(conrel
, ©_tuple
->t_self
, copy_tuple
);
5518 CatalogUpdateIndexes(conrel
, copy_tuple
);
5520 /* Make update visible */
5521 CommandCounterIncrement();
5524 heap_freetuple(copy_tuple
);
5527 systable_endscan(scan
);
5531 (errcode(ERRCODE_UNDEFINED_OBJECT
),
5532 errmsg("constraint \"%s\" of relation \"%s\" does not exist",
5534 RelationGetRelationName(childrel
))));
5536 heap_close(childrel
, NoLock
);
5539 heap_close(conrel
, RowExclusiveLock
);
5546 ATPrepAlterColumnType(List
**wqueue
,
5547 AlteredTableInfo
*tab
, Relation rel
,
5548 bool recurse
, bool recursing
,
5551 char *colName
= cmd
->name
;
5552 TypeName
*typename
= (TypeName
*) cmd
->def
;
5554 Form_pg_attribute attTup
;
5559 NewColumnValue
*newval
;
5560 ParseState
*pstate
= make_parsestate(NULL
);
5562 /* lookup the attribute so we can check inheritance status */
5563 tuple
= SearchSysCacheAttName(RelationGetRelid(rel
), colName
);
5564 if (!HeapTupleIsValid(tuple
))
5566 (errcode(ERRCODE_UNDEFINED_COLUMN
),
5567 errmsg("column \"%s\" of relation \"%s\" does not exist",
5568 colName
, RelationGetRelationName(rel
))));
5569 attTup
= (Form_pg_attribute
) GETSTRUCT(tuple
);
5570 attnum
= attTup
->attnum
;
5572 /* Can't alter a system attribute */
5575 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
5576 errmsg("cannot alter system column \"%s\"",
5579 /* Don't alter inherited columns */
5580 if (attTup
->attinhcount
> 0 && !recursing
)
5582 (errcode(ERRCODE_INVALID_TABLE_DEFINITION
),
5583 errmsg("cannot alter inherited column \"%s\"",
5586 /* Look up the target type */
5587 targettype
= typenameTypeId(NULL
, typename
, &targettypmod
);
5589 /* make sure datatype is legal for a column */
5590 CheckAttributeType(colName
, targettype
);
5593 * Set up an expression to transform the old data value to the new type.
5594 * If a USING option was given, transform and use that expression, else
5595 * just take the old value and try to coerce it. We do this first so that
5596 * type incompatibility can be detected before we waste effort, and
5597 * because we need the expression to be parsed against the original table
5604 /* Expression must be able to access vars of old table */
5605 rte
= addRangeTableEntryForRelation(pstate
,
5610 addRTEtoQuery(pstate
, rte
, false, true, true);
5612 transform
= transformExpr(pstate
, cmd
->transform
);
5614 /* It can't return a set */
5615 if (expression_returns_set(transform
))
5617 (errcode(ERRCODE_DATATYPE_MISMATCH
),
5618 errmsg("transform expression must not return a set")));
5620 /* No subplans or aggregates, either... */
5621 if (pstate
->p_hasSubLinks
)
5623 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
5624 errmsg("cannot use subquery in transform expression")));
5625 if (pstate
->p_hasAggs
)
5627 (errcode(ERRCODE_GROUPING_ERROR
),
5628 errmsg("cannot use aggregate function in transform expression")));
5629 if (pstate
->p_hasWindowFuncs
)
5631 (errcode(ERRCODE_WINDOWING_ERROR
),
5632 errmsg("cannot use window function in transform expression")));
5636 transform
= (Node
*) makeVar(1, attnum
,
5637 attTup
->atttypid
, attTup
->atttypmod
,
5641 transform
= coerce_to_target_type(pstate
,
5642 transform
, exprType(transform
),
5643 targettype
, targettypmod
,
5644 COERCION_ASSIGNMENT
,
5645 COERCE_IMPLICIT_CAST
,
5647 if (transform
== NULL
)
5649 (errcode(ERRCODE_DATATYPE_MISMATCH
),
5650 errmsg("column \"%s\" cannot be cast to type %s",
5651 colName
, format_type_be(targettype
))));
5654 * Add a work queue item to make ATRewriteTable update the column
5657 newval
= (NewColumnValue
*) palloc0(sizeof(NewColumnValue
));
5658 newval
->attnum
= attnum
;
5659 newval
->expr
= (Expr
*) transform
;
5661 tab
->newvals
= lappend(tab
->newvals
, newval
);
5663 ReleaseSysCache(tuple
);
5666 * The recursion case is handled by ATSimpleRecursion. However, if we are
5667 * told not to recurse, there had better not be any child tables; else the
5668 * alter would put them out of step.
5671 ATSimpleRecursion(wqueue
, rel
, cmd
, recurse
);
5672 else if (!recursing
&&
5673 find_inheritance_children(RelationGetRelid(rel
), NoLock
) != NIL
)
5675 (errcode(ERRCODE_INVALID_TABLE_DEFINITION
),
5676 errmsg("type of inherited column \"%s\" must be changed in child tables too",
5681 ATExecAlterColumnType(AlteredTableInfo
*tab
, Relation rel
,
5682 const char *colName
, TypeName
*typename
)
5685 Form_pg_attribute attTup
;
5687 HeapTuple typeTuple
;
5692 Relation attrelation
;
5698 attrelation
= heap_open(AttributeRelationId
, RowExclusiveLock
);
5700 /* Look up the target column */
5701 heapTup
= SearchSysCacheCopyAttName(RelationGetRelid(rel
), colName
);
5702 if (!HeapTupleIsValid(heapTup
)) /* shouldn't happen */
5704 (errcode(ERRCODE_UNDEFINED_COLUMN
),
5705 errmsg("column \"%s\" of relation \"%s\" does not exist",
5706 colName
, RelationGetRelationName(rel
))));
5707 attTup
= (Form_pg_attribute
) GETSTRUCT(heapTup
);
5708 attnum
= attTup
->attnum
;
5710 /* Check for multiple ALTER TYPE on same column --- can't cope */
5711 if (attTup
->atttypid
!= tab
->oldDesc
->attrs
[attnum
- 1]->atttypid
||
5712 attTup
->atttypmod
!= tab
->oldDesc
->attrs
[attnum
- 1]->atttypmod
)
5714 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
5715 errmsg("cannot alter type of column \"%s\" twice",
5718 /* Look up the target type (should not fail, since prep found it) */
5719 typeTuple
= typenameType(NULL
, typename
, &targettypmod
);
5720 tform
= (Form_pg_type
) GETSTRUCT(typeTuple
);
5721 targettype
= HeapTupleGetOid(typeTuple
);
5724 * If there is a default expression for the column, get it and ensure we
5725 * can coerce it to the new datatype. (We must do this before changing
5726 * the column type, because build_column_default itself will try to
5727 * coerce, and will not issue the error message we want if it fails.)
5729 * We remove any implicit coercion steps at the top level of the old
5730 * default expression; this has been agreed to satisfy the principle of
5731 * least surprise. (The conversion to the new column type should act like
5732 * it started from what the user sees as the stored expression, and the
5733 * implicit coercions aren't going to be shown.)
5735 if (attTup
->atthasdef
)
5737 defaultexpr
= build_column_default(rel
, attnum
);
5738 Assert(defaultexpr
);
5739 defaultexpr
= strip_implicit_coercions(defaultexpr
);
5740 defaultexpr
= coerce_to_target_type(NULL
, /* no UNKNOWN params */
5741 defaultexpr
, exprType(defaultexpr
),
5742 targettype
, targettypmod
,
5743 COERCION_ASSIGNMENT
,
5744 COERCE_IMPLICIT_CAST
,
5746 if (defaultexpr
== NULL
)
5748 (errcode(ERRCODE_DATATYPE_MISMATCH
),
5749 errmsg("default for column \"%s\" cannot be cast to type %s",
5750 colName
, format_type_be(targettype
))));
5756 * Find everything that depends on the column (constraints, indexes, etc),
5757 * and record enough information to let us recreate the objects.
5759 * The actual recreation does not happen here, but only after we have
5760 * performed all the individual ALTER TYPE operations. We have to save
5761 * the info before executing ALTER TYPE, though, else the deparser will
5764 * There could be multiple entries for the same object, so we must check
5765 * to ensure we process each one only once. Note: we assume that an index
5766 * that implements a constraint will not show a direct dependency on the
5769 depRel
= heap_open(DependRelationId
, RowExclusiveLock
);
5771 ScanKeyInit(&key
[0],
5772 Anum_pg_depend_refclassid
,
5773 BTEqualStrategyNumber
, F_OIDEQ
,
5774 ObjectIdGetDatum(RelationRelationId
));
5775 ScanKeyInit(&key
[1],
5776 Anum_pg_depend_refobjid
,
5777 BTEqualStrategyNumber
, F_OIDEQ
,
5778 ObjectIdGetDatum(RelationGetRelid(rel
)));
5779 ScanKeyInit(&key
[2],
5780 Anum_pg_depend_refobjsubid
,
5781 BTEqualStrategyNumber
, F_INT4EQ
,
5782 Int32GetDatum((int32
) attnum
));
5784 scan
= systable_beginscan(depRel
, DependReferenceIndexId
, true,
5785 SnapshotNow
, 3, key
);
5787 while (HeapTupleIsValid(depTup
= systable_getnext(scan
)))
5789 Form_pg_depend foundDep
= (Form_pg_depend
) GETSTRUCT(depTup
);
5790 ObjectAddress foundObject
;
5792 /* We don't expect any PIN dependencies on columns */
5793 if (foundDep
->deptype
== DEPENDENCY_PIN
)
5794 elog(ERROR
, "cannot alter type of a pinned column");
5796 foundObject
.classId
= foundDep
->classid
;
5797 foundObject
.objectId
= foundDep
->objid
;
5798 foundObject
.objectSubId
= foundDep
->objsubid
;
5800 switch (getObjectClass(&foundObject
))
5804 char relKind
= get_rel_relkind(foundObject
.objectId
);
5806 if (relKind
== RELKIND_INDEX
)
5808 Assert(foundObject
.objectSubId
== 0);
5809 if (!list_member_oid(tab
->changedIndexOids
, foundObject
.objectId
))
5811 tab
->changedIndexOids
= lappend_oid(tab
->changedIndexOids
,
5812 foundObject
.objectId
);
5813 tab
->changedIndexDefs
= lappend(tab
->changedIndexDefs
,
5814 pg_get_indexdef_string(foundObject
.objectId
));
5817 else if (relKind
== RELKIND_SEQUENCE
)
5820 * This must be a SERIAL column's sequence. We need
5821 * not do anything to it.
5823 Assert(foundObject
.objectSubId
== 0);
5827 /* Not expecting any other direct dependencies... */
5828 elog(ERROR
, "unexpected object depending on column: %s",
5829 getObjectDescription(&foundObject
));
5834 case OCLASS_CONSTRAINT
:
5835 Assert(foundObject
.objectSubId
== 0);
5836 if (!list_member_oid(tab
->changedConstraintOids
,
5837 foundObject
.objectId
))
5839 char *defstring
= pg_get_constraintdef_string(foundObject
.objectId
);
5842 * Put NORMAL dependencies at the front of the list and
5843 * AUTO dependencies at the back. This makes sure that
5844 * foreign-key constraints depending on this column will
5845 * be dropped before unique or primary-key constraints of
5846 * the column; which we must have because the FK
5847 * constraints depend on the indexes belonging to the
5848 * unique constraints.
5850 if (foundDep
->deptype
== DEPENDENCY_NORMAL
)
5852 tab
->changedConstraintOids
=
5853 lcons_oid(foundObject
.objectId
,
5854 tab
->changedConstraintOids
);
5855 tab
->changedConstraintDefs
=
5857 tab
->changedConstraintDefs
);
5861 tab
->changedConstraintOids
=
5862 lappend_oid(tab
->changedConstraintOids
,
5863 foundObject
.objectId
);
5864 tab
->changedConstraintDefs
=
5865 lappend(tab
->changedConstraintDefs
,
5871 case OCLASS_REWRITE
:
5872 /* XXX someday see if we can cope with revising views */
5874 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
5875 errmsg("cannot alter type of a column used by a view or rule"),
5876 errdetail("%s depends on column \"%s\"",
5877 getObjectDescription(&foundObject
),
5881 case OCLASS_DEFAULT
:
5884 * Ignore the column's default expression, since we will fix
5887 Assert(defaultexpr
);
5893 case OCLASS_CONVERSION
:
5894 case OCLASS_LANGUAGE
:
5895 case OCLASS_OPERATOR
:
5896 case OCLASS_OPCLASS
:
5897 case OCLASS_OPFAMILY
:
5898 case OCLASS_TRIGGER
:
5900 case OCLASS_TSPARSER
:
5902 case OCLASS_TSTEMPLATE
:
5903 case OCLASS_TSCONFIG
:
5906 * We don't expect any of these sorts of objects to depend on
5909 elog(ERROR
, "unexpected object depending on column: %s",
5910 getObjectDescription(&foundObject
));
5914 elog(ERROR
, "unrecognized object class: %u",
5915 foundObject
.classId
);
5919 systable_endscan(scan
);
5922 * Now scan for dependencies of this column on other things. The only
5923 * thing we should find is the dependency on the column datatype, which we
5926 ScanKeyInit(&key
[0],
5927 Anum_pg_depend_classid
,
5928 BTEqualStrategyNumber
, F_OIDEQ
,
5929 ObjectIdGetDatum(RelationRelationId
));
5930 ScanKeyInit(&key
[1],
5931 Anum_pg_depend_objid
,
5932 BTEqualStrategyNumber
, F_OIDEQ
,
5933 ObjectIdGetDatum(RelationGetRelid(rel
)));
5934 ScanKeyInit(&key
[2],
5935 Anum_pg_depend_objsubid
,
5936 BTEqualStrategyNumber
, F_INT4EQ
,
5937 Int32GetDatum((int32
) attnum
));
5939 scan
= systable_beginscan(depRel
, DependDependerIndexId
, true,
5940 SnapshotNow
, 3, key
);
5942 while (HeapTupleIsValid(depTup
= systable_getnext(scan
)))
5944 Form_pg_depend foundDep
= (Form_pg_depend
) GETSTRUCT(depTup
);
5946 if (foundDep
->deptype
!= DEPENDENCY_NORMAL
)
5947 elog(ERROR
, "found unexpected dependency type '%c'",
5949 if (foundDep
->refclassid
!= TypeRelationId
||
5950 foundDep
->refobjid
!= attTup
->atttypid
)
5951 elog(ERROR
, "found unexpected dependency for column");
5953 simple_heap_delete(depRel
, &depTup
->t_self
);
5956 systable_endscan(scan
);
5958 heap_close(depRel
, RowExclusiveLock
);
5961 * Here we go --- change the recorded column type. (Note heapTup is a
5962 * copy of the syscache entry, so okay to scribble on.)
5964 attTup
->atttypid
= targettype
;
5965 attTup
->atttypmod
= targettypmod
;
5966 attTup
->attndims
= list_length(typename
->arrayBounds
);
5967 attTup
->attlen
= tform
->typlen
;
5968 attTup
->attbyval
= tform
->typbyval
;
5969 attTup
->attalign
= tform
->typalign
;
5970 attTup
->attstorage
= tform
->typstorage
;
5972 ReleaseSysCache(typeTuple
);
5974 simple_heap_update(attrelation
, &heapTup
->t_self
, heapTup
);
5976 /* keep system catalog indexes current */
5977 CatalogUpdateIndexes(attrelation
, heapTup
);
5979 heap_close(attrelation
, RowExclusiveLock
);
5981 /* Install dependency on new datatype */
5982 add_column_datatype_dependency(RelationGetRelid(rel
), attnum
, targettype
);
5985 * Drop any pg_statistic entry for the column, since it's now wrong type
5987 RemoveStatistics(RelationGetRelid(rel
), attnum
);
5990 * Update the default, if present, by brute force --- remove and re-add
5991 * the default. Probably unsafe to take shortcuts, since the new version
5992 * may well have additional dependencies. (It's okay to do this now,
5993 * rather than after other ALTER TYPE commands, since the default won't
5994 * depend on other column types.)
5998 /* Must make new row visible since it will be updated again */
5999 CommandCounterIncrement();
6002 * We use RESTRICT here for safety, but at present we do not expect
6003 * anything to depend on the default.
6005 RemoveAttrDefault(RelationGetRelid(rel
), attnum
, DROP_RESTRICT
, true);
6007 StoreAttrDefault(rel
, attnum
, defaultexpr
);
6011 heap_freetuple(heapTup
);
6015 * Cleanup after we've finished all the ALTER TYPE operations for a
6016 * particular relation. We have to drop and recreate all the indexes
6017 * and constraints that depend on the altered columns.
6020 ATPostAlterTypeCleanup(List
**wqueue
, AlteredTableInfo
*tab
)
6026 * Re-parse the index and constraint definitions, and attach them to the
6027 * appropriate work queue entries. We do this before dropping because in
6028 * the case of a FOREIGN KEY constraint, we might not yet have exclusive
6029 * lock on the table the constraint is attached to, and we need to get
6030 * that before dropping. It's safe because the parser won't actually look
6031 * at the catalogs to detect the existing entry.
6033 foreach(l
, tab
->changedIndexDefs
)
6034 ATPostAlterTypeParse((char *) lfirst(l
), wqueue
);
6035 foreach(l
, tab
->changedConstraintDefs
)
6036 ATPostAlterTypeParse((char *) lfirst(l
), wqueue
);
6039 * Now we can drop the existing constraints and indexes --- constraints
6040 * first, since some of them might depend on the indexes. In fact, we
6041 * have to delete FOREIGN KEY constraints before UNIQUE constraints, but
6042 * we already ordered the constraint list to ensure that would happen. It
6043 * should be okay to use DROP_RESTRICT here, since nothing else should be
6044 * depending on these objects.
6046 foreach(l
, tab
->changedConstraintOids
)
6048 obj
.classId
= ConstraintRelationId
;
6049 obj
.objectId
= lfirst_oid(l
);
6050 obj
.objectSubId
= 0;
6051 performDeletion(&obj
, DROP_RESTRICT
);
6054 foreach(l
, tab
->changedIndexOids
)
6056 obj
.classId
= RelationRelationId
;
6057 obj
.objectId
= lfirst_oid(l
);
6058 obj
.objectSubId
= 0;
6059 performDeletion(&obj
, DROP_RESTRICT
);
6063 * The objects will get recreated during subsequent passes over the work
6069 ATPostAlterTypeParse(char *cmd
, List
**wqueue
)
6071 List
*raw_parsetree_list
;
6072 List
*querytree_list
;
6073 ListCell
*list_item
;
6076 * We expect that we will get only ALTER TABLE and CREATE INDEX
6077 * statements. Hence, there is no need to pass them through
6078 * parse_analyze() or the rewriter, but instead we need to pass them
6079 * through parse_utilcmd.c to make them ready for execution.
6081 raw_parsetree_list
= raw_parser(cmd
);
6082 querytree_list
= NIL
;
6083 foreach(list_item
, raw_parsetree_list
)
6085 Node
*stmt
= (Node
*) lfirst(list_item
);
6087 if (IsA(stmt
, IndexStmt
))
6088 querytree_list
= lappend(querytree_list
,
6089 transformIndexStmt((IndexStmt
*) stmt
,
6091 else if (IsA(stmt
, AlterTableStmt
))
6092 querytree_list
= list_concat(querytree_list
,
6093 transformAlterTableStmt((AlterTableStmt
*) stmt
,
6096 querytree_list
= lappend(querytree_list
, stmt
);
6100 * Attach each generated command to the proper place in the work queue.
6101 * Note this could result in creation of entirely new work-queue entries.
6103 foreach(list_item
, querytree_list
)
6105 Node
*stm
= (Node
*) lfirst(list_item
);
6107 AlteredTableInfo
*tab
;
6109 switch (nodeTag(stm
))
6113 IndexStmt
*stmt
= (IndexStmt
*) stm
;
6114 AlterTableCmd
*newcmd
;
6116 rel
= relation_openrv(stmt
->relation
, AccessExclusiveLock
);
6117 tab
= ATGetQueueEntry(wqueue
, rel
);
6118 newcmd
= makeNode(AlterTableCmd
);
6119 newcmd
->subtype
= AT_ReAddIndex
;
6120 newcmd
->def
= (Node
*) stmt
;
6121 tab
->subcmds
[AT_PASS_OLD_INDEX
] =
6122 lappend(tab
->subcmds
[AT_PASS_OLD_INDEX
], newcmd
);
6123 relation_close(rel
, NoLock
);
6126 case T_AlterTableStmt
:
6128 AlterTableStmt
*stmt
= (AlterTableStmt
*) stm
;
6131 rel
= relation_openrv(stmt
->relation
, AccessExclusiveLock
);
6132 tab
= ATGetQueueEntry(wqueue
, rel
);
6133 foreach(lcmd
, stmt
->cmds
)
6135 AlterTableCmd
*cmd
= (AlterTableCmd
*) lfirst(lcmd
);
6137 switch (cmd
->subtype
)
6140 cmd
->subtype
= AT_ReAddIndex
;
6141 tab
->subcmds
[AT_PASS_OLD_INDEX
] =
6142 lappend(tab
->subcmds
[AT_PASS_OLD_INDEX
], cmd
);
6144 case AT_AddConstraint
:
6145 tab
->subcmds
[AT_PASS_OLD_CONSTR
] =
6146 lappend(tab
->subcmds
[AT_PASS_OLD_CONSTR
], cmd
);
6149 elog(ERROR
, "unexpected statement type: %d",
6150 (int) cmd
->subtype
);
6153 relation_close(rel
, NoLock
);
6157 elog(ERROR
, "unexpected statement type: %d",
6158 (int) nodeTag(stm
));
6167 * recursing is true if we are recursing from a table to its indexes,
6168 * sequences, or toast table. We don't allow the ownership of those things to
6169 * be changed separately from the parent table. Also, we can skip permission
6170 * checks (this is necessary not just an optimization, else we'd fail to
6171 * handle toast tables properly).
6173 * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
6174 * free-standing composite type.
6177 ATExecChangeOwner(Oid relationOid
, Oid newOwnerId
, bool recursing
)
6179 Relation target_rel
;
6182 Form_pg_class tuple_class
;
6185 * Get exclusive lock till end of transaction on the target table. Use
6186 * relation_open so that we can work on indexes and sequences.
6188 target_rel
= relation_open(relationOid
, AccessExclusiveLock
);
6190 /* Get its pg_class tuple, too */
6191 class_rel
= heap_open(RelationRelationId
, RowExclusiveLock
);
6193 tuple
= SearchSysCache(RELOID
,
6194 ObjectIdGetDatum(relationOid
),
6196 if (!HeapTupleIsValid(tuple
))
6197 elog(ERROR
, "cache lookup failed for relation %u", relationOid
);
6198 tuple_class
= (Form_pg_class
) GETSTRUCT(tuple
);
6200 /* Can we change the ownership of this tuple? */
6201 switch (tuple_class
->relkind
)
6203 case RELKIND_RELATION
:
6205 /* ok to change owner */
6211 * Because ALTER INDEX OWNER used to be allowed, and in fact
6212 * is generated by old versions of pg_dump, we give a warning
6213 * and do nothing rather than erroring out. Also, to avoid
6214 * unnecessary chatter while restoring those old dumps, say
6215 * nothing at all if the command would be a no-op anyway.
6217 if (tuple_class
->relowner
!= newOwnerId
)
6219 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
6220 errmsg("cannot change owner of index \"%s\"",
6221 NameStr(tuple_class
->relname
)),
6222 errhint("Change the ownership of the index's table, instead.")));
6223 /* quick hack to exit via the no-op path */
6224 newOwnerId
= tuple_class
->relowner
;
6227 case RELKIND_SEQUENCE
:
6229 tuple_class
->relowner
!= newOwnerId
)
6231 /* if it's an owned sequence, disallow changing it by itself */
6235 if (sequenceIsOwned(relationOid
, &tableId
, &colId
))
6237 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
6238 errmsg("cannot change owner of sequence \"%s\"",
6239 NameStr(tuple_class
->relname
)),
6240 errdetail("Sequence \"%s\" is linked to table \"%s\".",
6241 NameStr(tuple_class
->relname
),
6242 get_rel_name(tableId
))));
6245 case RELKIND_COMPOSITE_TYPE
:
6249 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
6250 errmsg("\"%s\" is a composite type",
6251 NameStr(tuple_class
->relname
)),
6252 errhint("Use ALTER TYPE instead.")));
6254 case RELKIND_TOASTVALUE
:
6260 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
6261 errmsg("\"%s\" is not a table, view, or sequence",
6262 NameStr(tuple_class
->relname
))));
6266 * If the new owner is the same as the existing owner, consider the
6267 * command to have succeeded. This is for dump restoration purposes.
6269 if (tuple_class
->relowner
!= newOwnerId
)
6271 Datum repl_val
[Natts_pg_class
];
6272 bool repl_null
[Natts_pg_class
];
6273 bool repl_repl
[Natts_pg_class
];
6279 /* skip permission checks when recursing to index or toast table */
6282 /* Superusers can always do it */
6285 Oid namespaceOid
= tuple_class
->relnamespace
;
6286 AclResult aclresult
;
6288 /* Otherwise, must be owner of the existing object */
6289 if (!pg_class_ownercheck(relationOid
, GetUserId()))
6290 aclcheck_error(ACLCHECK_NOT_OWNER
, ACL_KIND_CLASS
,
6291 RelationGetRelationName(target_rel
));
6293 /* Must be able to become new owner */
6294 check_is_member_of_role(GetUserId(), newOwnerId
);
6296 /* New owner must have CREATE privilege on namespace */
6297 aclresult
= pg_namespace_aclcheck(namespaceOid
, newOwnerId
,
6299 if (aclresult
!= ACLCHECK_OK
)
6300 aclcheck_error(aclresult
, ACL_KIND_NAMESPACE
,
6301 get_namespace_name(namespaceOid
));
6305 memset(repl_null
, false, sizeof(repl_null
));
6306 memset(repl_repl
, false, sizeof(repl_repl
));
6308 repl_repl
[Anum_pg_class_relowner
- 1] = true;
6309 repl_val
[Anum_pg_class_relowner
- 1] = ObjectIdGetDatum(newOwnerId
);
6312 * Determine the modified ACL for the new owner. This is only
6313 * necessary when the ACL is non-null.
6315 aclDatum
= SysCacheGetAttr(RELOID
, tuple
,
6316 Anum_pg_class_relacl
,
6320 newAcl
= aclnewowner(DatumGetAclP(aclDatum
),
6321 tuple_class
->relowner
, newOwnerId
);
6322 repl_repl
[Anum_pg_class_relacl
- 1] = true;
6323 repl_val
[Anum_pg_class_relacl
- 1] = PointerGetDatum(newAcl
);
6326 newtuple
= heap_modify_tuple(tuple
, RelationGetDescr(class_rel
), repl_val
, repl_null
, repl_repl
);
6328 simple_heap_update(class_rel
, &newtuple
->t_self
, newtuple
);
6329 CatalogUpdateIndexes(class_rel
, newtuple
);
6331 heap_freetuple(newtuple
);
6334 * Update owner dependency reference, if any. A composite type has
6335 * none, because it's tracked for the pg_type entry instead of here;
6336 * indexes and TOAST tables don't have their own entries either.
6338 if (tuple_class
->relkind
!= RELKIND_COMPOSITE_TYPE
&&
6339 tuple_class
->relkind
!= RELKIND_INDEX
&&
6340 tuple_class
->relkind
!= RELKIND_TOASTVALUE
)
6341 changeDependencyOnOwner(RelationRelationId
, relationOid
,
6345 * Also change the ownership of the table's rowtype, if it has one
6347 if (tuple_class
->relkind
!= RELKIND_INDEX
)
6348 AlterTypeOwnerInternal(tuple_class
->reltype
, newOwnerId
,
6349 tuple_class
->relkind
== RELKIND_COMPOSITE_TYPE
);
6352 * If we are operating on a table, also change the ownership of any
6353 * indexes and sequences that belong to the table, as well as the
6354 * table's toast table (if it has one)
6356 if (tuple_class
->relkind
== RELKIND_RELATION
||
6357 tuple_class
->relkind
== RELKIND_TOASTVALUE
)
6359 List
*index_oid_list
;
6362 /* Find all the indexes belonging to this relation */
6363 index_oid_list
= RelationGetIndexList(target_rel
);
6365 /* For each index, recursively change its ownership */
6366 foreach(i
, index_oid_list
)
6367 ATExecChangeOwner(lfirst_oid(i
), newOwnerId
, true);
6369 list_free(index_oid_list
);
6372 if (tuple_class
->relkind
== RELKIND_RELATION
)
6374 /* If it has a toast table, recurse to change its ownership */
6375 if (tuple_class
->reltoastrelid
!= InvalidOid
)
6376 ATExecChangeOwner(tuple_class
->reltoastrelid
, newOwnerId
,
6379 /* If it has dependent sequences, recurse to change them too */
6380 change_owner_recurse_to_sequences(relationOid
, newOwnerId
);
6384 ReleaseSysCache(tuple
);
6385 heap_close(class_rel
, RowExclusiveLock
);
6386 relation_close(target_rel
, NoLock
);
6390 * change_owner_recurse_to_sequences
6392 * Helper function for ATExecChangeOwner. Examines pg_depend searching
6393 * for sequences that are dependent on serial columns, and changes their
6397 change_owner_recurse_to_sequences(Oid relationOid
, Oid newOwnerId
)
6405 * SERIAL sequences are those having an auto dependency on one of the
6406 * table's columns (we don't care *which* column, exactly).
6408 depRel
= heap_open(DependRelationId
, AccessShareLock
);
6410 ScanKeyInit(&key
[0],
6411 Anum_pg_depend_refclassid
,
6412 BTEqualStrategyNumber
, F_OIDEQ
,
6413 ObjectIdGetDatum(RelationRelationId
));
6414 ScanKeyInit(&key
[1],
6415 Anum_pg_depend_refobjid
,
6416 BTEqualStrategyNumber
, F_OIDEQ
,
6417 ObjectIdGetDatum(relationOid
));
6418 /* we leave refobjsubid unspecified */
6420 scan
= systable_beginscan(depRel
, DependReferenceIndexId
, true,
6421 SnapshotNow
, 2, key
);
6423 while (HeapTupleIsValid(tup
= systable_getnext(scan
)))
6425 Form_pg_depend depForm
= (Form_pg_depend
) GETSTRUCT(tup
);
6428 /* skip dependencies other than auto dependencies on columns */
6429 if (depForm
->refobjsubid
== 0 ||
6430 depForm
->classid
!= RelationRelationId
||
6431 depForm
->objsubid
!= 0 ||
6432 depForm
->deptype
!= DEPENDENCY_AUTO
)
6435 /* Use relation_open just in case it's an index */
6436 seqRel
= relation_open(depForm
->objid
, AccessExclusiveLock
);
6438 /* skip non-sequence relations */
6439 if (RelationGetForm(seqRel
)->relkind
!= RELKIND_SEQUENCE
)
6441 /* No need to keep the lock */
6442 relation_close(seqRel
, AccessExclusiveLock
);
6446 /* We don't need to close the sequence while we alter it. */
6447 ATExecChangeOwner(depForm
->objid
, newOwnerId
, true);
6449 /* Now we can close it. Keep the lock till end of transaction. */
6450 relation_close(seqRel
, NoLock
);
6453 systable_endscan(scan
);
6455 relation_close(depRel
, AccessShareLock
);
6459 * ALTER TABLE CLUSTER ON
6461 * The only thing we have to do is to change the indisclustered bits.
6464 ATExecClusterOn(Relation rel
, const char *indexName
)
6468 indexOid
= get_relname_relid(indexName
, rel
->rd_rel
->relnamespace
);
6470 if (!OidIsValid(indexOid
))
6472 (errcode(ERRCODE_UNDEFINED_OBJECT
),
6473 errmsg("index \"%s\" for table \"%s\" does not exist",
6474 indexName
, RelationGetRelationName(rel
))));
6476 /* Check index is valid to cluster on */
6477 check_index_is_clusterable(rel
, indexOid
, false);
6479 /* And do the work */
6480 mark_index_clustered(rel
, indexOid
);
6484 * ALTER TABLE SET WITHOUT CLUSTER
6486 * We have to find any indexes on the table that have indisclustered bit
6487 * set and turn it off.
6490 ATExecDropCluster(Relation rel
)
6492 mark_index_clustered(rel
, InvalidOid
);
6496 * ALTER TABLE SET TABLESPACE
6499 ATPrepSetTableSpace(AlteredTableInfo
*tab
, Relation rel
, char *tablespacename
)
6502 AclResult aclresult
;
6504 /* Check that the tablespace exists */
6505 tablespaceId
= get_tablespace_oid(tablespacename
);
6506 if (!OidIsValid(tablespaceId
))
6508 (errcode(ERRCODE_UNDEFINED_OBJECT
),
6509 errmsg("tablespace \"%s\" does not exist", tablespacename
)));
6511 /* Check its permissions */
6512 aclresult
= pg_tablespace_aclcheck(tablespaceId
, GetUserId(), ACL_CREATE
);
6513 if (aclresult
!= ACLCHECK_OK
)
6514 aclcheck_error(aclresult
, ACL_KIND_TABLESPACE
, tablespacename
);
6516 /* Save info for Phase 3 to do the real work */
6517 if (OidIsValid(tab
->newTableSpace
))
6519 (errcode(ERRCODE_SYNTAX_ERROR
),
6520 errmsg("cannot have multiple SET TABLESPACE subcommands")));
6521 tab
->newTableSpace
= tablespaceId
;
6525 * ALTER TABLE/INDEX SET (...) or RESET (...)
6528 ATExecSetRelOptions(Relation rel
, List
*defList
, bool isReset
)
6537 Datum repl_val
[Natts_pg_class
];
6538 bool repl_null
[Natts_pg_class
];
6539 bool repl_repl
[Natts_pg_class
];
6540 static char *validnsps
[] = HEAP_RELOPT_NAMESPACES
;
6543 return; /* nothing to do */
6545 pgclass
= heap_open(RelationRelationId
, RowExclusiveLock
);
6547 /* Get the old reloptions */
6548 relid
= RelationGetRelid(rel
);
6549 tuple
= SearchSysCache(RELOID
,
6550 ObjectIdGetDatum(relid
),
6552 if (!HeapTupleIsValid(tuple
))
6553 elog(ERROR
, "cache lookup failed for relation %u", relid
);
6555 datum
= SysCacheGetAttr(RELOID
, tuple
, Anum_pg_class_reloptions
, &isnull
);
6557 /* Generate new proposed reloptions (text array) */
6558 newOptions
= transformRelOptions(isnull
? (Datum
) 0 : datum
,
6559 defList
, NULL
, validnsps
, false, isReset
);
6562 switch (rel
->rd_rel
->relkind
)
6564 case RELKIND_RELATION
:
6565 case RELKIND_TOASTVALUE
:
6566 (void) heap_reloptions(rel
->rd_rel
->relkind
, newOptions
, true);
6569 (void) index_reloptions(rel
->rd_am
->amoptions
, newOptions
, true);
6573 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
6574 errmsg("\"%s\" is not a table, index, or TOAST table",
6575 RelationGetRelationName(rel
))));
6580 * All we need do here is update the pg_class row; the new options will be
6581 * propagated into relcaches during post-commit cache inval.
6583 memset(repl_val
, 0, sizeof(repl_val
));
6584 memset(repl_null
, false, sizeof(repl_null
));
6585 memset(repl_repl
, false, sizeof(repl_repl
));
6587 if (newOptions
!= (Datum
) 0)
6588 repl_val
[Anum_pg_class_reloptions
- 1] = newOptions
;
6590 repl_null
[Anum_pg_class_reloptions
- 1] = true;
6592 repl_repl
[Anum_pg_class_reloptions
- 1] = true;
6594 newtuple
= heap_modify_tuple(tuple
, RelationGetDescr(pgclass
),
6595 repl_val
, repl_null
, repl_repl
);
6597 simple_heap_update(pgclass
, &newtuple
->t_self
, newtuple
);
6599 CatalogUpdateIndexes(pgclass
, newtuple
);
6601 heap_freetuple(newtuple
);
6603 ReleaseSysCache(tuple
);
6605 /* repeat the whole exercise for the toast table, if there's one */
6606 if (OidIsValid(rel
->rd_rel
->reltoastrelid
))
6609 Oid toastid
= rel
->rd_rel
->reltoastrelid
;
6611 toastrel
= heap_open(toastid
, AccessExclusiveLock
);
6613 /* Get the old reloptions */
6614 tuple
= SearchSysCache(RELOID
,
6615 ObjectIdGetDatum(toastid
),
6617 if (!HeapTupleIsValid(tuple
))
6618 elog(ERROR
, "cache lookup failed for relation %u", toastid
);
6620 datum
= SysCacheGetAttr(RELOID
, tuple
, Anum_pg_class_reloptions
, &isnull
);
6622 newOptions
= transformRelOptions(isnull
? (Datum
) 0 : datum
,
6623 defList
, "toast", validnsps
, false, isReset
);
6625 (void) heap_reloptions(RELKIND_TOASTVALUE
, newOptions
, true);
6627 memset(repl_val
, 0, sizeof(repl_val
));
6628 memset(repl_null
, false, sizeof(repl_null
));
6629 memset(repl_repl
, false, sizeof(repl_repl
));
6631 if (newOptions
!= (Datum
) 0)
6632 repl_val
[Anum_pg_class_reloptions
- 1] = newOptions
;
6634 repl_null
[Anum_pg_class_reloptions
- 1] = true;
6636 repl_repl
[Anum_pg_class_reloptions
- 1] = true;
6638 newtuple
= heap_modify_tuple(tuple
, RelationGetDescr(pgclass
),
6639 repl_val
, repl_null
, repl_repl
);
6641 simple_heap_update(pgclass
, &newtuple
->t_self
, newtuple
);
6643 CatalogUpdateIndexes(pgclass
, newtuple
);
6645 heap_freetuple(newtuple
);
6647 ReleaseSysCache(tuple
);
6649 heap_close(toastrel
, NoLock
);
6652 heap_close(pgclass
, RowExclusiveLock
);
6656 * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
6657 * rewriting to be done, so we just want to copy the data as fast as possible.
6660 ATExecSetTableSpace(Oid tableOid
, Oid newTableSpace
)
6667 RelFileNode newrnode
;
6668 SMgrRelation dstrel
;
6671 Form_pg_class rd_rel
;
6675 * Need lock here in case we are recursing to toast table or index
6677 rel
= relation_open(tableOid
, AccessExclusiveLock
);
6680 * We can never allow moving of shared or nailed-in-cache relations,
6681 * because we can't support changing their reltablespace values.
6683 if (rel
->rd_rel
->relisshared
|| rel
->rd_isnailed
)
6685 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
6686 errmsg("cannot move system relation \"%s\"",
6687 RelationGetRelationName(rel
))));
6689 /* Can't move a non-shared relation into pg_global */
6690 if (newTableSpace
== GLOBALTABLESPACE_OID
)
6692 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
6693 errmsg("only shared relations can be placed in pg_global tablespace")));
6696 * Don't allow moving temp tables of other backends ... their local buffer
6697 * manager is not going to cope.
6699 if (RELATION_IS_OTHER_TEMP(rel
))
6701 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
6702 errmsg("cannot move temporary tables of other sessions")));
6705 * No work if no change in tablespace.
6707 oldTableSpace
= rel
->rd_rel
->reltablespace
;
6708 if (newTableSpace
== oldTableSpace
||
6709 (newTableSpace
== MyDatabaseTableSpace
&& oldTableSpace
== 0))
6711 relation_close(rel
, NoLock
);
6715 reltoastrelid
= rel
->rd_rel
->reltoastrelid
;
6716 reltoastidxid
= rel
->rd_rel
->reltoastidxid
;
6718 /* Get a modifiable copy of the relation's pg_class row */
6719 pg_class
= heap_open(RelationRelationId
, RowExclusiveLock
);
6721 tuple
= SearchSysCacheCopy(RELOID
,
6722 ObjectIdGetDatum(tableOid
),
6724 if (!HeapTupleIsValid(tuple
))
6725 elog(ERROR
, "cache lookup failed for relation %u", tableOid
);
6726 rd_rel
= (Form_pg_class
) GETSTRUCT(tuple
);
6729 * Since we copy the file directly without looking at the shared buffers,
6730 * we'd better first flush out any pages of the source relation that are
6731 * in shared buffers. We assume no new changes will be made while we are
6732 * holding exclusive lock on the rel.
6734 FlushRelationBuffers(rel
);
6737 * Relfilenodes are not unique across tablespaces, so we need to allocate
6738 * a new one in the new tablespace.
6740 newrelfilenode
= GetNewRelFileNode(newTableSpace
,
6741 rel
->rd_rel
->relisshared
,
6744 /* Open old and new relation */
6745 newrnode
= rel
->rd_node
;
6746 newrnode
.relNode
= newrelfilenode
;
6747 newrnode
.spcNode
= newTableSpace
;
6748 dstrel
= smgropen(newrnode
);
6750 RelationOpenSmgr(rel
);
6753 * Create and copy all forks of the relation, and schedule unlinking of
6754 * old physical files.
6756 * NOTE: any conflict in relfilenode value will be caught in
6757 * RelationCreateStorage().
6759 RelationCreateStorage(newrnode
, rel
->rd_istemp
);
6761 /* copy main fork */
6762 copy_relation_data(rel
->rd_smgr
, dstrel
, MAIN_FORKNUM
, rel
->rd_istemp
);
6764 /* copy those extra forks that exist */
6765 for (forkNum
= MAIN_FORKNUM
+ 1; forkNum
<= MAX_FORKNUM
; forkNum
++)
6767 if (smgrexists(rel
->rd_smgr
, forkNum
))
6769 smgrcreate(dstrel
, forkNum
, false);
6770 copy_relation_data(rel
->rd_smgr
, dstrel
, forkNum
, rel
->rd_istemp
);
6774 /* drop old relation, and close new one */
6775 RelationDropStorage(rel
);
6778 /* update the pg_class row */
6779 rd_rel
->reltablespace
= (newTableSpace
== MyDatabaseTableSpace
) ? InvalidOid
: newTableSpace
;
6780 rd_rel
->relfilenode
= newrelfilenode
;
6781 simple_heap_update(pg_class
, &tuple
->t_self
, tuple
);
6782 CatalogUpdateIndexes(pg_class
, tuple
);
6784 heap_freetuple(tuple
);
6786 heap_close(pg_class
, RowExclusiveLock
);
6788 relation_close(rel
, NoLock
);
6790 /* Make sure the reltablespace change is visible */
6791 CommandCounterIncrement();
6793 /* Move associated toast relation and/or index, too */
6794 if (OidIsValid(reltoastrelid
))
6795 ATExecSetTableSpace(reltoastrelid
, newTableSpace
);
6796 if (OidIsValid(reltoastidxid
))
6797 ATExecSetTableSpace(reltoastidxid
, newTableSpace
);
6801 * Copy data, block by block
6804 copy_relation_data(SMgrRelation src
, SMgrRelation dst
,
6805 ForkNumber forkNum
, bool istemp
)
6808 BlockNumber nblocks
;
6811 Page page
= (Page
) buf
;
6814 * We need to log the copied data in WAL iff WAL archiving is enabled AND
6815 * it's not a temp rel.
6817 use_wal
= XLogArchivingActive() && !istemp
;
6819 nblocks
= smgrnblocks(src
, forkNum
);
6821 for (blkno
= 0; blkno
< nblocks
; blkno
++)
6823 smgrread(src
, forkNum
, blkno
, buf
);
6827 log_newpage(&dst
->smgr_rnode
, forkNum
, blkno
, page
);
6830 * Now write the page. We say isTemp = true even if it's not a temp
6831 * rel, because there's no need for smgr to schedule an fsync for this
6832 * write; we'll do it ourselves below.
6834 smgrextend(dst
, forkNum
, blkno
, buf
, true);
6838 * If the rel isn't temp, we must fsync it down to disk before it's safe
6839 * to commit the transaction. (For a temp rel we don't care since the rel
6840 * will be uninteresting after a crash anyway.)
6842 * It's obvious that we must do this when not WAL-logging the copy. It's
6843 * less obvious that we have to do it even if we did WAL-log the copied
6844 * pages. The reason is that since we're copying outside shared buffers, a
6845 * CHECKPOINT occurring during the copy has no way to flush the previously
6846 * written data to disk (indeed it won't know the new rel even exists). A
6847 * crash later on would replay WAL from the checkpoint, therefore it
6848 * wouldn't replay our earlier WAL entries. If we do not fsync those pages
6849 * here, they might still not be on disk when the crash occurs.
6852 smgrimmedsync(dst
, forkNum
);
6856 * ALTER TABLE ENABLE/DISABLE TRIGGER
6858 * We just pass this off to trigger.c.
6861 ATExecEnableDisableTrigger(Relation rel
, char *trigname
,
6862 char fires_when
, bool skip_system
)
6864 EnableDisableTrigger(rel
, trigname
, fires_when
, skip_system
);
6868 * ALTER TABLE ENABLE/DISABLE RULE
6870 * We just pass this off to rewriteDefine.c.
6873 ATExecEnableDisableRule(Relation rel
, char *trigname
,
6876 EnableDisableRule(rel
, trigname
, fires_when
);
6880 * ALTER TABLE INHERIT
6882 * Add a parent to the child's parents. This verifies that all the columns and
6883 * check constraints of the parent appear in the child and that they have the
6884 * same data types and expressions.
6887 ATExecAddInherit(Relation child_rel
, RangeVar
*parent
)
6889 Relation parent_rel
,
6893 HeapTuple inheritsTuple
;
6898 * AccessShareLock on the parent is what's obtained during normal CREATE
6899 * TABLE ... INHERITS ..., so should be enough here.
6901 parent_rel
= heap_openrv(parent
, AccessShareLock
);
6904 * Must be owner of both parent and child -- child was checked by
6905 * ATSimplePermissions call in ATPrepCmd
6907 ATSimplePermissions(parent_rel
, false);
6909 /* Permanent rels cannot inherit from temporary ones */
6910 if (parent_rel
->rd_istemp
&& !child_rel
->rd_istemp
)
6912 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
6913 errmsg("cannot inherit from temporary relation \"%s\"",
6914 RelationGetRelationName(parent_rel
))));
6917 * Check for duplicates in the list of parents, and determine the highest
6918 * inhseqno already present; we'll use the next one for the new parent.
6919 * (Note: get RowExclusiveLock because we will write pg_inherits below.)
6921 * Note: we do not reject the case where the child already inherits from
6922 * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
6924 catalogRelation
= heap_open(InheritsRelationId
, RowExclusiveLock
);
6926 Anum_pg_inherits_inhrelid
,
6927 BTEqualStrategyNumber
, F_OIDEQ
,
6928 ObjectIdGetDatum(RelationGetRelid(child_rel
)));
6929 scan
= systable_beginscan(catalogRelation
, InheritsRelidSeqnoIndexId
,
6930 true, SnapshotNow
, 1, &key
);
6932 /* inhseqno sequences start at 1 */
6934 while (HeapTupleIsValid(inheritsTuple
= systable_getnext(scan
)))
6936 Form_pg_inherits inh
= (Form_pg_inherits
) GETSTRUCT(inheritsTuple
);
6938 if (inh
->inhparent
== RelationGetRelid(parent_rel
))
6940 (errcode(ERRCODE_DUPLICATE_TABLE
),
6941 errmsg("relation \"%s\" would be inherited from more than once",
6942 RelationGetRelationName(parent_rel
))));
6943 if (inh
->inhseqno
> inhseqno
)
6944 inhseqno
= inh
->inhseqno
;
6946 systable_endscan(scan
);
6949 * Prevent circularity by seeing if proposed parent inherits from child.
6950 * (In particular, this disallows making a rel inherit from itself.)
6952 * This is not completely bulletproof because of race conditions: in
6953 * multi-level inheritance trees, someone else could concurrently be
6954 * making another inheritance link that closes the loop but does not join
6955 * either of the rels we have locked. Preventing that seems to require
6956 * exclusive locks on the entire inheritance tree, which is a cure worse
6957 * than the disease. find_all_inheritors() will cope with circularity
6958 * anyway, so don't sweat it too much.
6960 * We use weakest lock we can on child's children, namely AccessShareLock.
6962 children
= find_all_inheritors(RelationGetRelid(child_rel
),
6965 if (list_member_oid(children
, RelationGetRelid(parent_rel
)))
6967 (errcode(ERRCODE_DUPLICATE_TABLE
),
6968 errmsg("circular inheritance not allowed"),
6969 errdetail("\"%s\" is already a child of \"%s\".",
6971 RelationGetRelationName(child_rel
))));
6973 /* If parent has OIDs then child must have OIDs */
6974 if (parent_rel
->rd_rel
->relhasoids
&& !child_rel
->rd_rel
->relhasoids
)
6976 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
6977 errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
6978 RelationGetRelationName(child_rel
),
6979 RelationGetRelationName(parent_rel
))));
6981 /* Match up the columns and bump attinhcount as needed */
6982 MergeAttributesIntoExisting(child_rel
, parent_rel
);
6984 /* Match up the constraints and bump coninhcount as needed */
6985 MergeConstraintsIntoExisting(child_rel
, parent_rel
);
6988 * OK, it looks valid. Make the catalog entries that show inheritance.
6990 StoreCatalogInheritance1(RelationGetRelid(child_rel
),
6991 RelationGetRelid(parent_rel
),
6995 /* Now we're done with pg_inherits */
6996 heap_close(catalogRelation
, RowExclusiveLock
);
6998 /* keep our lock on the parent relation until commit */
6999 heap_close(parent_rel
, NoLock
);
7003 * Obtain the source-text form of the constraint expression for a check
7004 * constraint, given its pg_constraint tuple
7007 decompile_conbin(HeapTuple contup
, TupleDesc tupdesc
)
7009 Form_pg_constraint con
;
7014 con
= (Form_pg_constraint
) GETSTRUCT(contup
);
7015 attr
= heap_getattr(contup
, Anum_pg_constraint_conbin
, tupdesc
, &isnull
);
7017 elog(ERROR
, "null conbin for constraint %u", HeapTupleGetOid(contup
));
7019 expr
= DirectFunctionCall2(pg_get_expr
, attr
,
7020 ObjectIdGetDatum(con
->conrelid
));
7021 return TextDatumGetCString(expr
);
7025 * Determine whether two check constraints are functionally equivalent
7027 * The test we apply is to see whether they reverse-compile to the same
7028 * source string. This insulates us from issues like whether attributes
7029 * have the same physical column numbers in parent and child relations.
7032 constraints_equivalent(HeapTuple a
, HeapTuple b
, TupleDesc tupleDesc
)
7034 Form_pg_constraint acon
= (Form_pg_constraint
) GETSTRUCT(a
);
7035 Form_pg_constraint bcon
= (Form_pg_constraint
) GETSTRUCT(b
);
7037 if (acon
->condeferrable
!= bcon
->condeferrable
||
7038 acon
->condeferred
!= bcon
->condeferred
||
7039 strcmp(decompile_conbin(a
, tupleDesc
),
7040 decompile_conbin(b
, tupleDesc
)) != 0)
7047 * Check columns in child table match up with columns in parent, and increment
7048 * their attinhcount.
7050 * Called by ATExecAddInherit
7052 * Currently all parent columns must be found in child. Missing columns are an
7053 * error. One day we might consider creating new columns like CREATE TABLE
7054 * does. However, that is widely unpopular --- in the common use case of
7055 * partitioned tables it's a foot-gun.
7057 * The data type must match exactly. If the parent column is NOT NULL then
7058 * the child must be as well. Defaults are not compared, however.
7061 MergeAttributesIntoExisting(Relation child_rel
, Relation parent_rel
)
7064 AttrNumber parent_attno
;
7066 TupleDesc tupleDesc
;
7067 TupleConstr
*constr
;
7070 attrrel
= heap_open(AttributeRelationId
, RowExclusiveLock
);
7072 tupleDesc
= RelationGetDescr(parent_rel
);
7073 parent_natts
= tupleDesc
->natts
;
7074 constr
= tupleDesc
->constr
;
7076 for (parent_attno
= 1; parent_attno
<= parent_natts
; parent_attno
++)
7078 Form_pg_attribute attribute
= tupleDesc
->attrs
[parent_attno
- 1];
7079 char *attributeName
= NameStr(attribute
->attname
);
7081 /* Ignore dropped columns in the parent. */
7082 if (attribute
->attisdropped
)
7085 /* Find same column in child (matching on column name). */
7086 tuple
= SearchSysCacheCopyAttName(RelationGetRelid(child_rel
),
7088 if (HeapTupleIsValid(tuple
))
7090 /* Check they are same type and typmod */
7091 Form_pg_attribute childatt
= (Form_pg_attribute
) GETSTRUCT(tuple
);
7093 if (attribute
->atttypid
!= childatt
->atttypid
||
7094 attribute
->atttypmod
!= childatt
->atttypmod
)
7096 (errcode(ERRCODE_DATATYPE_MISMATCH
),
7097 errmsg("child table \"%s\" has different type for column \"%s\"",
7098 RelationGetRelationName(child_rel
),
7101 if (attribute
->attnotnull
&& !childatt
->attnotnull
)
7103 (errcode(ERRCODE_DATATYPE_MISMATCH
),
7104 errmsg("column \"%s\" in child table must be marked NOT NULL",
7108 * OK, bump the child column's inheritance count. (If we fail
7109 * later on, this change will just roll back.)
7111 childatt
->attinhcount
++;
7112 simple_heap_update(attrrel
, &tuple
->t_self
, tuple
);
7113 CatalogUpdateIndexes(attrrel
, tuple
);
7114 heap_freetuple(tuple
);
7119 (errcode(ERRCODE_DATATYPE_MISMATCH
),
7120 errmsg("child table is missing column \"%s\"",
7125 heap_close(attrrel
, RowExclusiveLock
);
7129 * Check constraints in child table match up with constraints in parent,
7130 * and increment their coninhcount.
7132 * Called by ATExecAddInherit
7134 * Currently all constraints in parent must be present in the child. One day we
7135 * may consider adding new constraints like CREATE TABLE does. We may also want
7136 * to allow an optional flag on parent table constraints indicating they are
7137 * intended to ONLY apply to the master table, not to the children. That would
7138 * make it possible to ensure no records are mistakenly inserted into the
7139 * master in partitioned tables rather than the appropriate child.
7141 * XXX This is O(N^2) which may be an issue with tables with hundreds of
7142 * constraints. As long as tables have more like 10 constraints it shouldn't be
7143 * a problem though. Even 100 constraints ought not be the end of the world.
7146 MergeConstraintsIntoExisting(Relation child_rel
, Relation parent_rel
)
7148 Relation catalog_relation
;
7149 TupleDesc tuple_desc
;
7150 SysScanDesc parent_scan
;
7151 ScanKeyData parent_key
;
7152 HeapTuple parent_tuple
;
7154 catalog_relation
= heap_open(ConstraintRelationId
, RowExclusiveLock
);
7155 tuple_desc
= RelationGetDescr(catalog_relation
);
7157 /* Outer loop scans through the parent's constraint definitions */
7158 ScanKeyInit(&parent_key
,
7159 Anum_pg_constraint_conrelid
,
7160 BTEqualStrategyNumber
, F_OIDEQ
,
7161 ObjectIdGetDatum(RelationGetRelid(parent_rel
)));
7162 parent_scan
= systable_beginscan(catalog_relation
, ConstraintRelidIndexId
,
7163 true, SnapshotNow
, 1, &parent_key
);
7165 while (HeapTupleIsValid(parent_tuple
= systable_getnext(parent_scan
)))
7167 Form_pg_constraint parent_con
= (Form_pg_constraint
) GETSTRUCT(parent_tuple
);
7168 SysScanDesc child_scan
;
7169 ScanKeyData child_key
;
7170 HeapTuple child_tuple
;
7173 if (parent_con
->contype
!= CONSTRAINT_CHECK
)
7176 /* Search for a child constraint matching this one */
7177 ScanKeyInit(&child_key
,
7178 Anum_pg_constraint_conrelid
,
7179 BTEqualStrategyNumber
, F_OIDEQ
,
7180 ObjectIdGetDatum(RelationGetRelid(child_rel
)));
7181 child_scan
= systable_beginscan(catalog_relation
, ConstraintRelidIndexId
,
7182 true, SnapshotNow
, 1, &child_key
);
7184 while (HeapTupleIsValid(child_tuple
= systable_getnext(child_scan
)))
7186 Form_pg_constraint child_con
= (Form_pg_constraint
) GETSTRUCT(child_tuple
);
7187 HeapTuple child_copy
;
7189 if (child_con
->contype
!= CONSTRAINT_CHECK
)
7192 if (strcmp(NameStr(parent_con
->conname
),
7193 NameStr(child_con
->conname
)) != 0)
7196 if (!constraints_equivalent(parent_tuple
, child_tuple
, tuple_desc
))
7198 (errcode(ERRCODE_DATATYPE_MISMATCH
),
7199 errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
7200 RelationGetRelationName(child_rel
),
7201 NameStr(parent_con
->conname
))));
7204 * OK, bump the child constraint's inheritance count. (If we fail
7205 * later on, this change will just roll back.)
7207 child_copy
= heap_copytuple(child_tuple
);
7208 child_con
= (Form_pg_constraint
) GETSTRUCT(child_copy
);
7209 child_con
->coninhcount
++;
7210 simple_heap_update(catalog_relation
, &child_copy
->t_self
, child_copy
);
7211 CatalogUpdateIndexes(catalog_relation
, child_copy
);
7212 heap_freetuple(child_copy
);
7218 systable_endscan(child_scan
);
7222 (errcode(ERRCODE_DATATYPE_MISMATCH
),
7223 errmsg("child table is missing constraint \"%s\"",
7224 NameStr(parent_con
->conname
))));
7227 systable_endscan(parent_scan
);
7228 heap_close(catalog_relation
, RowExclusiveLock
);
7232 * ALTER TABLE NO INHERIT
7234 * Drop a parent from the child's parents. This just adjusts the attinhcount
7235 * and attislocal of the columns and removes the pg_inherit and pg_depend
7238 * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
7239 * up attislocal stays true, which means if a child is ever removed from a
7240 * parent then its columns will never be automatically dropped which may
7241 * surprise. But at least we'll never surprise by dropping columns someone
7242 * isn't expecting to be dropped which would actually mean data loss.
7244 * coninhcount and conislocal for inherited constraints are adjusted in
7245 * exactly the same way.
7248 ATExecDropInherit(Relation rel
, RangeVar
*parent
)
7250 Relation parent_rel
;
7251 Relation catalogRelation
;
7254 HeapTuple inheritsTuple
,
7262 * AccessShareLock on the parent is probably enough, seeing that DROP
7263 * TABLE doesn't lock parent tables at all. We need some lock since we'll
7264 * be inspecting the parent's schema.
7266 parent_rel
= heap_openrv(parent
, AccessShareLock
);
7269 * We don't bother to check ownership of the parent table --- ownership of
7270 * the child is presumed enough rights.
7274 * Find and destroy the pg_inherits entry linking the two, or error out if
7277 catalogRelation
= heap_open(InheritsRelationId
, RowExclusiveLock
);
7278 ScanKeyInit(&key
[0],
7279 Anum_pg_inherits_inhrelid
,
7280 BTEqualStrategyNumber
, F_OIDEQ
,
7281 ObjectIdGetDatum(RelationGetRelid(rel
)));
7282 scan
= systable_beginscan(catalogRelation
, InheritsRelidSeqnoIndexId
,
7283 true, SnapshotNow
, 1, key
);
7285 while (HeapTupleIsValid(inheritsTuple
= systable_getnext(scan
)))
7289 inhparent
= ((Form_pg_inherits
) GETSTRUCT(inheritsTuple
))->inhparent
;
7290 if (inhparent
== RelationGetRelid(parent_rel
))
7292 simple_heap_delete(catalogRelation
, &inheritsTuple
->t_self
);
7298 systable_endscan(scan
);
7299 heap_close(catalogRelation
, RowExclusiveLock
);
7303 (errcode(ERRCODE_UNDEFINED_TABLE
),
7304 errmsg("relation \"%s\" is not a parent of relation \"%s\"",
7305 RelationGetRelationName(parent_rel
),
7306 RelationGetRelationName(rel
))));
7309 * Search through child columns looking for ones matching parent rel
7311 catalogRelation
= heap_open(AttributeRelationId
, RowExclusiveLock
);
7312 ScanKeyInit(&key
[0],
7313 Anum_pg_attribute_attrelid
,
7314 BTEqualStrategyNumber
, F_OIDEQ
,
7315 ObjectIdGetDatum(RelationGetRelid(rel
)));
7316 scan
= systable_beginscan(catalogRelation
, AttributeRelidNumIndexId
,
7317 true, SnapshotNow
, 1, key
);
7318 while (HeapTupleIsValid(attributeTuple
= systable_getnext(scan
)))
7320 Form_pg_attribute att
= (Form_pg_attribute
) GETSTRUCT(attributeTuple
);
7322 /* Ignore if dropped or not inherited */
7323 if (att
->attisdropped
)
7325 if (att
->attinhcount
<= 0)
7328 if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel
),
7329 NameStr(att
->attname
)))
7331 /* Decrement inhcount and possibly set islocal to true */
7332 HeapTuple copyTuple
= heap_copytuple(attributeTuple
);
7333 Form_pg_attribute copy_att
= (Form_pg_attribute
) GETSTRUCT(copyTuple
);
7335 copy_att
->attinhcount
--;
7336 if (copy_att
->attinhcount
== 0)
7337 copy_att
->attislocal
= true;
7339 simple_heap_update(catalogRelation
, ©Tuple
->t_self
, copyTuple
);
7340 CatalogUpdateIndexes(catalogRelation
, copyTuple
);
7341 heap_freetuple(copyTuple
);
7344 systable_endscan(scan
);
7345 heap_close(catalogRelation
, RowExclusiveLock
);
7348 * Likewise, find inherited check constraints and disinherit them. To do
7349 * this, we first need a list of the names of the parent's check
7350 * constraints. (We cheat a bit by only checking for name matches,
7351 * assuming that the expressions will match.)
7353 catalogRelation
= heap_open(ConstraintRelationId
, RowExclusiveLock
);
7354 ScanKeyInit(&key
[0],
7355 Anum_pg_constraint_conrelid
,
7356 BTEqualStrategyNumber
, F_OIDEQ
,
7357 ObjectIdGetDatum(RelationGetRelid(parent_rel
)));
7358 scan
= systable_beginscan(catalogRelation
, ConstraintRelidIndexId
,
7359 true, SnapshotNow
, 1, key
);
7363 while (HeapTupleIsValid(constraintTuple
= systable_getnext(scan
)))
7365 Form_pg_constraint con
= (Form_pg_constraint
) GETSTRUCT(constraintTuple
);
7367 if (con
->contype
== CONSTRAINT_CHECK
)
7368 connames
= lappend(connames
, pstrdup(NameStr(con
->conname
)));
7371 systable_endscan(scan
);
7373 /* Now scan the child's constraints */
7374 ScanKeyInit(&key
[0],
7375 Anum_pg_constraint_conrelid
,
7376 BTEqualStrategyNumber
, F_OIDEQ
,
7377 ObjectIdGetDatum(RelationGetRelid(rel
)));
7378 scan
= systable_beginscan(catalogRelation
, ConstraintRelidIndexId
,
7379 true, SnapshotNow
, 1, key
);
7381 while (HeapTupleIsValid(constraintTuple
= systable_getnext(scan
)))
7383 Form_pg_constraint con
= (Form_pg_constraint
) GETSTRUCT(constraintTuple
);
7387 if (con
->contype
!= CONSTRAINT_CHECK
)
7391 foreach(lc
, connames
)
7393 if (strcmp(NameStr(con
->conname
), (char *) lfirst(lc
)) == 0)
7402 /* Decrement inhcount and possibly set islocal to true */
7403 HeapTuple copyTuple
= heap_copytuple(constraintTuple
);
7404 Form_pg_constraint copy_con
= (Form_pg_constraint
) GETSTRUCT(copyTuple
);
7406 if (copy_con
->coninhcount
<= 0) /* shouldn't happen */
7407 elog(ERROR
, "relation %u has non-inherited constraint \"%s\"",
7408 RelationGetRelid(rel
), NameStr(copy_con
->conname
));
7410 copy_con
->coninhcount
--;
7411 if (copy_con
->coninhcount
== 0)
7412 copy_con
->conislocal
= true;
7414 simple_heap_update(catalogRelation
, ©Tuple
->t_self
, copyTuple
);
7415 CatalogUpdateIndexes(catalogRelation
, copyTuple
);
7416 heap_freetuple(copyTuple
);
7420 systable_endscan(scan
);
7421 heap_close(catalogRelation
, RowExclusiveLock
);
7424 * Drop the dependency
7426 * There's no convenient way to do this, so go trawling through pg_depend
7428 catalogRelation
= heap_open(DependRelationId
, RowExclusiveLock
);
7430 ScanKeyInit(&key
[0],
7431 Anum_pg_depend_classid
,
7432 BTEqualStrategyNumber
, F_OIDEQ
,
7433 ObjectIdGetDatum(RelationRelationId
));
7434 ScanKeyInit(&key
[1],
7435 Anum_pg_depend_objid
,
7436 BTEqualStrategyNumber
, F_OIDEQ
,
7437 ObjectIdGetDatum(RelationGetRelid(rel
)));
7438 ScanKeyInit(&key
[2],
7439 Anum_pg_depend_objsubid
,
7440 BTEqualStrategyNumber
, F_INT4EQ
,
7443 scan
= systable_beginscan(catalogRelation
, DependDependerIndexId
, true,
7444 SnapshotNow
, 3, key
);
7446 while (HeapTupleIsValid(depTuple
= systable_getnext(scan
)))
7448 Form_pg_depend dep
= (Form_pg_depend
) GETSTRUCT(depTuple
);
7450 if (dep
->refclassid
== RelationRelationId
&&
7451 dep
->refobjid
== RelationGetRelid(parent_rel
) &&
7452 dep
->refobjsubid
== 0 &&
7453 dep
->deptype
== DEPENDENCY_NORMAL
)
7454 simple_heap_delete(catalogRelation
, &depTuple
->t_self
);
7457 systable_endscan(scan
);
7458 heap_close(catalogRelation
, RowExclusiveLock
);
7460 /* keep our lock on the parent relation until commit */
7461 heap_close(parent_rel
, NoLock
);
7466 * Execute ALTER TABLE SET SCHEMA
7468 * Note: caller must have checked ownership of the relation already
7471 AlterTableNamespace(RangeVar
*relation
, const char *newschema
,
7472 ObjectType stmttype
)
7480 rel
= relation_openrv(relation
, AccessExclusiveLock
);
7482 relid
= RelationGetRelid(rel
);
7483 oldNspOid
= RelationGetNamespace(rel
);
7485 /* Check relation type against type specified in the ALTER command */
7491 * For mostly-historical reasons, we allow ALTER TABLE to apply to
7492 * all relation types.
7496 case OBJECT_SEQUENCE
:
7497 if (rel
->rd_rel
->relkind
!= RELKIND_SEQUENCE
)
7499 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
7500 errmsg("\"%s\" is not a sequence",
7501 RelationGetRelationName(rel
))));
7505 if (rel
->rd_rel
->relkind
!= RELKIND_VIEW
)
7507 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
7508 errmsg("\"%s\" is not a view",
7509 RelationGetRelationName(rel
))));
7513 elog(ERROR
, "unrecognized object type: %d", (int) stmttype
);
7516 /* Can we change the schema of this tuple? */
7517 switch (rel
->rd_rel
->relkind
)
7519 case RELKIND_RELATION
:
7521 /* ok to change schema */
7523 case RELKIND_SEQUENCE
:
7525 /* if it's an owned sequence, disallow moving it by itself */
7529 if (sequenceIsOwned(relid
, &tableId
, &colId
))
7531 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
7532 errmsg("cannot move an owned sequence into another schema"),
7533 errdetail("Sequence \"%s\" is linked to table \"%s\".",
7534 RelationGetRelationName(rel
),
7535 get_rel_name(tableId
))));
7538 case RELKIND_COMPOSITE_TYPE
:
7540 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
7541 errmsg("\"%s\" is a composite type",
7542 RelationGetRelationName(rel
)),
7543 errhint("Use ALTER TYPE instead.")));
7546 case RELKIND_TOASTVALUE
:
7550 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
7551 errmsg("\"%s\" is not a table, view, or sequence",
7552 RelationGetRelationName(rel
))));
7555 /* get schema OID and check its permissions */
7556 nspOid
= LookupCreationNamespace(newschema
);
7558 if (oldNspOid
== nspOid
)
7560 (errcode(ERRCODE_DUPLICATE_TABLE
),
7561 errmsg("relation \"%s\" is already in schema \"%s\"",
7562 RelationGetRelationName(rel
),
7565 /* disallow renaming into or out of temp schemas */
7566 if (isAnyTempNamespace(nspOid
) || isAnyTempNamespace(oldNspOid
))
7568 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
7569 errmsg("cannot move objects into or out of temporary schemas")));
7571 /* same for TOAST schema */
7572 if (nspOid
== PG_TOAST_NAMESPACE
|| oldNspOid
== PG_TOAST_NAMESPACE
)
7574 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
7575 errmsg("cannot move objects into or out of TOAST schema")));
7577 /* OK, modify the pg_class row and pg_depend entry */
7578 classRel
= heap_open(RelationRelationId
, RowExclusiveLock
);
7580 AlterRelationNamespaceInternal(classRel
, relid
, oldNspOid
, nspOid
, true);
7582 /* Fix the table's rowtype too */
7583 AlterTypeNamespaceInternal(rel
->rd_rel
->reltype
, nspOid
, false, false);
7585 /* Fix other dependent stuff */
7586 if (rel
->rd_rel
->relkind
== RELKIND_RELATION
)
7588 AlterIndexNamespaces(classRel
, rel
, oldNspOid
, nspOid
);
7589 AlterSeqNamespaces(classRel
, rel
, oldNspOid
, nspOid
, newschema
);
7590 AlterConstraintNamespaces(relid
, oldNspOid
, nspOid
, false);
7593 heap_close(classRel
, RowExclusiveLock
);
7595 /* close rel, but keep lock until commit */
7596 relation_close(rel
, NoLock
);
7600 * The guts of relocating a relation to another namespace: fix the pg_class
7601 * entry, and the pg_depend entry if any. Caller must already have
7602 * opened and write-locked pg_class.
7605 AlterRelationNamespaceInternal(Relation classRel
, Oid relOid
,
7606 Oid oldNspOid
, Oid newNspOid
,
7607 bool hasDependEntry
)
7610 Form_pg_class classForm
;
7612 classTup
= SearchSysCacheCopy(RELOID
,
7613 ObjectIdGetDatum(relOid
),
7615 if (!HeapTupleIsValid(classTup
))
7616 elog(ERROR
, "cache lookup failed for relation %u", relOid
);
7617 classForm
= (Form_pg_class
) GETSTRUCT(classTup
);
7619 Assert(classForm
->relnamespace
== oldNspOid
);
7621 /* check for duplicate name (more friendly than unique-index failure) */
7622 if (get_relname_relid(NameStr(classForm
->relname
),
7623 newNspOid
) != InvalidOid
)
7625 (errcode(ERRCODE_DUPLICATE_TABLE
),
7626 errmsg("relation \"%s\" already exists in schema \"%s\"",
7627 NameStr(classForm
->relname
),
7628 get_namespace_name(newNspOid
))));
7630 /* classTup is a copy, so OK to scribble on */
7631 classForm
->relnamespace
= newNspOid
;
7633 simple_heap_update(classRel
, &classTup
->t_self
, classTup
);
7634 CatalogUpdateIndexes(classRel
, classTup
);
7636 /* Update dependency on schema if caller said so */
7637 if (hasDependEntry
&&
7638 changeDependencyFor(RelationRelationId
, relOid
,
7639 NamespaceRelationId
, oldNspOid
, newNspOid
) != 1)
7640 elog(ERROR
, "failed to change schema dependency for relation \"%s\"",
7641 NameStr(classForm
->relname
));
7643 heap_freetuple(classTup
);
7647 * Move all indexes for the specified relation to another namespace.
7649 * Note: we assume adequate permission checking was done by the caller,
7650 * and that the caller has a suitable lock on the owning relation.
7653 AlterIndexNamespaces(Relation classRel
, Relation rel
,
7654 Oid oldNspOid
, Oid newNspOid
)
7659 indexList
= RelationGetIndexList(rel
);
7661 foreach(l
, indexList
)
7663 Oid indexOid
= lfirst_oid(l
);
7666 * Note: currently, the index will not have its own dependency on the
7667 * namespace, so we don't need to do changeDependencyFor(). There's no
7668 * rowtype in pg_type, either.
7670 AlterRelationNamespaceInternal(classRel
, indexOid
,
7671 oldNspOid
, newNspOid
,
7675 list_free(indexList
);
7679 * Move all SERIAL-column sequences of the specified relation to another
7682 * Note: we assume adequate permission checking was done by the caller,
7683 * and that the caller has a suitable lock on the owning relation.
7686 AlterSeqNamespaces(Relation classRel
, Relation rel
,
7687 Oid oldNspOid
, Oid newNspOid
, const char *newNspName
)
7695 * SERIAL sequences are those having an auto dependency on one of the
7696 * table's columns (we don't care *which* column, exactly).
7698 depRel
= heap_open(DependRelationId
, AccessShareLock
);
7700 ScanKeyInit(&key
[0],
7701 Anum_pg_depend_refclassid
,
7702 BTEqualStrategyNumber
, F_OIDEQ
,
7703 ObjectIdGetDatum(RelationRelationId
));
7704 ScanKeyInit(&key
[1],
7705 Anum_pg_depend_refobjid
,
7706 BTEqualStrategyNumber
, F_OIDEQ
,
7707 ObjectIdGetDatum(RelationGetRelid(rel
)));
7708 /* we leave refobjsubid unspecified */
7710 scan
= systable_beginscan(depRel
, DependReferenceIndexId
, true,
7711 SnapshotNow
, 2, key
);
7713 while (HeapTupleIsValid(tup
= systable_getnext(scan
)))
7715 Form_pg_depend depForm
= (Form_pg_depend
) GETSTRUCT(tup
);
7718 /* skip dependencies other than auto dependencies on columns */
7719 if (depForm
->refobjsubid
== 0 ||
7720 depForm
->classid
!= RelationRelationId
||
7721 depForm
->objsubid
!= 0 ||
7722 depForm
->deptype
!= DEPENDENCY_AUTO
)
7725 /* Use relation_open just in case it's an index */
7726 seqRel
= relation_open(depForm
->objid
, AccessExclusiveLock
);
7728 /* skip non-sequence relations */
7729 if (RelationGetForm(seqRel
)->relkind
!= RELKIND_SEQUENCE
)
7731 /* No need to keep the lock */
7732 relation_close(seqRel
, AccessExclusiveLock
);
7736 /* Fix the pg_class and pg_depend entries */
7737 AlterRelationNamespaceInternal(classRel
, depForm
->objid
,
7738 oldNspOid
, newNspOid
,
7742 * Sequences have entries in pg_type. We need to be careful to move
7743 * them to the new namespace, too.
7745 AlterTypeNamespaceInternal(RelationGetForm(seqRel
)->reltype
,
7746 newNspOid
, false, false);
7748 /* Now we can close it. Keep the lock till end of transaction. */
7749 relation_close(seqRel
, NoLock
);
7752 systable_endscan(scan
);
7754 relation_close(depRel
, AccessShareLock
);
7759 * This code supports
7760 * CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
7762 * Because we only support this for TEMP tables, it's sufficient to remember
7763 * the state in a backend-local data structure.
7767 * Register a newly-created relation's ON COMMIT action.
7770 register_on_commit_action(Oid relid
, OnCommitAction action
)
7773 MemoryContext oldcxt
;
7776 * We needn't bother registering the relation unless there is an ON COMMIT
7777 * action we need to take.
7779 if (action
== ONCOMMIT_NOOP
|| action
== ONCOMMIT_PRESERVE_ROWS
)
7782 oldcxt
= MemoryContextSwitchTo(CacheMemoryContext
);
7784 oc
= (OnCommitItem
*) palloc(sizeof(OnCommitItem
));
7786 oc
->oncommit
= action
;
7787 oc
->creating_subid
= GetCurrentSubTransactionId();
7788 oc
->deleting_subid
= InvalidSubTransactionId
;
7790 on_commits
= lcons(oc
, on_commits
);
7792 MemoryContextSwitchTo(oldcxt
);
7796 * Unregister any ON COMMIT action when a relation is deleted.
7798 * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
7801 remove_on_commit_action(Oid relid
)
7805 foreach(l
, on_commits
)
7807 OnCommitItem
*oc
= (OnCommitItem
*) lfirst(l
);
7809 if (oc
->relid
== relid
)
7811 oc
->deleting_subid
= GetCurrentSubTransactionId();
7818 * Perform ON COMMIT actions.
7820 * This is invoked just before actually committing, since it's possible
7821 * to encounter errors.
7824 PreCommit_on_commit_actions(void)
7827 List
*oids_to_truncate
= NIL
;
7829 foreach(l
, on_commits
)
7831 OnCommitItem
*oc
= (OnCommitItem
*) lfirst(l
);
7833 /* Ignore entry if already dropped in this xact */
7834 if (oc
->deleting_subid
!= InvalidSubTransactionId
)
7837 switch (oc
->oncommit
)
7840 case ONCOMMIT_PRESERVE_ROWS
:
7841 /* Do nothing (there shouldn't be such entries, actually) */
7843 case ONCOMMIT_DELETE_ROWS
:
7844 oids_to_truncate
= lappend_oid(oids_to_truncate
, oc
->relid
);
7848 ObjectAddress object
;
7850 object
.classId
= RelationRelationId
;
7851 object
.objectId
= oc
->relid
;
7852 object
.objectSubId
= 0;
7853 performDeletion(&object
, DROP_CASCADE
);
7856 * Note that table deletion will call
7857 * remove_on_commit_action, so the entry should get marked
7860 Assert(oc
->deleting_subid
!= InvalidSubTransactionId
);
7865 if (oids_to_truncate
!= NIL
)
7867 heap_truncate(oids_to_truncate
);
7868 CommandCounterIncrement(); /* XXX needed? */
7873 * Post-commit or post-abort cleanup for ON COMMIT management.
7875 * All we do here is remove no-longer-needed OnCommitItem entries.
7877 * During commit, remove entries that were deleted during this transaction;
7878 * during abort, remove those created during this transaction.
7881 AtEOXact_on_commit_actions(bool isCommit
)
7884 ListCell
*prev_item
;
7887 cur_item
= list_head(on_commits
);
7889 while (cur_item
!= NULL
)
7891 OnCommitItem
*oc
= (OnCommitItem
*) lfirst(cur_item
);
7893 if (isCommit
? oc
->deleting_subid
!= InvalidSubTransactionId
:
7894 oc
->creating_subid
!= InvalidSubTransactionId
)
7896 /* cur_item must be removed */
7897 on_commits
= list_delete_cell(on_commits
, cur_item
, prev_item
);
7900 cur_item
= lnext(prev_item
);
7902 cur_item
= list_head(on_commits
);
7906 /* cur_item must be preserved */
7907 oc
->creating_subid
= InvalidSubTransactionId
;
7908 oc
->deleting_subid
= InvalidSubTransactionId
;
7909 prev_item
= cur_item
;
7910 cur_item
= lnext(prev_item
);
7916 * Post-subcommit or post-subabort cleanup for ON COMMIT management.
7918 * During subabort, we can immediately remove entries created during this
7919 * subtransaction. During subcommit, just relabel entries marked during
7920 * this subtransaction as being the parent's responsibility.
7923 AtEOSubXact_on_commit_actions(bool isCommit
, SubTransactionId mySubid
,
7924 SubTransactionId parentSubid
)
7927 ListCell
*prev_item
;
7930 cur_item
= list_head(on_commits
);
7932 while (cur_item
!= NULL
)
7934 OnCommitItem
*oc
= (OnCommitItem
*) lfirst(cur_item
);
7936 if (!isCommit
&& oc
->creating_subid
== mySubid
)
7938 /* cur_item must be removed */
7939 on_commits
= list_delete_cell(on_commits
, cur_item
, prev_item
);
7942 cur_item
= lnext(prev_item
);
7944 cur_item
= list_head(on_commits
);
7948 /* cur_item must be preserved */
7949 if (oc
->creating_subid
== mySubid
)
7950 oc
->creating_subid
= parentSubid
;
7951 if (oc
->deleting_subid
== mySubid
)
7952 oc
->deleting_subid
= isCommit
? parentSubid
: InvalidSubTransactionId
;
7953 prev_item
= cur_item
;
7954 cur_item
= lnext(prev_item
);