PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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

Function Documentation

◆ AlterRelationNamespaceInternal()

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

Definition at line 19079 of file tablecmds.c.

19083{
19087 bool already_done = false;
19088
19089 /* no rel lock for relkind=c so use LOCKTAG_TUPLE */
19092 elog(ERROR, "cache lookup failed for relation %u", relOid);
19094
19095 Assert(classForm->relnamespace == oldNspOid);
19096
19097 thisobj.classId = RelationRelationId;
19098 thisobj.objectId = relOid;
19099 thisobj.objectSubId = 0;
19100
19101 /*
19102 * If the object has already been moved, don't move it again. If it's
19103 * already in the right place, don't move it, but still fire the object
19104 * access hook.
19105 */
19107 if (!already_done && oldNspOid != newNspOid)
19108 {
19109 ItemPointerData otid = classTup->t_self;
19110
19111 /* check for duplicate name (more friendly than unique-index failure) */
19112 if (get_relname_relid(NameStr(classForm->relname),
19114 ereport(ERROR,
19116 errmsg("relation \"%s\" already exists in schema \"%s\"",
19117 NameStr(classForm->relname),
19119
19120 /* classTup is a copy, so OK to scribble on */
19121 classForm->relnamespace = newNspOid;
19122
19125
19126
19127 /* Update dependency on schema if caller said so */
19128 if (hasDependEntry &&
19130 relOid,
19132 oldNspOid,
19133 newNspOid) != 1)
19134 elog(ERROR, "could not change schema dependency for relation \"%s\"",
19135 NameStr(classForm->relname));
19136 }
19137 else
19139 if (!already_done)
19140 {
19142
19144 }
19145
19147}
#define NameStr(name)
Definition c.h:777
#define Assert(condition)
Definition c.h:885
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
int errcode(int sqlerrcode)
Definition elog.c:874
int errmsg(const char *fmt,...)
Definition elog.c:1093
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define ereport(elevel,...)
Definition elog.h:150
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1435
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
void CatalogTupleUpdate(Relation heapRel, const ItemPointerData *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:3518
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition lsyscache.c:2035
#define InvokeObjectPostAlterHook(classId, objectId, subId)
FormData_pg_class * Form_pg_class
Definition pg_class.h:160
long changeDependencyFor(Oid classId, Oid objectId, Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition pg_depend.c:459
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:262
#define InvalidOid
static int fb(int x)
HeapTuple SearchSysCacheLockedCopy1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:399

References add_exact_object_address(), Assert, CatalogTupleUpdate(), changeDependencyFor(), elog, ereport, errcode(), errmsg(), ERROR, fb(), get_namespace_name(), get_relname_relid(), GETSTRUCT(), heap_freetuple(), HeapTupleIsValid, InplaceUpdateTupleLock, InvalidOid, InvokeObjectPostAlterHook, NameStr, object_address_present(), ObjectIdGetDatum(), SearchSysCacheLockedCopy1(), and UnlockTuple().

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

◆ AlterTable()

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

Definition at line 4542 of file tablecmds.c.

4544{
4545 Relation rel;
4546
4547 /* Caller is required to provide an adequate lock. */
4548 rel = relation_open(context->relid, NoLock);
4549
4551
4552 ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
4553}
#define stmt
#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:4457
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition tablecmds.c:4883

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

Referenced by ProcessUtilitySlow().

◆ AlterTableGetLockLevel()

LOCKMODE AlterTableGetLockLevel ( List cmds)
extern

Definition at line 4616 of file tablecmds.c.

4617{
4618 /*
4619 * This only works if we read catalog tables using MVCC snapshots.
4620 */
4621 ListCell *lcmd;
4623
4624 foreach(lcmd, cmds)
4625 {
4627 LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
4628
4629 switch (cmd->subtype)
4630 {
4631 /*
4632 * These subcommands rewrite the heap, so require full locks.
4633 */
4634 case AT_AddColumn: /* may rewrite heap, in some cases and visible
4635 * to SELECT */
4636 case AT_SetAccessMethod: /* must rewrite heap */
4637 case AT_SetTableSpace: /* must rewrite heap */
4638 case AT_AlterColumnType: /* must rewrite heap */
4640 break;
4641
4642 /*
4643 * These subcommands may require addition of toast tables. If
4644 * we add a toast table to a table currently being scanned, we
4645 * might miss data added to the new toast table by concurrent
4646 * insert transactions.
4647 */
4648 case AT_SetStorage: /* may add toast tables, see
4649 * ATRewriteCatalogs() */
4651 break;
4652
4653 /*
4654 * Removing constraints can affect SELECTs that have been
4655 * optimized assuming the constraint holds true. See also
4656 * CloneFkReferenced.
4657 */
4658 case AT_DropConstraint: /* as DROP INDEX */
4659 case AT_DropNotNull: /* may change some SQL plans */
4661 break;
4662
4663 /*
4664 * Subcommands that may be visible to concurrent SELECTs
4665 */
4666 case AT_DropColumn: /* change visible to SELECT */
4667 case AT_AddColumnToView: /* CREATE VIEW */
4668 case AT_DropOids: /* used to equiv to DropColumn */
4669 case AT_EnableAlwaysRule: /* may change SELECT rules */
4670 case AT_EnableReplicaRule: /* may change SELECT rules */
4671 case AT_EnableRule: /* may change SELECT rules */
4672 case AT_DisableRule: /* may change SELECT rules */
4674 break;
4675
4676 /*
4677 * Changing owner may remove implicit SELECT privileges
4678 */
4679 case AT_ChangeOwner: /* change visible to SELECT */
4681 break;
4682
4683 /*
4684 * Changing foreign table options may affect optimization.
4685 */
4686 case AT_GenericOptions:
4689 break;
4690
4691 /*
4692 * These subcommands affect write operations only.
4693 */
4694 case AT_EnableTrig:
4697 case AT_EnableTrigAll:
4698 case AT_EnableTrigUser:
4699 case AT_DisableTrig:
4700 case AT_DisableTrigAll:
4701 case AT_DisableTrigUser:
4703 break;
4704
4705 /*
4706 * These subcommands affect write operations only. XXX
4707 * Theoretically, these could be ShareRowExclusiveLock.
4708 */
4709 case AT_ColumnDefault:
4711 case AT_AlterConstraint:
4712 case AT_AddIndex: /* from ADD CONSTRAINT */
4714 case AT_ReplicaIdentity:
4715 case AT_SetNotNull:
4720 case AT_AddIdentity:
4721 case AT_DropIdentity:
4722 case AT_SetIdentity:
4723 case AT_SetExpression:
4724 case AT_DropExpression:
4725 case AT_SetCompression:
4727 break;
4728
4729 case AT_AddConstraint:
4730 case AT_ReAddConstraint: /* becomes AT_AddConstraint */
4731 case AT_ReAddDomainConstraint: /* becomes AT_AddConstraint */
4732 if (IsA(cmd->def, Constraint))
4733 {
4734 Constraint *con = (Constraint *) cmd->def;
4735
4736 switch (con->contype)
4737 {
4738 case CONSTR_EXCLUSION:
4739 case CONSTR_PRIMARY:
4740 case CONSTR_UNIQUE:
4741
4742 /*
4743 * Cases essentially the same as CREATE INDEX. We
4744 * could reduce the lock strength to ShareLock if
4745 * we can work out how to allow concurrent catalog
4746 * updates. XXX Might be set down to
4747 * ShareRowExclusiveLock but requires further
4748 * analysis.
4749 */
4751 break;
4752 case CONSTR_FOREIGN:
4753
4754 /*
4755 * We add triggers to both tables when we add a
4756 * Foreign Key, so the lock level must be at least
4757 * as strong as CREATE TRIGGER.
4758 */
4760 break;
4761
4762 default:
4764 }
4765 }
4766 break;
4767
4768 /*
4769 * These subcommands affect inheritance behaviour. Queries
4770 * started before us will continue to see the old inheritance
4771 * behaviour, while queries started after we commit will see
4772 * new behaviour. No need to prevent reads or writes to the
4773 * subtable while we hook it up though. Changing the TupDesc
4774 * may be a problem, so keep highest lock.
4775 */
4776 case AT_AddInherit:
4777 case AT_DropInherit:
4779 break;
4780
4781 /*
4782 * These subcommands affect implicit row type conversion. They
4783 * have affects similar to CREATE/DROP CAST on queries. don't
4784 * provide for invalidating parse trees as a result of such
4785 * changes, so we keep these at AccessExclusiveLock.
4786 */
4787 case AT_AddOf:
4788 case AT_DropOf:
4790 break;
4791
4792 /*
4793 * Only used by CREATE OR REPLACE VIEW which must conflict
4794 * with an SELECTs currently using the view.
4795 */
4798 break;
4799
4800 /*
4801 * These subcommands affect general strategies for performance
4802 * and maintenance, though don't change the semantic results
4803 * from normal data reads and writes. Delaying an ALTER TABLE
4804 * behind currently active writes only delays the point where
4805 * the new strategy begins to take effect, so there is no
4806 * benefit in waiting. In this case the minimum restriction
4807 * applies: we don't currently allow concurrent catalog
4808 * updates.
4809 */
4810 case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
4811 case AT_ClusterOn: /* Uses MVCC in getIndexes() */
4812 case AT_DropCluster: /* Uses MVCC in getIndexes() */
4813 case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
4814 case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
4816 break;
4817
4818 case AT_SetLogged:
4819 case AT_SetUnLogged:
4821 break;
4822
4823 case AT_ValidateConstraint: /* Uses MVCC in getConstraints() */
4825 break;
4826
4827 /*
4828 * Rel options are more complex than first appears. Options
4829 * are set here for tables, views and indexes; for historical
4830 * reasons these can all be used with ALTER TABLE, so we can't
4831 * decide between them using the basic grammar.
4832 */
4833 case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
4834 * getTables() */
4835 case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
4836 * getTables() */
4838 break;
4839
4840 case AT_AttachPartition:
4842 break;
4843
4844 case AT_DetachPartition:
4845 if (((PartitionCmd *) cmd->def)->concurrent)
4847 else
4849 break;
4850
4853 break;
4854
4855 case AT_MergePartitions:
4856 case AT_SplitPartition:
4858 break;
4859
4860 default: /* oops */
4861 elog(ERROR, "unrecognized alter table type: %d",
4862 (int) cmd->subtype);
4863 break;
4864 }
4865
4866 /*
4867 * Take the greatest lockmode from any subcommand
4868 */
4869 if (cmd_lockmode > lockmode)
4870 lockmode = cmd_lockmode;
4871 }
4872
4873 return lockmode;
4874}
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
@ CONSTR_UNIQUE
@ CONSTR_EXCLUSION
@ CONSTR_PRIMARY
@ AT_AddIndexConstraint
@ AT_MergePartitions
@ AT_DropOf
@ AT_SetOptions
@ AT_DropIdentity
@ AT_DisableTrigUser
@ AT_DropNotNull
@ AT_AddOf
@ AT_ResetOptions
@ AT_ReplicaIdentity
@ AT_ReplaceRelOptions
@ AT_EnableRowSecurity
@ AT_AddColumnToView
@ AT_ResetRelOptions
@ AT_EnableReplicaTrig
@ AT_DropOids
@ AT_SetIdentity
@ AT_SetUnLogged
@ AT_DisableTrig
@ AT_SetCompression
@ AT_DropExpression
@ AT_AddIndex
@ AT_EnableReplicaRule
@ AT_DropConstraint
@ AT_SetNotNull
@ AT_ClusterOn
@ AT_AddIdentity
@ AT_ForceRowSecurity
@ AT_EnableAlwaysRule
@ AT_SetAccessMethod
@ AT_AlterColumnType
@ AT_DetachPartitionFinalize
@ AT_AddInherit
@ AT_ReAddDomainConstraint
@ AT_EnableTrig
@ AT_DropColumn
@ AT_AlterColumnGenericOptions
@ AT_DisableTrigAll
@ AT_EnableRule
@ AT_NoForceRowSecurity
@ AT_DetachPartition
@ AT_SetStatistics
@ AT_AttachPartition
@ AT_AddConstraint
@ AT_DropInherit
@ AT_EnableAlwaysTrig
@ AT_SetLogged
@ AT_SetStorage
@ AT_DisableRule
@ AT_DisableRowSecurity
@ AT_SetRelOptions
@ AT_ChangeOwner
@ AT_EnableTrigUser
@ AT_SetExpression
@ AT_ReAddConstraint
@ AT_SetTableSpace
@ AT_GenericOptions
@ AT_ColumnDefault
@ AT_CookedColumnDefault
@ AT_AlterConstraint
@ AT_EnableTrigAll
@ AT_SplitPartition
@ AT_DropCluster
@ AT_ValidateConstraint
@ AT_AddColumn
#define lfirst(lc)
Definition pg_list.h:172
LOCKMODE AlterTableGetRelOptionsLockLevel(List *defList)
AlterTableType subtype
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_MergePartitions, 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_SplitPartition, AT_ValidateConstraint, CONSTR_EXCLUSION, CONSTR_FOREIGN, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, AlterTableCmd::def, elog, ERROR, fb(), IsA, lfirst, ShareRowExclusiveLock, ShareUpdateExclusiveLock, and AlterTableCmd::subtype.

Referenced by AlterTableInternal(), and ProcessUtilitySlow().

◆ AlterTableInternal()

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

Definition at line 4571 of file tablecmds.c.

4572{
4573 Relation rel;
4574 LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
4575
4576 rel = relation_open(relid, lockmode);
4577
4579
4580 ATController(NULL, rel, cmds, recurse, lockmode, NULL);
4581}
void EventTriggerAlterTableRelid(Oid objectId)
LOCKMODE AlterTableGetLockLevel(List *cmds)
Definition tablecmds.c:4616

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

Referenced by AlterTableMoveAll(), and DefineVirtualRelation().

◆ AlterTableLookupRelation()

Oid AlterTableLookupRelation ( AlterTableStmt stmt,
LOCKMODE  lockmode 
)
extern

Definition at line 4483 of file tablecmds.c.

4484{
4485 return RangeVarGetRelidExtended(stmt->relation, lockmode,
4486 stmt->missing_ok ? RVR_MISSING_OK : 0,
4488 stmt);
4489}
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition namespace.c:442
@ RVR_MISSING_OK
Definition namespace.h:90
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)

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

Referenced by ProcessUtilitySlow().

◆ AlterTableMoveAll()

Oid AlterTableMoveAll ( AlterTableMoveAllStmt stmt)
extern

Definition at line 17012 of file tablecmds.c.

17013{
17014 List *relations = NIL;
17015 ListCell *l;
17016 ScanKeyData key[1];
17017 Relation rel;
17018 TableScanDesc scan;
17019 HeapTuple tuple;
17022 List *role_oids = roleSpecsToIds(stmt->roles);
17023
17024 /* Ensure we were not asked to move something we can't */
17025 if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
17026 stmt->objtype != OBJECT_MATVIEW)
17027 ereport(ERROR,
17029 errmsg("only tables, indexes, and materialized views exist in tablespaces")));
17030
17031 /* Get the orig and new tablespace OIDs */
17032 orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
17033 new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
17034
17035 /* Can't move shared relations in to or out of pg_global */
17036 /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
17039 ereport(ERROR,
17041 errmsg("cannot move relations in to or out of pg_global tablespace")));
17042
17043 /*
17044 * Must have CREATE rights on the new tablespace, unless it is the
17045 * database default tablespace (which all users implicitly have CREATE
17046 * rights on).
17047 */
17049 {
17051
17053 ACL_CREATE);
17054 if (aclresult != ACLCHECK_OK)
17057 }
17058
17059 /*
17060 * Now that the checks are done, check if we should set either to
17061 * InvalidOid because it is our database's default tablespace.
17062 */
17065
17068
17069 /* no-op */
17071 return new_tablespaceoid;
17072
17073 /*
17074 * Walk the list of objects in the tablespace and move them. This will
17075 * only find objects in our database, of course.
17076 */
17077 ScanKeyInit(&key[0],
17081
17083 scan = table_beginscan_catalog(rel, 1, key);
17084 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
17085 {
17087 Oid relOid = relForm->oid;
17088
17089 /*
17090 * Do not move objects in pg_catalog as part of this, if an admin
17091 * really wishes to do so, they can issue the individual ALTER
17092 * commands directly.
17093 *
17094 * Also, explicitly avoid any shared tables, temp tables, or TOAST
17095 * (TOAST will be moved with the main table).
17096 */
17097 if (IsCatalogNamespace(relForm->relnamespace) ||
17098 relForm->relisshared ||
17099 isAnyTempNamespace(relForm->relnamespace) ||
17100 IsToastNamespace(relForm->relnamespace))
17101 continue;
17102
17103 /* Only move the object type requested */
17104 if ((stmt->objtype == OBJECT_TABLE &&
17105 relForm->relkind != RELKIND_RELATION &&
17106 relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
17107 (stmt->objtype == OBJECT_INDEX &&
17108 relForm->relkind != RELKIND_INDEX &&
17109 relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
17110 (stmt->objtype == OBJECT_MATVIEW &&
17111 relForm->relkind != RELKIND_MATVIEW))
17112 continue;
17113
17114 /* Check if we are only moving objects owned by certain roles */
17115 if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
17116 continue;
17117
17118 /*
17119 * Handle permissions-checking here since we are locking the tables
17120 * and also to avoid doing a bunch of work only to fail part-way. Note
17121 * that permissions will also be checked by AlterTableInternal().
17122 *
17123 * Caller must be considered an owner on the table to move it.
17124 */
17127 NameStr(relForm->relname));
17128
17129 if (stmt->nowait &&
17131 ereport(ERROR,
17133 errmsg("aborting because lock on relation \"%s.%s\" is not available",
17134 get_namespace_name(relForm->relnamespace),
17135 NameStr(relForm->relname))));
17136 else
17138
17139 /* Add to our list of objects to move */
17140 relations = lappend_oid(relations, relOid);
17141 }
17142
17143 table_endscan(scan);
17145
17146 if (relations == NIL)
17149 errmsg("no matching relations in tablespace \"%s\" found",
17150 orig_tablespaceoid == InvalidOid ? "(database default)" :
17152
17153 /* Everything is locked, loop through and move all of the relations. */
17154 foreach(l, relations)
17155 {
17156 List *cmds = NIL;
17158
17160 cmd->name = stmt->new_tablespacename;
17161
17162 cmds = lappend(cmds, cmd);
17163
17165 /* OID is set by AlterTableInternal */
17166 AlterTableInternal(lfirst_oid(l), cmds, false);
17168 }
17169
17170 return new_tablespaceoid;
17171}
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:2654
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition aclchk.c:3854
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition aclchk.c:4108
char * get_tablespace_name(Oid spc_oid)
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
#define OidIsValid(objectId)
Definition c.h:800
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:1410
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:2153
Oid GetUserId(void)
Definition miscinit.c:469
bool isAnyTempNamespace(Oid namespaceId)
Definition namespace.c:3759
#define makeNode(_type_)
Definition nodes.h:161
ObjectType get_relkind_objtype(char relkind)
@ OBJECT_MATVIEW
@ OBJECT_TABLESPACE
@ OBJECT_INDEX
@ OBJECT_TABLE
#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
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:1004
void AlterTableInternal(Oid relid, List *cmds, bool recurse)
Definition tablecmds.c:4571
List * roleSpecsToIds(List *memberNames)
Definition user.c:1665

References AccessExclusiveLock, AccessShareLock, ACL_CREATE, aclcheck_error(), ACLCHECK_NOT_OWNER, ACLCHECK_OK, AlterTableInternal(), AT_SetTableSpace, BTEqualStrategyNumber, ConditionalLockRelationOid(), ereport, errcode(), errmsg(), ERROR, EventTriggerAlterTableEnd(), EventTriggerAlterTableStart(), fb(), ForwardScanDirection, get_namespace_name(), get_rel_relkind(), get_relkind_objtype(), get_tablespace_name(), get_tablespace_oid(), GETSTRUCT(), GetUserId(), heap_getnext(), InvalidOid, isAnyTempNamespace(), IsCatalogNamespace(), IsToastNamespace(), 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 
)
extern

Definition at line 18971 of file tablecmds.c.

18972{
18973 Relation rel;
18974 Oid relid;
18975 Oid oldNspOid;
18976 Oid nspOid;
18977 RangeVar *newrv;
18980
18982 stmt->missing_ok ? RVR_MISSING_OK : 0,
18984 stmt);
18985
18986 if (!OidIsValid(relid))
18987 {
18989 (errmsg("relation \"%s\" does not exist, skipping",
18990 stmt->relation->relname)));
18991 return InvalidObjectAddress;
18992 }
18993
18994 rel = relation_open(relid, NoLock);
18995
18997
18998 /* If it's an owned sequence, disallow moving it by itself. */
18999 if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
19000 {
19001 Oid tableId;
19002 int32 colId;
19003
19004 if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
19006 ereport(ERROR,
19008 errmsg("cannot move an owned sequence into another schema"),
19009 errdetail("Sequence \"%s\" is linked to table \"%s\".",
19012 }
19013
19014 /* Get and lock schema OID and check its permissions. */
19015 newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
19017
19018 /* common checks on switching namespaces */
19020
19024
19026
19027 if (oldschema)
19029
19030 /* close rel, but keep lock until commit */
19031 relation_close(rel, NoLock);
19032
19033 return myself;
19034}
int32_t int32
Definition c.h:554
ObjectAddresses * new_object_addresses(void)
void free_object_addresses(ObjectAddresses *addrs)
@ DEPENDENCY_AUTO
Definition dependency.h:34
@ DEPENDENCY_INTERNAL
Definition dependency.h:35
int errdetail(const char *fmt,...) pg_attribute_printf(1
char * get_rel_name(Oid relid)
Definition lsyscache.c:2078
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:740
void CheckSetNamespace(Oid oldNspOid, Oid nspOid)
Definition namespace.c:3531
const ObjectAddress InvalidObjectAddress
#define ObjectAddressSet(addr, class_id, object_id)
bool sequenceIsOwned(Oid seqId, char deptype, Oid *tableId, int32 *colId)
Definition pg_depend.c:901
#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)

References AccessExclusiveLock, AlterTableNamespaceInternal(), CheckSetNamespace(), DEPENDENCY_AUTO, DEPENDENCY_INTERNAL, ereport, errcode(), errdetail(), errmsg(), ERROR, fb(), 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 
)
extern

Definition at line 19042 of file tablecmds.c.

19044{
19046
19047 Assert(objsMoved != NULL);
19048
19049 /* OK, modify the pg_class row and pg_depend entry */
19051
19053 nspOid, true, objsMoved);
19054
19055 /* Fix the table's row type too, if it has one */
19056 if (OidIsValid(rel->rd_rel->reltype))
19058 false, /* isImplicitArray */
19059 false, /* ignoreDependent */
19060 false, /* errorOnTableType */
19061 objsMoved);
19062
19063 /* Fix other dependent stuff */
19068 false, objsMoved);
19069
19071}
#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)
static void AlterSeqNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved, LOCKMODE lockmode)
static void AlterIndexNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
Oid AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid, bool isImplicitArray, bool ignoreDependent, bool errorOnTableType, ObjectAddresses *objsMoved)
Definition typecmds.c:4197

