Thanks to visit codestin.com
Credit goes to doxygen.postgresql.org

PostgreSQL Source Code git master
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.

Typedefs

typedef struct AlterTableUtilityContext AlterTableUtilityContext
 

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, 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)
 

Typedef Documentation

◆ AlterTableUtilityContext

Definition at line 24 of file tablecmds.h.

Function Documentation

◆ AlterRelationNamespaceInternal()

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

Definition at line 19020 of file tablecmds.c.

19024{
19025 HeapTuple classTup;
19026 Form_pg_class classForm;
19027 ObjectAddress thisobj;
19028 bool already_done = false;
19029
19030 /* no rel lock for relkind=c so use LOCKTAG_TUPLE */
19031 classTup = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(relOid));
19032 if (!HeapTupleIsValid(classTup))
19033 elog(ERROR, "cache lookup failed for relation %u", relOid);
19034 classForm = (Form_pg_class) GETSTRUCT(classTup);
19035
19036 Assert(classForm->relnamespace == oldNspOid);
19037
19038 thisobj.classId = RelationRelationId;
19039 thisobj.objectId = relOid;
19040 thisobj.objectSubId = 0;
19041
19042 /*
19043 * If the object has already been moved, don't move it again. If it's
19044 * already in the right place, don't move it, but still fire the object
19045 * access hook.
19046 */
19047 already_done = object_address_present(&thisobj, objsMoved);
19048 if (!already_done && oldNspOid != newNspOid)
19049 {
19050 ItemPointerData otid = classTup->t_self;
19051
19052 /* check for duplicate name (more friendly than unique-index failure) */
19053 if (get_relname_relid(NameStr(classForm->relname),
19054 newNspOid) != InvalidOid)
19055 ereport(ERROR,
19056 (errcode(ERRCODE_DUPLICATE_TABLE),
19057 errmsg("relation \"%s\" already exists in schema \"%s\"",
19058 NameStr(classForm->relname),
19059 get_namespace_name(newNspOid))));
19060
19061 /* classTup is a copy, so OK to scribble on */
19062 classForm->relnamespace = newNspOid;
19063
19064 CatalogTupleUpdate(classRel, &otid, classTup);
19065 UnlockTuple(classRel, &otid, InplaceUpdateTupleLock);
19066
19067
19068 /* Update dependency on schema if caller said so */
19069 if (hasDependEntry &&
19070 changeDependencyFor(RelationRelationId,
19071 relOid,
19072 NamespaceRelationId,
19073 oldNspOid,
19074 newNspOid) != 1)
19075 elog(ERROR, "could not change schema dependency for relation \"%s\"",
19076 NameStr(classForm->relname));
19077 }
19078 else
19079 UnlockTuple(classRel, &classTup->t_self, InplaceUpdateTupleLock);
19080 if (!already_done)
19081 {
19082 add_exact_object_address(&thisobj, objsMoved);
19083
19084 InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
19085 }
19086
19087 heap_freetuple(classTup);
19088}
#define NameStr(name)
Definition: c.h:752
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2619
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2559
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:150
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, const ItemPointerData *tid, LOCKMODE lockmode)
Definition: lmgr.c:601
#define InplaceUpdateTupleLock
Definition: lockdefs.h:48
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3533
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:2052
#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:262
#define InvalidOid
Definition: postgres_ext.h:37
ItemPointerData t_self
Definition: htup.h:65
HeapTuple SearchSysCacheLockedCopy1(int cacheId, Datum key1)
Definition: syscache.c:399

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,
AlterTableUtilityContext context 
)

Definition at line 4527 of file tablecmds.c.

4529{
4530 Relation rel;
4531
4532 /* Caller is required to provide an adequate lock. */
4533 rel = relation_open(context->relid, NoLock);
4534
4536
4537 ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
4538}
#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:4442
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:4863

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

Referenced by ProcessUtilitySlow().

◆ AlterTableGetLockLevel()

LOCKMODE AlterTableGetLockLevel ( List cmds)

Definition at line 4601 of file tablecmds.c.

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

4557{
4558 Relation rel;
4559 LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
4560
4561 rel = relation_open(relid, lockmode);
4562
4564
4565 ATController(NULL, rel, cmds, recurse, lockmode, NULL);
4566}
void EventTriggerAlterTableRelid(Oid objectId)
LOCKMODE AlterTableGetLockLevel(List *cmds)
Definition: tablecmds.c:4601

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

Referenced by AlterTableMoveAll(), and DefineVirtualRelation().

◆ AlterTableLookupRelation()

Oid AlterTableLookupRelation ( AlterTableStmt stmt,
LOCKMODE  lockmode 
)

Definition at line 4468 of file tablecmds.c.

4469{
4470 return RangeVarGetRelidExtended(stmt->relation, lockmode,
4471 stmt->missing_ok ? RVR_MISSING_OK : 0,
4473 stmt);
4474}
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:440
@ RVR_MISSING_OK
Definition: namespace.h:90
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:19552

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

Referenced by ProcessUtilitySlow().

◆ AlterTableMoveAll()

Oid AlterTableMoveAll ( AlterTableMoveAllStmt stmt)

Definition at line 16953 of file tablecmds.c.

