PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
tablecmds.h File Reference
#include "access/htup.h"
#include "catalog/dependency.h"
#include "catalog/objectaddress.h"
#include "nodes/parsenodes.h"
#include "storage/lock.h"
#include "utils/relcache.h"
Include dependency graph for tablecmds.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

ObjectAddress DefineRelation (CreateStmt *stmt, char relkind, Oid ownerId, ObjectAddress *typaddress, const char *queryString)
 
TupleDesc BuildDescForRelation (const List *columns)
 
void RemoveRelations (DropStmt *drop)
 
Oid AlterTableLookupRelation (AlterTableStmt *stmt, LOCKMODE lockmode)
 
void AlterTable (AlterTableStmt *stmt, LOCKMODE lockmode, struct AlterTableUtilityContext *context)
 
LOCKMODE AlterTableGetLockLevel (List *cmds)
 
void ATExecChangeOwner (Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
 
void AlterTableInternal (Oid relid, List *cmds, bool recurse)
 
Oid AlterTableMoveAll (AlterTableMoveAllStmt *stmt)
 
ObjectAddress AlterTableNamespace (AlterObjectSchemaStmt *stmt, Oid *oldschema)
 
void AlterTableNamespaceInternal (Relation rel, Oid oldNspOid, Oid nspOid, ObjectAddresses *objsMoved)
 
void AlterRelationNamespaceInternal (Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
 
void CheckTableNotInUse (Relation rel, const char *stmt)
 
void ExecuteTruncate (TruncateStmt *stmt)
 
void ExecuteTruncateGuts (List *explicit_rels, List *relids, List *relids_logged, DropBehavior behavior, bool restart_seqs, bool run_as_table_owner)
 
void SetRelationHasSubclass (Oid relationId, bool relhassubclass)
 
bool CheckRelationTableSpaceMove (Relation rel, Oid newTableSpaceId)
 
void SetRelationTableSpace (Relation rel, Oid newTableSpaceId, RelFileNumber newRelFilenumber)
 
ObjectAddress renameatt (RenameStmt *stmt)
 
ObjectAddress RenameConstraint (RenameStmt *stmt)
 
ObjectAddress RenameRelation (RenameStmt *stmt)
 
void RenameRelationInternal (Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
 
void ResetRelRewrite (Oid myrelid)
 
void find_composite_type_dependencies (Oid typeOid, Relation origRelation, const char *origTypeName)
 
void check_of_type (HeapTuple typetuple)
 
void register_on_commit_action (Oid relid, OnCommitAction action)
 
void remove_on_commit_action (Oid relid)
 
void PreCommit_on_commit_actions (void)
 
void AtEOXact_on_commit_actions (bool isCommit)
 
void AtEOSubXact_on_commit_actions (bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
 
void RangeVarCallbackMaintainsTable (const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
 
void RangeVarCallbackOwnsRelation (const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
 
bool PartConstraintImpliedByRelConstraint (Relation scanrel, List *partConstraint)
 

Function Documentation

◆ AlterRelationNamespaceInternal()

void AlterRelationNamespaceInternal ( Relation  classRel,
Oid  relOid,
Oid  oldNspOid,
Oid  newNspOid,
bool  hasDependEntry,
ObjectAddresses objsMoved 
)

Definition at line 18977 of file tablecmds.c.

18981{
18982 HeapTuple classTup;
18983 Form_pg_class classForm;
18984 ObjectAddress thisobj;
18985 bool already_done = false;
18986
18987 /* no rel lock for relkind=c so use LOCKTAG_TUPLE */
18988 classTup = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(relOid));
18989 if (!HeapTupleIsValid(classTup))
18990 elog(ERROR, "cache lookup failed for relation %u", relOid);
18991 classForm = (Form_pg_class) GETSTRUCT(classTup);
18992
18993 Assert(classForm->relnamespace == oldNspOid);
18994
18995 thisobj.classId = RelationRelationId;
18996 thisobj.objectId = relOid;
18997 thisobj.objectSubId = 0;
18998
18999 /*
19000 * If the object has already been moved, don't move it again. If it's
19001 * already in the right place, don't move it, but still fire the object
19002 * access hook.
19003 */
19004 already_done = object_address_present(&thisobj, objsMoved);
19005 if (!already_done && oldNspOid != newNspOid)
19006 {
19007 ItemPointerData otid = classTup->t_self;
19008
19009 /* check for duplicate name (more friendly than unique-index failure) */
19010 if (get_relname_relid(NameStr(classForm->relname),
19011 newNspOid) != InvalidOid)
19012 ereport(ERROR,
19013 (errcode(ERRCODE_DUPLICATE_TABLE),
19014 errmsg("relation \"%s\" already exists in schema \"%s\"",
19015 NameStr(classForm->relname),
19016 get_namespace_name(newNspOid))));
19017
19018 /* classTup is a copy, so OK to scribble on */
19019 classForm->relnamespace = newNspOid;
19020
19021 CatalogTupleUpdate(classRel, &otid, classTup);
19022 UnlockTuple(classRel, &otid, InplaceUpdateTupleLock);
19023
19024
19025 /* Update dependency on schema if caller said so */
19026 if (hasDependEntry &&
19027 changeDependencyFor(RelationRelationId,
19028 relOid,
19029 NamespaceRelationId,
19030 oldNspOid,
19031 newNspOid) != 1)
19032 elog(ERROR, "could not change schema dependency for relation \"%s\"",
19033 NameStr(classForm->relname));
19034 }
19035 else
19036 UnlockTuple(classRel, &classTup->t_self, InplaceUpdateTupleLock);
19037 if (!already_done)
19038 {
19039 add_exact_object_address(&thisobj, objsMoved);
19040
19041 InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
19042 }
19043
19044 heap_freetuple(classTup);
19045}
#define NameStr(name)
Definition: c.h:717
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2608
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2548
int errcode(int sqlerrcode)
Definition: elog.c:854
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
#define ereport(elevel,...)
Definition: elog.h:149
Assert(PointerIsAligned(start, uint64))
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1435
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
Definition: htup_details.h:728
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:313
void UnlockTuple(Relation relation, ItemPointer tid, LOCKMODE lockmode)
Definition: lmgr.c:601
#define InplaceUpdateTupleLock
Definition: lockdefs.h:48
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3506
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:2025
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:197
FormData_pg_class * Form_pg_class
Definition: pg_class.h:156
long changeDependencyFor(Oid classId, Oid objectId, Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition: pg_depend.c:457
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:257
#define InvalidOid
Definition: postgres_ext.h:35
ItemPointerData t_self
Definition: htup.h:65
HeapTuple SearchSysCacheLockedCopy1(int cacheId, Datum key1)
Definition: syscache.c:404

References add_exact_object_address(), Assert(), CatalogTupleUpdate(), changeDependencyFor(), ObjectAddress::classId, elog, ereport, errcode(), errmsg(), ERROR, get_namespace_name(), get_relname_relid(), GETSTRUCT(), heap_freetuple(), HeapTupleIsValid, InplaceUpdateTupleLock, InvalidOid, InvokeObjectPostAlterHook, NameStr, object_address_present(), ObjectAddress::objectId, ObjectIdGetDatum(), ObjectAddress::objectSubId, SearchSysCacheLockedCopy1(), HeapTupleData::t_self, and UnlockTuple().

Referenced by AlterIndexNamespaces(), AlterSeqNamespaces(), AlterTableNamespaceInternal(), and AlterTypeNamespaceInternal().

◆ AlterTable()

void AlterTable ( AlterTableStmt stmt,
LOCKMODE  lockmode,
struct AlterTableUtilityContext context 
)

Definition at line 4524 of file tablecmds.c.

4526{
4527 Relation rel;
4528
4529 /* Caller is required to provide an adequate lock. */
4530 rel = relation_open(context->relid, NoLock);
4531
4533
4534 ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
4535}
#define stmt
Definition: indent_codes.h:59
#define NoLock
Definition: lockdefs.h:34
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:47
static void CheckAlterTableIsSafe(Relation rel)
Definition: tablecmds.c:4439
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:4860

References ATController(), CheckAlterTableIsSafe(), NoLock, relation_open(), AlterTableUtilityContext::relid, and stmt.

Referenced by ProcessUtilitySlow().

◆ AlterTableGetLockLevel()

LOCKMODE AlterTableGetLockLevel ( List cmds)

Definition at line 4598 of file tablecmds.c.

4599{
4600 /*
4601 * This only works if we read catalog tables using MVCC snapshots.
4602 */
4603 ListCell *lcmd;
4605
4606 foreach(lcmd, cmds)
4607 {
4608 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
4609 LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
4610
4611 switch (cmd->subtype)
4612 {
4613 /*
4614 * These subcommands rewrite the heap, so require full locks.
4615 */
4616 case AT_AddColumn: /* may rewrite heap, in some cases and visible
4617 * to SELECT */
4618 case AT_SetAccessMethod: /* must rewrite heap */
4619 case AT_SetTableSpace: /* must rewrite heap */
4620 case AT_AlterColumnType: /* must rewrite heap */
4621 cmd_lockmode = AccessExclusiveLock;
4622 break;
4623
4624 /*
4625 * These subcommands may require addition of toast tables. If
4626 * we add a toast table to a table currently being scanned, we
4627 * might miss data added to the new toast table by concurrent
4628 * insert transactions.
4629 */
4630 case AT_SetStorage: /* may add toast tables, see
4631 * ATRewriteCatalogs() */
4632 cmd_lockmode = AccessExclusiveLock;
4633 break;
4634
4635 /*
4636 * Removing constraints can affect SELECTs that have been
4637 * optimized assuming the constraint holds true. See also
4638 * CloneFkReferenced.
4639 */
4640 case AT_DropConstraint: /* as DROP INDEX */
4641 case AT_DropNotNull: /* may change some SQL plans */
4642 cmd_lockmode = AccessExclusiveLock;
4643 break;
4644
4645 /*
4646 * Subcommands that may be visible to concurrent SELECTs
4647 */
4648 case AT_DropColumn: /* change visible to SELECT */
4649 case AT_AddColumnToView: /* CREATE VIEW */
4650 case AT_DropOids: /* used to equiv to DropColumn */
4651 case AT_EnableAlwaysRule: /* may change SELECT rules */
4652 case AT_EnableReplicaRule: /* may change SELECT rules */
4653 case AT_EnableRule: /* may change SELECT rules */
4654 case AT_DisableRule: /* may change SELECT rules */
4655 cmd_lockmode = AccessExclusiveLock;
4656 break;
4657
4658 /*
4659 * Changing owner may remove implicit SELECT privileges
4660 */
4661 case AT_ChangeOwner: /* change visible to SELECT */
4662 cmd_lockmode = AccessExclusiveLock;
4663 break;
4664
4665 /*
4666 * Changing foreign table options may affect optimization.
4667 */
4668 case AT_GenericOptions:
4670 cmd_lockmode = AccessExclusiveLock;
4671 break;
4672
4673 /*
4674 * These subcommands affect write operations only.
4675 */
4676 case AT_EnableTrig:
4679 case AT_EnableTrigAll:
4680 case AT_EnableTrigUser:
4681 case AT_DisableTrig:
4682 case AT_DisableTrigAll:
4683 case AT_DisableTrigUser:
4684 cmd_lockmode = ShareRowExclusiveLock;
4685 break;
4686
4687 /*
4688 * These subcommands affect write operations only. XXX
4689 * Theoretically, these could be ShareRowExclusiveLock.
4690 */
4691 case AT_ColumnDefault:
4693 case AT_AlterConstraint:
4694 case AT_AddIndex: /* from ADD CONSTRAINT */
4696 case AT_ReplicaIdentity:
4697 case AT_SetNotNull:
4702 case AT_AddIdentity:
4703 case AT_DropIdentity:
4704 case AT_SetIdentity:
4705 case AT_SetExpression:
4706 case AT_DropExpression:
4707 case AT_SetCompression:
4708 cmd_lockmode = AccessExclusiveLock;
4709 break;
4710
4711 case AT_AddConstraint:
4712 case AT_ReAddConstraint: /* becomes AT_AddConstraint */
4713 case AT_ReAddDomainConstraint: /* becomes AT_AddConstraint */
4714 if (IsA(cmd->def, Constraint))
4715 {
4716 Constraint *con = (Constraint *) cmd->def;
4717
4718 switch (con->contype)
4719 {
4720 case CONSTR_EXCLUSION:
4721 case CONSTR_PRIMARY:
4722 case CONSTR_UNIQUE:
4723
4724 /*
4725 * Cases essentially the same as CREATE INDEX. We
4726 * could reduce the lock strength to ShareLock if
4727 * we can work out how to allow concurrent catalog
4728 * updates. XXX Might be set down to
4729 * ShareRowExclusiveLock but requires further
4730 * analysis.
4731 */
4732 cmd_lockmode = AccessExclusiveLock;
4733 break;
4734 case CONSTR_FOREIGN:
4735
4736 /*
4737 * We add triggers to both tables when we add a
4738 * Foreign Key, so the lock level must be at least
4739 * as strong as CREATE TRIGGER.
4740 */
4741 cmd_lockmode = ShareRowExclusiveLock;
4742 break;
4743
4744 default:
4745 cmd_lockmode = AccessExclusiveLock;
4746 }
4747 }
4748 break;
4749
4750 /*
4751 * These subcommands affect inheritance behaviour. Queries
4752 * started before us will continue to see the old inheritance
4753 * behaviour, while queries started after we commit will see
4754 * new behaviour. No need to prevent reads or writes to the
4755 * subtable while we hook it up though. Changing the TupDesc
4756 * may be a problem, so keep highest lock.
4757 */
4758 case AT_AddInherit:
4759 case AT_DropInherit:
4760 cmd_lockmode = AccessExclusiveLock;
4761 break;
4762
4763 /*
4764 * These subcommands affect implicit row type conversion. They
4765 * have affects similar to CREATE/DROP CAST on queries. don't
4766 * provide for invalidating parse trees as a result of such
4767 * changes, so we keep these at AccessExclusiveLock.
4768 */
4769 case AT_AddOf:
4770 case AT_DropOf:
4771 cmd_lockmode = AccessExclusiveLock;
4772 break;
4773
4774 /*
4775 * Only used by CREATE OR REPLACE VIEW which must conflict
4776 * with an SELECTs currently using the view.
4777 */
4779 cmd_lockmode = AccessExclusiveLock;
4780 break;
4781
4782 /*
4783 * These subcommands affect general strategies for performance
4784 * and maintenance, though don't change the semantic results
4785 * from normal data reads and writes. Delaying an ALTER TABLE
4786 * behind currently active writes only delays the point where
4787 * the new strategy begins to take effect, so there is no
4788 * benefit in waiting. In this case the minimum restriction
4789 * applies: we don't currently allow concurrent catalog
4790 * updates.
4791 */
4792 case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
4793 case AT_ClusterOn: /* Uses MVCC in getIndexes() */
4794 case AT_DropCluster: /* Uses MVCC in getIndexes() */
4795 case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
4796 case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
4797 cmd_lockmode = ShareUpdateExclusiveLock;
4798 break;
4799
4800 case AT_SetLogged:
4801 case AT_SetUnLogged:
4802 cmd_lockmode = AccessExclusiveLock;
4803 break;
4804
4805 case AT_ValidateConstraint: /* Uses MVCC in getConstraints() */
4806 cmd_lockmode = ShareUpdateExclusiveLock;
4807 break;
4808
4809 /*
4810 * Rel options are more complex than first appears. Options
4811 * are set here for tables, views and indexes; for historical
4812 * reasons these can all be used with ALTER TABLE, so we can't
4813 * decide between them using the basic grammar.
4814 */
4815 case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
4816 * getTables() */
4817 case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
4818 * getTables() */
4819 cmd_lockmode = AlterTableGetRelOptionsLockLevel((List *) cmd->def);
4820 break;
4821
4822 case AT_AttachPartition:
4823 cmd_lockmode = ShareUpdateExclusiveLock;
4824 break;
4825
4826 case AT_DetachPartition:
4827 if (((PartitionCmd *) cmd->def)->concurrent)
4828 cmd_lockmode = ShareUpdateExclusiveLock;
4829 else
4830 cmd_lockmode = AccessExclusiveLock;
4831 break;
4832
4834 cmd_lockmode = ShareUpdateExclusiveLock;
4835 break;
4836
4837 default: /* oops */
4838 elog(ERROR, "unrecognized alter table type: %d",
4839 (int) cmd->subtype);
4840 break;
4841 }
4842
4843 /*
4844 * Take the greatest lockmode from any subcommand
4845 */
4846 if (cmd_lockmode > lockmode)
4847 lockmode = cmd_lockmode;
4848 }
4849
4850 return lockmode;
4851}
int LOCKMODE
Definition: lockdefs.h:26
#define AccessExclusiveLock
Definition: lockdefs.h:43
#define ShareRowExclusiveLock
Definition: lockdefs.h:41
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define IsA(nodeptr, _type_)
Definition: nodes.h:164
@ CONSTR_FOREIGN
Definition: parsenodes.h:2798
@ CONSTR_UNIQUE
Definition: parsenodes.h:2796
@ CONSTR_EXCLUSION
Definition: parsenodes.h:2797
@ CONSTR_PRIMARY
Definition: parsenodes.h:2795
@ AT_AddIndexConstraint
Definition: parsenodes.h:2430
@ AT_DropOf
Definition: parsenodes.h:2461
@ AT_SetOptions
Definition: parsenodes.h:2418
@ AT_DropIdentity
Definition: parsenodes.h:2473
@ AT_DisableTrigUser
Definition: parsenodes.h:2453
@ AT_DropNotNull
Definition: parsenodes.h:2413
@ AT_AddOf
Definition: parsenodes.h:2460
@ AT_ResetOptions
Definition: parsenodes.h:2419
@ AT_ReplicaIdentity
Definition: parsenodes.h:2462
@ AT_ReplaceRelOptions
Definition: parsenodes.h:2445
@ AT_EnableRowSecurity
Definition: parsenodes.h:2463
@ AT_AddColumnToView
Definition: parsenodes.h:2410
@ AT_ResetRelOptions
Definition: parsenodes.h:2444
@ AT_EnableReplicaTrig
Definition: parsenodes.h:2448
@ AT_DropOids
Definition: parsenodes.h:2440
@ AT_SetIdentity
Definition: parsenodes.h:2472
@ AT_SetUnLogged
Definition: parsenodes.h:2439
@ AT_DisableTrig
Definition: parsenodes.h:2449
@ AT_SetCompression
Definition: parsenodes.h:2421
@ AT_DropExpression
Definition: parsenodes.h:2416
@ AT_AddIndex
Definition: parsenodes.h:2423
@ AT_EnableReplicaRule
Definition: parsenodes.h:2456
@ AT_DropConstraint
Definition: parsenodes.h:2431
@ AT_SetNotNull
Definition: parsenodes.h:2414
@ AT_ClusterOn
Definition: parsenodes.h:2436
@ AT_AddIdentity
Definition: parsenodes.h:2471
@ AT_ForceRowSecurity
Definition: parsenodes.h:2465
@ AT_EnableAlwaysRule
Definition: parsenodes.h:2455
@ AT_SetAccessMethod
Definition: parsenodes.h:2441
@ AT_AlterColumnType
Definition: parsenodes.h:2433
@ AT_DetachPartitionFinalize
Definition: parsenodes.h:2470
@ AT_AddInherit
Definition: parsenodes.h:2458
@ AT_ReAddDomainConstraint
Definition: parsenodes.h:2427
@ AT_EnableTrig
Definition: parsenodes.h:2446
@ AT_DropColumn
Definition: parsenodes.h:2422
@ AT_AlterColumnGenericOptions
Definition: parsenodes.h:2434
@ AT_DisableTrigAll
Definition: parsenodes.h:2451
@ AT_EnableRule
Definition: parsenodes.h:2454
@ AT_NoForceRowSecurity
Definition: parsenodes.h:2466
@ AT_DetachPartition
Definition: parsenodes.h:2469
@ AT_SetStatistics
Definition: parsenodes.h:2417
@ AT_AttachPartition
Definition: parsenodes.h:2468
@ AT_AddConstraint
Definition: parsenodes.h:2425
@ AT_DropInherit
Definition: parsenodes.h:2459
@ AT_EnableAlwaysTrig
Definition: parsenodes.h:2447
@ AT_SetLogged
Definition: parsenodes.h:2438
@ AT_SetStorage
Definition: parsenodes.h:2420
@ AT_DisableRule
Definition: parsenodes.h:2457
@ AT_DisableRowSecurity
Definition: parsenodes.h:2464
@ AT_SetRelOptions
Definition: parsenodes.h:2443
@ AT_ChangeOwner
Definition: parsenodes.h:2435
@ AT_EnableTrigUser
Definition: parsenodes.h:2452
@ AT_SetExpression
Definition: parsenodes.h:2415
@ AT_ReAddConstraint
Definition: parsenodes.h:2426
@ AT_SetTableSpace
Definition: parsenodes.h:2442
@ AT_GenericOptions
Definition: parsenodes.h:2467
@ AT_ColumnDefault
Definition: parsenodes.h:2411
@ AT_CookedColumnDefault
Definition: parsenodes.h:2412
@ AT_AlterConstraint
Definition: parsenodes.h:2428
@ AT_EnableTrigAll
Definition: parsenodes.h:2450
@ AT_DropCluster
Definition: parsenodes.h:2437
@ AT_ValidateConstraint
Definition: parsenodes.h:2429
@ AT_AddColumn
Definition: parsenodes.h:2409
#define lfirst(lc)
Definition: pg_list.h:172
LOCKMODE AlterTableGetRelOptionsLockLevel(List *defList)
Definition: reloptions.c:2135
AlterTableType subtype
Definition: parsenodes.h:2480
ConstrType contype
Definition: parsenodes.h:2822
Definition: pg_list.h:54

References AccessExclusiveLock, AlterTableGetRelOptionsLockLevel(), AT_AddColumn, AT_AddColumnToView, AT_AddConstraint, AT_AddIdentity, AT_AddIndex, AT_AddIndexConstraint, AT_AddInherit, AT_AddOf, AT_AlterColumnGenericOptions, AT_AlterColumnType, AT_AlterConstraint, AT_AttachPartition, AT_ChangeOwner, AT_ClusterOn, AT_ColumnDefault, AT_CookedColumnDefault, AT_DetachPartition, AT_DetachPartitionFinalize, AT_DisableRowSecurity, AT_DisableRule, AT_DisableTrig, AT_DisableTrigAll, AT_DisableTrigUser, AT_DropCluster, AT_DropColumn, AT_DropConstraint, AT_DropExpression, AT_DropIdentity, AT_DropInherit, AT_DropNotNull, AT_DropOf, AT_DropOids, AT_EnableAlwaysRule, AT_EnableAlwaysTrig, AT_EnableReplicaRule, AT_EnableReplicaTrig, AT_EnableRowSecurity, AT_EnableRule, AT_EnableTrig, AT_EnableTrigAll, AT_EnableTrigUser, AT_ForceRowSecurity, AT_GenericOptions, AT_NoForceRowSecurity, AT_ReAddConstraint, AT_ReAddDomainConstraint, AT_ReplaceRelOptions, AT_ReplicaIdentity, AT_ResetOptions, AT_ResetRelOptions, AT_SetAccessMethod, AT_SetCompression, AT_SetExpression, AT_SetIdentity, AT_SetLogged, AT_SetNotNull, AT_SetOptions, AT_SetRelOptions, AT_SetStatistics, AT_SetStorage, AT_SetTableSpace, AT_SetUnLogged, AT_ValidateConstraint, CONSTR_EXCLUSION, CONSTR_FOREIGN, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, AlterTableCmd::def, elog, ERROR, IsA, lfirst, ShareRowExclusiveLock, ShareUpdateExclusiveLock, and AlterTableCmd::subtype.

Referenced by AlterTableInternal(), and ProcessUtilitySlow().

◆ AlterTableInternal()

void AlterTableInternal ( Oid  relid,
List cmds,
bool  recurse 
)

Definition at line 4553 of file tablecmds.c.

4554{
4555 Relation rel;
4556 LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
4557
4558 rel = relation_open(relid, lockmode);
4559
4561
4562 ATController(NULL, rel, cmds, recurse, lockmode, NULL);
4563}
void EventTriggerAlterTableRelid(Oid objectId)
LOCKMODE AlterTableGetLockLevel(List *cmds)
Definition: tablecmds.c:4598

References AlterTableGetLockLevel(), ATController(), EventTriggerAlterTableRelid(), and relation_open().

Referenced by AlterTableMoveAll(), and DefineVirtualRelation().

◆ AlterTableLookupRelation()

Oid AlterTableLookupRelation ( AlterTableStmt stmt,
LOCKMODE  lockmode 
)

Definition at line 4465 of file tablecmds.c.

4466{
4467 return RangeVarGetRelidExtended(stmt->relation, lockmode,
4468 stmt->missing_ok ? RVR_MISSING_OK : 0,
4470 stmt);
4471}
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:441
@ RVR_MISSING_OK
Definition: namespace.h:72
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:19509

References RangeVarCallbackForAlterRelation(), RangeVarGetRelidExtended(), RVR_MISSING_OK, and stmt.

Referenced by ProcessUtilitySlow().

◆ AlterTableMoveAll()

Oid AlterTableMoveAll ( AlterTableMoveAllStmt stmt)

Definition at line 16908 of file tablecmds.c.

16909{
16910 List *relations = NIL;
16911 ListCell *l;
16912 ScanKeyData key[1];
16913 Relation rel;
16914 TableScanDesc scan;
16915 HeapTuple tuple;
16916 Oid orig_tablespaceoid;
16917 Oid new_tablespaceoid;
16918 List *role_oids = roleSpecsToIds(stmt->roles);
16919
16920 /* Ensure we were not asked to move something we can't */
16921 if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
16922 stmt->objtype != OBJECT_MATVIEW)
16923 ereport(ERROR,
16924 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
16925 errmsg("only tables, indexes, and materialized views exist in tablespaces")));
16926
16927 /* Get the orig and new tablespace OIDs */
16928 orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
16929 new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
16930
16931 /* Can't move shared relations in to or out of pg_global */
16932 /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
16933 if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
16934 new_tablespaceoid == GLOBALTABLESPACE_OID)
16935 ereport(ERROR,
16936 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
16937 errmsg("cannot move relations in to or out of pg_global tablespace")));
16938
16939 /*
16940 * Must have CREATE rights on the new tablespace, unless it is the
16941 * database default tablespace (which all users implicitly have CREATE
16942 * rights on).
16943 */
16944 if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
16945 {
16946 AclResult aclresult;
16947
16948 aclresult = object_aclcheck(TableSpaceRelationId, new_tablespaceoid, GetUserId(),
16949 ACL_CREATE);
16950 if (aclresult != ACLCHECK_OK)
16952 get_tablespace_name(new_tablespaceoid));
16953 }
16954
16955 /*
16956 * Now that the checks are done, check if we should set either to
16957 * InvalidOid because it is our database's default tablespace.
16958 */
16959 if (orig_tablespaceoid == MyDatabaseTableSpace)
16960 orig_tablespaceoid = InvalidOid;
16961
16962 if (new_tablespaceoid == MyDatabaseTableSpace)
16963 new_tablespaceoid = InvalidOid;
16964
16965 /* no-op */
16966 if (orig_tablespaceoid == new_tablespaceoid)
16967 return new_tablespaceoid;
16968
16969 /*
16970 * Walk the list of objects in the tablespace and move them. This will
16971 * only find objects in our database, of course.
16972 */
16973 ScanKeyInit(&key[0],
16974 Anum_pg_class_reltablespace,
16975 BTEqualStrategyNumber, F_OIDEQ,
16976 ObjectIdGetDatum(orig_tablespaceoid));
16977
16978 rel = table_open(RelationRelationId, AccessShareLock);
16979 scan = table_beginscan_catalog(rel, 1, key);
16980 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
16981 {
16982 Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
16983 Oid relOid = relForm->oid;
16984
16985 /*
16986 * Do not move objects in pg_catalog as part of this, if an admin
16987 * really wishes to do so, they can issue the individual ALTER
16988 * commands directly.
16989 *
16990 * Also, explicitly avoid any shared tables, temp tables, or TOAST
16991 * (TOAST will be moved with the main table).
16992 */
16993 if (IsCatalogNamespace(relForm->relnamespace) ||
16994 relForm->relisshared ||
16995 isAnyTempNamespace(relForm->relnamespace) ||
16996 IsToastNamespace(relForm->relnamespace))
16997 continue;
16998
16999 /* Only move the object type requested */
17000 if ((stmt->objtype == OBJECT_TABLE &&
17001 relForm->relkind != RELKIND_RELATION &&
17002 relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
17003 (stmt->objtype == OBJECT_INDEX &&
17004 relForm->relkind != RELKIND_INDEX &&
17005 relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
17006 (stmt->objtype == OBJECT_MATVIEW &&
17007 relForm->relkind != RELKIND_MATVIEW))
17008 continue;
17009
17010 /* Check if we are only moving objects owned by certain roles */
17011 if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
17012 continue;
17013
17014 /*
17015 * Handle permissions-checking here since we are locking the tables
17016 * and also to avoid doing a bunch of work only to fail part-way. Note
17017 * that permissions will also be checked by AlterTableInternal().
17018 *
17019 * Caller must be considered an owner on the table to move it.
17020 */
17021 if (!object_ownercheck(RelationRelationId, relOid, GetUserId()))
17023 NameStr(relForm->relname));
17024
17025 if (stmt->nowait &&
17027 ereport(ERROR,
17028 (errcode(ERRCODE_OBJECT_IN_USE),
17029 errmsg("aborting because lock on relation \"%s.%s\" is not available",
17030 get_namespace_name(relForm->relnamespace),
17031 NameStr(relForm->relname))));
17032 else
17034
17035 /* Add to our list of objects to move */
17036 relations = lappend_oid(relations, relOid);
17037 }
17038
17039 table_endscan(scan);
17041
17042 if (relations == NIL)
17044 (errcode(ERRCODE_NO_DATA_FOUND),
17045 errmsg("no matching relations in tablespace \"%s\" found",
17046 orig_tablespaceoid == InvalidOid ? "(database default)" :
17047 get_tablespace_name(orig_tablespaceoid))));
17048
17049 /* Everything is locked, loop through and move all of the relations. */
17050 foreach(l, relations)
17051 {
17052 List *cmds = NIL;
17054
17056 cmd->name = stmt->new_tablespacename;
17057
17058 cmds = lappend(cmds, cmd);
17059
17061 /* OID is set by AlterTableInternal */
17062 AlterTableInternal(lfirst_oid(l), cmds, false);
17064 }
17065
17066 return new_tablespaceoid;
17067}
AclResult
Definition: acl.h:182
@ ACLCHECK_OK
Definition: acl.h:183
@ ACLCHECK_NOT_OWNER
Definition: acl.h:185
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2639
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:3821
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4075
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1472
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1426
#define OidIsValid(objectId)
Definition: c.h:746
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:261
bool IsCatalogNamespace(Oid namespaceId)
Definition: catalog.c:243
#define NOTICE
Definition: elog.h:35
void EventTriggerAlterTableStart(Node *parsetree)
void EventTriggerAlterTableEnd(void)
Oid MyDatabaseTableSpace
Definition: globals.c:97
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1314
List * lappend(List *list, void *datum)
Definition: list.c:339
List * lappend_oid(List *list, Oid datum)
Definition: list.c:375
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:722
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:151
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:107
#define AccessShareLock
Definition: lockdefs.h:36
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:2143
Oid GetUserId(void)
Definition: miscinit.c:520
bool isAnyTempNamespace(Oid namespaceId)
Definition: namespace.c:3687
#define makeNode(_type_)
Definition: nodes.h:161
ObjectType get_relkind_objtype(char relkind)
@ OBJECT_MATVIEW
Definition: parsenodes.h:2340
@ OBJECT_TABLESPACE
Definition: parsenodes.h:2359
@ OBJECT_INDEX
Definition: parsenodes.h:2337
@ OBJECT_TABLE
Definition: parsenodes.h:2358
#define ACL_CREATE
Definition: parsenodes.h:85
#define NIL
Definition: pg_list.h:68
#define lfirst_oid(lc)
Definition: pg_list.h:174
unsigned int Oid
Definition: postgres_ext.h:30
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
@ ForwardScanDirection
Definition: sdir.h:28
#define BTEqualStrategyNumber
Definition: stratnum.h:31
Definition: nodes.h:135
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:113
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:979
void AlterTableInternal(Oid relid, List *cmds, bool recurse)
Definition: tablecmds.c:4553
List * roleSpecsToIds(List *memberNames)
Definition: user.c:1652

References AccessExclusiveLock, AccessShareLock, ACL_CREATE, aclcheck_error(), ACLCHECK_NOT_OWNER, ACLCHECK_OK, AlterTableInternal(), AT_SetTableSpace, BTEqualStrategyNumber, ConditionalLockRelationOid(), ereport, errcode(), errmsg(), ERROR, EventTriggerAlterTableEnd(), EventTriggerAlterTableStart(), ForwardScanDirection, get_namespace_name(), get_rel_relkind(), get_relkind_objtype(), get_tablespace_name(), get_tablespace_oid(), GETSTRUCT(), GetUserId(), heap_getnext(), InvalidOid, isAnyTempNamespace(), IsCatalogNamespace(), IsToastNamespace(), sort-test::key, lappend(), lappend_oid(), lfirst_oid, list_member_oid(), LockRelationOid(), makeNode, MyDatabaseTableSpace, AlterTableCmd::name, NameStr, NIL, NOTICE, object_aclcheck(), OBJECT_INDEX, OBJECT_MATVIEW, object_ownercheck(), OBJECT_TABLE, OBJECT_TABLESPACE, ObjectIdGetDatum(), OidIsValid, roleSpecsToIds(), ScanKeyInit(), stmt, AlterTableCmd::subtype, table_beginscan_catalog(), table_close(), table_endscan(), and table_open().

Referenced by ProcessUtilitySlow().

◆ AlterTableNamespace()

ObjectAddress AlterTableNamespace ( AlterObjectSchemaStmt stmt,
Oid oldschema 
)

Definition at line 18869 of file tablecmds.c.

18870{
18871 Relation rel;
18872 Oid relid;
18873 Oid oldNspOid;
18874 Oid nspOid;
18875 RangeVar *newrv;
18876 ObjectAddresses *objsMoved;
18877 ObjectAddress myself;
18878
18880 stmt->missing_ok ? RVR_MISSING_OK : 0,
18882 stmt);
18883
18884 if (!OidIsValid(relid))
18885 {
18887 (errmsg("relation \"%s\" does not exist, skipping",
18888 stmt->relation->relname)));
18889 return InvalidObjectAddress;
18890 }
18891
18892 rel = relation_open(relid, NoLock);
18893
18894 oldNspOid = RelationGetNamespace(rel);
18895
18896 /* If it's an owned sequence, disallow moving it by itself. */
18897 if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
18898 {
18899 Oid tableId;
18900 int32 colId;
18901
18902 if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
18903 sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
18904 ereport(ERROR,
18905 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
18906 errmsg("cannot move an owned sequence into another schema"),
18907 errdetail("Sequence \"%s\" is linked to table \"%s\".",
18909 get_rel_name(tableId))));
18910 }
18911
18912 /* Get and lock schema OID and check its permissions. */
18913 newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
18914 nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
18915
18916 /* common checks on switching namespaces */
18917 CheckSetNamespace(oldNspOid, nspOid);
18918
18919 objsMoved = new_object_addresses();
18920 AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
18921 free_object_addresses(objsMoved);
18922
18923 ObjectAddressSet(myself, RelationRelationId, relid);
18924
18925 if (oldschema)
18926 *oldschema = oldNspOid;
18927
18928 /* close rel, but keep lock until commit */
18929 relation_close(rel, NoLock);
18930
18931 return myself;
18932}
int32_t int32
Definition: c.h:498
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2502
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2788
@ DEPENDENCY_AUTO
Definition: dependency.h:34
@ DEPENDENCY_INTERNAL
Definition: dependency.h:35
int errdetail(const char *fmt,...)
Definition: elog.c:1204
char * get_rel_name(Oid relid)
Definition: lsyscache.c:2068
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:473
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:739
void CheckSetNamespace(Oid oldNspOid, Oid nspOid)
Definition: namespace.c:3459
const ObjectAddress InvalidObjectAddress
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
bool sequenceIsOwned(Oid seqId, char deptype, Oid *tableId, int32 *colId)
Definition: pg_depend.c:828
#define RelationGetRelationName(relation)
Definition: rel.h:550
#define RelationGetNamespace(relation)
Definition: rel.h:557
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:205
Form_pg_class rd_rel
Definition: rel.h:111
void AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:18940