References AccessExclusiveLock, AlterConstraintNamespaces(), AlterIndexNamespaces(), AlterRelationNamespaceInternal(), AlterSeqNamespaces(), AlterTypeNamespaceInternal(), Assert, fb(), 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 
)
extern

Definition at line 19484 of file tablecmds.c.

19486{
19488
19489 foreach(cur_item, on_commits)
19490 {
19492
19493 if (!isCommit && oc->creating_subid == mySubid)
19494 {
19495 /* cur_item must be removed */
19497 pfree(oc);
19498 }
19499 else
19500 {
19501 /* cur_item must be preserved */
19502 if (oc->creating_subid == mySubid)
19503 oc->creating_subid = parentSubid;
19504 if (oc->deleting_subid == mySubid)
19505 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
19506 }
19507 }
19508}
#define InvalidSubTransactionId
Definition c.h:684
void pfree(void *pointer)
Definition mcxt.c:1616
#define foreach_delete_current(lst, var_or_cell)
Definition pg_list.h:391
static List * on_commits
Definition tablecmds.c:132

References fb(), 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)
extern

Definition at line 19452 of file tablecmds.c.

19453{
19455
19456 foreach(cur_item, on_commits)
19457 {
19459
19460 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
19461 oc->creating_subid != InvalidSubTransactionId)
19462 {
19463 /* cur_item must be removed */
19465 pfree(oc);
19466 }
19467 else
19468 {
19469 /* cur_item must be preserved */
19470 oc->creating_subid = InvalidSubTransactionId;
19471 oc->deleting_subid = InvalidSubTransactionId;
19472 }
19473 }
19474}