16954{
16955 List *relations = NIL;
16956 ListCell *l;
16957 ScanKeyData key[1];
16958 Relation rel;
16959 TableScanDesc scan;
16960 HeapTuple tuple;
16961 Oid orig_tablespaceoid;
16962 Oid new_tablespaceoid;
16963 List *role_oids = roleSpecsToIds(stmt->roles);
16964
16965 /* Ensure we were not asked to move something we can't */
16966 if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
16967 stmt->objtype != OBJECT_MATVIEW)
16968 ereport(ERROR,
16969 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
16970 errmsg("only tables, indexes, and materialized views exist in tablespaces")));
16971
16972 /* Get the orig and new tablespace OIDs */
16973 orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
16974 new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
16975
16976 /* Can't move shared relations in to or out of pg_global */
16977 /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
16978 if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
16979 new_tablespaceoid == GLOBALTABLESPACE_OID)
16980 ereport(ERROR,
16981 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
16982 errmsg("cannot move relations in to or out of pg_global tablespace")));
16983
16984 /*
16985 * Must have CREATE rights on the new tablespace, unless it is the
16986 * database default tablespace (which all users implicitly have CREATE
16987 * rights on).
16988 */
16989 if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
16990 {
16991 AclResult aclresult;
16992
16993 aclresult = object_aclcheck(TableSpaceRelationId, new_tablespaceoid, GetUserId(),
16994 ACL_CREATE);
16995 if (aclresult != ACLCHECK_OK)
16997 get_tablespace_name(new_tablespaceoid));
16998 }
16999
17000 /*
17001 * Now that the checks are done, check if we should set either to
17002 * InvalidOid because it is our database's default tablespace.
17003 */
17004 if (orig_tablespaceoid == MyDatabaseTableSpace)
17005 orig_tablespaceoid = InvalidOid;
17006
17007 if (new_tablespaceoid == MyDatabaseTableSpace)
17008 new_tablespaceoid = InvalidOid;
17009
17010 /* no-op */
17011 if (orig_tablespaceoid == new_tablespaceoid)
17012 return new_tablespaceoid;
17013
17014 /*
17015 * Walk the list of objects in the tablespace and move them. This will
17016 * only find objects in our database, of course.
17017 */
17018 ScanKeyInit(&key[0],
17019 Anum_pg_class_reltablespace,
17020 BTEqualStrategyNumber, F_OIDEQ,
17021 ObjectIdGetDatum(orig_tablespaceoid));
17022
17023 rel = table_open(RelationRelationId, AccessShareLock);
17024 scan = table_beginscan_catalog(rel, 1, key);
17025 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
17026 {
17027 Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
17028 Oid relOid = relForm->oid;
17029
17030 /*
17031 * Do not move objects in pg_catalog as part of this, if an admin
17032 * really wishes to do so, they can issue the individual ALTER
17033 * commands directly.
17034 *
17035 * Also, explicitly avoid any shared tables, temp tables, or TOAST
17036 * (TOAST will be moved with the main table).
17037 */
17038 if (IsCatalogNamespace(relForm->relnamespace) ||
17039 relForm->relisshared ||
17040 isAnyTempNamespace(relForm->relnamespace) ||
17041 IsToastNamespace(relForm->relnamespace))
17042 continue;
17043
17044 /* Only move the object type requested */
17045 if ((stmt->objtype == OBJECT_TABLE &&
17046 relForm->relkind != RELKIND_RELATION &&
17047 relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
17048 (stmt->objtype == OBJECT_INDEX &&
17049 relForm->relkind != RELKIND_INDEX &&
17050 relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
17051 (stmt->objtype == OBJECT_MATVIEW &&
17052 relForm->relkind != RELKIND_MATVIEW))
17053 continue;
17054
17055 /* Check if we are only moving objects owned by certain roles */
17056 if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
17057 continue;
17058
17059 /*
17060 * Handle permissions-checking here since we are locking the tables
17061 * and also to avoid doing a bunch of work only to fail part-way. Note
17062 * that permissions will also be checked by AlterTableInternal().
17063 *
17064 * Caller must be considered an owner on the table to move it.
17065 */
17066 if (!object_ownercheck(RelationRelationId, relOid, GetUserId()))
17068 NameStr(relForm->relname));
17069
17070 if (stmt->nowait &&
17072 ereport(ERROR,
17073 (errcode(ERRCODE_OBJECT_IN_USE),
17074 errmsg("aborting because lock on relation \"%s.%s\" is not available",
17075 get_namespace_name(relForm->relnamespace),
17076 NameStr(relForm->relname))));
17077 else
17079
17080 /* Add to our list of objects to move */
17081 relations = lappend_oid(relations, relOid);
17082 }
17083
17084 table_endscan(scan);
17086
17087 if (relations == NIL)
17089 (errcode(ERRCODE_NO_DATA_FOUND),
17090 errmsg("no matching relations in tablespace \"%s\" found",
17091 orig_tablespaceoid == InvalidOid ? "(database default)" :
17092 get_tablespace_name(orig_tablespaceoid))));
17093
17094 /* Everything is locked, loop through and move all of the relations. */
17095 foreach(l, relations)
17096 {
17097 List *cmds = NIL;
17099
17101 cmd->name = stmt->new_tablespacename;
17102
17103 cmds = lappend(cmds, cmd);
17104
17106 /* OID is set by AlterTableInternal */
17107 AlterTableInternal(lfirst_oid(l), cmds, false);
17109 }
17110
17111 return new_tablespaceoid;
17112}
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:2652
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:3834
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4088
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:775
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:96
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1346
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:2170
Oid GetUserId(void)
Definition: miscinit.c:469
bool isAnyTempNamespace(Oid namespaceId)
Definition: namespace.c:3757
#define makeNode(_type_)
Definition: nodes.h:161
ObjectType get_relkind_objtype(char relkind)
@ OBJECT_MATVIEW
Definition: parsenodes.h:2347
@ OBJECT_TABLESPACE
Definition: parsenodes.h:2366
@ OBJECT_INDEX
Definition: parsenodes.h:2344
@ OBJECT_TABLE
Definition: parsenodes.h:2365
#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:32
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, ScanKeyData *key)
Definition: tableam.c:113
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:985
void AlterTableInternal(Oid relid, List *cmds, bool recurse)
Definition: tablecmds.c:4556
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 18912 of file tablecmds.c.