References AccessExclusiveLock, AlterTableNamespaceInternal(), CheckSetNamespace(), DEPENDENCY_AUTO, DEPENDENCY_INTERNAL, ereport, errcode(), errdetail(), errmsg(), ERROR, free_object_addresses(), get_rel_name(), InvalidObjectAddress, makeRangeVar(), new_object_addresses(), NoLock, NOTICE, ObjectAddressSet, OidIsValid, RangeVarCallbackForAlterRelation(), RangeVarGetAndCheckCreationNamespace(), RangeVarGetRelidExtended(), RelationData::rd_rel, relation_close(), relation_open(), RelationGetNamespace, RelationGetRelationName, RVR_MISSING_OK, sequenceIsOwned(), and stmt.

Referenced by ExecAlterObjectSchemaStmt().

◆ AlterTableNamespaceInternal()

void AlterTableNamespaceInternal ( Relation  rel,
Oid  oldNspOid,
Oid  nspOid,
ObjectAddresses objsMoved 
)

Definition at line 18940 of file tablecmds.c.

18942{
18943 Relation classRel;
18944
18945 Assert(objsMoved != NULL);
18946
18947 /* OK, modify the pg_class row and pg_depend entry */
18948 classRel = table_open(RelationRelationId, RowExclusiveLock);
18949
18950 AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
18951 nspOid, true, objsMoved);
18952
18953 /* Fix the table's row type too, if it has one */
18954 if (OidIsValid(rel->rd_rel->reltype))
18955 AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid,
18956 false, /* isImplicitArray */
18957 false, /* ignoreDependent */
18958 false, /* errorOnTableType */
18959 objsMoved);
18960
18961 /* Fix other dependent stuff */
18962 AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
18963 AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
18964 objsMoved, AccessExclusiveLock);
18965 AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
18966 false, objsMoved);
18967
18968 table_close(classRel, RowExclusiveLock);
18969}
#define RowExclusiveLock
Definition: lockdefs.h:38
void AlterConstraintNamespaces(Oid ownerId, Oid oldNspId, Oid newNspId, bool isType, ObjectAddresses *objsMoved)
#define RelationGetRelid(relation)
Definition: rel.h:516
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
Definition: tablecmds.c:18977
static void AlterSeqNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved, LOCKMODE lockmode)
Definition: tablecmds.c:19099
static void AlterIndexNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:19054
Oid AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid, bool isImplicitArray, bool ignoreDependent, bool errorOnTableType, ObjectAddresses *objsMoved)
Definition: typecmds.c:4147

References AccessExclusiveLock, AlterConstraintNamespaces(), AlterIndexNamespaces(), AlterRelationNamespaceInternal(), AlterSeqNamespaces(), AlterTypeNamespaceInternal(), Assert(), OidIsValid, RelationData::rd_rel, RelationGetRelid, RowExclusiveLock, table_close(), and table_open().

Referenced by AlterObjectNamespace_oid(), and AlterTableNamespace().

◆ AtEOSubXact_on_commit_actions()