References fb(), 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 
)
extern

Definition at line 16099 of file tablecmds.c.

16100{
16103 HeapTuple tuple;
16105
16106 /*
16107 * Get exclusive lock till end of transaction on the target table. Use
16108 * relation_open so that we can work on indexes and sequences.
16109 */
16110 target_rel = relation_open(relationOid, lockmode);
16111
16112 /* Get its pg_class tuple, too */
16114
16115 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
16116 if (!HeapTupleIsValid(tuple))
16117 elog(ERROR, "cache lookup failed for relation %u", relationOid);
16119
16120 /* Can we change the ownership of this tuple? */
16121 switch (tuple_class->relkind)
16122 {
16123 case RELKIND_RELATION:
16124 case RELKIND_VIEW:
16125 case RELKIND_MATVIEW:
16128 /* ok to change owner */
16129 break;
16130 case RELKIND_INDEX:
16131 if (!recursing)
16132 {
16133 /*
16134 * Because ALTER INDEX OWNER used to be allowed, and in fact
16135 * is generated by old versions of pg_dump, we give a warning
16136 * and do nothing rather than erroring out. Also, to avoid
16137 * unnecessary chatter while restoring those old dumps, say
16138 * nothing at all if the command would be a no-op anyway.
16139 */
16140 if (tuple_class->relowner != newOwnerId)
16143 errmsg("cannot change owner of index \"%s\"",
16144 NameStr(tuple_class->relname)),
16145 errhint("Change the ownership of the index's table instead.")));
16146 /* quick hack to exit via the no-op path */
16147 newOwnerId = tuple_class->relowner;
16148 }
16149 break;
16151 if (recursing)
16152 break;
16153 ereport(ERROR,
16155 errmsg("cannot change owner of index \"%s\"",
16156 NameStr(tuple_class->relname)),
16157 errhint("Change the ownership of the index's table instead.")));
16158 break;
16159 case RELKIND_SEQUENCE:
16160 if (!recursing &&
16161 tuple_class->relowner != newOwnerId)
16162 {
16163 /* if it's an owned sequence, disallow changing it by itself */
16164 Oid tableId;
16165 int32 colId;
16166
16167 if (sequenceIsOwned(relationOid, DEPENDENCY_AUTO, &tableId, &colId) ||
16169 ereport(ERROR,
16171 errmsg("cannot change owner of sequence \"%s\"",
16172 NameStr(tuple_class->relname)),
16173 errdetail("Sequence \"%s\" is linked to table \"%s\".",
16174 NameStr(tuple_class->relname),
16176 }
16177 break;
16179 if (recursing)
16180 break;
16181 ereport(ERROR,
16183 errmsg("\"%s\" is a composite type",
16184 NameStr(tuple_class->relname)),
16185 /* translator: %s is an SQL ALTER command */
16186 errhint("Use %s instead.",
16187 "ALTER TYPE")));
16188 break;
16189 case RELKIND_TOASTVALUE:
16190 if (recursing)
16191 break;
16193 default:
16194 ereport(ERROR,
16196 errmsg("cannot change owner of relation \"%s\"",
16197 NameStr(tuple_class->relname)),
16199 }
16200
16201 /*
16202 * If the new owner is the same as the existing owner, consider the
16203 * command to have succeeded. This is for dump restoration purposes.
16204 */
16205 if (tuple_class->relowner != newOwnerId)
16206 {
16210 Acl *newAcl;
16212 bool isNull;
16213 HeapTuple newtuple;
16214
16215 /* skip permission checks when recursing to index or toast table */
16216 if (!recursing)
16217 {
16218 /* Superusers can always do it */
16219 if (!superuser())
16220 {
16221 Oid namespaceOid = tuple_class->relnamespace;
16223
16224 /* Otherwise, must be owner of the existing object */
16225 if (!object_ownercheck(RelationRelationId, relationOid, GetUserId()))
16228
16229 /* Must be able to become new owner */
16231
16232 /* New owner must have CREATE privilege on namespace */
16234 ACL_CREATE);
16235 if (aclresult != ACLCHECK_OK)
16238 }
16239 }
16240
16241 memset(repl_null, false, sizeof(repl_null));
16242 memset(repl_repl, false, sizeof(repl_repl));
16243
16246
16247 /*
16248 * Determine the modified ACL for the new owner. This is only
16249 * necessary when the ACL is non-null.
16250 */
16253 &isNull);
16254 if (!isNull)
16255 {
16257 tuple_class->relowner, newOwnerId);
16258 repl_repl[Anum_pg_class_relacl - 1] = true;
16260 }
16261
16263
16264 CatalogTupleUpdate(class_rel, &newtuple->t_self, newtuple);
16265
16266 heap_freetuple(newtuple);
16267
16268 /*
16269 * We must similarly update any per-column ACLs to reflect the new
16270 * owner; for neatness reasons that's split out as a subroutine.
16271 */
16272 change_owner_fix_column_acls(relationOid,
16273 tuple_class->relowner,
16274 newOwnerId);
16275
16276 /*
16277 * Update owner dependency reference, if any. A composite type has
16278 * none, because it's tracked for the pg_type entry instead of here;
16279 * indexes and TOAST tables don't have their own entries either.
16280 */
16281 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
16282 tuple_class->relkind != RELKIND_INDEX &&
16284 tuple_class->relkind != RELKIND_TOASTVALUE)
16286 newOwnerId);
16287
16288 /*
16289 * Also change the ownership of the table's row type, if it has one
16290 */
16291 if (OidIsValid(tuple_class->reltype))
16293
16294 /*
16295 * If we are operating on a table or materialized view, also change
16296 * the ownership of any indexes and sequences that belong to the
16297 * relation, as well as its toast table (if it has one).
16298 */
16299 if (tuple_class->relkind == RELKIND_RELATION ||
16301 tuple_class->relkind == RELKIND_MATVIEW ||
16302 tuple_class->relkind == RELKIND_TOASTVALUE)
16303 {
16305 ListCell *i;
16306
16307 /* Find all the indexes belonging to this relation */
16309
16310 /* For each index, recursively change its ownership */
16311 foreach(i, index_oid_list)
16312 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
16313
16315 }
16316
16317 /* If it has a toast table, recurse to change its ownership */
16318 if (tuple_class->reltoastrelid != InvalidOid)
16320 true, lockmode);
16321
16322 /* If it has dependent sequences, recurse to change them too */
16323 change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
16324 }
16325
16327
16328 ReleaseSysCache(tuple);
16331}
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition acl.c:1120
void check_can_set_role(Oid member, Oid role)
Definition acl.c:5343
#define DatumGetAclP(X)
Definition acl.h:120
#define pg_fallthrough
Definition c.h:144
int errhint(const char *fmt,...) pg_attribute_printf(1
#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
int errdetail_relkind_not_supported(char relkind)
Definition pg_class.c:24
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
static Datum PointerGetDatum(const void *X)
Definition postgres.h:352
uint64_t Datum
Definition postgres.h:70
#define RelationGetDescr(relation)
Definition rel.h:540
List * RelationGetIndexList(Relation relation)
Definition relcache.c:4831
ItemPointerData t_self
Definition htup.h:65
bool superuser(void)
Definition superuser.c:47
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:264
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:220
Datum SysCacheGetAttr(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition syscache.c:595
void ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
static void change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
static void change_owner_fix_column_acls(Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
void AlterTypeOwnerInternal(Oid typeOid, Oid newOwnerId)
Definition typecmds.c:4028

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, fb(), 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, pg_fallthrough, 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)
extern

Definition at line 1386 of file tablecmds.c.

1387{
1388 int natts;
1390 ListCell *l;
1391 TupleDesc desc;
1392 char *attname;
1393 Oid atttypid;
1394 int32 atttypmod;
1395 Oid attcollation;
1396 int attdim;
1397
1398 /*
1399 * allocate a new tuple descriptor
1400 */
1401 natts = list_length(columns);
1402 desc = CreateTemplateTupleDesc(natts);
1403
1404 attnum = 0;
1405
1406 foreach(l, columns)
1407 {
1408 ColumnDef *entry = lfirst(l);
1411
1412 /*
1413 * for each entry in the list, get the name and type information from
1414 * the list and have TupleDescInitEntry fill in the attribute
1415 * information we need.
1416 */
1417 attnum++;
1418
1419 attname = entry->colname;
1420 typenameTypeIdAndMod(NULL, entry->typeName, &atttypid, &atttypmod);
1421
1423 if (aclresult != ACLCHECK_OK)
1425
1426 attcollation = GetColumnDefCollation(NULL, entry, atttypid);
1428 if (attdim > PG_INT16_MAX)
1429 ereport(ERROR,
1431 errmsg("too many array dimensions"));
1432
1433 if (entry->typeName->setof)
1434 ereport(ERROR,
1436 errmsg("column \"%s\" cannot be declared SETOF",
1437 attname)));
1438
1440 atttypid, atttypmod, attdim);
1441 att = TupleDescAttr(desc, attnum - 1);
1442
1443 /* Override TupleDescInitEntry's settings as requested */
1444 TupleDescInitEntryCollation(desc, attnum, attcollation);
1445
1446 /* Fill in additional stuff not handled by TupleDescInitEntry */
1447 att->attnotnull = entry->is_not_null;
1448 att->attislocal = entry->is_local;
1449 att->attinhcount = entry->inhcount;
1450 att->attidentity = entry->identity;
1451 att->attgenerated = entry->generated;
1452 att->attcompression = GetAttributeCompression(att->atttypid, entry->compression);
1453 if (entry->storage)
1454 att->attstorage = entry->storage;
1455 else if (entry->storage_name)
1456 att->attstorage = GetAttributeStorage(att->atttypid, entry->storage_name);
1457
1459 }
1460
1461 return desc;
1462}
void aclcheck_error_type(AclResult aclerr, Oid typeOid)
Definition aclchk.c:2973
int16 AttrNumber
Definition attnum.h:21
#define PG_INT16_MAX
Definition c.h:612
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
int16 attnum
FormData_pg_attribute * Form_pg_attribute
static int list_length(const List *l)
Definition pg_list.h:152
bool is_not_null
Definition parsenodes.h:759
char identity
Definition parsenodes.h:765
char * storage_name
Definition parsenodes.h:762
char * colname
Definition parsenodes.h:754
TypeName * typeName
Definition parsenodes.h:755
char generated
Definition parsenodes.h:768
char storage
Definition parsenodes.h:761
bool is_local
Definition parsenodes.h:758
int16 inhcount
Definition parsenodes.h:757
char * compression
Definition parsenodes.h:756
bool setof
Definition parsenodes.h:287
List * arrayBounds
Definition parsenodes.h:291
static char GetAttributeCompression(Oid atttypid, const char *compression)
static char GetAttributeStorage(Oid atttypid, const char *storagemode)
TupleDesc CreateTemplateTupleDesc(int natts)
Definition tupdesc.c:165
void populate_compact_attribute(TupleDesc tupdesc, int attnum)
Definition tupdesc.c:100
void TupleDescInitEntryCollation(TupleDesc desc, AttrNumber attributeNumber, Oid collationid)
Definition tupdesc.c:1009
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition tupdesc.c:825
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, fb(), 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(), createPartitionTable(), DefineRelation(), and DefineVirtualRelation().