18913{
18914 Relation rel;
18915 Oid relid;
18916 Oid oldNspOid;
18917 Oid nspOid;
18918 RangeVar *newrv;
18919 ObjectAddresses *objsMoved;
18920 ObjectAddress myself;
18921
18923 stmt->missing_ok ? RVR_MISSING_OK : 0,
18925 stmt);
18926
18927 if (!OidIsValid(relid))
18928 {
18930 (errmsg("relation \"%s\" does not exist, skipping",
18931 stmt->relation->relname)));
18932 return InvalidObjectAddress;
18933 }
18934
18935 rel = relation_open(relid, NoLock);
18936
18937 oldNspOid = RelationGetNamespace(rel);
18938
18939 /* If it's an owned sequence, disallow moving it by itself. */
18940 if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
18941 {
18942 Oid tableId;
18943 int32 colId;
18944
18945 if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
18946 sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
18947 ereport(ERROR,
18948 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
18949 errmsg("cannot move an owned sequence into another schema"),
18950 errdetail("Sequence \"%s\" is linked to table \"%s\".",
18952 get_rel_name(tableId))));
18953 }
18954
18955 /* Get and lock schema OID and check its permissions. */
18956 newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
18957 nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
18958
18959 /* common checks on switching namespaces */
18960 CheckSetNamespace(oldNspOid, nspOid);
18961
18962 objsMoved = new_object_addresses();
18963 AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
18964 free_object_addresses(objsMoved);
18965
18966 ObjectAddressSet(myself, RelationRelationId, relid);
18967
18968 if (oldschema)
18969 *oldschema = oldNspOid;
18970
18971 /* close rel, but keep lock until commit */
18972 relation_close(rel, NoLock);
18973
18974 return myself;
18975}
int32_t int32
Definition: c.h:535
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2513
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2799
@ DEPENDENCY_AUTO
Definition: dependency.h:34
@ DEPENDENCY_INTERNAL
Definition: dependency.h:35
int errdetail(const char *fmt,...)
Definition: elog.c:1207
char * get_rel_name(Oid relid)
Definition: lsyscache.c:2095
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:738
void CheckSetNamespace(Oid oldNspOid, Oid nspOid)
Definition: namespace.c:3529
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:548
#define RelationGetNamespace(relation)
Definition: rel.h:555
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:18983

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 18983 of file tablecmds.c.

18985{
18986 Relation classRel;
18987
18988 Assert(objsMoved != NULL);
18989
18990 /* OK, modify the pg_class row and pg_depend entry */
18991 classRel = table_open(RelationRelationId, RowExclusiveLock);
18992
18993 AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
18994 nspOid, true, objsMoved);
18995
18996 /* Fix the table's row type too, if it has one */
18997 if (OidIsValid(rel->rd_rel->reltype))
18998 AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid,
18999 false, /* isImplicitArray */
19000 false, /* ignoreDependent */
19001 false, /* errorOnTableType */
19002 objsMoved);
19003
19004 /* Fix other dependent stuff */
19005 AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
19006 AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
19007 objsMoved, AccessExclusiveLock);
19008 AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
19009 false, objsMoved);
19010
19011 table_close(classRel, RowExclusiveLock);
19012}
#define RowExclusiveLock
Definition: lockdefs.h:38
void AlterConstraintNamespaces(Oid ownerId, Oid oldNspId, Oid newNspId, bool isType, ObjectAddresses *objsMoved)
#define RelationGetRelid(relation)
Definition: rel.h:514
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
Definition: tablecmds.c:19020
static void AlterSeqNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved, LOCKMODE lockmode)
Definition: tablecmds.c:19142
static void AlterIndexNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:19097
Oid AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid, bool isImplicitArray, bool ignoreDependent, bool errorOnTableType, ObjectAddresses *objsMoved)
Definition: typecmds.c:4165

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 19425 of file tablecmds.c.

19427{
19428 ListCell *cur_item;
19429
19430 foreach(cur_item, on_commits)
19431 {
19432 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
19433
19434 if (!isCommit && oc->creating_subid == mySubid)
19435 {
19436 /* cur_item must be removed */
19438 pfree(oc);
19439 }
19440 else
19441 {
19442 /* cur_item must be preserved */
19443 if (oc->creating_subid == mySubid)
19444 oc->creating_subid = parentSubid;
19445 if (oc->deleting_subid == mySubid)
19446 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
19447 }
19448 }
19449}
#define InvalidSubTransactionId
Definition: c.h:664
void pfree(void *pointer)
Definition: mcxt.c:1594
#define foreach_delete_current(lst, var_or_cell)
Definition: pg_list.h:391
SubTransactionId creating_subid
Definition: tablecmds.c:128
SubTransactionId deleting_subid
Definition: tablecmds.c:129
static List * on_commits
Definition: tablecmds.c:132

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 19393 of file tablecmds.c.