void AtEOSubXact_on_commit_actions ( bool  isCommit,
SubTransactionId  mySubid,
SubTransactionId  parentSubid 
)

Definition at line 19382 of file tablecmds.c.

19384{
19385 ListCell *cur_item;
19386
19387 foreach(cur_item, on_commits)
19388 {
19389 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
19390
19391 if (!isCommit && oc->creating_subid == mySubid)
19392 {
19393 /* cur_item must be removed */
19395 pfree(oc);
19396 }
19397 else
19398 {
19399 /* cur_item must be preserved */
19400 if (oc->creating_subid == mySubid)
19401 oc->creating_subid = parentSubid;
19402 if (oc->deleting_subid == mySubid)
19403 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
19404 }
19405 }
19406}
#define InvalidSubTransactionId
Definition: c.h:629
void pfree(void *pointer)
Definition: mcxt.c:2146
#define foreach_delete_current(lst, var_or_cell)
Definition: pg_list.h:391
SubTransactionId creating_subid
Definition: tablecmds.c:127
SubTransactionId deleting_subid
Definition: tablecmds.c:128
static List * on_commits
Definition: tablecmds.c:131

References OnCommitItem::creating_subid, OnCommitItem::deleting_subid, foreach_delete_current, InvalidSubTransactionId, lfirst, on_commits, and pfree().

Referenced by AbortSubTransaction(), and CommitSubTransaction().

◆ AtEOXact_on_commit_actions()

void AtEOXact_on_commit_actions ( bool  isCommit)

Definition at line 19350 of file tablecmds.c.

19351{
19352 ListCell *cur_item;
19353
19354 foreach(cur_item, on_commits)
19355 {
19356 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
19357
19358 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
19360 {
19361 /* cur_item must be removed */
19363 pfree(oc);
19364 }
19365 else
19366 {
19367 /* cur_item must be preserved */
19370 }
19371 }
19372}

References OnCommitItem::creating_subid, OnCommitItem::deleting_subid, foreach_delete_current, InvalidSubTransactionId, lfirst, on_commits, and pfree().

Referenced by AbortTransaction(), CommitTransaction(), and PrepareTransaction().

◆ ATExecChangeOwner()

void ATExecChangeOwner ( Oid  relationOid,
Oid  newOwnerId,
bool  recursing,
LOCKMODE  lockmode 
)

Definition at line 15995 of file tablecmds.c.

15996{
15997 Relation target_rel;
15998 Relation class_rel;
15999 HeapTuple tuple;
16000 Form_pg_class tuple_class;
16001
16002 /*
16003 * Get exclusive lock till end of transaction on the target table. Use
16004 * relation_open so that we can work on indexes and sequences.
16005 */
16006 target_rel = relation_open(relationOid, lockmode);
16007
16008 /* Get its pg_class tuple, too */
16009 class_rel = table_open(RelationRelationId, RowExclusiveLock);
16010
16011 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
16012 if (!HeapTupleIsValid(tuple))
16013 elog(ERROR, "cache lookup failed for relation %u", relationOid);
16014 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
16015
16016 /* Can we change the ownership of this tuple? */
16017 switch (tuple_class->relkind)
16018 {
16019 case RELKIND_RELATION:
16020 case RELKIND_VIEW:
16021 case RELKIND_MATVIEW:
16022 case RELKIND_FOREIGN_TABLE:
16023 case RELKIND_PARTITIONED_TABLE:
16024 /* ok to change owner */
16025 break;
16026 case RELKIND_INDEX:
16027 if (!recursing)
16028 {
16029 /*
16030 * Because ALTER INDEX OWNER used to be allowed, and in fact
16031 * is generated by old versions of pg_dump, we give a warning
16032 * and do nothing rather than erroring out. Also, to avoid
16033 * unnecessary chatter while restoring those old dumps, say
16034 * nothing at all if the command would be a no-op anyway.
16035 */
16036 if (tuple_class->relowner != newOwnerId)
16038 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16039 errmsg("cannot change owner of index \"%s\"",
16040 NameStr(tuple_class->relname)),
16041 errhint("Change the ownership of the index's table instead.")));
16042 /* quick hack to exit via the no-op path */
16043 newOwnerId = tuple_class->relowner;
16044 }
16045 break;
16046 case RELKIND_PARTITIONED_INDEX:
16047 if (recursing)
16048 break;
16049 ereport(ERROR,
16050 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16051 errmsg("cannot change owner of index \"%s\"",
16052 NameStr(tuple_class->relname)),
16053 errhint("Change the ownership of the index's table instead.")));
16054 break;
16055 case RELKIND_SEQUENCE:
16056 if (!recursing &&
16057 tuple_class->relowner != newOwnerId)
16058 {
16059 /* if it's an owned sequence, disallow changing it by itself */
16060 Oid tableId;
16061 int32 colId;
16062
16063 if (sequenceIsOwned(relationOid, DEPENDENCY_AUTO, &tableId, &colId) ||
16064 sequenceIsOwned(relationOid, DEPENDENCY_INTERNAL, &tableId, &colId))
16065 ereport(ERROR,
16066 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
16067 errmsg("cannot change owner of sequence \"%s\"",
16068 NameStr(tuple_class->relname)),
16069 errdetail("Sequence \"%s\" is linked to table \"%s\".",
16070 NameStr(tuple_class->relname),
16071 get_rel_name(tableId))));
16072 }
16073 break;
16074 case RELKIND_COMPOSITE_TYPE:
16075 if (recursing)
16076 break;
16077 ereport(ERROR,
16078 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16079 errmsg("\"%s\" is a composite type",
16080 NameStr(tuple_class->relname)),
16081 /* translator: %s is an SQL ALTER command */
16082 errhint("Use %s instead.",
16083 "ALTER TYPE")));
16084 break;
16085 case RELKIND_TOASTVALUE:
16086 if (recursing)
16087 break;
16088 /* FALL THRU */
16089 default:
16090 ereport(ERROR,
16091 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16092 errmsg("cannot change owner of relation \"%s\"",
16093 NameStr(tuple_class->relname)),
16094 errdetail_relkind_not_supported(tuple_class->relkind)));
16095 }
16096
16097 /*
16098 * If the new owner is the same as the existing owner, consider the
16099 * command to have succeeded. This is for dump restoration purposes.
16100 */
16101 if (tuple_class->relowner != newOwnerId)
16102 {
16103 Datum repl_val[Natts_pg_class];
16104 bool repl_null[Natts_pg_class];
16105 bool repl_repl[Natts_pg_class];
16106 Acl *newAcl;
16107 Datum aclDatum;
16108 bool isNull;
16109 HeapTuple newtuple;
16110
16111 /* skip permission checks when recursing to index or toast table */
16112 if (!recursing)
16113 {
16114 /* Superusers can always do it */
16115 if (!superuser())
16116 {
16117 Oid namespaceOid = tuple_class->relnamespace;
16118 AclResult aclresult;
16119
16120 /* Otherwise, must be owner of the existing object */
16121 if (!object_ownercheck(RelationRelationId, relationOid, GetUserId()))
16123 RelationGetRelationName(target_rel));
16124
16125 /* Must be able to become new owner */
16126 check_can_set_role(GetUserId(), newOwnerId);
16127
16128 /* New owner must have CREATE privilege on namespace */
16129 aclresult = object_aclcheck(NamespaceRelationId, namespaceOid, newOwnerId,
16130 ACL_CREATE);
16131 if (aclresult != ACLCHECK_OK)
16132 aclcheck_error(aclresult, OBJECT_SCHEMA,
16133 get_namespace_name(namespaceOid));
16134 }
16135 }
16136
16137 memset(repl_null, false, sizeof(repl_null));
16138 memset(repl_repl, false, sizeof(repl_repl));
16139
16140 repl_repl[Anum_pg_class_relowner - 1] = true;
16141 repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
16142
16143 /*
16144 * Determine the modified ACL for the new owner. This is only
16145 * necessary when the ACL is non-null.
16146 */
16147 aclDatum = SysCacheGetAttr(RELOID, tuple,
16148 Anum_pg_class_relacl,
16149 &isNull);
16150 if (!isNull)
16151 {
16152 newAcl = aclnewowner(DatumGetAclP(aclDatum),
16153 tuple_class->relowner, newOwnerId);
16154 repl_repl[Anum_pg_class_relacl - 1] = true;
16155 repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
16156 }
16157
16158 newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
16159
16160 CatalogTupleUpdate(class_rel, &newtuple->t_self, newtuple);
16161
16162 heap_freetuple(newtuple);
16163
16164 /*
16165 * We must similarly update any per-column ACLs to reflect the new
16166 * owner; for neatness reasons that's split out as a subroutine.
16167 */
16168 change_owner_fix_column_acls(relationOid,
16169 tuple_class->relowner,
16170 newOwnerId);
16171
16172 /*
16173 * Update owner dependency reference, if any. A composite type has
16174 * none, because it's tracked for the pg_type entry instead of here;
16175 * indexes and TOAST tables don't have their own entries either.
16176 */
16177 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
16178 tuple_class->relkind != RELKIND_INDEX &&
16179 tuple_class->relkind != RELKIND_PARTITIONED_INDEX &&
16180 tuple_class->relkind != RELKIND_TOASTVALUE)
16181 changeDependencyOnOwner(RelationRelationId, relationOid,
16182 newOwnerId);
16183
16184 /*
16185 * Also change the ownership of the table's row type, if it has one
16186 */
16187 if (OidIsValid(tuple_class->reltype))
16188 AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId);
16189
16190 /*
16191 * If we are operating on a table or materialized view, also change
16192 * the ownership of any indexes and sequences that belong to the
16193 * relation, as well as its toast table (if it has one).
16194 */
16195 if (tuple_class->relkind == RELKIND_RELATION ||
16196 tuple_class->relkind == RELKIND_PARTITIONED_TABLE ||
16197 tuple_class->relkind == RELKIND_MATVIEW ||
16198 tuple_class->relkind == RELKIND_TOASTVALUE)
16199 {
16200 List *index_oid_list;
16201 ListCell *i;
16202
16203 /* Find all the indexes belonging to this relation */
16204 index_oid_list = RelationGetIndexList(target_rel);
16205
16206 /* For each index, recursively change its ownership */
16207 foreach(i, index_oid_list)
16208 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
16209
16210 list_free(index_oid_list);
16211 }
16212
16213 /* If it has a toast table, recurse to change its ownership */
16214 if (tuple_class->reltoastrelid != InvalidOid)
16215 ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
16216 true, lockmode);
16217
16218 /* If it has dependent sequences, recurse to change them too */
16219 change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
16220 }
16221
16222 InvokeObjectPostAlterHook(RelationRelationId, relationOid, 0);
16223
16224 ReleaseSysCache(tuple);
16225 table_close(class_rel, RowExclusiveLock);
16226 relation_close(target_rel, NoLock);
16227}
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition: acl.c:1103
void check_can_set_role(Oid member, Oid role)
Definition: acl.c:5325
#define DatumGetAclP(X)
Definition: acl.h:120
int errhint(const char *fmt,...)
Definition: elog.c:1318
#define WARNING
Definition: elog.h:36
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition: heaptuple.c:1210
int i
Definition: isn.c:77
void list_free(List *list)
Definition: list.c:1546
@ OBJECT_SCHEMA
Definition: parsenodes.h:2353
int errdetail_relkind_not_supported(char relkind)
Definition: pg_class.c:24
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
Definition: pg_shdepend.c:316
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:327
uintptr_t Datum
Definition: postgres.h:69
#define RelationGetDescr(relation)
Definition: rel.h:542
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4833
bool superuser(void)
Definition: superuser.c:46
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:269
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:221
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:600
void ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
Definition: tablecmds.c:15995
static void change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
Definition: tablecmds.c:16301
static void change_owner_fix_column_acls(Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
Definition: tablecmds.c:16236
void AlterTypeOwnerInternal(Oid typeOid, Oid newOwnerId)
Definition: typecmds.c:3978

References ACL_CREATE, aclcheck_error(), ACLCHECK_NOT_OWNER, ACLCHECK_OK, aclnewowner(), AlterTypeOwnerInternal(), ATExecChangeOwner(), CatalogTupleUpdate(), change_owner_fix_column_acls(), change_owner_recurse_to_sequences(), changeDependencyOnOwner(), check_can_set_role(), DatumGetAclP, DEPENDENCY_AUTO, DEPENDENCY_INTERNAL, elog, ereport, errcode(), errdetail(), errdetail_relkind_not_supported(), errhint(), errmsg(), ERROR, get_namespace_name(), get_rel_name(), get_rel_relkind(), get_relkind_objtype(), GETSTRUCT(), GetUserId(), heap_freetuple(), heap_modify_tuple(), HeapTupleIsValid, i, InvalidOid, InvokeObjectPostAlterHook, lfirst_oid, list_free(), NameStr, NoLock, object_aclcheck(), object_ownercheck(), OBJECT_SCHEMA, ObjectIdGetDatum(), OidIsValid, PointerGetDatum(), relation_close(), relation_open(), RelationGetDescr, RelationGetIndexList(), RelationGetRelationName, ReleaseSysCache(), RowExclusiveLock, SearchSysCache1(), sequenceIsOwned(), superuser(), SysCacheGetAttr(), HeapTupleData::t_self, table_close(), table_open(), and WARNING.

Referenced by AlterTypeOwner_oid(), ATExecChangeOwner(), ATExecCmd(), change_owner_recurse_to_sequences(), and shdepReassignOwned_Owner().

◆ BuildDescForRelation()

TupleDesc BuildDescForRelation ( const List columns)

Definition at line 1370 of file tablecmds.c.

1371{
1372 int natts;
1374 ListCell *l;
1375 TupleDesc desc;
1376 char *attname;
1377 Oid atttypid;
1378 int32 atttypmod;
1379 Oid attcollation;
1380 int attdim;
1381
1382 /*
1383 * allocate a new tuple descriptor
1384 */
1385 natts = list_length(columns);
1386 desc = CreateTemplateTupleDesc(natts);
1387
1388 attnum = 0;
1389
1390 foreach(l, columns)
1391 {
1392 ColumnDef *entry = lfirst(l);
1393 AclResult aclresult;
1395
1396 /*
1397 * for each entry in the list, get the name and type information from
1398 * the list and have TupleDescInitEntry fill in the attribute
1399 * information we need.
1400 */
1401 attnum++;
1402
1403 attname = entry->colname;
1404 typenameTypeIdAndMod(NULL, entry->typeName, &atttypid, &atttypmod);
1405
1406 aclresult = object_aclcheck(TypeRelationId, atttypid, GetUserId(), ACL_USAGE);
1407 if (aclresult != ACLCHECK_OK)
1408 aclcheck_error_type(aclresult, atttypid);
1409
1410 attcollation = GetColumnDefCollation(NULL, entry, atttypid);
1411 attdim = list_length(entry->typeName->arrayBounds);
1412 if (attdim > PG_INT16_MAX)
1413 ereport(ERROR,
1414 errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1415 errmsg("too many array dimensions"));
1416
1417 if (entry->typeName->setof)
1418 ereport(ERROR,
1419 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1420 errmsg("column \"%s\" cannot be declared SETOF",
1421 attname)));
1422
1424 atttypid, atttypmod, attdim);
1425 att = TupleDescAttr(desc, attnum - 1);
1426
1427 /* Override TupleDescInitEntry's settings as requested */
1428 TupleDescInitEntryCollation(desc, attnum, attcollation);
1429
1430 /* Fill in additional stuff not handled by TupleDescInitEntry */
1431 att->attnotnull = entry->is_not_null;
1432 att->attislocal = entry->is_local;
1433 att->attinhcount = entry->inhcount;
1434 att->attidentity = entry->identity;
1435 att->attgenerated = entry->generated;
1436 att->attcompression = GetAttributeCompression(att->atttypid, entry->compression);
1437 if (entry->storage)
1438 att->attstorage = entry->storage;
1439 else if (entry->storage_name)
1440 att->attstorage = GetAttributeStorage(att->atttypid, entry->storage_name);
1441
1443 }
1444
1445 return desc;
1446}
void aclcheck_error_type(AclResult aclerr, Oid typeOid)
Definition: aclchk.c:2958
int16 AttrNumber
Definition: attnum.h:21
#define PG_INT16_MAX
Definition: c.h:557
void typenameTypeIdAndMod(ParseState *pstate, const TypeName *typeName, Oid *typeid_p, int32 *typmod_p)
Definition: parse_type.c:310
Oid GetColumnDefCollation(ParseState *pstate, const ColumnDef *coldef, Oid typeOid)
Definition: parse_type.c:540
#define ACL_USAGE
Definition: parsenodes.h:84
NameData attname
Definition: pg_attribute.h:41
int16 attnum
Definition: pg_attribute.h:74
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:202
static int list_length(const List *l)
Definition: pg_list.h:152
bool is_not_null
Definition: parsenodes.h:742
char identity
Definition: parsenodes.h:748
char * storage_name
Definition: parsenodes.h:745
char * colname
Definition: parsenodes.h:737
TypeName * typeName
Definition: parsenodes.h:738
char generated
Definition: parsenodes.h:751
char storage
Definition: parsenodes.h:744
bool is_local
Definition: parsenodes.h:741
int16 inhcount
Definition: parsenodes.h:740
char * compression
Definition: parsenodes.h:739
bool setof
Definition: parsenodes.h:281
List * arrayBounds
Definition: parsenodes.h:285
static char GetAttributeCompression(Oid atttypid, const char *compression)
Definition: tablecmds.c:21945
static char GetAttributeStorage(Oid atttypid, const char *storagemode)
Definition: tablecmds.c:21983
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:175
void populate_compact_attribute(TupleDesc tupdesc, int attnum)
Definition: tupdesc.c:117
void TupleDescInitEntryCollation(TupleDesc desc, AttrNumber attributeNumber, Oid collationid)
Definition: tupdesc.c:1019
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:835
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:160

References ACL_USAGE, aclcheck_error_type(), ACLCHECK_OK, TypeName::arrayBounds, attname, attnum, ColumnDef::colname, ColumnDef::compression, CreateTemplateTupleDesc(), ereport, errcode(), errmsg(), ERROR, ColumnDef::generated, GetAttributeCompression(), GetAttributeStorage(), GetColumnDefCollation(), GetUserId(), ColumnDef::identity, ColumnDef::inhcount, ColumnDef::is_local, ColumnDef::is_not_null, lfirst, list_length(), object_aclcheck(), PG_INT16_MAX, populate_compact_attribute(), TypeName::setof, ColumnDef::storage, ColumnDef::storage_name, TupleDescAttr(), TupleDescInitEntry(), TupleDescInitEntryCollation(), ColumnDef::typeName, and typenameTypeIdAndMod().

Referenced by ATExecAddColumn(), DefineRelation(), and DefineVirtualRelation().

◆ check_of_type()

void check_of_type ( HeapTuple  typetuple)

Definition at line 7133 of file tablecmds.c.

7134{
7135 Form_pg_type typ = (Form_pg_type) GETSTRUCT(typetuple);
7136 bool typeOk = false;
7137
7138 if (typ->typtype == TYPTYPE_COMPOSITE)
7139 {
7140 Relation typeRelation;
7141
7142 Assert(OidIsValid(typ->typrelid));
7143 typeRelation = relation_open(typ->typrelid, AccessShareLock);
7144 typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
7145
7146 /*
7147 * Close the parent rel, but keep our AccessShareLock on it until xact
7148 * commit. That will prevent someone else from deleting or ALTERing
7149 * the type before the typed table creation/conversion commits.
7150 */
7151 relation_close(typeRelation, NoLock);
7152
7153 if (!typeOk)
7154 ereport(ERROR,
7155 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7156 errmsg("type %s is the row type of another table",
7157 format_type_be(typ->oid)),
7158 errdetail("A typed table must use a stand-alone composite type created with CREATE TYPE.")));
7159 }
7160 else
7161 ereport(ERROR,
7162 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7163 errmsg("type %s is not a composite type",
7164 format_type_be(typ->oid))));
7165}
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261