◆ check_of_type()

void check_of_type ( HeapTuple  typetuple)
extern

Definition at line 7182 of file tablecmds.c.

7183{
7185 bool typeOk = false;
7186
7187 if (typ->typtype == TYPTYPE_COMPOSITE)
7188 {
7190
7191 Assert(OidIsValid(typ->typrelid));
7193 typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
7194
7195 /*
7196 * Close the parent rel, but keep our AccessShareLock on it until xact
7197 * commit. That will prevent someone else from deleting or ALTERing
7198 * the type before the typed table creation/conversion commits.
7199 */
7201
7202 if (!typeOk)
7203 ereport(ERROR,
7205 errmsg("type %s is the row type of another table",
7206 format_type_be(typ->oid)),
7207 errdetail("A typed table must use a stand-alone composite type created with CREATE TYPE.")));
7208 }
7209 else
7210 ereport(ERROR,
7212 errmsg("type %s is not a composite type",
7213 format_type_be(typ->oid))));
7214}
char * format_type_be(Oid type_oid)
END_CATALOG_STRUCT typedef FormData_pg_type * Form_pg_type
Definition pg_type.h:265

References AccessShareLock, Assert, ereport, errcode(), errdetail(), errmsg(), ERROR, fb(), Form_pg_type, format_type_be(), GETSTRUCT(), NoLock, OidIsValid, relation_close(), and relation_open().

Referenced by ATExecAddOf(), and transformOfType().

◆ CheckRelationTableSpaceMove()

bool CheckRelationTableSpaceMove ( Relation  rel,
Oid  newTableSpaceId 
)
extern

Definition at line 3701 of file tablecmds.c.

3702{
3704
3705 /*
3706 * No work if no change in tablespace. Note that MyDatabaseTableSpace is
3707 * stored as 0.
3708 */
3709 oldTableSpaceId = rel->rd_rel->reltablespace;
3712 return false;
3713
3714 /*
3715 * We cannot support moving mapped relations into different tablespaces.
3716 * (In particular this eliminates all shared catalogs.)
3717 */
3718 if (RelationIsMapped(rel))
3719 ereport(ERROR,
3721 errmsg("cannot move system relation \"%s\"",
3723
3724 /* Cannot move a non-shared relation into pg_global */
3726 ereport(ERROR,
3728 errmsg("only shared relations can be placed in pg_global tablespace")));
3729
3730 /*
3731 * Do not allow moving temp tables of other backends ... their local
3732 * buffer manager is not going to cope.
3733 */
3734 if (RELATION_IS_OTHER_TEMP(rel))
3735 ereport(ERROR,
3737 errmsg("cannot move temporary tables of other sessions")));
3738
3739 return true;
3740}
#define RelationIsMapped(relation)
Definition rel.h:563
#define RELATION_IS_OTHER_TEMP(relation)
Definition rel.h:667