19394{
19395 ListCell *cur_item;
19396
19397 foreach(cur_item, on_commits)
19398 {
19399 OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
19400
19401 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
19403 {
19404 /* cur_item must be removed */
19406 pfree(oc);
19407 }
19408 else
19409 {
19410 /* cur_item must be preserved */
19413 }
19414 }
19415}

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 16040 of file tablecmds.c.

16041{
16042 Relation target_rel;
16043 Relation class_rel;
16044 HeapTuple tuple;
16045 Form_pg_class tuple_class;
16046
16047 /*
16048 * Get exclusive lock till end of transaction on the target table. Use
16049 * relation_open so that we can work on indexes and sequences.
16050 */
16051 target_rel = relation_open(relationOid, lockmode);
16052
16053 /* Get its pg_class tuple, too */
16054 class_rel = table_open(RelationRelationId, RowExclusiveLock);
16055
16056 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
16057 if (!HeapTupleIsValid(tuple))
16058 elog(ERROR, "cache lookup failed for relation %u", relationOid);
16059 tuple_class = (Form_pg_class) GETSTRUCT(tuple);
16060
16061 /* Can we change the ownership of this tuple? */
16062 switch (tuple_class->relkind)
16063 {
16064 case RELKIND_RELATION:
16065 case RELKIND_VIEW:
16066 case RELKIND_MATVIEW:
16067 case RELKIND_FOREIGN_TABLE:
16068 case RELKIND_PARTITIONED_TABLE:
16069 /* ok to change owner */
16070 break;
16071 case RELKIND_INDEX:
16072 if (!recursing)
16073 {
16074 /*
16075 * Because ALTER INDEX OWNER used to be allowed, and in fact
16076 * is generated by old versions of pg_dump, we give a warning
16077 * and do nothing rather than erroring out. Also, to avoid
16078 * unnecessary chatter while restoring those old dumps, say
16079 * nothing at all if the command would be a no-op anyway.
16080 */
16081 if (tuple_class->relowner != newOwnerId)
16083 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16084 errmsg("cannot change owner of index \"%s\"",
16085 NameStr(tuple_class->relname)),
16086 errhint("Change the ownership of the index's table instead.")));
16087 /* quick hack to exit via the no-op path */
16088 newOwnerId = tuple_class->relowner;
16089 }
16090 break;
16091 case RELKIND_PARTITIONED_INDEX:
16092 if (recursing)
16093 break;
16094 ereport(ERROR,
16095 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16096 errmsg("cannot change owner of index \"%s\"",
16097 NameStr(tuple_class->relname)),
16098 errhint("Change the ownership of the index's table instead.")));
16099 break;
16100 case RELKIND_SEQUENCE:
16101 if (!recursing &&
16102 tuple_class->relowner != newOwnerId)
16103 {
16104 /* if it's an owned sequence, disallow changing it by itself */
16105 Oid tableId;
16106 int32 colId;
16107
16108 if (sequenceIsOwned(relationOid, DEPENDENCY_AUTO, &tableId, &colId) ||
16109 sequenceIsOwned(relationOid, DEPENDENCY_INTERNAL, &tableId, &colId))
16110 ereport(ERROR,
16111 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
16112 errmsg("cannot change owner of sequence \"%s\"",
16113 NameStr(tuple_class->relname)),
16114 errdetail("Sequence \"%s\" is linked to table \"%s\".",
16115 NameStr(tuple_class->relname),
16116 get_rel_name(tableId))));
16117 }
16118 break;
16119 case RELKIND_COMPOSITE_TYPE:
16120 if (recursing)
16121 break;
16122 ereport(ERROR,
16123 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16124 errmsg("\"%s\" is a composite type",
16125 NameStr(tuple_class->relname)),
16126 /* translator: %s is an SQL ALTER command */
16127 errhint("Use %s instead.",
16128 "ALTER TYPE")));
16129 break;
16130 case RELKIND_TOASTVALUE:
16131 if (recursing)
16132 break;
16133 /* FALL THRU */
16134 default:
16135 ereport(ERROR,
16136 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16137 errmsg("cannot change owner of relation \"%s\"",
16138 NameStr(tuple_class->relname)),
16139 errdetail_relkind_not_supported(tuple_class->relkind)));
16140 }
16141
16142 /*
16143 * If the new owner is the same as the existing owner, consider the
16144 * command to have succeeded. This is for dump restoration purposes.
16145 */
16146 if (tuple_class->relowner != newOwnerId)
16147 {
16148 Datum repl_val[Natts_pg_class];
16149 bool repl_null[Natts_pg_class];
16150 bool repl_repl[Natts_pg_class];
16151 Acl *newAcl;
16152 Datum aclDatum;
16153 bool isNull;
16154 HeapTuple newtuple;
16155
16156 /* skip permission checks when recursing to index or toast table */
16157 if (!recursing)
16158 {
16159 /* Superusers can always do it */
16160 if (!superuser())
16161 {
16162 Oid namespaceOid = tuple_class->relnamespace;
16163 AclResult aclresult;
16164
16165 /* Otherwise, must be owner of the existing object */
16166 if (!object_ownercheck(RelationRelationId, relationOid, GetUserId()))
16168 RelationGetRelationName(target_rel));
16169
16170 /* Must be able to become new owner */
16171 check_can_set_role(GetUserId(), newOwnerId);
16172
16173 /* New owner must have CREATE privilege on namespace */
16174 aclresult = object_aclcheck(NamespaceRelationId, namespaceOid, newOwnerId,
16175 ACL_CREATE);
16176 if (aclresult != ACLCHECK_OK)
16177 aclcheck_error(aclresult, OBJECT_SCHEMA,
16178 get_namespace_name(namespaceOid));
16179 }
16180 }
16181
16182 memset(repl_null, false, sizeof(repl_null));
16183 memset(repl_repl, false, sizeof(repl_repl));
16184
16185 repl_repl[Anum_pg_class_relowner - 1] = true;
16186 repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
16187
16188 /*
16189 * Determine the modified ACL for the new owner. This is only
16190 * necessary when the ACL is non-null.
16191 */
16192 aclDatum = SysCacheGetAttr(RELOID, tuple,
16193 Anum_pg_class_relacl,
16194 &isNull);
16195 if (!isNull)
16196 {
16197 newAcl = aclnewowner(DatumGetAclP(aclDatum),
16198 tuple_class->relowner, newOwnerId);
16199 repl_repl[Anum_pg_class_relacl - 1] = true;
16200 repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
16201 }
16202
16203 newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
16204
16205 CatalogTupleUpdate(class_rel, &newtuple->t_self, newtuple);
16206
16207 heap_freetuple(newtuple);
16208
16209 /*
16210 * We must similarly update any per-column ACLs to reflect the new
16211 * owner; for neatness reasons that's split out as a subroutine.
16212 */
16213 change_owner_fix_column_acls(relationOid,
16214 tuple_class->relowner,
16215 newOwnerId);
16216
16217 /*
16218 * Update owner dependency reference, if any. A composite type has
16219 * none, because it's tracked for the pg_type entry instead of here;
16220 * indexes and TOAST tables don't have their own entries either.
16221 */
16222 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
16223 tuple_class->relkind != RELKIND_INDEX &&
16224 tuple_class->relkind != RELKIND_PARTITIONED_INDEX &&
16225 tuple_class->relkind != RELKIND_TOASTVALUE)
16226 changeDependencyOnOwner(RelationRelationId, relationOid,
16227 newOwnerId);
16228
16229 /*
16230 * Also change the ownership of the table's row type, if it has one
16231 */
16232 if (OidIsValid(tuple_class->reltype))
16233 AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId);
16234
16235 /*
16236 * If we are operating on a table or materialized view, also change
16237 * the ownership of any indexes and sequences that belong to the
16238 * relation, as well as its toast table (if it has one).
16239 */
16240 if (tuple_class->relkind == RELKIND_RELATION ||
16241 tuple_class->relkind == RELKIND_PARTITIONED_TABLE ||
16242 tuple_class->relkind == RELKIND_MATVIEW ||
16243 tuple_class->relkind == RELKIND_TOASTVALUE)
16244 {
16245 List *index_oid_list;
16246 ListCell *i;
16247
16248 /* Find all the indexes belonging to this relation */
16249 index_oid_list = RelationGetIndexList(target_rel);
16250
16251 /* For each index, recursively change its ownership */
16252 foreach(i, index_oid_list)
16253 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
16254
16255 list_free(index_oid_list);
16256 }
16257
16258 /* If it has a toast table, recurse to change its ownership */
16259 if (tuple_class->reltoastrelid != InvalidOid)
16260 ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
16261 true, lockmode);
16262
16263 /* If it has dependent sequences, recurse to change them too */
16264 change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
16265 }
16266
16267 InvokeObjectPostAlterHook(RelationRelationId, relationOid, 0);
16268
16269 ReleaseSysCache(tuple);
16270 table_close(class_rel, RowExclusiveLock);
16271 relation_close(target_rel, NoLock);
16272}
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition: acl.c:1119
void check_can_set_role(Oid member, Oid role)
Definition: acl.c:5341
#define DatumGetAclP(X)
Definition: acl.h:120
int errhint(const char *fmt,...)
Definition: elog.c:1321
#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:2360
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:332
uint64_t Datum
Definition: postgres.h:70
#define RelationGetDescr(relation)
Definition: rel.h:540
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4836
bool superuser(void)
Definition: superuser.c:46
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:264
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:220
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:595
void ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
Definition: tablecmds.c:16040
static void change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
Definition: tablecmds.c:16346
static void change_owner_fix_column_acls(Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
Definition: tablecmds.c:16281
void AlterTypeOwnerInternal(Oid typeOid, Oid newOwnerId)
Definition: typecmds.c:3996

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 1371 of file tablecmds.c.

1372{
1373 int natts;
1375 ListCell *l;
1376 TupleDesc desc;
1377 char *attname;
1378 Oid atttypid;
1379 int32 atttypmod;
1380 Oid attcollation;
1381 int attdim;
1382
1383 /*
1384 * allocate a new tuple descriptor
1385 */
1386 natts = list_length(columns);
1387 desc = CreateTemplateTupleDesc(natts);
1388
1389 attnum = 0;
1390
1391 foreach(l, columns)
1392 {
1393 ColumnDef *entry = lfirst(l);
1394 AclResult aclresult;
1396
1397 /*
1398 * for each entry in the list, get the name and type information from
1399 * the list and have TupleDescInitEntry fill in the attribute
1400 * information we need.
1401 */
1402 attnum++;
1403
1404 attname = entry->colname;
1405 typenameTypeIdAndMod(NULL, entry->typeName, &atttypid, &atttypmod);
1406
1407 aclresult = object_aclcheck(TypeRelationId, atttypid, GetUserId(), ACL_USAGE);
1408 if (aclresult != ACLCHECK_OK)
1409 aclcheck_error_type(aclresult, atttypid);
1410
1411 attcollation = GetColumnDefCollation(NULL, entry, atttypid);
1412 attdim = list_length(entry->typeName->arrayBounds);
1413 if (attdim > PG_INT16_MAX)
1414 ereport(ERROR,
1415 errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1416 errmsg("too many array dimensions"));
1417
1418 if (entry->typeName->setof)
1419 ereport(ERROR,
1420 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1421 errmsg("column \"%s\" cannot be declared SETOF",
1422 attname)));
1423
1425 atttypid, atttypmod, attdim);
1426 att = TupleDescAttr(desc, attnum - 1);
1427
1428 /* Override TupleDescInitEntry's settings as requested */
1429 TupleDescInitEntryCollation(desc, attnum, attcollation);
1430
1431 /* Fill in additional stuff not handled by TupleDescInitEntry */
1432 att->attnotnull = entry->is_not_null;
1433 att->attislocal = entry->is_local;
1434 att->attinhcount = entry->inhcount;
1435 att->attidentity = entry->identity;
1436 att->attgenerated = entry->generated;
1437 att->attcompression = GetAttributeCompression(att->atttypid, entry->compression);
1438 if (entry->storage)
1439 att->attstorage = entry->storage;
1440 else if (entry->storage_name)
1441 att->attstorage = GetAttributeStorage(att->atttypid, entry->storage_name);
1442
1444 }
1445
1446 return desc;
1447}
void aclcheck_error_type(AclResult aclerr, Oid typeOid)
Definition: aclchk.c:2971
int16 AttrNumber
Definition: attnum.h:21
#define PG_INT16_MAX
Definition: c.h:592
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:758
char identity
Definition: parsenodes.h:764
char * storage_name
Definition: parsenodes.h:761
char * colname
Definition: parsenodes.h:753
TypeName * typeName
Definition: parsenodes.h:754
char generated
Definition: parsenodes.h:767
char storage
Definition: parsenodes.h:760
bool is_local
Definition: parsenodes.h:757
int16 inhcount
Definition: parsenodes.h:756
char * compression
Definition: parsenodes.h:755
bool setof
Definition: parsenodes.h:287
List * arrayBounds
Definition: parsenodes.h:291
static char GetAttributeCompression(Oid atttypid, const char *compression)
Definition: tablecmds.c:21995
static char GetAttributeStorage(Oid atttypid, const char *storagemode)
Definition: tablecmds.c:22033
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:182
void populate_compact_attribute(TupleDesc tupdesc, int attnum)
Definition: tupdesc.c:117
void TupleDescInitEntryCollation(TupleDesc desc, AttrNumber attributeNumber, Oid collationid)
Definition: tupdesc.c:1026
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:842
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 7136 of file tablecmds.c.

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

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

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 4409 of file tablecmds.c.

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

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 765 of file tablecmds.c.

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

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

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 1976 of file tablecmds.c.

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

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

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 20015 of file tablecmds.c.