References AccessShareLock, Assert(), ereport, errcode(), errdetail(), errmsg(), ERROR, format_type_be(), GETSTRUCT(), NoLock, OidIsValid, RelationData::rd_rel, relation_close(), and relation_open().

Referenced by ATExecAddOf(), and transformOfType().

◆ CheckRelationTableSpaceMove()

bool CheckRelationTableSpaceMove ( Relation  rel,
Oid  newTableSpaceId 
)

Definition at line 3683 of file tablecmds.c.

3684{
3685 Oid oldTableSpaceId;
3686
3687 /*
3688 * No work if no change in tablespace. Note that MyDatabaseTableSpace is
3689 * stored as 0.
3690 */
3691 oldTableSpaceId = rel->rd_rel->reltablespace;
3692 if (newTableSpaceId == oldTableSpaceId ||
3693 (newTableSpaceId == MyDatabaseTableSpace && oldTableSpaceId == 0))
3694 return false;
3695
3696 /*
3697 * We cannot support moving mapped relations into different tablespaces.
3698 * (In particular this eliminates all shared catalogs.)
3699 */
3700 if (RelationIsMapped(rel))
3701 ereport(ERROR,
3702 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3703 errmsg("cannot move system relation \"%s\"",
3705
3706 /* Cannot move a non-shared relation into pg_global */
3707 if (newTableSpaceId == GLOBALTABLESPACE_OID)
3708 ereport(ERROR,
3709 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3710 errmsg("only shared relations can be placed in pg_global tablespace")));
3711
3712 /*
3713 * Do not allow moving temp tables of other backends ... their local
3714 * buffer manager is not going to cope.
3715 */
3716 if (RELATION_IS_OTHER_TEMP(rel))
3717 ereport(ERROR,
3718 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3719 errmsg("cannot move temporary tables of other sessions")));
3720
3721 return true;
3722}
#define RelationIsMapped(relation)
Definition: rel.h:565
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:669

References ereport, errcode(), errmsg(), ERROR, MyDatabaseTableSpace, RelationData::rd_rel, RELATION_IS_OTHER_TEMP, RelationGetRelationName, and RelationIsMapped.

Referenced by ATExecSetTableSpace(), ATExecSetTableSpaceNoStorage(), reindex_index(), and SetRelationTableSpace().

◆ CheckTableNotInUse()

void CheckTableNotInUse ( Relation  rel,
const char *  stmt 
)

Definition at line 4406 of file tablecmds.c.

4407{
4408 int expected_refcnt;
4409
4410 expected_refcnt = rel->rd_isnailed ? 2 : 1;
4411 if (rel->rd_refcnt != expected_refcnt)
4412 ereport(ERROR,
4413 (errcode(ERRCODE_OBJECT_IN_USE),
4414 /* translator: first %s is a SQL command, eg ALTER TABLE */
4415 errmsg("cannot %s \"%s\" because it is being used by active queries in this session",
4417
4418 if (rel->rd_rel->relkind != RELKIND_INDEX &&
4419 rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
4421 ereport(ERROR,
4422 (errcode(ERRCODE_OBJECT_IN_USE),
4423 /* translator: first %s is a SQL command, eg ALTER TABLE */
4424 errmsg("cannot %s \"%s\" because it has pending trigger events",
4426}
int rd_refcnt
Definition: rel.h:59
bool rd_isnailed
Definition: rel.h:62
bool AfterTriggerPendingOnRel(Oid relid)
Definition: trigger.c:6024

References AfterTriggerPendingOnRel(), ereport, errcode(), errmsg(), ERROR, RelationData::rd_isnailed, RelationData::rd_refcnt, RelationData::rd_rel, RelationGetRelationName, RelationGetRelid, and stmt.

Referenced by CheckAlterTableIsSafe(), cluster_rel(), DefineIndex(), DefineVirtualRelation(), heap_drop_with_catalog(), index_drop(), MergeAttributes(), RefreshMatViewByOid(), reindex_index(), and truncate_check_activity().

◆ DefineRelation()

ObjectAddress DefineRelation ( CreateStmt stmt,
char  relkind,
Oid  ownerId,
ObjectAddress typaddress,
const char *  queryString 
)

Definition at line 764 of file tablecmds.c.

766{
767 char relname[NAMEDATALEN];
768 Oid namespaceId;
769 Oid relationId;
770 Oid tablespaceId;
771 Relation rel;
773 List *inheritOids;
774 List *old_constraints;
775 List *old_notnulls;
776 List *rawDefaults;
777 List *cookedDefaults;
778 List *nncols;
779 Datum reloptions;
780 ListCell *listptr;
782 bool partitioned;
783 const char *const validnsps[] = HEAP_RELOPT_NAMESPACES;
784 Oid ofTypeId;
785 ObjectAddress address;
786 LOCKMODE parentLockmode;
787 Oid accessMethodId = InvalidOid;
788
789 /*
790 * Truncate relname to appropriate length (probably a waste of time, as
791 * parser should have done this already).
792 */
793 strlcpy(relname, stmt->relation->relname, NAMEDATALEN);
794
795 /*
796 * Check consistency of arguments
797 */
798 if (stmt->oncommit != ONCOMMIT_NOOP
799 && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
801 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
802 errmsg("ON COMMIT can only be used on temporary tables")));
803
804 if (stmt->partspec != NULL)
805 {
806 if (relkind != RELKIND_RELATION)
807 elog(ERROR, "unexpected relkind: %d", (int) relkind);
808
809 relkind = RELKIND_PARTITIONED_TABLE;
810 partitioned = true;
811 }
812 else
813 partitioned = false;
814
815 if (relkind == RELKIND_PARTITIONED_TABLE &&
816 stmt->relation->relpersistence == RELPERSISTENCE_UNLOGGED)
818 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
819 errmsg("partitioned tables cannot be unlogged")));
820
821 /*
822 * Look up the namespace in which we are supposed to create the relation,
823 * check we have permission to create there, lock it against concurrent
824 * drop, and mark stmt->relation as RELPERSISTENCE_TEMP if a temporary
825 * namespace is selected.
826 */
827 namespaceId =
829
830 /*
831 * Security check: disallow creating temp tables from security-restricted
832 * code. This is needed because calling code might not expect untrusted
833 * tables to appear in pg_temp at the front of its search path.
834 */
835 if (stmt->relation->relpersistence == RELPERSISTENCE_TEMP
838 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
839 errmsg("cannot create temporary table within security-restricted operation")));
840
841 /*
842 * Determine the lockmode to use when scanning parents. A self-exclusive
843 * lock is needed here.
844 *
845 * For regular inheritance, if two backends attempt to add children to the
846 * same parent simultaneously, and that parent has no pre-existing
847 * children, then both will attempt to update the parent's relhassubclass
848 * field, leading to a "tuple concurrently updated" error. Also, this
849 * interlocks against a concurrent ANALYZE on the parent table, which
850 * might otherwise be attempting to clear the parent's relhassubclass
851 * field, if its previous children were recently dropped.
852 *
853 * If the child table is a partition, then we instead grab an exclusive
854 * lock on the parent because its partition descriptor will be changed by
855 * addition of the new partition.
856 */
857 parentLockmode = (stmt->partbound != NULL ? AccessExclusiveLock :
859
860 /* Determine the list of OIDs of the parents. */
861 inheritOids = NIL;
862 foreach(listptr, stmt->inhRelations)
863 {
864 RangeVar *rv = (RangeVar *) lfirst(listptr);
865 Oid parentOid;
866
867 parentOid = RangeVarGetRelid(rv, parentLockmode, false);
868
869 /*
870 * Reject duplications in the list of parents.
871 */
872 if (list_member_oid(inheritOids, parentOid))
874 (errcode(ERRCODE_DUPLICATE_TABLE),
875 errmsg("relation \"%s\" would be inherited from more than once",
876 get_rel_name(parentOid))));
877
878 inheritOids = lappend_oid(inheritOids, parentOid);
879 }
880
881 /*
882 * Select tablespace to use: an explicitly indicated one, or (in the case
883 * of a partitioned table) the parent's, if it has one.
884 */
885 if (stmt->tablespacename)
886 {
887 tablespaceId = get_tablespace_oid(stmt->tablespacename, false);
888
889 if (partitioned && tablespaceId == MyDatabaseTableSpace)
891 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
892 errmsg("cannot specify default tablespace for partitioned relations")));
893 }
894 else if (stmt->partbound)
895 {
896 Assert(list_length(inheritOids) == 1);
897 tablespaceId = get_rel_tablespace(linitial_oid(inheritOids));
898 }
899 else
900 tablespaceId = InvalidOid;
901
902 /* still nothing? use the default */
903 if (!OidIsValid(tablespaceId))
904 tablespaceId = GetDefaultTablespace(stmt->relation->relpersistence,
905 partitioned);
906
907 /* Check permissions except when using database's default */
908 if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
909 {
910 AclResult aclresult;
911
912 aclresult = object_aclcheck(TableSpaceRelationId, tablespaceId, GetUserId(),
913 ACL_CREATE);
914 if (aclresult != ACLCHECK_OK)
916 get_tablespace_name(tablespaceId));
917 }
918
919 /* In all cases disallow placing user relations in pg_global */
920 if (tablespaceId == GLOBALTABLESPACE_OID)
922 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
923 errmsg("only shared relations can be placed in pg_global tablespace")));
924
925 /* Identify user ID that will own the table */
926 if (!OidIsValid(ownerId))
927 ownerId = GetUserId();
928
929 /*
930 * Parse and validate reloptions, if any.
931 */
932 reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, validnsps,
933 true, false);
934
935 switch (relkind)
936 {
937 case RELKIND_VIEW:
938 (void) view_reloptions(reloptions, true);
939 break;
940 case RELKIND_PARTITIONED_TABLE:
941 (void) partitioned_table_reloptions(reloptions, true);
942 break;
943 default:
944 (void) heap_reloptions(relkind, reloptions, true);
945 }
946
947 if (stmt->ofTypename)
948 {
949 AclResult aclresult;
950
951 ofTypeId = typenameTypeId(NULL, stmt->ofTypename);
952
953 aclresult = object_aclcheck(TypeRelationId, ofTypeId, GetUserId(), ACL_USAGE);
954 if (aclresult != ACLCHECK_OK)
955 aclcheck_error_type(aclresult, ofTypeId);
956 }
957 else
958 ofTypeId = InvalidOid;
959
960 /*
961 * Look up inheritance ancestors and generate relation schema, including
962 * inherited attributes. (Note that stmt->tableElts is destructively
963 * modified by MergeAttributes.)
964 */
965 stmt->tableElts =
966 MergeAttributes(stmt->tableElts, inheritOids,
967 stmt->relation->relpersistence,
968 stmt->partbound != NULL,
969 &old_constraints, &old_notnulls);
970
971 /*
972 * Create a tuple descriptor from the relation schema. Note that this
973 * deals with column names, types, and in-descriptor NOT NULL flags, but
974 * not default values, NOT NULL or CHECK constraints; we handle those
975 * below.
976 */
978
979 /*
980 * Find columns with default values and prepare for insertion of the
981 * defaults. Pre-cooked (that is, inherited) defaults go into a list of
982 * CookedConstraint structs that we'll pass to heap_create_with_catalog,
983 * while raw defaults go into a list of RawColumnDefault structs that will
984 * be processed by AddRelationNewConstraints. (We can't deal with raw
985 * expressions until we can do transformExpr.)
986 */
987 rawDefaults = NIL;
988 cookedDefaults = NIL;
989 attnum = 0;
990
991 foreach(listptr, stmt->tableElts)
992 {
993 ColumnDef *colDef = lfirst(listptr);
994
995 attnum++;
996 if (colDef->raw_default != NULL)
997 {
998 RawColumnDefault *rawEnt;
999
1000 Assert(colDef->cooked_default == NULL);
1001
1002 rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
1003 rawEnt->attnum = attnum;
1004 rawEnt->raw_default = colDef->raw_default;
1005 rawEnt->generated = colDef->generated;
1006 rawDefaults = lappend(rawDefaults, rawEnt);
1007 }
1008 else if (colDef->cooked_default != NULL)
1009 {
1010 CookedConstraint *cooked;
1011
1012 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1013 cooked->contype = CONSTR_DEFAULT;
1014 cooked->conoid = InvalidOid; /* until created */
1015 cooked->name = NULL;
1016 cooked->attnum = attnum;
1017 cooked->expr = colDef->cooked_default;
1018 cooked->is_enforced = true;
1019 cooked->skip_validation = false;
1020 cooked->is_local = true; /* not used for defaults */
1021 cooked->inhcount = 0; /* ditto */
1022 cooked->is_no_inherit = false;
1023 cookedDefaults = lappend(cookedDefaults, cooked);
1024 }
1025 }
1026
1027 /*
1028 * For relations with table AM and partitioned tables, select access
1029 * method to use: an explicitly indicated one, or (in the case of a
1030 * partitioned table) the parent's, if it has one.
1031 */
1032 if (stmt->accessMethod != NULL)
1033 {
1034 Assert(RELKIND_HAS_TABLE_AM(relkind) || relkind == RELKIND_PARTITIONED_TABLE);
1035 accessMethodId = get_table_am_oid(stmt->accessMethod, false);
1036 }
1037 else if (RELKIND_HAS_TABLE_AM(relkind) || relkind == RELKIND_PARTITIONED_TABLE)
1038 {
1039 if (stmt->partbound)
1040 {
1041 Assert(list_length(inheritOids) == 1);
1042 accessMethodId = get_rel_relam(linitial_oid(inheritOids));
1043 }
1044
1045 if (RELKIND_HAS_TABLE_AM(relkind) && !OidIsValid(accessMethodId))
1046 accessMethodId = get_table_am_oid(default_table_access_method, false);
1047 }
1048
1049 /*
1050 * Create the relation. Inherited defaults and CHECK constraints are
1051 * passed in for immediate handling --- since they don't need parsing,
1052 * they can be stored immediately.
1053 */
1054 relationId = heap_create_with_catalog(relname,
1055 namespaceId,
1056 tablespaceId,
1057 InvalidOid,
1058 InvalidOid,
1059 ofTypeId,
1060 ownerId,
1061 accessMethodId,
1062 descriptor,
1063 list_concat(cookedDefaults,
1064 old_constraints),
1065 relkind,
1066 stmt->relation->relpersistence,
1067 false,
1068 false,
1069 stmt->oncommit,
1070 reloptions,
1071 true,
1073 false,
1074 InvalidOid,
1075 typaddress);
1076
1077 /*
1078 * We must bump the command counter to make the newly-created relation
1079 * tuple visible for opening.
1080 */
1082
1083 /*
1084 * Open the new relation and acquire exclusive lock on it. This isn't
1085 * really necessary for locking out other backends (since they can't see
1086 * the new rel anyway until we commit), but it keeps the lock manager from
1087 * complaining about deadlock risks.
1088 */
1089 rel = relation_open(relationId, AccessExclusiveLock);
1090
1091 /*
1092 * Now add any newly specified column default and generation expressions
1093 * to the new relation. These are passed to us in the form of raw
1094 * parsetrees; we need to transform them to executable expression trees
1095 * before they can be added. The most convenient way to do that is to
1096 * apply the parser's transformExpr routine, but transformExpr doesn't
1097 * work unless we have a pre-existing relation. So, the transformation has
1098 * to be postponed to this final step of CREATE TABLE.
1099 *
1100 * This needs to be before processing the partitioning clauses because
1101 * those could refer to generated columns.
1102 */
1103 if (rawDefaults)
1104 AddRelationNewConstraints(rel, rawDefaults, NIL,
1105 true, true, false, queryString);
1106
1107 /*
1108 * Make column generation expressions visible for use by partitioning.
1109 */
1111
1112 /* Process and store partition bound, if any. */
1113 if (stmt->partbound)
1114 {
1115 PartitionBoundSpec *bound;
1116 ParseState *pstate;
1117 Oid parentId = linitial_oid(inheritOids),
1118 defaultPartOid;
1119 Relation parent,
1120 defaultRel = NULL;
1121 ParseNamespaceItem *nsitem;
1122
1123 /* Already have strong enough lock on the parent */
1124 parent = table_open(parentId, NoLock);
1125
1126 /*
1127 * We are going to try to validate the partition bound specification
1128 * against the partition key of parentRel, so it better have one.
1129 */
1130 if (parent->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
1131 ereport(ERROR,
1132 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1133 errmsg("\"%s\" is not partitioned",
1134 RelationGetRelationName(parent))));
1135
1136 /*
1137 * The partition constraint of the default partition depends on the
1138 * partition bounds of every other partition. It is possible that
1139 * another backend might be about to execute a query on the default
1140 * partition table, and that the query relies on previously cached
1141 * default partition constraints. We must therefore take a table lock
1142 * strong enough to prevent all queries on the default partition from
1143 * proceeding until we commit and send out a shared-cache-inval notice
1144 * that will make them update their index lists.
1145 *
1146 * Order of locking: The relation being added won't be visible to
1147 * other backends until it is committed, hence here in
1148 * DefineRelation() the order of locking the default partition and the
1149 * relation being added does not matter. But at all other places we
1150 * need to lock the default relation before we lock the relation being
1151 * added or removed i.e. we should take the lock in same order at all
1152 * the places such that lock parent, lock default partition and then
1153 * lock the partition so as to avoid a deadlock.
1154 */
1155 defaultPartOid =
1157 true));
1158 if (OidIsValid(defaultPartOid))
1159 defaultRel = table_open(defaultPartOid, AccessExclusiveLock);
1160
1161 /* Transform the bound values */
1162 pstate = make_parsestate(NULL);
1163 pstate->p_sourcetext = queryString;
1164
1165 /*
1166 * Add an nsitem containing this relation, so that transformExpr
1167 * called on partition bound expressions is able to report errors
1168 * using a proper context.
1169 */
1170 nsitem = addRangeTableEntryForRelation(pstate, rel, AccessShareLock,
1171 NULL, false, false);
1172 addNSItemToQuery(pstate, nsitem, false, true, true);
1173
1174 bound = transformPartitionBound(pstate, parent, stmt->partbound);
1175
1176 /*
1177 * Check first that the new partition's bound is valid and does not
1178 * overlap with any of existing partitions of the parent.
1179 */
1180 check_new_partition_bound(relname, parent, bound, pstate);
1181
1182 /*
1183 * If the default partition exists, its partition constraints will
1184 * change after the addition of this new partition such that it won't
1185 * allow any row that qualifies for this new partition. So, check that
1186 * the existing data in the default partition satisfies the constraint
1187 * as it will exist after adding this partition.
1188 */
1189 if (OidIsValid(defaultPartOid))
1190 {
1191 check_default_partition_contents(parent, defaultRel, bound);
1192 /* Keep the lock until commit. */
1193 table_close(defaultRel, NoLock);
1194 }
1195
1196 /* Update the pg_class entry. */
1197 StorePartitionBound(rel, parent, bound);
1198
1199 table_close(parent, NoLock);
1200 }
1201
1202 /* Store inheritance information for new rel. */
1203 StoreCatalogInheritance(relationId, inheritOids, stmt->partbound != NULL);
1204
1205 /*
1206 * Process the partitioning specification (if any) and store the partition
1207 * key information into the catalog.
1208 */
1209 if (partitioned)
1210 {
1211 ParseState *pstate;
1212 int partnatts;
1213 AttrNumber partattrs[PARTITION_MAX_KEYS];
1214 Oid partopclass[PARTITION_MAX_KEYS];
1215 Oid partcollation[PARTITION_MAX_KEYS];
1216 List *partexprs = NIL;
1217
1218 pstate = make_parsestate(NULL);
1219 pstate->p_sourcetext = queryString;
1220
1221 partnatts = list_length(stmt->partspec->partParams);
1222
1223 /* Protect fixed-size arrays here and in executor */
1224 if (partnatts > PARTITION_MAX_KEYS)
1225 ereport(ERROR,
1226 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1227 errmsg("cannot partition using more than %d columns",
1229
1230 /*
1231 * We need to transform the raw parsetrees corresponding to partition
1232 * expressions into executable expression trees. Like column defaults
1233 * and CHECK constraints, we could not have done the transformation
1234 * earlier.
1235 */
1236 stmt->partspec = transformPartitionSpec(rel, stmt->partspec);
1237
1238 ComputePartitionAttrs(pstate, rel, stmt->partspec->partParams,
1239 partattrs, &partexprs, partopclass,
1240 partcollation, stmt->partspec->strategy);
1241
1242 StorePartitionKey(rel, stmt->partspec->strategy, partnatts, partattrs,
1243 partexprs,
1244 partopclass, partcollation);
1245
1246 /* make it all visible */
1248 }
1249
1250 /*
1251 * If we're creating a partition, create now all the indexes, triggers,
1252 * FKs defined in the parent.
1253 *
1254 * We can't do it earlier, because DefineIndex wants to know the partition
1255 * key which we just stored.
1256 */
1257 if (stmt->partbound)
1258 {
1259 Oid parentId = linitial_oid(inheritOids);
1260 Relation parent;
1261 List *idxlist;
1262 ListCell *cell;
1263
1264 /* Already have strong enough lock on the parent */
1265 parent = table_open(parentId, NoLock);
1266 idxlist = RelationGetIndexList(parent);
1267
1268 /*
1269 * For each index in the parent table, create one in the partition
1270 */
1271 foreach(cell, idxlist)
1272 {
1274 AttrMap *attmap;
1275 IndexStmt *idxstmt;
1276 Oid constraintOid;
1277
1278 if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1279 {
1280 if (idxRel->rd_index->indisunique)
1281 ereport(ERROR,
1282 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1283 errmsg("cannot create foreign partition of partitioned table \"%s\"",
1284 RelationGetRelationName(parent)),
1285 errdetail("Table \"%s\" contains indexes that are unique.",
1286 RelationGetRelationName(parent))));
1287 else
1288 {
1290 continue;
1291 }
1292 }
1293
1295 RelationGetDescr(parent),
1296 false);
1297 idxstmt =
1298 generateClonedIndexStmt(NULL, idxRel,
1299 attmap, &constraintOid);
1301 idxstmt,
1302 InvalidOid,
1303 RelationGetRelid(idxRel),
1304 constraintOid,
1305 -1,
1306 false, false, false, false, false);
1307
1309 }
1310
1311 list_free(idxlist);
1312
1313 /*
1314 * If there are any row-level triggers, clone them to the new
1315 * partition.
1316 */
1317 if (parent->trigdesc != NULL)
1318 CloneRowTriggersToPartition(parent, rel);
1319
1320 /*
1321 * And foreign keys too. Note that because we're freshly creating the
1322 * table, there is no need to verify these new constraints.
1323 */
1324 CloneForeignKeyConstraints(NULL, parent, rel);
1325
1326 table_close(parent, NoLock);
1327 }
1328
1329 /*
1330 * Now add any newly specified CHECK constraints to the new relation. Same
1331 * as for defaults above, but these need to come after partitioning is set
1332 * up.
1333 */
1334 if (stmt->constraints)
1335 AddRelationNewConstraints(rel, NIL, stmt->constraints,
1336 true, true, false, queryString);
1337
1338 /*
1339 * Finally, merge the not-null constraints that are declared directly with
1340 * those that come from parent relations (making sure to count inheritance
1341 * appropriately for each), create them, and set the attnotnull flag on
1342 * columns that don't yet have it.
1343 */
1344 nncols = AddRelationNotNullConstraints(rel, stmt->nnconstraints,
1345 old_notnulls);
1346 foreach_int(attrnum, nncols)
1347 set_attnotnull(NULL, rel, attrnum, true, false);
1348
1349 ObjectAddressSet(address, RelationRelationId, relationId);
1350
1351 /*
1352 * Clean up. We keep lock on new relation (although it shouldn't be
1353 * visible to anyone else anyway, until commit).
1354 */
1355 relation_close(rel, NoLock);
1356
1357 return address;
1358}
Oid get_table_am_oid(const char *amname, bool missing_ok)
Definition: amcmds.c:173
AttrMap * build_attrmap_by_name(TupleDesc indesc, TupleDesc outdesc, bool missing_ok)
Definition: attmap.c:175
Oid GetDefaultTablespace(char relpersistence, bool partitioned)
Definition: tablespace.c:1143
bool allowSystemTableMods
Definition: globals.c:131
void StorePartitionKey(Relation rel, char strategy, int16 partnatts, AttrNumber *partattrs, List *partexprs, Oid *partopclass, Oid *partcollation)
Definition: heap.c:3800
Oid heap_create_with_catalog(const char *relname, Oid relnamespace, Oid reltablespace, Oid relid, Oid reltypeid, Oid reloftypeid, Oid ownerid, Oid accessmtd, TupleDesc tupdesc, List *cooked_constraints, char relkind, char relpersistence, bool shared_relation, bool mapped_relation, OnCommitAction oncommit, Datum reloptions, bool use_user_acl, bool allow_system_table_mods, bool is_internal, Oid relrewrite, ObjectAddress *typaddress)
Definition: heap.c:1112
void StorePartitionBound(Relation rel, Relation parent, PartitionBoundSpec *bound)
Definition: heap.c:3956
List * AddRelationNotNullConstraints(Relation rel, List *constraints, List *old_notnulls)
Definition: heap.c:2884
List * AddRelationNewConstraints(Relation rel, List *newColDefaults, List *newConstraints, bool allow_merge, bool is_local, bool is_internal, const char *queryString)
Definition: heap.c:2375
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:177
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:133
ObjectAddress DefineIndex(Oid tableId, IndexStmt *stmt, Oid indexRelationId, Oid parentIndexId, Oid parentConstraintId, int total_parts, bool is_alter_table, bool check_rights, bool check_not_in_use, bool skip_build, bool quiet)
Definition: indexcmds.c:542
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
Oid get_rel_relam(Oid relid)
Definition: lsyscache.c:2240
Oid get_rel_tablespace(Oid relid)
Definition: lsyscache.c:2194
void * palloc(Size size)
Definition: mcxt.c:1939
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:690
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:80
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:39
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:291
PartitionBoundSpec * transformPartitionBound(ParseState *pstate, Relation parent, PartitionBoundSpec *spec)
IndexStmt * generateClonedIndexStmt(RangeVar *heapRel, Relation source_idx, const AttrMap *attmap, Oid *constraintOid)
@ CONSTR_DEFAULT
Definition: parsenodes.h:2791
void check_new_partition_bound(char *relname, Relation parent, PartitionBoundSpec *spec, ParseState *pstate)
Definition: partbounds.c:2896
void check_default_partition_contents(Relation parent, Relation default_rel, PartitionBoundSpec *new_spec)
Definition: partbounds.c:3251
PartitionDesc RelationGetPartitionDesc(Relation rel, bool omit_detached)
Definition: partdesc.c:71
Oid get_default_oid_from_partdesc(PartitionDesc partdesc)
Definition: partdesc.c:501
NameData relname
Definition: pg_class.h:38
#define PARTITION_MAX_KEYS
#define NAMEDATALEN
#define linitial_oid(l)
Definition: pg_list.h:180
#define foreach_int(var, lst)
Definition: pg_list.h:470
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
@ ONCOMMIT_NOOP
Definition: primnodes.h:58
Datum transformRelOptions(Datum oldOptions, List *defList, const char *namspace, const char *const validnsps[], bool acceptOidsOff, bool isReset)
Definition: reloptions.c:1167
bytea * view_reloptions(Datum reloptions, bool validate)
Definition: reloptions.c:2025
bytea * partitioned_table_reloptions(Datum reloptions, bool validate)
Definition: reloptions.c:2011
bytea * heap_reloptions(char relkind, Datum reloptions, bool validate)
Definition: reloptions.c:2046
#define HEAP_RELOPT_NAMESPACES
Definition: reloptions.h:61
Definition: attmap.h:35
Node * cooked_default
Definition: parsenodes.h:747
Node * raw_default
Definition: parsenodes.h:746
Oid conoid
Definition: heap.h:39
char * name
Definition: heap.h:40
AttrNumber attnum
Definition: heap.h:41
bool skip_validation
Definition: heap.h:44
bool is_enforced
Definition: heap.h:43
bool is_no_inherit
Definition: heap.h:47
int16 inhcount
Definition: heap.h:46
bool is_local
Definition: heap.h:45
ConstrType contype
Definition: heap.h:37
Node * expr
Definition: heap.h:42
const char * p_sourcetext
Definition: parse_node.h:209
Node * raw_default
Definition: heap.h:31
AttrNumber attnum
Definition: heap.h:30
char generated
Definition: heap.h:32
TriggerDesc * trigdesc
Definition: rel.h:117
Form_pg_index rd_index
Definition: rel.h:192
char * default_table_access_method
Definition: tableam.c:49
TupleDesc BuildDescForRelation(const List *columns)
Definition: tablecmds.c:1370
static void ComputePartitionAttrs(ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs, List **partexprs, Oid *partopclass, Oid *partcollation, PartitionStrategy strategy)
Definition: tablecmds.c:19708
static void CloneRowTriggersToPartition(Relation parent, Relation partition)
Definition: tablecmds.c:20668
static void StoreCatalogInheritance(Oid relationId, List *supers, bool child_is_partition)
Definition: tablecmds.c:3511
static void CloneForeignKeyConstraints(List **wqueue, Relation parentRel, Relation partitionRel)
Definition: tablecmds.c:11180
static PartitionSpec * transformPartitionSpec(Relation rel, PartitionSpec *partspec)
Definition: tablecmds.c:19650
static void set_attnotnull(List **wqueue, Relation rel, AttrNumber attnum, bool is_valid, bool queue_validation)
Definition: tablecmds.c:7830
static List * MergeAttributes(List *columns, const List *supers, char relpersistence, bool is_partition, List **supconstr, List **supnotnulls)
Definition: tablecmds.c:2536
void CommandCounterIncrement(void)
Definition: xact.c:1100