References ereport, errcode(), errmsg(), ERROR, fb(), 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 
)
extern

Definition at line 4424 of file tablecmds.c.

4425{
4426 int expected_refcnt;
4427
4428 expected_refcnt = rel->rd_isnailed ? 2 : 1;
4429 if (rel->rd_refcnt != expected_refcnt)
4430 ereport(ERROR,
4432 /* translator: first %s is a SQL command, eg ALTER TABLE */
4433 errmsg("cannot %s \"%s\" because it is being used by active queries in this session",
4435
4436 if (rel->rd_rel->relkind != RELKIND_INDEX &&
4437 rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
4439 ereport(ERROR,
4441 /* translator: first %s is a SQL command, eg ALTER TABLE */
4442 errmsg("cannot %s \"%s\" because it has pending trigger events",
4444}
int rd_refcnt
Definition rel.h:59
bool rd_isnailed
Definition rel.h:62
bool AfterTriggerPendingOnRel(Oid relid)
Definition trigger.c:6081

References AfterTriggerPendingOnRel(), ereport, errcode(), errmsg(), ERROR, fb(), 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 
)
extern

Definition at line 769 of file tablecmds.c.

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

References AccessExclusiveLock, AccessShareLock, ACL_CREATE, ACL_USAGE, aclcheck_error(), aclcheck_error_type(), ACLCHECK_OK, addNSItemToQuery(), addRangeTableEntryForRelation(), AddRelationNewConstraints(), AddRelationNotNullConstraints(), allowSystemTableMods, Assert, attnum, build_attrmap_by_name(), BuildDescForRelation(), check_default_partition_contents(), check_new_partition_bound(), CloneForeignKeyConstraints(), CloneRowTriggersToPartition(), CommandCounterIncrement(), ComputePartitionAttrs(), CONSTR_DEFAULT, default_table_access_method, DefineIndex(), elog, ereport, errcode(), errdetail(), errmsg(), ERROR, fb(), foreach_int, foreach_ptr, generateClonedIndexStmt(), 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(), InSecurityRestrictedOperation(), InvalidOid, lappend(), lappend_oid(), lfirst, lfirst_oid, linitial_oid, list_concat(), list_free(), list_length(), list_member_oid(), make_parsestate(), MergeAttributes(), MyDatabaseTableSpace, NAMEDATALEN, NIL, NoLock, object_aclcheck(), OBJECT_TABLESPACE, ObjectAddressSet, OidIsValid, ONCOMMIT_NOOP, ParseState::p_sourcetext, palloc_object, PARTITION_MAX_KEYS, partitioned_table_reloptions(), RangeVarGetAndCheckCreationNamespace(), RangeVarGetRelid, RelationData::rd_rel, relation_close(), relation_open(), RelationGetDescr, RelationGetIndexList(), RelationGetPartitionDesc(), RelationGetRelationName, RelationGetRelid, relname, set_attnotnull(), ShareUpdateExclusiveLock, 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)
extern

Definition at line 1867 of file tablecmds.c.

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

References AccessExclusiveLock, ereport, errcode(), errhint(), errmsg(), ERROR, ExecuteTruncateGuts(), fb(), 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 
)
extern

Definition at line 1991 of file tablecmds.c.

1996{
1997 List *rels;
1998 List *seq_relids = NIL;
1999 HTAB *ft_htab = NULL;
2000 EState *estate;
2002 ResultRelInfo *resultRelInfo;
2004 ListCell *cell;
2005 Oid *logrelids;
2006
2007 /*
2008 * Check the explicitly-specified relations.
2009 *
2010 * In CASCADE mode, suck in all referencing relations as well. This
2011 * requires multiple iterations to find indirectly-dependent relations. At
2012 * each phase, we need to exclusive-lock new rels before looking for their
2013 * dependencies, else we might miss something. Also, we check each rel as
2014 * soon as we open it, to avoid a faux pas such as holding lock for a long
2015 * time on a rel we have no permissions for.
2016 */
2017 rels = list_copy(explicit_rels);
2018 if (behavior == DROP_CASCADE)
2019 {
2020 for (;;)
2021 {
2022 List *newrelids;
2023
2025 if (newrelids == NIL)
2026 break; /* nothing else to add */
2027
2028 foreach(cell, newrelids)
2029 {
2030 Oid relid = lfirst_oid(cell);
2031 Relation rel;
2032
2033 rel = table_open(relid, AccessExclusiveLock);
2035 (errmsg("truncate cascades to table \"%s\"",
2037 truncate_check_rel(relid, rel->rd_rel);
2038 truncate_check_perms(relid, rel->rd_rel);
2040 rels = lappend(rels, rel);
2041 relids = lappend_oid(relids, relid);
2042
2043 /* Log this relation only if needed for logical decoding */
2046 }
2047 }
2048 }
2049
2050 /*
2051 * Check foreign key references. In CASCADE mode, this should be
2052 * unnecessary since we just pulled in all the references; but as a
2053 * cross-check, do it anyway if in an Assert-enabled build.
2054 */
2055#ifdef USE_ASSERT_CHECKING
2056 heap_truncate_check_FKs(rels, false);
2057#else
2058 if (behavior == DROP_RESTRICT)
2059 heap_truncate_check_FKs(rels, false);
2060#endif
2061
2062 /*
2063 * If we are asked to restart sequences, find all the sequences, lock them
2064 * (we need AccessExclusiveLock for ResetSequence), and check permissions.
2065 * We want to do this early since it's pointless to do all the truncation
2066 * work only to fail on sequence permissions.
2067 */
2068 if (restart_seqs)
2069 {
2070 foreach(cell, rels)
2071 {
2072 Relation rel = (Relation) lfirst(cell);
2075
2076 foreach(seqcell, seqlist)
2077 {
2080
2082
2083 /* This check must match AlterSequence! */
2087
2089
2091 }
2092 }
2093 }
2094
2095 /* Prepare to catch AFTER triggers. */
2097
2098 /*
2099 * To fire triggers, we'll need an EState as well as a ResultRelInfo for
2100 * each relation. We don't need to call ExecOpenIndices, though.
2101 *
2102 * We put the ResultRelInfos in the es_opened_result_relations list, even
2103 * though we don't have a range table and don't populate the
2104 * es_result_relations array. That's a bit bogus, but it's enough to make
2105 * ExecGetTriggerResultRel() find them.
2106 */
2107 estate = CreateExecutorState();
2109 palloc(list_length(rels) * sizeof(ResultRelInfo));
2110 resultRelInfo = resultRelInfos;
2111 foreach(cell, rels)
2112 {
2113 Relation rel = (Relation) lfirst(cell);
2114
2115 InitResultRelInfo(resultRelInfo,
2116 rel,
2117 0, /* dummy rangetable index */
2118 NULL,
2119 0);
2121 lappend(estate->es_opened_result_relations, resultRelInfo);
2122 resultRelInfo++;
2123 }
2124
2125 /*
2126 * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
2127 * truncating (this is because one of them might throw an error). Also, if
2128 * we were to allow them to prevent statement execution, that would need
2129 * to be handled here.
2130 */
2131 resultRelInfo = resultRelInfos;
2132 foreach(cell, rels)
2133 {
2135
2137 SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
2138 &ucxt);
2139 ExecBSTruncateTriggers(estate, resultRelInfo);
2142 resultRelInfo++;
2143 }
2144
2145 /*
2146 * OK, truncate each table.
2147 */
2149
2150 foreach(cell, rels)
2151 {
2152 Relation rel = (Relation) lfirst(cell);
2153
2154 /* Skip partitioned tables as there is nothing to do */
2155 if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2156 continue;
2157
2158 /*
2159 * Build the lists of foreign tables belonging to each foreign server
2160 * and pass each list to the foreign data wrapper's callback function,
2161 * so that each server can truncate its all foreign tables in bulk.
2162 * Each list is saved as a single entry in a hash table that uses the
2163 * server OID as lookup key.
2164 */
2165 if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2166 {
2168 bool found;
2170
2171 /* First time through, initialize hashtable for foreign tables */
2172 if (!ft_htab)
2173 {
2174 HASHCTL hctl;
2175
2176 memset(&hctl, 0, sizeof(HASHCTL));
2177 hctl.keysize = sizeof(Oid);
2178 hctl.entrysize = sizeof(ForeignTruncateInfo);
2180
2181 ft_htab = hash_create("TRUNCATE for Foreign Tables",
2182 32, /* start small and extend */
2183 &hctl,
2185 }
2186
2187 /* Find or create cached entry for the foreign table */
2188 ft_info = hash_search(ft_htab, &serverid, HASH_ENTER, &found);
2189 if (!found)
2190 ft_info->rels = NIL;
2191
2192 /*
2193 * Save the foreign table in the entry of the server that the
2194 * foreign table belongs to.
2195 */
2196 ft_info->rels = lappend(ft_info->rels, rel);
2197 continue;
2198 }
2199
2200 /*
2201 * Normally, we need a transaction-safe truncation here. However, if
2202 * the table was either created in the current (sub)transaction or has
2203 * a new relfilenumber in the current (sub)transaction, then we can
2204 * just truncate it in-place, because a rollback would cause the whole
2205 * table or the current physical file to be thrown away anyway.
2206 */
2207 if (rel->rd_createSubid == mySubid ||
2209 {
2210 /* Immediate, non-rollbackable truncation is OK */
2212 }
2213 else
2214 {
2218
2219 /*
2220 * This effectively deletes all rows in the table, and may be done
2221 * in a serializable transaction. In that case we must record a
2222 * rw-conflict in to this transaction from each transaction
2223 * holding a predicate lock on the table.
2224 */
2226
2227 /*
2228 * Need the full transaction-safe pushups.
2229 *
2230 * Create a new empty storage file for the relation, and assign it
2231 * as the relfilenumber value. The old storage file is scheduled
2232 * for deletion at commit.
2233 */
2234 RelationSetNewRelfilenumber(rel, rel->rd_rel->relpersistence);
2235
2237
2238 /*
2239 * The same for the toast table, if any.
2240 */
2241 toast_relid = rel->rd_rel->reltoastrelid;
2243 {
2246
2248 toastrel->rd_rel->relpersistence);
2250 }
2251
2252 /*
2253 * Reconstruct the indexes to match, and we're done.
2254 */
2257 }
2258
2260 }
2261
2262 /* Now go through the hash table, and truncate foreign tables */
2263 if (ft_htab)
2264 {
2267
2269
2270 PG_TRY();
2271 {
2272 while ((ft_info = hash_seq_search(&seq)) != NULL)
2273 {
2274 FdwRoutine *routine = GetFdwRoutineByServerId(ft_info->serverid);
2275
2276 /* truncate_check_rel() has checked that already */
2277 Assert(routine->ExecForeignTruncate != NULL);
2278
2279 routine->ExecForeignTruncate(ft_info->rels,
2280 behavior,
2281 restart_seqs);
2282 }
2283 }
2284 PG_FINALLY();
2285 {
2287 }
2288 PG_END_TRY();
2289 }
2290
2291 /*
2292 * Restart owned sequences if we were asked to.
2293 */
2294 foreach(cell, seq_relids)
2295 {
2296 Oid seq_relid = lfirst_oid(cell);
2297
2299 }
2300
2301 /*
2302 * Write a WAL record to allow this set of actions to be logically
2303 * decoded.
2304 *
2305 * Assemble an array of relids so we can write a single WAL record for the
2306 * whole action.
2307 */
2308 if (relids_logged != NIL)
2309 {
2311 int i = 0;
2312
2313 /* should only get here if effective_wal_level is 'logical' */
2315
2317 foreach(cell, relids_logged)
2318 logrelids[i++] = lfirst_oid(cell);
2319
2320 xlrec.dbId = MyDatabaseId;
2321 xlrec.nrelids = list_length(relids_logged);
2322 xlrec.flags = 0;
2323 if (behavior == DROP_CASCADE)
2324 xlrec.flags |= XLH_TRUNCATE_CASCADE;
2325 if (restart_seqs)
2327
2331
2333
2335 }
2336
2337 /*
2338 * Process all AFTER STATEMENT TRUNCATE triggers.
2339 */
2340 resultRelInfo = resultRelInfos;
2341 foreach(cell, rels)
2342 {
2344
2346 SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
2347 &ucxt);
2348 ExecASTruncateTriggers(estate, resultRelInfo);
2351 resultRelInfo++;
2352 }
2353
2354 /* Handle queued AFTER triggers */
2355 AfterTriggerEndQuery(estate);
2356
2357 /* We can clean up the EState now */
2358 FreeExecutorState(estate);
2359
2360 /*
2361 * Close any rels opened by CASCADE (can't do this while EState still
2362 * holds refs)
2363 */
2364 rels = list_difference_ptr(rels, explicit_rels);
2365 foreach(cell, rels)
2366 {
2367 Relation rel = (Relation) lfirst(cell);
2368
2369 table_close(rel, NoLock);
2370 }
2371}
uint32 SubTransactionId
Definition c.h:682
void ResetSequence(Oid seq_relid)
Definition sequence.c:255
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:1247
void FreeExecutorState(EState *estate)
Definition execUtils.c:192
EState * CreateExecutorState(void)
Definition execUtils.c:88
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:3770
void heap_truncate_check_FKs(List *relations, bool tempTables)
Definition heap.c:3675
void heap_truncate_one_rel(Relation rel)
Definition heap.c:3631
#define XLOG_HEAP_TRUNCATE
Definition heapam_xlog.h:36
#define XLH_TRUNCATE_RESTART_SEQS
#define SizeOfHeapTruncate
#define XLH_TRUNCATE_CASCADE
@ 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:3946
#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
void * palloc(Size size)
Definition mcxt.c:1387
MemoryContext CurrentMemoryContext
Definition mcxt.c:160
@ DROP_CASCADE
@ DROP_RESTRICT
@ OBJECT_SEQUENCE
List * getOwnedSequences(Oid relid)
Definition pg_depend.c:1009
void pgstat_count_truncate(Relation rel)
void CheckTableForSerializableConflictIn(Relation relation)
Definition predicate.c:4417
void RelationSetNewRelfilenumber(Relation relation, char persistence)
Definition relcache.c:3768
List * es_opened_result_relations
Definition execnodes.h:691
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
SubTransactionId rd_newRelfilelocatorSubid
Definition rel.h:104
SubTransactionId rd_createSubid
Definition rel.h:103
Relation ri_RelationDesc
Definition execnodes.h:483
static void truncate_check_perms(Oid relid, Form_pg_class reltuple)
Definition tablecmds.c:2429
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:5135
void AfterTriggerBeginQuery(void)
Definition trigger.c:5115
void SwitchToUntrustedUser(Oid userid, UserContext *context)
Definition usercontext.c:33
void RestoreUserContext(UserContext *context)
Definition usercontext.c:87
SubTransactionId GetCurrentSubTransactionId(void)
Definition xact.c:792
#define XLogLogicalInfoActive()
Definition xlog.h:136
#define XLOG_INCLUDE_ORIGIN
Definition xlog.h:165
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition xloginsert.c:478
void XLogRegisterData(const void *data, uint32 len)
Definition xloginsert.c:368
void XLogSetRecordFlags(uint8 flags)
Definition xloginsert.c:460
void XLogBeginInsert(void)
Definition xloginsert.c:152

References AccessExclusiveLock, aclcheck_error(), ACLCHECK_NOT_OWNER, AfterTriggerBeginQuery(), AfterTriggerEndQuery(), Assert, CheckTableForSerializableConflictIn(), CreateExecutorState(), CurrentMemoryContext, DROP_CASCADE, DROP_RESTRICT, HASHCTL::entrysize, ereport, errmsg(), EState::es_opened_result_relations, ExecASTruncateTriggers(), ExecBSTruncateTriggers(), FdwRoutine::ExecForeignTruncate, fb(), 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, 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(), ResetSequence(), RestoreUserContext(), ResultRelInfo::ri_RelationDesc, 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 
)
extern

Definition at line 6975 of file tablecmds.c.

6977{
6979 ScanKeyData key[2];
6982
6983 /* since this function recurses, it could be driven to stack overflow */
6985
6986 /*
6987 * We scan pg_depend to find those things that depend on the given type.
6988 * (We assume we can ignore refobjsubid for a type.)
6989 */
6991
6992 ScanKeyInit(&key[0],
6996 ScanKeyInit(&key[1],
6999 ObjectIdGetDatum(typeOid));
7000
7002 NULL, 2, key);
7003
7005 {
7007 Relation rel;
7010
7011 /* Check for directly dependent types */
7012 if (pg_depend->classid == TypeRelationId)
7013 {
7014 /*
7015 * This must be an array, domain, or range containing the given
7016 * type, so recursively check for uses of this type. Note that
7017 * any error message will mention the original type not the
7018 * container; this is intentional.
7019 */
7022 continue;
7023 }
7024
7025 /* Else, ignore dependees that aren't relations */
7026 if (pg_depend->classid != RelationRelationId)
7027 continue;
7028
7031
7032 /*
7033 * If objsubid identifies a specific column, refer to that in error
7034 * messages. Otherwise, search to see if there's a user column of the
7035 * type. (We assume system columns are never of interesting types.)
7036 * The search is needed because an index containing an expression
7037 * column of the target type will just be recorded as a whole-relation
7038 * dependency. If we do not find a column of the type, the dependency
7039 * must indicate that the type is transiently referenced in an index
7040 * expression but not stored on disk, which we assume is OK, just as
7041 * we do for references in views. (It could also be that the target
7042 * type is embedded in some container type that is stored in an index
7043 * column, but the previous recursion should catch such cases.)
7044 */
7045 if (pg_depend->objsubid > 0 && pg_depend->objsubid <= tupleDesc->natts)
7046 att = TupleDescAttr(tupleDesc, pg_depend->objsubid - 1);
7047 else
7048 {
7049 att = NULL;
7050 for (int attno = 1; attno <= tupleDesc->natts; attno++)
7051 {
7052 att = TupleDescAttr(tupleDesc, attno - 1);
7053 if (att->atttypid == typeOid && !att->attisdropped)
7054 break;
7055 att = NULL;
7056 }
7057 if (att == NULL)
7058 {
7059 /* No such column, so assume OK */
7061 continue;
7062 }
7063 }
7064
7065 /*
7066 * We definitely should reject if the relation has storage. If it's
7067 * partitioned, then perhaps we don't have to reject: if there are
7068 * partitions then we'll fail when we find one, else there is no
7069 * stored data to worry about. However, it's possible that the type
7070 * change would affect conclusions about whether the type is sortable
7071 * or hashable and thus (if it's a partitioning column) break the
7072 * partitioning rule. For now, reject for partitioned rels too.
7073 */
7074 if (RELKIND_HAS_STORAGE(rel->rd_rel->relkind) ||
7075 RELKIND_HAS_PARTITIONS(rel->rd_rel->relkind))
7076 {
7077 if (origTypeName)
7078 ereport(ERROR,
7080 errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
7083 NameStr(att->attname))));
7084 else if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
7085 ereport(ERROR,
7087 errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
7090 NameStr(att->attname))));
7091 else if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
7092 ereport(ERROR,
7094 errmsg("cannot alter foreign table \"%s\" because column \"%s.%s\" uses its row type",
7097 NameStr(att->attname))));
7098 else
7099 ereport(ERROR,
7101 errmsg("cannot alter table \"%s\" because column \"%s.%s\" uses its row type",
7104 NameStr(att->attname))));
7105 }
7106 else if (OidIsValid(rel->rd_rel->reltype))
7107 {
7108 /*
7109 * A view or composite type itself isn't a problem, but we must
7110 * recursively check for indirect dependencies via its rowtype.
7111 */
7114 }
7115
7117 }
7118
7120
7122}
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
END_CATALOG_STRUCT typedef FormData_pg_depend * Form_pg_depend
Definition pg_depend.h:76
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:6975