20017{
20018 List *existConstraint = NIL;
20019 TupleConstr *constr = RelationGetDescr(scanrel)->constr;
20020 int i;
20021
20022 if (constr && constr->has_not_null)
20023 {
20024 int natts = scanrel->rd_att->natts;
20025
20026 for (i = 1; i <= natts; i++)
20027 {
20028 CompactAttribute *att = TupleDescCompactAttr(scanrel->rd_att, i - 1);
20029
20030 /* invalid not-null constraint must be ignored here */
20031 if (att->attnullability == ATTNULLABLE_VALID && !att->attisdropped)
20032 {
20033 Form_pg_attribute wholeatt = TupleDescAttr(scanrel->rd_att, i - 1);
20034 NullTest *ntest = makeNode(NullTest);
20035
20036 ntest->arg = (Expr *) makeVar(1,
20037 i,
20038 wholeatt->atttypid,
20039 wholeatt->atttypmod,
20040 wholeatt->attcollation,
20041 0);
20042 ntest->nulltesttype = IS_NOT_NULL;
20043
20044 /*
20045 * argisrow=false is correct even for a composite column,
20046 * because attnotnull does not represent a SQL-spec IS NOT
20047 * NULL test in such a case, just IS DISTINCT FROM NULL.
20048 */
20049 ntest->argisrow = false;
20050 ntest->location = -1;
20051 existConstraint = lappend(existConstraint, ntest);
20052 }
20053 }
20054 }
20055
20056 return ConstraintImpliedByRelConstraint(scanrel, partConstraint, existConstraint);
20057}
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
@ IS_NOT_NULL
Definition: primnodes.h:1963
bool attisdropped
Definition: tupdesc.h:77
char attnullability
Definition: tupdesc.h:79
NullTestType nulltesttype
Definition: primnodes.h:1970
ParseLoc location
Definition: primnodes.h:1973
Expr * arg
Definition: primnodes.h:1969
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:20070
#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 19286 of file tablecmds.c.