References AccessExclusiveLock, AccessShareLock, ACL_CREATE, ACL_USAGE, aclcheck_error(), aclcheck_error_type(), ACLCHECK_OK, addNSItemToQuery(), addRangeTableEntryForRelation(), AddRelationNewConstraints(), AddRelationNotNullConstraints(), allowSystemTableMods, Assert(), RawColumnDefault::attnum, CookedConstraint::attnum, attnum, build_attrmap_by_name(), BuildDescForRelation(), check_default_partition_contents(), check_new_partition_bound(), CloneForeignKeyConstraints(), CloneRowTriggersToPartition(), CommandCounterIncrement(), ComputePartitionAttrs(), CookedConstraint::conoid, CONSTR_DEFAULT, CookedConstraint::contype, ColumnDef::cooked_default, default_table_access_method, DefineIndex(), elog, ereport, errcode(), errdetail(), errmsg(), ERROR, CookedConstraint::expr, foreach_int, generateClonedIndexStmt(), RawColumnDefault::generated, ColumnDef::generated, get_default_oid_from_partdesc(), get_rel_name(), get_rel_relam(), get_rel_tablespace(), get_table_am_oid(), get_tablespace_name(), get_tablespace_oid(), GetDefaultTablespace(), GetUserId(), heap_create_with_catalog(), HEAP_RELOPT_NAMESPACES, heap_reloptions(), index_close(), index_open(), CookedConstraint::inhcount, InSecurityRestrictedOperation(), InvalidOid, CookedConstraint::is_enforced, CookedConstraint::is_local, CookedConstraint::is_no_inherit, lappend(), lappend_oid(), lfirst, lfirst_oid, linitial_oid, list_concat(), list_free(), list_length(), list_member_oid(), make_parsestate(), MergeAttributes(), MyDatabaseTableSpace, CookedConstraint::name, NAMEDATALEN, NIL, NoLock, object_aclcheck(), OBJECT_TABLESPACE, ObjectAddressSet, OidIsValid, ONCOMMIT_NOOP, ParseState::p_sourcetext, palloc(), PARTITION_MAX_KEYS, partitioned_table_reloptions(), RangeVarGetAndCheckCreationNamespace(), RangeVarGetRelid, RawColumnDefault::raw_default, ColumnDef::raw_default, RelationData::rd_index, RelationData::rd_rel, relation_close(), relation_open(), RelationGetDescr, RelationGetIndexList(), RelationGetPartitionDesc(), RelationGetRelationName, RelationGetRelid, relname, set_attnotnull(), ShareUpdateExclusiveLock, CookedConstraint::skip_validation, stmt, StoreCatalogInheritance(), StorePartitionBound(), StorePartitionKey(), strlcpy(), table_close(), table_open(), transformPartitionBound(), transformPartitionSpec(), transformRelOptions(), RelationData::trigdesc, typenameTypeId(), and view_reloptions().

Referenced by create_ctas_internal(), DefineCompositeType(), DefineSequence(), DefineVirtualRelation(), and ProcessUtilitySlow().

◆ ExecuteTruncate()

void ExecuteTruncate ( TruncateStmt stmt)

Definition at line 1851 of file tablecmds.c.