References AccessShareLock, BTEqualStrategyNumber, check_stack_depth(), ereport, errcode(), errmsg(), ERROR, fb(), find_composite_type_dependencies(), Form_pg_depend, GETSTRUCT(), HeapTupleIsValid, NameStr, 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 
)
extern

Definition at line 20084 of file tablecmds.c.

20086{
20088 TupleConstr *constr = RelationGetDescr(scanrel)->constr;
20089 int i;
20090
20091 if (constr && constr->has_not_null)
20092 {
20093 int natts = scanrel->rd_att->natts;
20094
20095 for (i = 1; i <= natts; i++)
20096 {
20098
20099 /* invalid not-null constraint must be ignored here */
20100 if (att->attnullability == ATTNULLABLE_VALID && !att->attisdropped)
20101 {
20104
20105 ntest->arg = (Expr *) makeVar(1,
20106 i,
20107 wholeatt->atttypid,
20108 wholeatt->atttypmod,
20109 wholeatt->attcollation,
20110 0);
20111 ntest->nulltesttype = IS_NOT_NULL;
20112
20113 /*
20114 * argisrow=false is correct even for a composite column,
20115 * because attnotnull does not represent a SQL-spec IS NOT
20116 * NULL test in such a case, just IS DISTINCT FROM NULL.
20117 */
20118 ntest->argisrow = false;
20119 ntest->location = -1;
20121 }
20122 }
20123 }
20124
20126}
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition makefuncs.c:66
@ IS_NOT_NULL
Definition primnodes.h:1978
TupleDesc rd_att
Definition rel.h:112
bool has_not_null
Definition tupdesc.h:45
ParseLoc location
Definition primnodes.h:311
static bool ConstraintImpliedByRelConstraint(Relation scanrel, List *testConstraint, List *provenConstraint)
#define ATTNULLABLE_VALID
Definition tupdesc.h:86
static CompactAttribute * TupleDescCompactAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:175