19287{
19288 ListCell *l;
19289 List *oids_to_truncate = NIL;
19290 List *oids_to_drop = NIL;
19291
19292 foreach(l, on_commits)
19293 {
19294 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
19295
19296 /* Ignore entry if already dropped in this xact */
19298 continue;
19299
19300 switch (oc->oncommit)
19301 {
19302 case ONCOMMIT_NOOP:
19304 /* Do nothing (there shouldn't be such entries, actually) */
19305 break;
19307
19308 /*
19309 * If this transaction hasn't accessed any temporary
19310 * relations, we can skip truncating ON COMMIT DELETE ROWS
19311 * tables, as they must still be empty.
19312 */
19314 oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
19315 break;
19316 case ONCOMMIT_DROP:
19317 oids_to_drop = lappend_oid(oids_to_drop, oc->relid);
19318 break;
19319 }
19320 }
19321
19322 /*
19323 * Truncate relations before dropping so that all dependencies between
19324 * relations are removed after they are worked on. Doing it like this
19325 * might be a waste as it is possible that a relation being truncated will
19326 * be dropped anyway due to its parent being dropped, but this makes the
19327 * code more robust because of not having to re-check that the relation
19328 * exists at truncation time.
19329 */
19330 if (oids_to_truncate != NIL)
19331 heap_truncate(oids_to_truncate);
19332
19333 if (oids_to_drop != NIL)
19334 {
19335 ObjectAddresses *targetObjects = new_object_addresses();
19336
19337 foreach(l, oids_to_drop)
19338 {
19339 ObjectAddress object;
19340
19341 object.classId = RelationRelationId;
19342 object.objectId = lfirst_oid(l);
19343 object.objectSubId = 0;
19344
19345 Assert(!object_address_present(&object, targetObjects));
19346
19347 add_exact_object_address(&object, targetObjects);
19348 }
19349
19350 /*
19351 * Object deletion might involve toast table access (to clean up
19352 * toasted catalog entries), so ensure we have a valid snapshot.
19353 */
19355
19356 /*
19357 * Since this is an automatic drop, rather than one directly initiated
19358 * by the user, we pass the PERFORM_DELETION_INTERNAL flag.
19359 */
19362
19364
19365#ifdef USE_ASSERT_CHECKING
19366
19367 /*
19368 * Note that table deletion will call remove_on_commit_action, so the
19369 * entry should get marked as deleted.
19370 */
19371 foreach(l, on_commits)
19372 {
19373 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
19374
19375 if (oc->oncommit != ONCOMMIT_DROP)
19376 continue;
19377
19379 }
19380#endif
19381 }
19382}
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:3587
@ 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:680
void PopActiveSnapshot(void)
Definition: snapmgr.c:773
OnCommitAction oncommit
Definition: tablecmds.c:119
int MyXactFlags
Definition: xact.c:136
#define XACT_FLAGS_ACCESSEDTEMPNAMESPACE
Definition: xact.h:103

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 19460 of file tablecmds.c.