1852{
1853 List *rels = NIL;
1854 List *relids = NIL;
1855 List *relids_logged = NIL;
1856 ListCell *cell;
1857
1858 /*
1859 * Open, exclusive-lock, and check all the explicitly-specified relations
1860 */
1861 foreach(cell, stmt->relations)
1862 {
1863 RangeVar *rv = lfirst(cell);
1864 Relation rel;
1865 bool recurse = rv->inh;
1866 Oid myrelid;
1867 LOCKMODE lockmode = AccessExclusiveLock;
1868
1869 myrelid = RangeVarGetRelidExtended(rv, lockmode,
1871 NULL);
1872
1873 /* don't throw error for "TRUNCATE foo, foo" */
1874 if (list_member_oid(relids, myrelid))
1875 continue;
1876
1877 /* open the relation, we already hold a lock on it */
1878 rel = table_open(myrelid, NoLock);
1879
1880 /*
1881 * RangeVarGetRelidExtended() has done most checks with its callback,
1882 * but other checks with the now-opened Relation remain.
1883 */
1885
1886 rels = lappend(rels, rel);
1887 relids = lappend_oid(relids, myrelid);
1888
1889 /* Log this relation only if needed for logical decoding */
1891 relids_logged = lappend_oid(relids_logged, myrelid);
1892
1893 if (recurse)
1894 {
1895 ListCell *child;
1896 List *children;
1897
1898 children = find_all_inheritors(myrelid, lockmode, NULL);
1899
1900 foreach(child, children)
1901 {
1902 Oid childrelid = lfirst_oid(child);
1903
1904 if (list_member_oid(relids, childrelid))
1905 continue;
1906
1907 /* find_all_inheritors already got lock */
1908 rel = table_open(childrelid, NoLock);
1909
1910 /*
1911 * It is possible that the parent table has children that are
1912 * temp tables of other backends. We cannot safely access
1913 * such tables (because of buffering issues), and the best
1914 * thing to do is to silently ignore them. Note that this
1915 * check is the same as one of the checks done in
1916 * truncate_check_activity() called below, still it is kept
1917 * here for simplicity.
1918 */
1919 if (RELATION_IS_OTHER_TEMP(rel))
1920 {
1921 table_close(rel, lockmode);
1922 continue;
1923 }
1924
1925 /*
1926 * Inherited TRUNCATE commands perform access permission
1927 * checks on the parent table only. So we skip checking the
1928 * children's permissions and don't call
1929 * truncate_check_perms() here.
1930 */
1933
1934 rels = lappend(rels, rel);
1935 relids = lappend_oid(relids, childrelid);
1936
1937 /* Log this relation only if needed for logical decoding */
1939 relids_logged = lappend_oid(relids_logged, childrelid);
1940 }
1941 }
1942 else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1943 ereport(ERROR,
1944 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1945 errmsg("cannot truncate only a partitioned table"),
1946 errhint("Do not specify the ONLY keyword, or use TRUNCATE ONLY on the partitions directly.")));
1947 }
1948
1949 ExecuteTruncateGuts(rels, relids, relids_logged,
1950 stmt->behavior, stmt->restart_seqs, false);
1951
1952 /* And close the rels */
1953 foreach(cell, rels)
1954 {
1955 Relation rel = (Relation) lfirst(cell);
1956
1957 table_close(rel, NoLock);
1958 }
1959}
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:255
#define RelationIsLogicallyLogged(relation)
Definition: rel.h:712
struct RelationData * Relation
Definition: relcache.h:27
bool inh
Definition: primnodes.h:86
static void truncate_check_activity(Relation rel)
Definition: tablecmds.c:2428
static void truncate_check_rel(Oid relid, Form_pg_class reltuple)
Definition: tablecmds.c:2362
static void RangeVarCallbackForTruncate(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:19453
void ExecuteTruncateGuts(List *explicit_rels, List *relids, List *relids_logged, DropBehavior behavior, bool restart_seqs, bool run_as_table_owner)
Definition: tablecmds.c:1975

References AccessExclusiveLock, ereport, errcode(), errhint(), errmsg(), ERROR, ExecuteTruncateGuts(), find_all_inheritors(), RangeVar::inh, lappend(), lappend_oid(), lfirst, lfirst_oid, list_member_oid(), NIL, NoLock, RangeVarCallbackForTruncate(), RangeVarGetRelidExtended(), RelationData::rd_rel, RELATION_IS_OTHER_TEMP, RelationGetRelid, RelationIsLogicallyLogged, stmt, table_close(), table_open(), truncate_check_activity(), and truncate_check_rel().

Referenced by standard_ProcessUtility().

◆ ExecuteTruncateGuts()

void ExecuteTruncateGuts ( List explicit_rels,
List relids,
List relids_logged,
DropBehavior  behavior,
bool  restart_seqs,
bool  run_as_table_owner 
)

Definition at line 1975 of file tablecmds.c.

1980{
1981 List *rels;
1982 List *seq_relids = NIL;
1983 HTAB *ft_htab = NULL;
1984 EState *estate;
1985 ResultRelInfo *resultRelInfos;
1986 ResultRelInfo *resultRelInfo;
1987 SubTransactionId mySubid;
1988 ListCell *cell;
1989 Oid *logrelids;
1990
1991 /*
1992 * Check the explicitly-specified relations.
1993 *
1994 * In CASCADE mode, suck in all referencing relations as well. This
1995 * requires multiple iterations to find indirectly-dependent relations. At
1996 * each phase, we need to exclusive-lock new rels before looking for their
1997 * dependencies, else we might miss something. Also, we check each rel as
1998 * soon as we open it, to avoid a faux pas such as holding lock for a long
1999 * time on a rel we have no permissions for.
2000 */
2001 rels = list_copy(explicit_rels);
2002 if (behavior == DROP_CASCADE)
2003 {
2004 for (;;)
2005 {
2006 List *newrelids;
2007
2008 newrelids = heap_truncate_find_FKs(relids);
2009 if (newrelids == NIL)
2010 break; /* nothing else to add */
2011
2012 foreach(cell, newrelids)
2013 {
2014 Oid relid = lfirst_oid(cell);
2015 Relation rel;
2016
2017 rel = table_open(relid, AccessExclusiveLock);
2019 (errmsg("truncate cascades to table \"%s\"",
2021 truncate_check_rel(relid, rel->rd_rel);
2022 truncate_check_perms(relid, rel->rd_rel);
2024 rels = lappend(rels, rel);
2025 relids = lappend_oid(relids, relid);
2026
2027 /* Log this relation only if needed for logical decoding */
2029 relids_logged = lappend_oid(relids_logged, relid);
2030 }
2031 }
2032 }
2033
2034 /*
2035 * Check foreign key references. In CASCADE mode, this should be
2036 * unnecessary since we just pulled in all the references; but as a
2037 * cross-check, do it anyway if in an Assert-enabled build.
2038 */
2039#ifdef USE_ASSERT_CHECKING
2040 heap_truncate_check_FKs(rels, false);
2041#else
2042 if (behavior == DROP_RESTRICT)
2043 heap_truncate_check_FKs(rels, false);
2044#endif
2045
2046 /*
2047 * If we are asked to restart sequences, find all the sequences, lock them
2048 * (we need AccessExclusiveLock for ResetSequence), and check permissions.
2049 * We want to do this early since it's pointless to do all the truncation
2050 * work only to fail on sequence permissions.
2051 */
2052 if (restart_seqs)
2053 {
2054 foreach(cell, rels)
2055 {
2056 Relation rel = (Relation) lfirst(cell);
2057 List *seqlist = getOwnedSequences(RelationGetRelid(rel));
2058 ListCell *seqcell;
2059
2060 foreach(seqcell, seqlist)
2061 {
2062 Oid seq_relid = lfirst_oid(seqcell);
2063 Relation seq_rel;
2064
2065 seq_rel = relation_open(seq_relid, AccessExclusiveLock);
2066
2067 /* This check must match AlterSequence! */
2068 if (!object_ownercheck(RelationRelationId, seq_relid, GetUserId()))
2070 RelationGetRelationName(seq_rel));
2071
2072 seq_relids = lappend_oid(seq_relids, seq_relid);
2073
2074 relation_close(seq_rel, NoLock);
2075 }
2076 }
2077 }
2078
2079 /* Prepare to catch AFTER triggers. */
2081
2082 /*
2083 * To fire triggers, we'll need an EState as well as a ResultRelInfo for
2084 * each relation. We don't need to call ExecOpenIndices, though.
2085 *
2086 * We put the ResultRelInfos in the es_opened_result_relations list, even
2087 * though we don't have a range table and don't populate the
2088 * es_result_relations array. That's a bit bogus, but it's enough to make
2089 * ExecGetTriggerResultRel() find them.
2090 */
2091 estate = CreateExecutorState();
2092 resultRelInfos = (ResultRelInfo *)
2093 palloc(list_length(rels) * sizeof(ResultRelInfo));
2094 resultRelInfo = resultRelInfos;
2095 foreach(cell, rels)
2096 {
2097 Relation rel = (Relation) lfirst(cell);
2098
2099 InitResultRelInfo(resultRelInfo,
2100 rel,
2101 0, /* dummy rangetable index */
2102 NULL,
2103 0);
2105 lappend(estate->es_opened_result_relations, resultRelInfo);
2106 resultRelInfo++;
2107 }
2108
2109 /*
2110 * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
2111 * truncating (this is because one of them might throw an error). Also, if
2112 * we were to allow them to prevent statement execution, that would need
2113 * to be handled here.
2114 */
2115 resultRelInfo = resultRelInfos;
2116 foreach(cell, rels)
2117 {
2118 UserContext ucxt;
2119
2120 if (run_as_table_owner)
2121 SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
2122 &ucxt);
2123 ExecBSTruncateTriggers(estate, resultRelInfo);
2124 if (run_as_table_owner)
2125 RestoreUserContext(&ucxt);
2126 resultRelInfo++;
2127 }
2128
2129 /*
2130 * OK, truncate each table.
2131 */
2132 mySubid = GetCurrentSubTransactionId();
2133
2134 foreach(cell, rels)
2135 {
2136 Relation rel = (Relation) lfirst(cell);
2137
2138 /* Skip partitioned tables as there is nothing to do */
2139 if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2140 continue;
2141
2142 /*
2143 * Build the lists of foreign tables belonging to each foreign server
2144 * and pass each list to the foreign data wrapper's callback function,
2145 * so that each server can truncate its all foreign tables in bulk.
2146 * Each list is saved as a single entry in a hash table that uses the
2147 * server OID as lookup key.
2148 */
2149 if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2150 {
2152 bool found;
2153 ForeignTruncateInfo *ft_info;
2154
2155 /* First time through, initialize hashtable for foreign tables */
2156 if (!ft_htab)
2157 {
2158 HASHCTL hctl;
2159
2160 memset(&hctl, 0, sizeof(HASHCTL));
2161 hctl.keysize = sizeof(Oid);
2162 hctl.entrysize = sizeof(ForeignTruncateInfo);
2164
2165 ft_htab = hash_create("TRUNCATE for Foreign Tables",
2166 32, /* start small and extend */
2167 &hctl,
2169 }
2170
2171 /* Find or create cached entry for the foreign table */
2172 ft_info = hash_search(ft_htab, &serverid, HASH_ENTER, &found);
2173 if (!found)
2174 ft_info->rels = NIL;
2175
2176 /*
2177 * Save the foreign table in the entry of the server that the
2178 * foreign table belongs to.
2179 */
2180 ft_info->rels = lappend(ft_info->rels, rel);
2181 continue;
2182 }
2183
2184 /*
2185 * Normally, we need a transaction-safe truncation here. However, if
2186 * the table was either created in the current (sub)transaction or has
2187 * a new relfilenumber in the current (sub)transaction, then we can
2188 * just truncate it in-place, because a rollback would cause the whole
2189 * table or the current physical file to be thrown away anyway.
2190 */
2191 if (rel->rd_createSubid == mySubid ||
2192 rel->rd_newRelfilelocatorSubid == mySubid)
2193 {
2194 /* Immediate, non-rollbackable truncation is OK */
2196 }
2197 else
2198 {
2199 Oid heap_relid;
2200 Oid toast_relid;
2201 ReindexParams reindex_params = {0};
2202
2203 /*
2204 * This effectively deletes all rows in the table, and may be done
2205 * in a serializable transaction. In that case we must record a
2206 * rw-conflict in to this transaction from each transaction
2207 * holding a predicate lock on the table.
2208 */
2210
2211 /*
2212 * Need the full transaction-safe pushups.
2213 *
2214 * Create a new empty storage file for the relation, and assign it
2215 * as the relfilenumber value. The old storage file is scheduled
2216 * for deletion at commit.
2217 */
2218 RelationSetNewRelfilenumber(rel, rel->rd_rel->relpersistence);
2219
2220 heap_relid = RelationGetRelid(rel);
2221
2222 /*
2223 * The same for the toast table, if any.
2224 */
2225 toast_relid = rel->rd_rel->reltoastrelid;
2226 if (OidIsValid(toast_relid))
2227 {
2228 Relation toastrel = relation_open(toast_relid,
2230
2232 toastrel->rd_rel->relpersistence);
2233 table_close(toastrel, NoLock);
2234 }
2235
2236 /*
2237 * Reconstruct the indexes to match, and we're done.
2238 */
2240 &reindex_params);
2241 }
2242
2244 }
2245
2246 /* Now go through the hash table, and truncate foreign tables */
2247 if (ft_htab)
2248 {
2249 ForeignTruncateInfo *ft_info;
2250 HASH_SEQ_STATUS seq;
2251
2252 hash_seq_init(&seq, ft_htab);
2253
2254 PG_TRY();
2255 {
2256 while ((ft_info = hash_seq_search(&seq)) != NULL)
2257 {
2258 FdwRoutine *routine = GetFdwRoutineByServerId(ft_info->serverid);
2259
2260 /* truncate_check_rel() has checked that already */
2261 Assert(routine->ExecForeignTruncate != NULL);
2262
2263 routine->ExecForeignTruncate(ft_info->rels,
2264 behavior,
2265 restart_seqs);
2266 }
2267 }
2268 PG_FINALLY();
2269 {
2270 hash_destroy(ft_htab);
2271 }
2272 PG_END_TRY();
2273 }
2274
2275 /*
2276 * Restart owned sequences if we were asked to.
2277 */
2278 foreach(cell, seq_relids)
2279 {
2280 Oid seq_relid = lfirst_oid(cell);
2281
2282 ResetSequence(seq_relid);
2283 }
2284
2285 /*
2286 * Write a WAL record to allow this set of actions to be logically
2287 * decoded.
2288 *
2289 * Assemble an array of relids so we can write a single WAL record for the
2290 * whole action.
2291 */
2292 if (relids_logged != NIL)
2293 {
2294 xl_heap_truncate xlrec;
2295 int i = 0;
2296
2297 /* should only get here if wal_level >= logical */
2299
2300 logrelids = palloc(list_length(relids_logged) * sizeof(Oid));
2301 foreach(cell, relids_logged)
2302 logrelids[i++] = lfirst_oid(cell);
2303
2304 xlrec.dbId = MyDatabaseId;
2305 xlrec.nrelids = list_length(relids_logged);
2306 xlrec.flags = 0;
2307 if (behavior == DROP_CASCADE)
2308 xlrec.flags |= XLH_TRUNCATE_CASCADE;
2309 if (restart_seqs)
2311
2314 XLogRegisterData(logrelids, list_length(relids_logged) * sizeof(Oid));
2315
2317
2318 (void) XLogInsert(RM_HEAP_ID, XLOG_HEAP_TRUNCATE);
2319 }
2320
2321 /*
2322 * Process all AFTER STATEMENT TRUNCATE triggers.
2323 */
2324 resultRelInfo = resultRelInfos;
2325 foreach(cell, rels)
2326 {
2327 UserContext ucxt;
2328
2329 if (run_as_table_owner)
2330 SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
2331 &ucxt);
2332 ExecASTruncateTriggers(estate, resultRelInfo);
2333 if (run_as_table_owner)
2334 RestoreUserContext(&ucxt);
2335 resultRelInfo++;
2336 }
2337
2338 /* Handle queued AFTER triggers */
2339 AfterTriggerEndQuery(estate);
2340
2341 /* We can clean up the EState now */
2342 FreeExecutorState(estate);
2343
2344 /*
2345 * Close any rels opened by CASCADE (can't do this while EState still
2346 * holds refs)
2347 */
2348 rels = list_difference_ptr(rels, explicit_rels);
2349 foreach(cell, rels)
2350 {
2351 Relation rel = (Relation) lfirst(cell);
2352
2353 table_close(rel, NoLock);
2354 }
2355}
uint32 SubTransactionId
Definition: c.h:627
void ResetSequence(Oid seq_relid)
Definition: sequence.c:262
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:955
void hash_destroy(HTAB *hashp)
Definition: dynahash.c:865
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1420
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:352
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1385
#define PG_TRY(...)
Definition: elog.h:372
#define PG_END_TRY(...)
Definition: elog.h:397
#define PG_FINALLY(...)
Definition: elog.h:389
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, ResultRelInfo *partition_root_rri, int instrument_options)
Definition: execMain.c:1329
void FreeExecutorState(EState *estate)
Definition: execUtils.c:193
EState * CreateExecutorState(void)
Definition: execUtils.c:88
struct ResultRelInfo ResultRelInfo
FdwRoutine * GetFdwRoutineByServerId(Oid serverid)
Definition: foreign.c:377
Oid GetForeignServerIdByRelId(Oid relid)
Definition: foreign.c:355
Oid MyDatabaseId
Definition: globals.c:95
List * heap_truncate_find_FKs(List *relationIds)
Definition: heap.c:3673
void heap_truncate_check_FKs(List *relations, bool tempTables)
Definition: heap.c:3578
void heap_truncate_one_rel(Relation rel)
Definition: heap.c:3534
#define XLOG_HEAP_TRUNCATE
Definition: heapam_xlog.h:36
#define XLH_TRUNCATE_RESTART_SEQS
Definition: heapam_xlog.h:127
#define SizeOfHeapTruncate
Definition: heapam_xlog.h:142
#define XLH_TRUNCATE_CASCADE
Definition: heapam_xlog.h:126
@ HASH_ENTER
Definition: hsearch.h:114
#define HASH_CONTEXT
Definition: hsearch.h:102
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params)
Definition: index.c:3948
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:159
List * list_difference_ptr(const List *list1, const List *list2)
Definition: list.c:1263
List * list_copy(const List *oldlist)
Definition: list.c:1573
MemoryContext CurrentMemoryContext
Definition: mcxt.c:159
@ DROP_CASCADE
Definition: parsenodes.h:2391
@ DROP_RESTRICT
Definition: parsenodes.h:2390
@ OBJECT_SEQUENCE
Definition: parsenodes.h:2354
List * getOwnedSequences(Oid relid)
Definition: pg_depend.c:936
void pgstat_count_truncate(Relation rel)
void CheckTableForSerializableConflictIn(Relation relation)
Definition: predicate.c:4419
void RelationSetNewRelfilenumber(Relation relation, char persistence)
Definition: relcache.c:3773
List * es_opened_result_relations
Definition: execnodes.h:686
ExecForeignTruncate_function ExecForeignTruncate
Definition: fdwapi.h:263
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76
MemoryContext hcxt
Definition: hsearch.h:86
Definition: dynahash.c:220
SubTransactionId rd_newRelfilelocatorSubid
Definition: rel.h:104
SubTransactionId rd_createSubid
Definition: rel.h:103
Relation ri_RelationDesc
Definition: execnodes.h:475
struct ForeignTruncateInfo ForeignTruncateInfo
static void truncate_check_perms(Oid relid, Form_pg_class reltuple)
Definition: tablecmds.c:2410
void ExecBSTruncateTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:3231
void ExecASTruncateTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:3278
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:5088
void AfterTriggerBeginQuery(void)
Definition: trigger.c:5053
void SwitchToUntrustedUser(Oid userid, UserContext *context)
Definition: usercontext.c:33
void RestoreUserContext(UserContext *context)
Definition: usercontext.c:87
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:791
#define XLogLogicalInfoActive()
Definition: xlog.h:126
#define XLOG_INCLUDE_ORIGIN
Definition: xlog.h:154
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:474
void XLogRegisterData(const void *data, uint32 len)
Definition: xloginsert.c:364
void XLogSetRecordFlags(uint8 flags)
Definition: xloginsert.c:456
void XLogBeginInsert(void)
Definition: xloginsert.c:149

References AccessExclusiveLock, aclcheck_error(), ACLCHECK_NOT_OWNER, AfterTriggerBeginQuery(), AfterTriggerEndQuery(), Assert(), CheckTableForSerializableConflictIn(), CreateExecutorState(), CurrentMemoryContext, xl_heap_truncate::dbId, DROP_CASCADE, DROP_RESTRICT, HASHCTL::entrysize, ereport, errmsg(), EState::es_opened_result_relations, ExecASTruncateTriggers(), ExecBSTruncateTriggers(), FdwRoutine::ExecForeignTruncate, xl_heap_truncate::flags, FreeExecutorState(), GetCurrentSubTransactionId(), GetFdwRoutineByServerId(), GetForeignServerIdByRelId(), getOwnedSequences(), GetUserId(), HASH_BLOBS, HASH_CONTEXT, hash_create(), hash_destroy(), HASH_ELEM, HASH_ENTER, hash_search(), hash_seq_init(), hash_seq_search(), HASHCTL::hcxt, heap_truncate_check_FKs(), heap_truncate_find_FKs(), heap_truncate_one_rel(), i, InitResultRelInfo(), HASHCTL::keysize, lappend(), lappend_oid(), lfirst, lfirst_oid, list_copy(), list_difference_ptr(), list_length(), MyDatabaseId, NIL, NoLock, NOTICE, xl_heap_truncate::nrelids, object_ownercheck(), OBJECT_SEQUENCE, OidIsValid, palloc(), PG_END_TRY, PG_FINALLY, PG_TRY, pgstat_count_truncate(), RelationData::rd_createSubid, RelationData::rd_newRelfilelocatorSubid, RelationData::rd_rel, REINDEX_REL_PROCESS_TOAST, reindex_relation(), relation_close(), relation_open(), RelationGetRelationName, RelationGetRelid, RelationIsLogicallyLogged, RelationSetNewRelfilenumber(), ForeignTruncateInfo::rels, ResetSequence(), RestoreUserContext(), ResultRelInfo::ri_RelationDesc, ForeignTruncateInfo::serverid, SizeOfHeapTruncate, SwitchToUntrustedUser(), table_close(), table_open(), truncate_check_activity(), truncate_check_perms(), truncate_check_rel(), XLH_TRUNCATE_CASCADE, XLH_TRUNCATE_RESTART_SEQS, XLOG_HEAP_TRUNCATE, XLOG_INCLUDE_ORIGIN, XLogBeginInsert(), XLogInsert(), XLogLogicalInfoActive, XLogRegisterData(), and XLogSetRecordFlags().

Referenced by apply_handle_truncate(), and ExecuteTruncate().

◆ find_composite_type_dependencies()

void find_composite_type_dependencies ( Oid  typeOid,
Relation  origRelation,
const char *  origTypeName 
)

Definition at line 6926 of file tablecmds.c.

6928{
6929 Relation depRel;
6930 ScanKeyData key[2];
6931 SysScanDesc depScan;
6932 HeapTuple depTup;
6933
6934 /* since this function recurses, it could be driven to stack overflow */
6936
6937 /*
6938 * We scan pg_depend to find those things that depend on the given type.
6939 * (We assume we can ignore refobjsubid for a type.)
6940 */
6941 depRel = table_open(DependRelationId, AccessShareLock);
6942
6943 ScanKeyInit(&key[0],
6944 Anum_pg_depend_refclassid,
6945 BTEqualStrategyNumber, F_OIDEQ,
6946 ObjectIdGetDatum(TypeRelationId));
6947 ScanKeyInit(&key[1],
6948 Anum_pg_depend_refobjid,
6949 BTEqualStrategyNumber, F_OIDEQ,
6950 ObjectIdGetDatum(typeOid));
6951
6952 depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
6953 NULL, 2, key);
6954
6955 while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
6956 {
6957 Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
6958 Relation rel;
6959 TupleDesc tupleDesc;
6961
6962 /* Check for directly dependent types */
6963 if (pg_depend->classid == TypeRelationId)
6964 {
6965 /*
6966 * This must be an array, domain, or range containing the given
6967 * type, so recursively check for uses of this type. Note that
6968 * any error message will mention the original type not the
6969 * container; this is intentional.
6970 */
6971 find_composite_type_dependencies(pg_depend->objid,
6972 origRelation, origTypeName);
6973 continue;
6974 }
6975
6976 /* Else, ignore dependees that aren't relations */
6977 if (pg_depend->classid != RelationRelationId)
6978 continue;
6979
6980 rel = relation_open(pg_depend->objid, AccessShareLock);
6981 tupleDesc = RelationGetDescr(rel);
6982
6983 /*
6984 * If objsubid identifies a specific column, refer to that in error
6985 * messages. Otherwise, search to see if there's a user column of the
6986 * type. (We assume system columns are never of interesting types.)
6987 * The search is needed because an index containing an expression
6988 * column of the target type will just be recorded as a whole-relation
6989 * dependency. If we do not find a column of the type, the dependency
6990 * must indicate that the type is transiently referenced in an index
6991 * expression but not stored on disk, which we assume is OK, just as
6992 * we do for references in views. (It could also be that the target
6993 * type is embedded in some container type that is stored in an index
6994 * column, but the previous recursion should catch such cases.)
6995 */
6996 if (pg_depend->objsubid > 0 && pg_depend->objsubid <= tupleDesc->natts)
6997 att = TupleDescAttr(tupleDesc, pg_depend->objsubid - 1);
6998 else
6999 {
7000 att = NULL;
7001 for (int attno = 1; attno <= tupleDesc->natts; attno++)
7002 {
7003 att = TupleDescAttr(tupleDesc, attno - 1);
7004 if (att->atttypid == typeOid && !att->attisdropped)
7005 break;
7006 att = NULL;
7007 }
7008 if (att == NULL)
7009 {
7010 /* No such column, so assume OK */
7012 continue;
7013 }
7014 }
7015
7016 /*
7017 * We definitely should reject if the relation has storage. If it's
7018 * partitioned, then perhaps we don't have to reject: if there are
7019 * partitions then we'll fail when we find one, else there is no
7020 * stored data to worry about. However, it's possible that the type
7021 * change would affect conclusions about whether the type is sortable
7022 * or hashable and thus (if it's a partitioning column) break the
7023 * partitioning rule. For now, reject for partitioned rels too.
7024 */
7025 if (RELKIND_HAS_STORAGE(rel->rd_rel->relkind) ||
7026 RELKIND_HAS_PARTITIONS(rel->rd_rel->relkind))
7027 {
7028 if (origTypeName)
7029 ereport(ERROR,
7030 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7031 errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
7032 origTypeName,
7034 NameStr(att->attname))));
7035 else if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
7036 ereport(ERROR,
7037 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7038 errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
7039 RelationGetRelationName(origRelation),
7041 NameStr(att->attname))));
7042 else if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
7043 ereport(ERROR,
7044 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7045 errmsg("cannot alter foreign table \"%s\" because column \"%s.%s\" uses its row type",
7046 RelationGetRelationName(origRelation),
7048 NameStr(att->attname))));
7049 else
7050 ereport(ERROR,
7051 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7052 errmsg("cannot alter table \"%s\" because column \"%s.%s\" uses its row type",
7053 RelationGetRelationName(origRelation),
7055 NameStr(att->attname))));
7056 }
7057 else if (OidIsValid(rel->rd_rel->reltype))
7058 {
7059 /*
7060 * A view or composite type itself isn't a problem, but we must
7061 * recursively check for indirect dependencies via its rowtype.
7062 */
7064 origRelation, origTypeName);
7065 }
7066
7068 }
7069
7070 systable_endscan(depScan);
7071
7073}
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:603
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:514
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:388
FormData_pg_depend * Form_pg_depend
Definition: pg_depend.h:72
void check_stack_depth(void)
Definition: stack_depth.c:95
void find_composite_type_dependencies(Oid typeOid, Relation origRelation, const char *origTypeName)
Definition: tablecmds.c:6926