References ATTNULLABLE_VALID, ConstraintImpliedByRelConstraint(), fb(), TupleConstr::has_not_null, i, IS_NOT_NULL, lappend(), Var::location, makeNode, makeVar(), TupleDescData::natts, NIL, RelationData::rd_att, RelationGetDescr, TupleDescAttr(), and TupleDescCompactAttr().

Referenced by check_default_partition_contents(), and QueuePartitionConstraintValidation().

◆ PreCommit_on_commit_actions()

void PreCommit_on_commit_actions ( void  )
extern

Definition at line 19345 of file tablecmds.c.

19346{
19347 ListCell *l;
19350
19351 foreach(l, on_commits)
19352 {
19354
19355 /* Ignore entry if already dropped in this xact */
19356 if (oc->deleting_subid != InvalidSubTransactionId)
19357 continue;
19358
19359 switch (oc->oncommit)
19360 {
19361 case ONCOMMIT_NOOP:
19363 /* Do nothing (there shouldn't be such entries, actually) */
19364 break;
19366
19367 /*
19368 * If this transaction hasn't accessed any temporary
19369 * relations, we can skip truncating ON COMMIT DELETE ROWS
19370 * tables, as they must still be empty.
19371 */
19374 break;
19375 case ONCOMMIT_DROP:
19377 break;
19378 }
19379 }
19380
19381 /*
19382 * Truncate relations before dropping so that all dependencies between
19383 * relations are removed after they are worked on. Doing it like this
19384 * might be a waste as it is possible that a relation being truncated will
19385 * be dropped anyway due to its parent being dropped, but this makes the
19386 * code more robust because of not having to re-check that the relation
19387 * exists at truncation time.
19388 */
19389 if (oids_to_truncate != NIL)
19391
19392 if (oids_to_drop != NIL)
19393 {
19395
19396 foreach(l, oids_to_drop)
19397 {
19398 ObjectAddress object;
19399
19400 object.classId = RelationRelationId;
19401 object.objectId = lfirst_oid(l);
19402 object.objectSubId = 0;
19403
19405
19407 }
19408
19409 /*
19410 * Object deletion might involve toast table access (to clean up
19411 * toasted catalog entries), so ensure we have a valid snapshot.
19412 */
19414
19415 /*
19416 * Since this is an automatic drop, rather than one directly initiated
19417 * by the user, we pass the PERFORM_DELETION_INTERNAL flag.
19418 */
19421
19423
19424#ifdef USE_ASSERT_CHECKING
19425
19426 /*
19427 * Note that table deletion will call remove_on_commit_action, so the
19428 * entry should get marked as deleted.
19429 */
19430 foreach(l, on_commits)
19431 {
19433
19434 if (oc->oncommit != ONCOMMIT_DROP)
19435 continue;
19436
19437 Assert(oc->deleting_subid != InvalidSubTransactionId);
19438 }
19439#endif
19440 }
19441}
void performMultipleDeletions(const ObjectAddresses *objects, DropBehavior behavior, int flags)
Definition dependency.c:383
#define PERFORM_DELETION_QUIETLY
Definition dependency.h:94
#define PERFORM_DELETION_INTERNAL
Definition dependency.h:92
void heap_truncate(List *relids)
Definition heap.c:3590
@ ONCOMMIT_DELETE_ROWS
Definition primnodes.h:61
@ ONCOMMIT_PRESERVE_ROWS
Definition primnodes.h:60
@ ONCOMMIT_DROP
Definition primnodes.h:62
Snapshot GetTransactionSnapshot(void)
Definition snapmgr.c:272
void PushActiveSnapshot(Snapshot snapshot)
Definition snapmgr.c:682
void PopActiveSnapshot(void)
Definition snapmgr.c:775
int MyXactFlags
Definition xact.c:137
#define XACT_FLAGS_ACCESSEDTEMPNAMESPACE
Definition xact.h:103

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

Referenced by CommitTransaction(), and PrepareTransaction().

◆ RangeVarCallbackMaintainsTable()

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

Definition at line 19519 of file tablecmds.c.

19521{
19522 char relkind;
19524
19525 /* Nothing to do if the relation was not found. */
19526 if (!OidIsValid(relId))
19527 return;
19528
19529 /*
19530 * If the relation does exist, check whether it's an index. But note that
19531 * the relation might have been dropped between the time we did the name
19532 * lookup and now. In that case, there's nothing to do.
19533 */
19534 relkind = get_rel_relkind(relId);
19535 if (!relkind)
19536 return;
19537 if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
19538 relkind != RELKIND_MATVIEW && relkind != RELKIND_PARTITIONED_TABLE)
19539 ereport(ERROR,
19541 errmsg("\"%s\" is not a table or materialized view", relation->relname)));
19542
19543 /* Check permissions */
19545 if (aclresult != ACLCHECK_OK)
19548 relation->relname);
19549}
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition aclchk.c:4057
#define ACL_MAINTAIN
Definition parsenodes.h:90
char * relname
Definition primnodes.h:84

References ACL_MAINTAIN, aclcheck_error(), ACLCHECK_OK, ereport, errcode(), errmsg(), ERROR, fb(), 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 
)
extern

Definition at line 19579 of file tablecmds.c.

19581{
19582 HeapTuple tuple;
19583
19584 /* Nothing to do if the relation was not found. */
19585 if (!OidIsValid(relId))
19586 return;
19587
19588 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
19589 if (!HeapTupleIsValid(tuple)) /* should not happen */
19590 elog(ERROR, "cache lookup failed for relation %u", relId);
19591
19594 relation->relname);
19595
19596 if (!allowSystemTableMods &&
19597 IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
19598 ereport(ERROR,
19600 errmsg("permission denied: \"%s\" is a system catalog",
19601 relation->relname)));
19602
19603 ReleaseSysCache(tuple);
19604}
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
Definition catalog.c:86

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

Referenced by AlterSequence(), ProcessUtilitySlow(), transformPartitionCmdForMerge(), and transformPartitionCmdForSplit().

◆ register_on_commit_action()

void register_on_commit_action ( Oid  relid,
OnCommitAction  action 
)
extern

Definition at line 19286 of file tablecmds.c.

19287{
19290
19291 /*
19292 * We needn't bother registering the relation unless there is an ON COMMIT
19293 * action we need to take.
19294 */
19295 if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
19296 return;
19297
19299
19301 oc->relid = relid;
19302 oc->oncommit = action;
19303 oc->creating_subid = GetCurrentSubTransactionId();
19304 oc->deleting_subid = InvalidSubTransactionId;
19305
19306 /*
19307 * We use lcons() here so that ON COMMIT actions are processed in reverse
19308 * order of registration. That might not be essential but it seems
19309 * reasonable.
19310 */
19312
19314}
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 CacheMemoryContext, fb(), GetCurrentSubTransactionId(), InvalidSubTransactionId, lcons(), MemoryContextSwitchTo(), on_commits, ONCOMMIT_NOOP, ONCOMMIT_PRESERVE_ROWS, and palloc_object.