19462{
19463 char relkind;
19464 AclResult aclresult;
19465
19466 /* Nothing to do if the relation was not found. */
19467 if (!OidIsValid(relId))
19468 return;
19469
19470 /*
19471 * If the relation does exist, check whether it's an index. But note that
19472 * the relation might have been dropped between the time we did the name
19473 * lookup and now. In that case, there's nothing to do.
19474 */
19475 relkind = get_rel_relkind(relId);
19476 if (!relkind)
19477 return;
19478 if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
19479 relkind != RELKIND_MATVIEW && relkind != RELKIND_PARTITIONED_TABLE)
19480 ereport(ERROR,
19481 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19482 errmsg("\"%s\" is not a table or materialized view", relation->relname)));
19483
19484 /* Check permissions */
19485 aclresult = pg_class_aclcheck(relId, GetUserId(), ACL_MAINTAIN);
19486 if (aclresult != ACLCHECK_OK)
19487 aclcheck_error(aclresult,
19489 relation->relname);
19490}
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4037
#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 19520 of file tablecmds.c.

19522{
19523 HeapTuple tuple;
19524
19525 /* Nothing to do if the relation was not found. */
19526 if (!OidIsValid(relId))
19527 return;
19528
19529 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
19530 if (!HeapTupleIsValid(tuple)) /* should not happen */
19531 elog(ERROR, "cache lookup failed for relation %u", relId);
19532
19533 if (!object_ownercheck(RelationRelationId, relId, GetUserId()))
19535 relation->relname);
19536
19537 if (!allowSystemTableMods &&
19538 IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
19539 ereport(ERROR,
19540 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
19541 errmsg("permission denied: \"%s\" is a system catalog",
19542 relation->relname)));
19543
19544 ReleaseSysCache(tuple);
19545}
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 19227 of file tablecmds.c.

19228{
19229 OnCommitItem *oc;
19230 MemoryContext oldcxt;
19231
19232 /*
19233 * We needn't bother registering the relation unless there is an ON COMMIT
19234 * action we need to take.
19235 */
19237 return;
19238
19240
19241 oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
19242 oc->relid = relid;
19243 oc->oncommit = action;
19246
19247 /*
19248 * We use lcons() here so that ON COMMIT actions are processed in reverse
19249 * order of registration. That might not be essential but it seems
19250 * reasonable.
19251 */
19253
19254 MemoryContextSwitchTo(oldcxt);
19255}
List * lcons(void *datum, List *list)
Definition: list.c:495
MemoryContext CacheMemoryContext
Definition: mcxt.c:169
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 19263 of file tablecmds.c.