References AccessShareLock, BTEqualStrategyNumber, check_stack_depth(), ereport, errcode(), errmsg(), ERROR, find_composite_type_dependencies(), GETSTRUCT(), HeapTupleIsValid, sort-test::key, NameStr, TupleDescData::natts, ObjectIdGetDatum(), OidIsValid, RelationData::rd_rel, relation_close(), relation_open(), RelationGetDescr, RelationGetRelationName, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), table_open(), and TupleDescAttr().

Referenced by ATPrepAlterColumnType(), ATRewriteTables(), find_composite_type_dependencies(), and get_rels_with_domain().

◆ PartConstraintImpliedByRelConstraint()

bool PartConstraintImpliedByRelConstraint ( Relation  scanrel,
List partConstraint 
)

Definition at line 19972 of file tablecmds.c.

19974{
19975 List *existConstraint = NIL;
19976 TupleConstr *constr = RelationGetDescr(scanrel)->constr;
19977 int i;
19978
19979 if (constr && constr->has_not_null)
19980 {
19981 int natts = scanrel->rd_att->natts;
19982
19983 for (i = 1; i <= natts; i++)
19984 {
19985 CompactAttribute *att = TupleDescCompactAttr(scanrel->rd_att, i - 1);
19986
19987 /* invalid not-null constraint must be ignored here */
19988 if (att->attnullability == ATTNULLABLE_VALID && !att->attisdropped)
19989 {
19990 Form_pg_attribute wholeatt = TupleDescAttr(scanrel->rd_att, i - 1);
19991 NullTest *ntest = makeNode(NullTest);
19992
19993 ntest->arg = (Expr *) makeVar(1,
19994 i,
19995 wholeatt->atttypid,
19996 wholeatt->atttypmod,
19997 wholeatt->attcollation,
19998 0);
19999 ntest->nulltesttype = IS_NOT_NULL;
20000
20001 /*
20002 * argisrow=false is correct even for a composite column,
20003 * because attnotnull does not represent a SQL-spec IS NOT
20004 * NULL test in such a case, just IS DISTINCT FROM NULL.
20005 */
20006 ntest->argisrow = false;
20007 ntest->location = -1;
20008 existConstraint = lappend(existConstraint, ntest);
20009 }
20010 }
20011 }
20012
20013 return ConstraintImpliedByRelConstraint(scanrel, partConstraint, existConstraint);
20014}
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
@ IS_NOT_NULL
Definition: primnodes.h:1957
bool attisdropped
Definition: tupdesc.h:77
char attnullability
Definition: tupdesc.h:79
NullTestType nulltesttype
Definition: primnodes.h:1964
ParseLoc location
Definition: primnodes.h:1967
Expr * arg
Definition: primnodes.h:1963
TupleDesc rd_att
Definition: rel.h:112
bool has_not_null
Definition: tupdesc.h:45
static bool ConstraintImpliedByRelConstraint(Relation scanrel, List *testConstraint, List *provenConstraint)
Definition: tablecmds.c:20027
#define ATTNULLABLE_VALID
Definition: tupdesc.h:86
static CompactAttribute * TupleDescCompactAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:175

References NullTest::arg, CompactAttribute::attisdropped, CompactAttribute::attnullability, ATTNULLABLE_VALID, ConstraintImpliedByRelConstraint(), TupleConstr::has_not_null, i, IS_NOT_NULL, lappend(), NullTest::location, makeNode, makeVar(), TupleDescData::natts, NIL, NullTest::nulltesttype, RelationData::rd_att, RelationGetDescr, TupleDescAttr(), and TupleDescCompactAttr().

Referenced by check_default_partition_contents(), DetachAddConstraintIfNeeded(), and QueuePartitionConstraintValidation().

◆ PreCommit_on_commit_actions()

void PreCommit_on_commit_actions ( void  )

Definition at line 19243 of file tablecmds.c.

19244{
19245 ListCell *l;
19246 List *oids_to_truncate = NIL;
19247 List *oids_to_drop = NIL;
19248
19249 foreach(l, on_commits)
19250 {
19251 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
19252
19253 /* Ignore entry if already dropped in this xact */
19255 continue;
19256
19257 switch (oc->oncommit)
19258 {
19259 case ONCOMMIT_NOOP:
19261 /* Do nothing (there shouldn't be such entries, actually) */
19262 break;
19264
19265 /*
19266 * If this transaction hasn't accessed any temporary
19267 * relations, we can skip truncating ON COMMIT DELETE ROWS
19268 * tables, as they must still be empty.
19269 */
19271 oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
19272 break;
19273 case ONCOMMIT_DROP:
19274 oids_to_drop = lappend_oid(oids_to_drop, oc->relid);
19275 break;
19276 }
19277 }
19278
19279 /*
19280 * Truncate relations before dropping so that all dependencies between
19281 * relations are removed after they are worked on. Doing it like this
19282 * might be a waste as it is possible that a relation being truncated will
19283 * be dropped anyway due to its parent being dropped, but this makes the
19284 * code more robust because of not having to re-check that the relation
19285 * exists at truncation time.
19286 */
19287 if (oids_to_truncate != NIL)
19288 heap_truncate(oids_to_truncate);
19289
19290 if (oids_to_drop != NIL)
19291 {
19292 ObjectAddresses *targetObjects = new_object_addresses();
19293
19294 foreach(l, oids_to_drop)
19295 {
19296 ObjectAddress object;
19297
19298 object.classId = RelationRelationId;
19299 object.objectId = lfirst_oid(l);
19300 object.objectSubId = 0;
19301
19302 Assert(!object_address_present(&object, targetObjects));
19303
19304 add_exact_object_address(&object, targetObjects);
19305 }
19306
19307 /*
19308 * Object deletion might involve toast table access (to clean up
19309 * toasted catalog entries), so ensure we have a valid snapshot.
19310 */
19312
19313 /*
19314 * Since this is an automatic drop, rather than one directly initiated
19315 * by the user, we pass the PERFORM_DELETION_INTERNAL flag.
19316 */
19319
19321
19322#ifdef USE_ASSERT_CHECKING
19323
19324 /*
19325 * Note that table deletion will call remove_on_commit_action, so the
19326 * entry should get marked as deleted.
19327 */
19328 foreach(l, on_commits)
19329 {
19330 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
19331
19332 if (oc->oncommit != ONCOMMIT_DROP)
19333 continue;
19334
19336 }
19337#endif
19338 }
19339}
void performMultipleDeletions(const ObjectAddresses *objects, DropBehavior behavior, int flags)
Definition: dependency.c:332
#define PERFORM_DELETION_QUIETLY
Definition: dependency.h:94
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:92
void heap_truncate(List *relids)
Definition: heap.c:3493
@ ONCOMMIT_DELETE_ROWS
Definition: primnodes.h:60
@ ONCOMMIT_PRESERVE_ROWS
Definition: primnodes.h:59
@ ONCOMMIT_DROP
Definition: primnodes.h:61
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:271
void PushActiveSnapshot(Snapshot snapshot)
Definition: snapmgr.c:669
void PopActiveSnapshot(void)
Definition: snapmgr.c:762
OnCommitAction oncommit
Definition: tablecmds.c:118
int MyXactFlags
Definition: xact.c:136
#define XACT_FLAGS_ACCESSEDTEMPNAMESPACE
Definition: xact.h:102

References add_exact_object_address(), Assert(), ObjectAddress::classId, OnCommitItem::deleting_subid, DROP_CASCADE, GetTransactionSnapshot(), heap_truncate(), InvalidSubTransactionId, lappend_oid(), lfirst, lfirst_oid, MyXactFlags, new_object_addresses(), NIL, object_address_present(), on_commits, OnCommitItem::oncommit, ONCOMMIT_DELETE_ROWS, ONCOMMIT_DROP, ONCOMMIT_NOOP, ONCOMMIT_PRESERVE_ROWS, PERFORM_DELETION_INTERNAL, PERFORM_DELETION_QUIETLY, performMultipleDeletions(), PopActiveSnapshot(), PushActiveSnapshot(), OnCommitItem::relid, and XACT_FLAGS_ACCESSEDTEMPNAMESPACE.

Referenced by CommitTransaction(), and PrepareTransaction().

◆ RangeVarCallbackMaintainsTable()

void RangeVarCallbackMaintainsTable ( const RangeVar relation,
Oid  relId,
Oid  oldRelId,
void *  arg 
)

Definition at line 19417 of file tablecmds.c.

19419{
19420 char relkind;
19421 AclResult aclresult;
19422
19423 /* Nothing to do if the relation was not found. */
19424 if (!OidIsValid(relId))
19425 return;
19426
19427 /*
19428 * If the relation does exist, check whether it's an index. But note that
19429 * the relation might have been dropped between the time we did the name
19430 * lookup and now. In that case, there's nothing to do.
19431 */
19432 relkind = get_rel_relkind(relId);
19433 if (!relkind)
19434 return;
19435 if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
19436 relkind != RELKIND_MATVIEW && relkind != RELKIND_PARTITIONED_TABLE)
19437 ereport(ERROR,
19438 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19439 errmsg("\"%s\" is not a table or materialized view", relation->relname)));
19440
19441 /* Check permissions */
19442 aclresult = pg_class_aclcheck(relId, GetUserId(), ACL_MAINTAIN);
19443 if (aclresult != ACLCHECK_OK)
19444 aclcheck_error(aclresult,
19446 relation->relname);
19447}
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4024
#define ACL_MAINTAIN
Definition: parsenodes.h:90
char * relname
Definition: primnodes.h:83

References ACL_MAINTAIN, aclcheck_error(), ACLCHECK_OK, ereport, errcode(), errmsg(), ERROR, get_rel_relkind(), get_relkind_objtype(), GetUserId(), OidIsValid, pg_class_aclcheck(), and RangeVar::relname.

Referenced by cluster(), ExecRefreshMatView(), and ReindexTable().

◆ RangeVarCallbackOwnsRelation()

void RangeVarCallbackOwnsRelation ( const RangeVar relation,
Oid  relId,
Oid  oldRelId,
void *  arg 
)

Definition at line 19477 of file tablecmds.c.

19479{
19480 HeapTuple tuple;
19481
19482 /* Nothing to do if the relation was not found. */
19483 if (!OidIsValid(relId))
19484 return;
19485
19486 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
19487 if (!HeapTupleIsValid(tuple)) /* should not happen */
19488 elog(ERROR, "cache lookup failed for relation %u", relId);
19489
19490 if (!object_ownercheck(RelationRelationId, relId, GetUserId()))
19492 relation->relname);
19493
19494 if (!allowSystemTableMods &&
19495 IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
19496 ereport(ERROR,
19497 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
19498 errmsg("permission denied: \"%s\" is a system catalog",
19499 relation->relname)));
19500
19501 ReleaseSysCache(tuple);
19502}
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
Definition: catalog.c:86

References aclcheck_error(), ACLCHECK_NOT_OWNER, allowSystemTableMods, elog, ereport, errcode(), errmsg(), ERROR, get_rel_relkind(), get_relkind_objtype(), GETSTRUCT(), GetUserId(), HeapTupleIsValid, IsSystemClass(), object_ownercheck(), ObjectIdGetDatum(), OidIsValid, ReleaseSysCache(), RangeVar::relname, and SearchSysCache1().

Referenced by AlterSequence(), and ProcessUtilitySlow().

◆ register_on_commit_action()

void register_on_commit_action ( Oid  relid,
OnCommitAction  action 
)

Definition at line 19184 of file tablecmds.c.

19185{
19186 OnCommitItem *oc;
19187 MemoryContext oldcxt;
19188
19189 /*
19190 * We needn't bother registering the relation unless there is an ON COMMIT
19191 * action we need to take.
19192 */
19194 return;
19195
19197
19198 oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
19199 oc->relid = relid;
19200 oc->oncommit = action;
19203
19204 /*
19205 * We use lcons() here so that ON COMMIT actions are processed in reverse
19206 * order of registration. That might not be essential but it seems
19207 * reasonable.
19208 */
19210
19211 MemoryContextSwitchTo(oldcxt);
19212}
List * lcons(void *datum, List *list)
Definition: list.c:495
MemoryContext CacheMemoryContext
Definition: mcxt.c:168
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124

References generate_unaccent_rules::action, CacheMemoryContext, OnCommitItem::creating_subid, OnCommitItem::deleting_subid, GetCurrentSubTransactionId(), InvalidSubTransactionId, lcons(), MemoryContextSwitchTo(), on_commits, OnCommitItem::oncommit, ONCOMMIT_NOOP, ONCOMMIT_PRESERVE_ROWS, palloc(), and OnCommitItem::relid.

Referenced by heap_create_with_catalog().

◆ remove_on_commit_action()

void remove_on_commit_action ( Oid  relid)

Definition at line 19220 of file tablecmds.c.

19221{
19222 ListCell *l;
19223
19224 foreach(l, on_commits)
19225 {
19226 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
19227
19228 if (oc->relid == relid)
19229 {
19231 break;
19232 }
19233 }
19234}

References OnCommitItem::deleting_subid, GetCurrentSubTransactionId(), lfirst, on_commits, and OnCommitItem::relid.

Referenced by heap_drop_with_catalog().

◆ RemoveRelations()

void RemoveRelations ( DropStmt drop)

Definition at line 1528 of file tablecmds.c.

1529{
1530 ObjectAddresses *objects;
1531 char relkind;
1532 ListCell *cell;
1533 int flags = 0;
1534 LOCKMODE lockmode = AccessExclusiveLock;
1535
1536 /* DROP CONCURRENTLY uses a weaker lock, and has some restrictions */
1537 if (drop->concurrent)
1538 {
1539 /*
1540 * Note that for temporary relations this lock may get upgraded later
1541 * on, but as no other session can access a temporary relation, this
1542 * is actually fine.
1543 */
1544 lockmode = ShareUpdateExclusiveLock;
1545 Assert(drop->removeType == OBJECT_INDEX);
1546 if (list_length(drop->objects) != 1)
1547 ereport(ERROR,
1548 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1549 errmsg("DROP INDEX CONCURRENTLY does not support dropping multiple objects")));
1550 if (drop->behavior == DROP_CASCADE)
1551 ereport(ERROR,
1552 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1553 errmsg("DROP INDEX CONCURRENTLY does not support CASCADE")));
1554 }
1555
1556 /*
1557 * First we identify all the relations, then we delete them in a single
1558 * performMultipleDeletions() call. This is to avoid unwanted DROP
1559 * RESTRICT errors if one of the relations depends on another.
1560 */
1561
1562 /* Determine required relkind */
1563 switch (drop->removeType)
1564 {
1565 case OBJECT_TABLE:
1566 relkind = RELKIND_RELATION;
1567 break;
1568
1569 case OBJECT_INDEX:
1570 relkind = RELKIND_INDEX;
1571 break;
1572
1573 case OBJECT_SEQUENCE:
1574 relkind = RELKIND_SEQUENCE;
1575 break;
1576
1577 case OBJECT_VIEW:
1578 relkind = RELKIND_VIEW;
1579 break;
1580
1581 case OBJECT_MATVIEW:
1582 relkind = RELKIND_MATVIEW;
1583 break;
1584
1586 relkind = RELKIND_FOREIGN_TABLE;
1587 break;
1588
1589 default:
1590 elog(ERROR, "unrecognized drop object type: %d",
1591 (int) drop->removeType);
1592 relkind = 0; /* keep compiler quiet */
1593 break;
1594 }
1595
1596 /* Lock and validate each relation; build a list of object addresses */
1597 objects = new_object_addresses();
1598
1599 foreach(cell, drop->objects)
1600 {
1601 RangeVar *rel = makeRangeVarFromNameList((List *) lfirst(cell));
1602 Oid relOid;
1603 ObjectAddress obj;
1605
1606 /*
1607 * These next few steps are a great deal like relation_openrv, but we
1608 * don't bother building a relcache entry since we don't need it.
1609 *
1610 * Check for shared-cache-inval messages before trying to access the
1611 * relation. This is needed to cover the case where the name
1612 * identifies a rel that has been dropped and recreated since the
1613 * start of our transaction: if we don't flush the old syscache entry,
1614 * then we'll latch onto that entry and suffer an error later.
1615 */
1617
1618 /* Look up the appropriate relation using namespace search. */
1619 state.expected_relkind = relkind;
1620 state.heap_lockmode = drop->concurrent ?
1622 /* We must initialize these fields to show that no locks are held: */
1623 state.heapOid = InvalidOid;
1624 state.partParentOid = InvalidOid;
1625
1626 relOid = RangeVarGetRelidExtended(rel, lockmode, RVR_MISSING_OK,
1628 &state);
1629
1630 /* Not there? */
1631 if (!OidIsValid(relOid))
1632 {
1633 DropErrorMsgNonExistent(rel, relkind, drop->missing_ok);
1634 continue;
1635 }
1636
1637 /*
1638 * Decide if concurrent mode needs to be used here or not. The
1639 * callback retrieved the rel's persistence for us.
1640 */
1641 if (drop->concurrent &&
1642 state.actual_relpersistence != RELPERSISTENCE_TEMP)
1643 {
1644 Assert(list_length(drop->objects) == 1 &&
1645 drop->removeType == OBJECT_INDEX);
1647 }
1648
1649 /*
1650 * Concurrent index drop cannot be used with partitioned indexes,
1651 * either.
1652 */
1653 if ((flags & PERFORM_DELETION_CONCURRENTLY) != 0 &&
1654 state.actual_relkind == RELKIND_PARTITIONED_INDEX)
1655 ereport(ERROR,
1656 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1657 errmsg("cannot drop partitioned index \"%s\" concurrently",
1658 rel->relname)));
1659
1660 /*
1661 * If we're told to drop a partitioned index, we must acquire lock on
1662 * all the children of its parent partitioned table before proceeding.
1663 * Otherwise we'd try to lock the child index partitions before their
1664 * tables, leading to potential deadlock against other sessions that
1665 * will lock those objects in the other order.
1666 */
1667 if (state.actual_relkind == RELKIND_PARTITIONED_INDEX)
1668 (void) find_all_inheritors(state.heapOid,
1669 state.heap_lockmode,
1670 NULL);
1671
1672 /* OK, we're ready to delete this one */
1673 obj.classId = RelationRelationId;
1674 obj.objectId = relOid;
1675 obj.objectSubId = 0;
1676
1677 add_exact_object_address(&obj, objects);
1678 }
1679
1680 performMultipleDeletions(objects, drop->behavior, flags);
1681
1682 free_object_addresses(objects);
1683}
#define PERFORM_DELETION_CONCURRENTLY
Definition: dependency.h:93
void AcceptInvalidationMessages(void)
Definition: inval.c:930
RangeVar * makeRangeVarFromNameList(const List *names)
Definition: namespace.c:3554
@ OBJECT_FOREIGN_TABLE
Definition: parsenodes.h:2335
@ OBJECT_VIEW
Definition: parsenodes.h:2368
bool missing_ok
Definition: parsenodes.h:3326
List * objects
Definition: parsenodes.h:3323
ObjectType removeType
Definition: parsenodes.h:3324
bool concurrent
Definition: parsenodes.h:3327
DropBehavior behavior
Definition: parsenodes.h:3325
Definition: regguts.h:323
static void DropErrorMsgNonExistent(RangeVar *rel, char rightkind, bool missing_ok)
Definition: tablecmds.c:1453
static void RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid, Oid oldRelOid, void *arg)
Definition: tablecmds.c:1692