Referenced by heap_create_with_catalog().

◆ remove_on_commit_action()

void remove_on_commit_action ( Oid  relid)
extern

Definition at line 19322 of file tablecmds.c.

19323{
19324 ListCell *l;
19325
19326 foreach(l, on_commits)
19327 {
19329
19330 if (oc->relid == relid)
19331 {
19333 break;
19334 }
19335 }
19336}
SubTransactionId deleting_subid
Definition tablecmds.c:129

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

Referenced by heap_drop_with_catalog().

◆ RemoveRelations()

void RemoveRelations ( DropStmt drop)
extern

Definition at line 1544 of file tablecmds.c.

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

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

Referenced by ExecDropStmt().

◆ renameatt()

ObjectAddress renameatt ( RenameStmt stmt)
extern

Definition at line 4017 of file tablecmds.c.

4018{
4019 Oid relid;
4021 ObjectAddress address;
4022
4023 /* lock level taken here should match renameatt_internal */
4025 stmt->missing_ok ? RVR_MISSING_OK : 0,
4027 NULL);
4028
4029 if (!OidIsValid(relid))
4030 {
4032 (errmsg("relation \"%s\" does not exist, skipping",
4033 stmt->relation->relname)));
4034 return InvalidObjectAddress;
4035 }
4036
4037 attnum =
4038 renameatt_internal(relid,
4039 stmt->subname, /* old att name */
4040 stmt->newname, /* new att name */
4041 stmt->relation->inh, /* recursive? */
4042 false, /* recursing? */
4043 0, /* expected inhcount */
4044 stmt->behavior);
4045
4047
4048 return address;
4049}
#define ObjectAddressSubSet(addr, class_id, object_id, object_sub_id)
static AttrNumber renameatt_internal(Oid myrelid, const char *oldattname, const char *newattname, bool recurse, bool recursing, int expected_parents, DropBehavior behavior)
Definition tablecmds.c:3852
static void RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition tablecmds.c:3997

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

Referenced by ExecRenameStmt().

◆ RenameConstraint()

ObjectAddress RenameConstraint ( RenameStmt stmt)
extern

Definition at line 4164 of file tablecmds.c.

4165{
4166 Oid relid = InvalidOid;
4167 Oid typid = InvalidOid;
4168
4169 if (stmt->renameType == OBJECT_DOMCONSTRAINT)
4170 {
4171 Relation rel;
4172 HeapTuple tup;
4173
4177 if (!HeapTupleIsValid(tup))
4178 elog(ERROR, "cache lookup failed for type %u", typid);
4181 table_close(rel, NoLock);
4182 }
4183 else
4184 {
4185 /* lock level taken here should match rename_constraint_internal */
4187 stmt->missing_ok ? RVR_MISSING_OK : 0,
4189 NULL);
4190 if (!OidIsValid(relid))
4191 {
4193 (errmsg("relation \"%s\" does not exist, skipping",
4194 stmt->relation->relname)));
4195 return InvalidObjectAddress;
4196 }
4197 }
4198
4199 return
4200 rename_constraint_internal(relid, typid,
4201 stmt->subname,
4202 stmt->newname,
4203 (stmt->relation &&
4204 stmt->relation->inh), /* recursive? */
4205 false, /* recursing? */
4206 0 /* expected inhcount */ );
4207}
TypeName * makeTypeNameFromNameList(List *names)
Definition makefuncs.c:531
#define castNode(_type_, nodeptr)
Definition nodes.h:182
@ OBJECT_DOMCONSTRAINT
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:4055
void checkDomainOwner(HeapTuple tup)
Definition typecmds.c:3527

References AccessExclusiveLock, castNode, checkDomainOwner(), elog, ereport, errmsg(), ERROR, fb(), 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)
extern

Definition at line 4214 of file tablecmds.c.

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

References AccessExclusiveLock, ereport, errmsg(), fb(), 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 
)
extern

Definition at line 4278 of file tablecmds.c.

4279{
4281 Relation relrelation; /* for RELATION relation */
4286
4287 /*
4288 * Grab a lock on the target relation, which we will NOT release until end
4289 * of transaction. We need at least a self-exclusive lock so that
4290 * concurrent DDL doesn't overwrite the rename if they start updating
4291 * while still seeing the old version. The lock also guards against
4292 * triggering relcache reloads in concurrent sessions, which might not
4293 * handle this information changing under them. For indexes, we can use a
4294 * reduced lock level because RelationReloadIndexInfo() handles indexes
4295 * specially.
4296 */
4299
4300 /*
4301 * Find relation's pg_class tuple, and make sure newrelname isn't in use.
4302 */
4304
4306 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
4307 elog(ERROR, "cache lookup failed for relation %u", myrelid);
4308 otid = reltup->t_self;
4310
4312 ereport(ERROR,
4314 errmsg("relation \"%s\" already exists",
4315 newrelname)));
4316
4317 /*
4318 * RenameRelation is careful not to believe the caller's idea of the
4319 * relation kind being handled. We don't have to worry about this, but
4320 * let's not be totally oblivious to it. We can process an index as
4321 * not-an-index, but not the other way around.
4322 */
4323 Assert(!is_index ||
4324 is_index == (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
4325 targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX));
4326
4327 /*
4328 * Update pg_class tuple with new relname. (Scribbling on reltup is OK
4329 * because it's a copy...)
4330 */
4331 namestrcpy(&(relform->relname), newrelname);
4332
4335
4337 InvalidOid, is_internal);
4338
4341
4342 /*
4343 * Also rename the associated type, if any.
4344 */
4345 if (OidIsValid(targetrelation->rd_rel->reltype))
4346 RenameTypeInternal(targetrelation->rd_rel->reltype,
4348
4349 /*
4350 * Also rename the associated constraint, if any.
4351 */
4352 if (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
4353 targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
4354 {
4356
4359 }
4360
4361 /*
4362 * Close rel, but keep lock!
4363 */
4365}
void namestrcpy(Name name, const char *str)
Definition name.c:233
#define InvokeObjectPostAlterHookArg(classId, objectId, subId, auxiliaryId, is_internal)
void RenameConstraintById(Oid conId, const char *newname)
Oid get_index_constraint(Oid indexId)
Definition pg_depend.c:1061
void RenameTypeInternal(Oid typeOid, const char *newTypeName, Oid typeNamespace)
Definition pg_type.c:763

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

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

◆ ResetRelRewrite()

void ResetRelRewrite ( Oid  myrelid)
extern

Definition at line 4371 of file tablecmds.c.

4372{
4373 Relation relrelation; /* for RELATION relation */
4376
4377 /*
4378 * Find relation's pg_class tuple.
4379 */
4381
4383 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
4384 elog(ERROR, "cache lookup failed for relation %u", myrelid);
4386
4387 /*
4388 * Update pg_class tuple.
4389 */
4390 relform->relrewrite = InvalidOid;
4391
4393
4396}
#define SearchSysCacheCopy1(cacheId, key1)
Definition syscache.h:91

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

Referenced by finish_heap_swap().

◆ SetRelationHasSubclass()

void SetRelationHasSubclass ( Oid  relationId,
bool  relhassubclass 
)
extern

Definition at line 3655 of file tablecmds.c.

3656{
3658 HeapTuple tuple;
3660
3662 ShareUpdateExclusiveLock, false) ||
3664 ShareRowExclusiveLock, true));
3665
3666 /*
3667 * Fetch a modifiable copy of the tuple, modify it, update pg_class.
3668 */
3671 if (!HeapTupleIsValid(tuple))
3672 elog(ERROR, "cache lookup failed for relation %u", relationId);
3674
3675 if (classtuple->relhassubclass != relhassubclass)
3676 {
3677 classtuple->relhassubclass = relhassubclass;
3679 }
3680 else
3681 {
3682 /* no need to change tuple, but force relcache rebuild anyway */
3684 }
3685
3686 heap_freetuple(tuple);
3688}
void CacheInvalidateRelcacheByTuple(HeapTuple classTuple)
Definition inval.c:1669
bool CheckRelationOidLockedByMe(Oid relid, LOCKMODE lockmode, bool orstronger)
Definition lmgr.c:351

References Assert, CacheInvalidateRelcacheByTuple(), CatalogTupleUpdate(), CheckRelationOidLockedByMe(), elog, ERROR, fb(), 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 
)
extern

Definition at line 3758 of file tablecmds.c.

3761{
3763 HeapTuple tuple;
3765 Form_pg_class rd_rel;
3766 Oid reloid = RelationGetRelid(rel);
3767
3769
3770 /* Get a modifiable copy of the relation's pg_class row. */
3772
3774 if (!HeapTupleIsValid(tuple))
3775 elog(ERROR, "cache lookup failed for relation %u", reloid);
3776 otid = tuple->t_self;
3777 rd_rel = (Form_pg_class) GETSTRUCT(tuple);
3778
3779 /* Update the pg_class row. */
3780 rd_rel->reltablespace = (newTableSpaceId == MyDatabaseTableSpace) ?
3783 rd_rel->relfilenode = newRelFilenumber;
3786
3787 /*
3788 * Record dependency on tablespace. This is only required for relations
3789 * that have no physical storage.
3790 */
3791 if (!RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
3793 rd_rel->reltablespace);
3794
3795 heap_freetuple(tuple);
3797}
void changeDependencyOnTablespace(Oid classId, Oid objectId, Oid newTablespaceId)
#define RelFileNumberIsValid(relnumber)
Definition relpath.h:27
bool CheckRelationTableSpaceMove(Relation rel, Oid newTableSpaceId)
Definition tablecmds.c:3701

References Assert, CatalogTupleUpdate(), changeDependencyOnTablespace(), CheckRelationTableSpaceMove(), elog, ERROR, fb(), 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().