19264{
19265 ListCell *l;
19266
19267 foreach(l, on_commits)
19268 {
19269 OnCommitItem *oc = (OnCommitItem *) lfirst(l);
19270
19271 if (oc->relid == relid)
19272 {
19274 break;
19275 }
19276 }
19277}

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 1529 of file tablecmds.c.

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

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 4002 of file tablecmds.c.

4003{
4004 Oid relid;
4006 ObjectAddress address;
4007
4008 /* lock level taken here should match renameatt_internal */
4010 stmt->missing_ok ? RVR_MISSING_OK : 0,
4012 NULL);
4013
4014 if (!OidIsValid(relid))
4015 {
4017 (errmsg("relation \"%s\" does not exist, skipping",
4018 stmt->relation->relname)));
4019 return InvalidObjectAddress;
4020 }
4021
4022 attnum =
4023 renameatt_internal(relid,
4024 stmt->subname, /* old att name */
4025 stmt->newname, /* new att name */
4026 stmt->relation->inh, /* recursive? */
4027 false, /* recursing? */
4028 0, /* expected inhcount */
4029 stmt->behavior);
4030
4031 ObjectAddressSubSet(address, RelationRelationId, relid, attnum);
4032
4033 return address;
4034}
#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:3837
static void RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:3982

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 4149 of file tablecmds.c.

4150{
4151 Oid relid = InvalidOid;
4152 Oid typid = InvalidOid;
4153
4154 if (stmt->renameType == OBJECT_DOMCONSTRAINT)
4155 {
4156 Relation rel;
4157 HeapTuple tup;
4158
4159 typid = typenameTypeId(NULL, makeTypeNameFromNameList(castNode(List, stmt->object)));
4160 rel = table_open(TypeRelationId, RowExclusiveLock);
4161 tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
4162 if (!HeapTupleIsValid(tup))
4163 elog(ERROR, "cache lookup failed for type %u", typid);
4164 checkDomainOwner(tup);
4165 ReleaseSysCache(tup);
4166 table_close(rel, NoLock);
4167 }
4168 else
4169 {
4170 /* lock level taken here should match rename_constraint_internal */
4172 stmt->missing_ok ? RVR_MISSING_OK : 0,
4174 NULL);
4175 if (!OidIsValid(relid))
4176 {
4178 (errmsg("relation \"%s\" does not exist, skipping",
4179 stmt->relation->relname)));
4180 return InvalidObjectAddress;
4181 }
4182 }
4183
4184 return
4185 rename_constraint_internal(relid, typid,
4186 stmt->subname,
4187 stmt->newname,
4188 (stmt->relation &&
4189 stmt->relation->inh), /* recursive? */
4190 false, /* recursing? */
4191 0 /* expected inhcount */ );
4192}
TypeName * makeTypeNameFromNameList(List *names)
Definition: makefuncs.c:531
#define castNode(_type_, nodeptr)
Definition: nodes.h:182
@ OBJECT_DOMCONSTRAINT
Definition: parsenodes.h:2337
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:4040
void checkDomainOwner(HeapTuple tup)
Definition: typecmds.c:3495

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 4199 of file tablecmds.c.

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

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 4263 of file tablecmds.c.

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

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 4356 of file tablecmds.c.

4357{
4358 Relation relrelation; /* for RELATION relation */
4359 HeapTuple reltup;
4360 Form_pg_class relform;
4361
4362 /*
4363 * Find relation's pg_class tuple.
4364 */
4365 relrelation = table_open(RelationRelationId, RowExclusiveLock);
4366
4367 reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
4368 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
4369 elog(ERROR, "cache lookup failed for relation %u", myrelid);
4370 relform = (Form_pg_class) GETSTRUCT(reltup);
4371
4372 /*
4373 * Update pg_class tuple.
4374 */
4375 relform->relrewrite = InvalidOid;
4376
4377 CatalogTupleUpdate(relrelation, &reltup->t_self, reltup);
4378
4379 heap_freetuple(reltup);
4380 table_close(relrelation, RowExclusiveLock);
4381}
#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 3640 of file tablecmds.c.

3641{
3642 Relation relationRelation;
3643 HeapTuple tuple;
3644 Form_pg_class classtuple;
3645
3647 ShareUpdateExclusiveLock, false) ||
3648 CheckRelationOidLockedByMe(relationId,
3649 ShareRowExclusiveLock, true));
3650
3651 /*
3652 * Fetch a modifiable copy of the tuple, modify it, update pg_class.
3653 */
3654 relationRelation = table_open(RelationRelationId, RowExclusiveLock);
3655 tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
3656 if (!HeapTupleIsValid(tuple))
3657 elog(ERROR, "cache lookup failed for relation %u", relationId);
3658 classtuple = (Form_pg_class) GETSTRUCT(tuple);
3659
3660 if (classtuple->relhassubclass != relhassubclass)
3661 {
3662 classtuple->relhassubclass = relhassubclass;
3663 CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
3664 }
3665 else
3666 {
3667 /* no need to change tuple, but force relcache rebuild anyway */
3669 }
3670
3671 heap_freetuple(tuple);
3672 table_close(relationRelation, RowExclusiveLock);
3673}
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 3743 of file tablecmds.c.

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

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().