References AcceptInvalidationMessages(), AccessExclusiveLock, add_exact_object_address(), Assert(), DropStmt::behavior, ObjectAddress::classId, DropStmt::concurrent, DROP_CASCADE, DropErrorMsgNonExistent(), elog, ereport, errcode(), errmsg(), ERROR, find_all_inheritors(), free_object_addresses(), InvalidOid, lfirst, list_length(), makeRangeVarFromNameList(), DropStmt::missing_ok, new_object_addresses(), OBJECT_FOREIGN_TABLE, OBJECT_INDEX, OBJECT_MATVIEW, OBJECT_SEQUENCE, OBJECT_TABLE, OBJECT_VIEW, ObjectAddress::objectId, DropStmt::objects, ObjectAddress::objectSubId, OidIsValid, PERFORM_DELETION_CONCURRENTLY, performMultipleDeletions(), RangeVarCallbackForDropRelation(), RangeVarGetRelidExtended(), RangeVar::relname, DropStmt::removeType, RVR_MISSING_OK, and ShareUpdateExclusiveLock.

Referenced by ExecDropStmt().

◆ renameatt()

ObjectAddress renameatt ( RenameStmt stmt)

Definition at line 3999 of file tablecmds.c.

4000{
4001 Oid relid;
4003 ObjectAddress address;
4004
4005 /* lock level taken here should match renameatt_internal */
4007 stmt->missing_ok ? RVR_MISSING_OK : 0,
4009 NULL);
4010
4011 if (!OidIsValid(relid))
4012 {
4014 (errmsg("relation \"%s\" does not exist, skipping",
4015 stmt->relation->relname)));
4016 return InvalidObjectAddress;
4017 }
4018
4019 attnum =
4020 renameatt_internal(relid,
4021 stmt->subname, /* old att name */
4022 stmt->newname, /* new att name */
4023 stmt->relation->inh, /* recursive? */
4024 false, /* recursing? */
4025 0, /* expected inhcount */
4026 stmt->behavior);
4027
4028 ObjectAddressSubSet(address, RelationRelationId, relid, attnum);
4029
4030 return address;
4031}
#define ObjectAddressSubSet(addr, class_id, object_id, object_sub_id)
Definition: objectaddress.h:33
static AttrNumber renameatt_internal(Oid myrelid, const char *oldattname, const char *newattname, bool recurse, bool recursing, int expected_parents, DropBehavior behavior)
Definition: tablecmds.c:3834
static void RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:3979

References AccessExclusiveLock, attnum, ereport, errmsg(), InvalidObjectAddress, NOTICE, ObjectAddressSubSet, OidIsValid, RangeVarCallbackForRenameAttribute(), RangeVarGetRelidExtended(), renameatt_internal(), RVR_MISSING_OK, and stmt.

Referenced by ExecRenameStmt().

◆ RenameConstraint()

ObjectAddress RenameConstraint ( RenameStmt stmt)

Definition at line 4146 of file tablecmds.c.

4147{
4148 Oid relid = InvalidOid;
4149 Oid typid = InvalidOid;
4150
4151 if (stmt->renameType == OBJECT_DOMCONSTRAINT)
4152 {
4153 Relation rel;
4154 HeapTuple tup;
4155
4156 typid = typenameTypeId(NULL, makeTypeNameFromNameList(castNode(List, stmt->object)));
4157 rel = table_open(TypeRelationId, RowExclusiveLock);
4158 tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
4159 if (!HeapTupleIsValid(tup))
4160 elog(ERROR, "cache lookup failed for type %u", typid);
4161 checkDomainOwner(tup);
4162 ReleaseSysCache(tup);
4163 table_close(rel, NoLock);
4164 }
4165 else
4166 {
4167 /* lock level taken here should match rename_constraint_internal */
4169 stmt->missing_ok ? RVR_MISSING_OK : 0,
4171 NULL);
4172 if (!OidIsValid(relid))
4173 {
4175 (errmsg("relation \"%s\" does not exist, skipping",
4176 stmt->relation->relname)));
4177 return InvalidObjectAddress;
4178 }
4179 }
4180
4181 return
4182 rename_constraint_internal(relid, typid,
4183 stmt->subname,
4184 stmt->newname,
4185 (stmt->relation &&
4186 stmt->relation->inh), /* recursive? */
4187 false, /* recursing? */
4188 0 /* expected inhcount */ );
4189}
TypeName * makeTypeNameFromNameList(List *names)
Definition: makefuncs.c:531
#define castNode(_type_, nodeptr)
Definition: nodes.h:182
@ OBJECT_DOMCONSTRAINT
Definition: parsenodes.h:2330
static ObjectAddress rename_constraint_internal(Oid myrelid, Oid mytypid, const char *oldconname, const char *newconname, bool recurse, bool recursing, int expected_parents)
Definition: tablecmds.c:4037
void checkDomainOwner(HeapTuple tup)
Definition: typecmds.c:3477

References AccessExclusiveLock, castNode, checkDomainOwner(), elog, ereport, errmsg(), ERROR, HeapTupleIsValid, InvalidObjectAddress, InvalidOid, makeTypeNameFromNameList(), NoLock, NOTICE, OBJECT_DOMCONSTRAINT, ObjectIdGetDatum(), OidIsValid, RangeVarCallbackForRenameAttribute(), RangeVarGetRelidExtended(), ReleaseSysCache(), rename_constraint_internal(), RowExclusiveLock, RVR_MISSING_OK, SearchSysCache1(), stmt, table_close(), table_open(), and typenameTypeId().

Referenced by ExecRenameStmt().

◆ RenameRelation()

ObjectAddress RenameRelation ( RenameStmt stmt)

Definition at line 4196 of file tablecmds.c.

4197{
4198 bool is_index_stmt = stmt->renameType == OBJECT_INDEX;
4199 Oid relid;
4200 ObjectAddress address;
4201
4202 /*
4203 * Grab an exclusive lock on the target table, index, sequence, view,
4204 * materialized view, or foreign table, which we will NOT release until
4205 * end of transaction.
4206 *
4207 * Lock level used here should match RenameRelationInternal, to avoid lock
4208 * escalation. However, because ALTER INDEX can be used with any relation
4209 * type, we mustn't believe without verification.
4210 */
4211 for (;;)
4212 {
4213 LOCKMODE lockmode;
4214 char relkind;
4215 bool obj_is_index;
4216
4217 lockmode = is_index_stmt ? ShareUpdateExclusiveLock : AccessExclusiveLock;
4218
4219 relid = RangeVarGetRelidExtended(stmt->relation, lockmode,
4220 stmt->missing_ok ? RVR_MISSING_OK : 0,
4222 stmt);
4223
4224 if (!OidIsValid(relid))
4225 {
4227 (errmsg("relation \"%s\" does not exist, skipping",
4228 stmt->relation->relname)));
4229 return InvalidObjectAddress;
4230 }
4231
4232 /*
4233 * We allow mismatched statement and object types (e.g., ALTER INDEX
4234 * to rename a table), but we might've used the wrong lock level. If
4235 * that happens, retry with the correct lock level. We don't bother
4236 * if we already acquired AccessExclusiveLock with an index, however.
4237 */
4238 relkind = get_rel_relkind(relid);
4239 obj_is_index = (relkind == RELKIND_INDEX ||
4240 relkind == RELKIND_PARTITIONED_INDEX);
4241 if (obj_is_index || is_index_stmt == obj_is_index)
4242 break;
4243
4244 UnlockRelationOid(relid, lockmode);
4245 is_index_stmt = obj_is_index;
4246 }
4247
4248 /* Do the work */
4249 RenameRelationInternal(relid, stmt->newname, false, is_index_stmt);
4250
4251 ObjectAddressSet(address, RelationRelationId, relid);
4252
4253 return address;
4254}
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:229
void RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
Definition: tablecmds.c:4260

References AccessExclusiveLock, ereport, errmsg(), get_rel_relkind(), InvalidObjectAddress, NOTICE, OBJECT_INDEX, ObjectAddressSet, OidIsValid, RangeVarCallbackForAlterRelation(), RangeVarGetRelidExtended(), RenameRelationInternal(), RVR_MISSING_OK, ShareUpdateExclusiveLock, stmt, and UnlockRelationOid().

Referenced by ExecRenameStmt().

◆ RenameRelationInternal()

void RenameRelationInternal ( Oid  myrelid,
const char *  newrelname,
bool  is_internal,
bool  is_index 
)

Definition at line 4260 of file tablecmds.c.

4261{
4262 Relation targetrelation;
4263 Relation relrelation; /* for RELATION relation */
4264 ItemPointerData otid;
4265 HeapTuple reltup;
4266 Form_pg_class relform;
4267 Oid namespaceId;
4268
4269 /*
4270 * Grab a lock on the target relation, which we will NOT release until end
4271 * of transaction. We need at least a self-exclusive lock so that
4272 * concurrent DDL doesn't overwrite the rename if they start updating
4273 * while still seeing the old version. The lock also guards against
4274 * triggering relcache reloads in concurrent sessions, which might not
4275 * handle this information changing under them. For indexes, we can use a
4276 * reduced lock level because RelationReloadIndexInfo() handles indexes
4277 * specially.
4278 */
4279 targetrelation = relation_open(myrelid, is_index ? ShareUpdateExclusiveLock : AccessExclusiveLock);
4280 namespaceId = RelationGetNamespace(targetrelation);
4281
4282 /*
4283 * Find relation's pg_class tuple, and make sure newrelname isn't in use.
4284 */
4285 relrelation = table_open(RelationRelationId, RowExclusiveLock);
4286
4287 reltup = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(myrelid));
4288 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
4289 elog(ERROR, "cache lookup failed for relation %u", myrelid);
4290 otid = reltup->t_self;
4291 relform = (Form_pg_class) GETSTRUCT(reltup);
4292
4293 if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
4294 ereport(ERROR,
4295 (errcode(ERRCODE_DUPLICATE_TABLE),
4296 errmsg("relation \"%s\" already exists",
4297 newrelname)));
4298
4299 /*
4300 * RenameRelation is careful not to believe the caller's idea of the
4301 * relation kind being handled. We don't have to worry about this, but
4302 * let's not be totally oblivious to it. We can process an index as
4303 * not-an-index, but not the other way around.
4304 */
4305 Assert(!is_index ||
4306 is_index == (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
4307 targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX));
4308
4309 /*
4310 * Update pg_class tuple with new relname. (Scribbling on reltup is OK
4311 * because it's a copy...)
4312 */
4313 namestrcpy(&(relform->relname), newrelname);
4314
4315 CatalogTupleUpdate(relrelation, &otid, reltup);
4316 UnlockTuple(relrelation, &otid, InplaceUpdateTupleLock);
4317
4318 InvokeObjectPostAlterHookArg(RelationRelationId, myrelid, 0,
4319 InvalidOid, is_internal);
4320
4321 heap_freetuple(reltup);
4322 table_close(relrelation, RowExclusiveLock);
4323
4324 /*
4325 * Also rename the associated type, if any.
4326 */
4327 if (OidIsValid(targetrelation->rd_rel->reltype))
4328 RenameTypeInternal(targetrelation->rd_rel->reltype,
4329 newrelname, namespaceId);
4330
4331 /*
4332 * Also rename the associated constraint, if any.
4333 */
4334 if (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
4335 targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
4336 {
4337 Oid constraintId = get_index_constraint(myrelid);
4338
4339 if (OidIsValid(constraintId))
4340 RenameConstraintById(constraintId, newrelname);
4341 }
4342
4343 /*
4344 * Close rel, but keep lock!
4345 */
4346 relation_close(targetrelation, NoLock);
4347}
void namestrcpy(Name name, const char *str)
Definition: name.c:233
#define InvokeObjectPostAlterHookArg(classId, objectId, subId, auxiliaryId, is_internal)
Definition: objectaccess.h:200
void RenameConstraintById(Oid conId, const char *newname)
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:988
void RenameTypeInternal(Oid typeOid, const char *newTypeName, Oid typeNamespace)
Definition: pg_type.c:765

References AccessExclusiveLock, Assert(), CatalogTupleUpdate(), elog, ereport, errcode(), errmsg(), ERROR, get_index_constraint(), get_relname_relid(), GETSTRUCT(), heap_freetuple(), HeapTupleIsValid, InplaceUpdateTupleLock, InvalidOid, InvokeObjectPostAlterHookArg, namestrcpy(), NoLock, ObjectIdGetDatum(), OidIsValid, RelationData::rd_rel, relation_close(), relation_open(), RelationGetNamespace, RenameConstraintById(), RenameTypeInternal(), RowExclusiveLock, SearchSysCacheLockedCopy1(), ShareUpdateExclusiveLock, HeapTupleData::t_self, table_close(), table_open(), and UnlockTuple().

Referenced by ATExecAddIndexConstraint(), finish_heap_swap(), rename_constraint_internal(), RenameRelation(), and RenameType().

◆ ResetRelRewrite()

void ResetRelRewrite ( Oid  myrelid)

Definition at line 4353 of file tablecmds.c.

4354{
4355 Relation relrelation; /* for RELATION relation */
4356 HeapTuple reltup;
4357 Form_pg_class relform;
4358
4359 /*
4360 * Find relation's pg_class tuple.
4361 */
4362 relrelation = table_open(RelationRelationId, RowExclusiveLock);
4363
4364 reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
4365 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
4366 elog(ERROR, "cache lookup failed for relation %u", myrelid);
4367 relform = (Form_pg_class) GETSTRUCT(reltup);
4368
4369 /*
4370 * Update pg_class tuple.
4371 */
4372 relform->relrewrite = InvalidOid;
4373
4374 CatalogTupleUpdate(relrelation, &reltup->t_self, reltup);
4375
4376 heap_freetuple(reltup);
4377 table_close(relrelation, RowExclusiveLock);
4378}
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:91

References CatalogTupleUpdate(), elog, ERROR, GETSTRUCT(), heap_freetuple(), HeapTupleIsValid, InvalidOid, ObjectIdGetDatum(), RowExclusiveLock, SearchSysCacheCopy1, HeapTupleData::t_self, table_close(), and table_open().

Referenced by finish_heap_swap().

◆ SetRelationHasSubclass()

void SetRelationHasSubclass ( Oid  relationId,
bool  relhassubclass 
)

Definition at line 3637 of file tablecmds.c.

3638{
3639 Relation relationRelation;
3640 HeapTuple tuple;
3641 Form_pg_class classtuple;
3642
3644 ShareUpdateExclusiveLock, false) ||
3645 CheckRelationOidLockedByMe(relationId,
3646 ShareRowExclusiveLock, true));
3647
3648 /*
3649 * Fetch a modifiable copy of the tuple, modify it, update pg_class.
3650 */
3651 relationRelation = table_open(RelationRelationId, RowExclusiveLock);
3652 tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
3653 if (!HeapTupleIsValid(tuple))
3654 elog(ERROR, "cache lookup failed for relation %u", relationId);
3655 classtuple = (Form_pg_class) GETSTRUCT(tuple);
3656
3657 if (classtuple->relhassubclass != relhassubclass)
3658 {
3659 classtuple->relhassubclass = relhassubclass;
3660 CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
3661 }
3662 else
3663 {
3664 /* no need to change tuple, but force relcache rebuild anyway */
3666 }
3667
3668 heap_freetuple(tuple);
3669 table_close(relationRelation, RowExclusiveLock);
3670}
void CacheInvalidateRelcacheByTuple(HeapTuple classTuple)
Definition: inval.c:1665
bool CheckRelationOidLockedByMe(Oid relid, LOCKMODE lockmode, bool orstronger)
Definition: lmgr.c:351

References Assert(), CacheInvalidateRelcacheByTuple(), CatalogTupleUpdate(), CheckRelationOidLockedByMe(), elog, ERROR, GETSTRUCT(), heap_freetuple(), HeapTupleIsValid, ObjectIdGetDatum(), RowExclusiveLock, SearchSysCacheCopy1, ShareRowExclusiveLock, ShareUpdateExclusiveLock, HeapTupleData::t_self, table_close(), and table_open().

Referenced by acquire_inherited_sample_rows(), index_create(), IndexSetParentIndex(), and StoreCatalogInheritance1().

◆ SetRelationTableSpace()

void SetRelationTableSpace ( Relation  rel,
Oid  newTableSpaceId,
RelFileNumber  newRelFilenumber 
)

Definition at line 3740 of file tablecmds.c.

3743{
3744 Relation pg_class;
3745 HeapTuple tuple;
3746 ItemPointerData otid;
3747 Form_pg_class rd_rel;
3748 Oid reloid = RelationGetRelid(rel);
3749
3750 Assert(CheckRelationTableSpaceMove(rel, newTableSpaceId));
3751
3752 /* Get a modifiable copy of the relation's pg_class row. */
3753 pg_class = table_open(RelationRelationId, RowExclusiveLock);
3754
3755 tuple = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(reloid));
3756 if (!HeapTupleIsValid(tuple))
3757 elog(ERROR, "cache lookup failed for relation %u", reloid);
3758 otid = tuple->t_self;
3759 rd_rel = (Form_pg_class) GETSTRUCT(tuple);
3760
3761 /* Update the pg_class row. */
3762 rd_rel->reltablespace = (newTableSpaceId == MyDatabaseTableSpace) ?
3763 InvalidOid : newTableSpaceId;
3764 if (RelFileNumberIsValid(newRelFilenumber))
3765 rd_rel->relfilenode = newRelFilenumber;
3766 CatalogTupleUpdate(pg_class, &otid, tuple);
3767 UnlockTuple(pg_class, &otid, InplaceUpdateTupleLock);
3768
3769 /*
3770 * Record dependency on tablespace. This is only required for relations
3771 * that have no physical storage.
3772 */
3773 if (!RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
3774 changeDependencyOnTablespace(RelationRelationId, reloid,
3775 rd_rel->reltablespace);
3776
3777 heap_freetuple(tuple);
3778 table_close(pg_class, RowExclusiveLock);
3779}
void changeDependencyOnTablespace(Oid classId, Oid objectId, Oid newTablespaceId)
Definition: pg_shdepend.c:391
#define RelFileNumberIsValid(relnumber)
Definition: relpath.h:27
bool CheckRelationTableSpaceMove(Relation rel, Oid newTableSpaceId)
Definition: tablecmds.c:3683

References Assert(), CatalogTupleUpdate(), changeDependencyOnTablespace(), CheckRelationTableSpaceMove(), elog, ERROR, GETSTRUCT(), heap_freetuple(), HeapTupleIsValid, InplaceUpdateTupleLock, InvalidOid, MyDatabaseTableSpace, ObjectIdGetDatum(), RelationData::rd_rel, RelationGetRelid, RelFileNumberIsValid, RowExclusiveLock, SearchSysCacheLockedCopy1(), HeapTupleData::t_self, table_close(), table_open(), and UnlockTuple().

Referenced by ATExecSetTableSpace(), ATExecSetTableSpaceNoStorage(), and reindex_index().