PostgreSQL Source Code  git master
tablecmds.h File Reference
#include "access/htup.h"
#include "catalog/dependency.h"
#include "catalog/objectaddress.h"
#include "nodes/parsenodes.h"
#include "storage/lock.h"
#include "utils/relcache.h"
Include dependency graph for tablecmds.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

ObjectAddress DefineRelation (CreateStmt *stmt, char relkind, Oid ownerId, ObjectAddress *typaddress, const char *queryString)
 
void RemoveRelations (DropStmt *drop)
 
Oid AlterTableLookupRelation (AlterTableStmt *stmt, LOCKMODE lockmode)
 
void AlterTable (AlterTableStmt *stmt, LOCKMODE lockmode, struct AlterTableUtilityContext *context)
 
LOCKMODE AlterTableGetLockLevel (List *cmds)
 
void ATExecChangeOwner (Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
 
void AlterTableInternal (Oid relid, List *cmds, bool recurse)
 
Oid AlterTableMoveAll (AlterTableMoveAllStmt *stmt)
 
ObjectAddress AlterTableNamespace (AlterObjectSchemaStmt *stmt, Oid *oldschema)
 
void AlterTableNamespaceInternal (Relation rel, Oid oldNspOid, Oid nspOid, ObjectAddresses *objsMoved)
 
void AlterRelationNamespaceInternal (Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
 
void CheckTableNotInUse (Relation rel, const char *stmt)
 
void ExecuteTruncate (TruncateStmt *stmt)
 
void ExecuteTruncateGuts (List *explicit_rels, List *relids, List *relids_logged, DropBehavior behavior, bool restart_seqs)
 
void SetRelationHasSubclass (Oid relationId, bool relhassubclass)
 
bool CheckRelationTableSpaceMove (Relation rel, Oid newTableSpaceId)
 
void SetRelationTableSpace (Relation rel, Oid newTableSpaceId, Oid newRelFileNode)
 
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 RangeVarCallbackOwnsTable (const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
 
void RangeVarCallbackOwnsRelation (const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
 
bool PartConstraintImpliedByRelConstraint (Relation scanrel, List *partConstraint)
 

Function Documentation

◆ AlterRelationNamespaceInternal()

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

Definition at line 16446 of file tablecmds.c.

16450 {
16451  HeapTuple classTup;
16452  Form_pg_class classForm;
16453  ObjectAddress thisobj;
16454  bool already_done = false;
16455 
16456  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
16457  if (!HeapTupleIsValid(classTup))
16458  elog(ERROR, "cache lookup failed for relation %u", relOid);
16459  classForm = (Form_pg_class) GETSTRUCT(classTup);
16460 
16461  Assert(classForm->relnamespace == oldNspOid);
16462 
16463  thisobj.classId = RelationRelationId;
16464  thisobj.objectId = relOid;
16465  thisobj.objectSubId = 0;
16466 
16467  /*
16468  * If the object has already been moved, don't move it again. If it's
16469  * already in the right place, don't move it, but still fire the object
16470  * access hook.
16471  */
16472  already_done = object_address_present(&thisobj, objsMoved);
16473  if (!already_done && oldNspOid != newNspOid)
16474  {
16475  /* check for duplicate name (more friendly than unique-index failure) */
16476  if (get_relname_relid(NameStr(classForm->relname),
16477  newNspOid) != InvalidOid)
16478  ereport(ERROR,
16479  (errcode(ERRCODE_DUPLICATE_TABLE),
16480  errmsg("relation \"%s\" already exists in schema \"%s\"",
16481  NameStr(classForm->relname),
16482  get_namespace_name(newNspOid))));
16483 
16484  /* classTup is a copy, so OK to scribble on */
16485  classForm->relnamespace = newNspOid;
16486 
16487  CatalogTupleUpdate(classRel, &classTup->t_self, classTup);
16488 
16489  /* Update dependency on schema if caller said so */
16490  if (hasDependEntry &&
16491  changeDependencyFor(RelationRelationId,
16492  relOid,
16493  NamespaceRelationId,
16494  oldNspOid,
16495  newNspOid) != 1)
16496  elog(ERROR, "failed to change schema dependency for relation \"%s\"",
16497  NameStr(classForm->relname));
16498  }
16499  if (!already_done)
16500  {
16501  add_exact_object_address(&thisobj, objsMoved);
16502 
16503  InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
16504  }
16505 
16506  heap_freetuple(classTup);
16507 }
#define NameStr(name)
Definition: c.h:681
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2560
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2500
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
#define ereport(elevel,...)
Definition: elog.h:143
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
Assert(fmt[strlen(fmt) - 1] !='\n')
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1856
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
long changeDependencyFor(Oid classId, Oid objectId, Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition: pg_depend.c:399
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define InvalidOid
Definition: postgres_ext.h:36
ItemPointerData t_self
Definition: htup.h:65
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:177
@ RELOID
Definition: syscache.h:87

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

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

◆ AlterTable()

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

Definition at line 4047 of file tablecmds.c.

4049 {
4050  Relation rel;
4051 
4052  /* Caller is required to provide an adequate lock. */
4053  rel = relation_open(context->relid, NoLock);
4054 
4055  CheckTableNotInUse(rel, "ALTER TABLE");
4056 
4057  ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
4058 }
#define NoLock
Definition: lockdefs.h:34
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
RangeVar * relation
Definition: parsenodes.h:1872
bool inh
Definition: primnodes.h:69
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3963
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:4392

References ATController(), CheckTableNotInUse(), AlterTableStmt::cmds, RangeVar::inh, NoLock, AlterTableStmt::relation, relation_open(), and AlterTableUtilityContext::relid.

Referenced by ProcessUtilitySlow().

◆ AlterTableGetLockLevel()

LOCKMODE AlterTableGetLockLevel ( List cmds)

Definition at line 4121 of file tablecmds.c.

4122 {
4123  /*
4124  * This only works if we read catalog tables using MVCC snapshots.
4125  */
4126  ListCell *lcmd;
4128 
4129  foreach(lcmd, cmds)
4130  {
4131  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
4132  LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
4133 
4134  switch (cmd->subtype)
4135  {
4136  /*
4137  * These subcommands rewrite the heap, so require full locks.
4138  */
4139  case AT_AddColumn: /* may rewrite heap, in some cases and visible
4140  * to SELECT */
4141  case AT_SetAccessMethod: /* must rewrite heap */
4142  case AT_SetTableSpace: /* must rewrite heap */
4143  case AT_AlterColumnType: /* must rewrite heap */
4144  cmd_lockmode = AccessExclusiveLock;
4145  break;
4146 
4147  /*
4148  * These subcommands may require addition of toast tables. If
4149  * we add a toast table to a table currently being scanned, we
4150  * might miss data added to the new toast table by concurrent
4151  * insert transactions.
4152  */
4153  case AT_SetStorage: /* may add toast tables, see
4154  * ATRewriteCatalogs() */
4155  cmd_lockmode = AccessExclusiveLock;
4156  break;
4157 
4158  /*
4159  * Removing constraints can affect SELECTs that have been
4160  * optimized assuming the constraint holds true. See also
4161  * CloneFkReferenced.
4162  */
4163  case AT_DropConstraint: /* as DROP INDEX */
4164  case AT_DropNotNull: /* may change some SQL plans */
4165  cmd_lockmode = AccessExclusiveLock;
4166  break;
4167 
4168  /*
4169  * Subcommands that may be visible to concurrent SELECTs
4170  */
4171  case AT_DropColumn: /* change visible to SELECT */
4172  case AT_AddColumnToView: /* CREATE VIEW */
4173  case AT_DropOids: /* used to equiv to DropColumn */
4174  case AT_EnableAlwaysRule: /* may change SELECT rules */
4175  case AT_EnableReplicaRule: /* may change SELECT rules */
4176  case AT_EnableRule: /* may change SELECT rules */
4177  case AT_DisableRule: /* may change SELECT rules */
4178  cmd_lockmode = AccessExclusiveLock;
4179  break;
4180 
4181  /*
4182  * Changing owner may remove implicit SELECT privileges
4183  */
4184  case AT_ChangeOwner: /* change visible to SELECT */
4185  cmd_lockmode = AccessExclusiveLock;
4186  break;
4187 
4188  /*
4189  * Changing foreign table options may affect optimization.
4190  */
4191  case AT_GenericOptions:
4193  cmd_lockmode = AccessExclusiveLock;
4194  break;
4195 
4196  /*
4197  * These subcommands affect write operations only.
4198  */
4199  case AT_EnableTrig:
4200  case AT_EnableAlwaysTrig:
4201  case AT_EnableReplicaTrig:
4202  case AT_EnableTrigAll:
4203  case AT_EnableTrigUser:
4204  case AT_DisableTrig:
4205  case AT_DisableTrigAll:
4206  case AT_DisableTrigUser:
4207  cmd_lockmode = ShareRowExclusiveLock;
4208  break;
4209 
4210  /*
4211  * These subcommands affect write operations only. XXX
4212  * Theoretically, these could be ShareRowExclusiveLock.
4213  */
4214  case AT_ColumnDefault:
4216  case AT_AlterConstraint:
4217  case AT_AddIndex: /* from ADD CONSTRAINT */
4218  case AT_AddIndexConstraint:
4219  case AT_ReplicaIdentity:
4220  case AT_SetNotNull:
4221  case AT_EnableRowSecurity:
4222  case AT_DisableRowSecurity:
4223  case AT_ForceRowSecurity:
4224  case AT_NoForceRowSecurity:
4225  case AT_AddIdentity:
4226  case AT_DropIdentity:
4227  case AT_SetIdentity:
4228  case AT_DropExpression:
4229  case AT_SetCompression:
4230  cmd_lockmode = AccessExclusiveLock;
4231  break;
4232 
4233  case AT_AddConstraint:
4234  case AT_AddConstraintRecurse: /* becomes AT_AddConstraint */
4235  case AT_ReAddConstraint: /* becomes AT_AddConstraint */
4236  case AT_ReAddDomainConstraint: /* becomes AT_AddConstraint */
4237  if (IsA(cmd->def, Constraint))
4238  {
4239  Constraint *con = (Constraint *) cmd->def;
4240 
4241  switch (con->contype)
4242  {
4243  case CONSTR_EXCLUSION:
4244  case CONSTR_PRIMARY:
4245  case CONSTR_UNIQUE:
4246 
4247  /*
4248  * Cases essentially the same as CREATE INDEX. We
4249  * could reduce the lock strength to ShareLock if
4250  * we can work out how to allow concurrent catalog
4251  * updates. XXX Might be set down to
4252  * ShareRowExclusiveLock but requires further
4253  * analysis.
4254  */
4255  cmd_lockmode = AccessExclusiveLock;
4256  break;
4257  case CONSTR_FOREIGN:
4258 
4259  /*
4260  * We add triggers to both tables when we add a
4261  * Foreign Key, so the lock level must be at least
4262  * as strong as CREATE TRIGGER.
4263  */
4264  cmd_lockmode = ShareRowExclusiveLock;
4265  break;
4266 
4267  default:
4268  cmd_lockmode = AccessExclusiveLock;
4269  }
4270  }
4271  break;
4272 
4273  /*
4274  * These subcommands affect inheritance behaviour. Queries
4275  * started before us will continue to see the old inheritance
4276  * behaviour, while queries started after we commit will see
4277  * new behaviour. No need to prevent reads or writes to the
4278  * subtable while we hook it up though. Changing the TupDesc
4279  * may be a problem, so keep highest lock.
4280  */
4281  case AT_AddInherit:
4282  case AT_DropInherit:
4283  cmd_lockmode = AccessExclusiveLock;
4284  break;
4285 
4286  /*
4287  * These subcommands affect implicit row type conversion. They
4288  * have affects similar to CREATE/DROP CAST on queries. don't
4289  * provide for invalidating parse trees as a result of such
4290  * changes, so we keep these at AccessExclusiveLock.
4291  */
4292  case AT_AddOf:
4293  case AT_DropOf:
4294  cmd_lockmode = AccessExclusiveLock;
4295  break;
4296 
4297  /*
4298  * Only used by CREATE OR REPLACE VIEW which must conflict
4299  * with an SELECTs currently using the view.
4300  */
4301  case AT_ReplaceRelOptions:
4302  cmd_lockmode = AccessExclusiveLock;
4303  break;
4304 
4305  /*
4306  * These subcommands affect general strategies for performance
4307  * and maintenance, though don't change the semantic results
4308  * from normal data reads and writes. Delaying an ALTER TABLE
4309  * behind currently active writes only delays the point where
4310  * the new strategy begins to take effect, so there is no
4311  * benefit in waiting. In this case the minimum restriction
4312  * applies: we don't currently allow concurrent catalog
4313  * updates.
4314  */
4315  case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
4316  case AT_ClusterOn: /* Uses MVCC in getIndexes() */
4317  case AT_DropCluster: /* Uses MVCC in getIndexes() */
4318  case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
4319  case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
4320  cmd_lockmode = ShareUpdateExclusiveLock;
4321  break;
4322 
4323  case AT_SetLogged:
4324  case AT_SetUnLogged:
4325  cmd_lockmode = AccessExclusiveLock;
4326  break;
4327 
4328  case AT_ValidateConstraint: /* Uses MVCC in getConstraints() */
4329  cmd_lockmode = ShareUpdateExclusiveLock;
4330  break;
4331 
4332  /*
4333  * Rel options are more complex than first appears. Options
4334  * are set here for tables, views and indexes; for historical
4335  * reasons these can all be used with ALTER TABLE, so we can't
4336  * decide between them using the basic grammar.
4337  */
4338  case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
4339  * getTables() */
4340  case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
4341  * getTables() */
4342  cmd_lockmode = AlterTableGetRelOptionsLockLevel((List *) cmd->def);
4343  break;
4344 
4345  case AT_AttachPartition:
4346  cmd_lockmode = ShareUpdateExclusiveLock;
4347  break;
4348 
4349  case AT_DetachPartition:
4350  if (((PartitionCmd *) cmd->def)->concurrent)
4351  cmd_lockmode = ShareUpdateExclusiveLock;
4352  else
4353  cmd_lockmode = AccessExclusiveLock;
4354  break;
4355 
4357  cmd_lockmode = ShareUpdateExclusiveLock;
4358  break;
4359 
4360  case AT_CheckNotNull:
4361 
4362  /*
4363  * This only examines the table's schema; but lock must be
4364  * strong enough to prevent concurrent DROP NOT NULL.
4365  */
4366  cmd_lockmode = AccessShareLock;
4367  break;
4368 
4369  default: /* oops */
4370  elog(ERROR, "unrecognized alter table type: %d",
4371  (int) cmd->subtype);
4372  break;
4373  }
4374 
4375  /*
4376  * Take the greatest lockmode from any subcommand
4377  */
4378  if (cmd_lockmode > lockmode)
4379  lockmode = cmd_lockmode;
4380  }
4381 
4382  return lockmode;
4383 }
int LOCKMODE
Definition: lockdefs.h:26
#define AccessExclusiveLock
Definition: lockdefs.h:43
#define ShareRowExclusiveLock
Definition: lockdefs.h:41
#define AccessShareLock
Definition: lockdefs.h:36
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
@ CONSTR_FOREIGN
Definition: parsenodes.h:2242
@ CONSTR_UNIQUE
Definition: parsenodes.h:2240
@ CONSTR_EXCLUSION
Definition: parsenodes.h:2241
@ CONSTR_PRIMARY
Definition: parsenodes.h:2239
@ AT_AddIndexConstraint
Definition: parsenodes.h:1905
@ AT_DropOf
Definition: parsenodes.h:1937
@ AT_CheckNotNull
Definition: parsenodes.h:1888
@ AT_SetOptions
Definition: parsenodes.h:1890
@ AT_DropIdentity
Definition: parsenodes.h:1949
@ AT_DisableTrigUser
Definition: parsenodes.h:1929
@ AT_DropNotNull
Definition: parsenodes.h:1885
@ AT_AddOf
Definition: parsenodes.h:1936
@ AT_ResetOptions
Definition: parsenodes.h:1891
@ AT_ReplicaIdentity
Definition: parsenodes.h:1938
@ AT_ReplaceRelOptions
Definition: parsenodes.h:1921
@ AT_EnableRowSecurity
Definition: parsenodes.h:1939
@ AT_AddColumnToView
Definition: parsenodes.h:1882
@ AT_ResetRelOptions
Definition: parsenodes.h:1920
@ AT_AddConstraintRecurse
Definition: parsenodes.h:1899
@ AT_EnableReplicaTrig
Definition: parsenodes.h:1924
@ AT_DropOids
Definition: parsenodes.h:1916
@ AT_SetIdentity
Definition: parsenodes.h:1948
@ AT_SetUnLogged
Definition: parsenodes.h:1915
@ AT_DisableTrig
Definition: parsenodes.h:1925
@ AT_SetCompression
Definition: parsenodes.h:1893
@ AT_DropExpression
Definition: parsenodes.h:1887
@ AT_AddIndex
Definition: parsenodes.h:1896
@ AT_EnableReplicaRule
Definition: parsenodes.h:1932
@ AT_DropConstraint
Definition: parsenodes.h:1906
@ AT_SetNotNull
Definition: parsenodes.h:1886
@ AT_ClusterOn
Definition: parsenodes.h:1912
@ AT_AddIdentity
Definition: parsenodes.h:1947
@ AT_ForceRowSecurity
Definition: parsenodes.h:1941
@ AT_EnableAlwaysRule
Definition: parsenodes.h:1931
@ AT_SetAccessMethod
Definition: parsenodes.h:1917
@ AT_AlterColumnType
Definition: parsenodes.h:1909
@ AT_DetachPartitionFinalize
Definition: parsenodes.h:1946
@ AT_AddInherit
Definition: parsenodes.h:1934
@ AT_ReAddDomainConstraint
Definition: parsenodes.h:1901
@ AT_EnableTrig
Definition: parsenodes.h:1922
@ AT_DropColumn
Definition: parsenodes.h:1894
@ AT_AlterColumnGenericOptions
Definition: parsenodes.h:1910
@ AT_DisableTrigAll
Definition: parsenodes.h:1927
@ AT_EnableRule
Definition: parsenodes.h:1930
@ AT_NoForceRowSecurity
Definition: parsenodes.h:1942
@ AT_DetachPartition
Definition: parsenodes.h:1945
@ AT_SetStatistics
Definition: parsenodes.h:1889
@ AT_AttachPartition
Definition: parsenodes.h:1944
@ AT_AddConstraint
Definition: parsenodes.h:1898
@ AT_DropInherit
Definition: parsenodes.h:1935
@ AT_EnableAlwaysTrig
Definition: parsenodes.h:1923
@ AT_SetLogged
Definition: parsenodes.h:1914
@ AT_SetStorage
Definition: parsenodes.h:1892
@ AT_DisableRule
Definition: parsenodes.h:1933
@ AT_DisableRowSecurity
Definition: parsenodes.h:1940
@ AT_SetRelOptions
Definition: parsenodes.h:1919
@ AT_ChangeOwner
Definition: parsenodes.h:1911
@ AT_EnableTrigUser
Definition: parsenodes.h:1928
@ AT_ReAddConstraint
Definition: parsenodes.h:1900
@ AT_SetTableSpace
Definition: parsenodes.h:1918
@ AT_GenericOptions
Definition: parsenodes.h:1943
@ AT_ColumnDefault
Definition: parsenodes.h:1883
@ AT_CookedColumnDefault
Definition: parsenodes.h:1884
@ AT_AlterConstraint
Definition: parsenodes.h:1902
@ AT_EnableTrigAll
Definition: parsenodes.h:1926
@ AT_DropCluster
Definition: parsenodes.h:1913
@ AT_ValidateConstraint
Definition: parsenodes.h:1903
@ AT_AddColumn
Definition: parsenodes.h:1880
#define lfirst(lc)
Definition: pg_list.h:169
LOCKMODE AlterTableGetRelOptionsLockLevel(List *defList)
Definition: reloptions.c:2102
AlterTableType subtype
Definition: parsenodes.h:1963
ConstrType contype
Definition: parsenodes.h:2264
Definition: pg_list.h:51

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

Referenced by AlterTableInternal(), and ProcessUtilitySlow().

◆ AlterTableInternal()

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

Definition at line 4076 of file tablecmds.c.

4077 {
4078  Relation rel;
4079  LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
4080 
4081  rel = relation_open(relid, lockmode);
4082 
4084 
4085  ATController(NULL, rel, cmds, recurse, lockmode, NULL);
4086 }
void EventTriggerAlterTableRelid(Oid objectId)
LOCKMODE AlterTableGetLockLevel(List *cmds)
Definition: tablecmds.c:4121

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

Referenced by AlterTableMoveAll(), and DefineVirtualRelation().

◆ AlterTableLookupRelation()

Oid AlterTableLookupRelation ( AlterTableStmt stmt,
LOCKMODE  lockmode 
)

Definition at line 3991 of file tablecmds.c.

3992 {
3993  return RangeVarGetRelidExtended(stmt->relation, lockmode,
3994  stmt->missing_ok ? RVR_MISSING_OK : 0,
3996  (void *) stmt);
3997 }
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:237
@ RVR_MISSING_OK
Definition: namespace.h:71
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:16960

References AlterTableStmt::missing_ok, RangeVarCallbackForAlterRelation(), RangeVarGetRelidExtended(), AlterTableStmt::relation, and RVR_MISSING_OK.

Referenced by ProcessUtilitySlow().

◆ AlterTableMoveAll()

Oid AlterTableMoveAll ( AlterTableMoveAllStmt stmt)

Definition at line 14421 of file tablecmds.c.

14422 {
14423  List *relations = NIL;
14424  ListCell *l;
14425  ScanKeyData key[1];
14426  Relation rel;
14427  TableScanDesc scan;
14428  HeapTuple tuple;
14429  Oid orig_tablespaceoid;
14430  Oid new_tablespaceoid;
14431  List *role_oids = roleSpecsToIds(stmt->roles);
14432 
14433  /* Ensure we were not asked to move something we can't */
14434  if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
14435  stmt->objtype != OBJECT_MATVIEW)
14436  ereport(ERROR,
14437  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
14438  errmsg("only tables, indexes, and materialized views exist in tablespaces")));
14439 
14440  /* Get the orig and new tablespace OIDs */
14441  orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
14442  new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
14443 
14444  /* Can't move shared relations in to or out of pg_global */
14445  /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
14446  if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
14447  new_tablespaceoid == GLOBALTABLESPACE_OID)
14448  ereport(ERROR,
14449  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
14450  errmsg("cannot move relations in to or out of pg_global tablespace")));
14451 
14452  /*
14453  * Must have CREATE rights on the new tablespace, unless it is the
14454  * database default tablespace (which all users implicitly have CREATE
14455  * rights on).
14456  */
14457  if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
14458  {
14459  AclResult aclresult;
14460 
14461  aclresult = pg_tablespace_aclcheck(new_tablespaceoid, GetUserId(),
14462  ACL_CREATE);
14463  if (aclresult != ACLCHECK_OK)
14464  aclcheck_error(aclresult, OBJECT_TABLESPACE,
14465  get_tablespace_name(new_tablespaceoid));
14466  }
14467 
14468  /*
14469  * Now that the checks are done, check if we should set either to
14470  * InvalidOid because it is our database's default tablespace.
14471  */
14472  if (orig_tablespaceoid == MyDatabaseTableSpace)
14473  orig_tablespaceoid = InvalidOid;
14474 
14475  if (new_tablespaceoid == MyDatabaseTableSpace)
14476  new_tablespaceoid = InvalidOid;
14477 
14478  /* no-op */
14479  if (orig_tablespaceoid == new_tablespaceoid)
14480  return new_tablespaceoid;
14481 
14482  /*
14483  * Walk the list of objects in the tablespace and move them. This will
14484  * only find objects in our database, of course.
14485  */
14486  ScanKeyInit(&key[0],
14487  Anum_pg_class_reltablespace,
14488  BTEqualStrategyNumber, F_OIDEQ,
14489  ObjectIdGetDatum(orig_tablespaceoid));
14490 
14491  rel = table_open(RelationRelationId, AccessShareLock);
14492  scan = table_beginscan_catalog(rel, 1, key);
14493  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
14494  {
14495  Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
14496  Oid relOid = relForm->oid;
14497 
14498  /*
14499  * Do not move objects in pg_catalog as part of this, if an admin
14500  * really wishes to do so, they can issue the individual ALTER
14501  * commands directly.
14502  *
14503  * Also, explicitly avoid any shared tables, temp tables, or TOAST
14504  * (TOAST will be moved with the main table).
14505  */
14506  if (IsCatalogNamespace(relForm->relnamespace) ||
14507  relForm->relisshared ||
14508  isAnyTempNamespace(relForm->relnamespace) ||
14509  IsToastNamespace(relForm->relnamespace))
14510  continue;
14511 
14512  /* Only move the object type requested */
14513  if ((stmt->objtype == OBJECT_TABLE &&
14514  relForm->relkind != RELKIND_RELATION &&
14515  relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
14516  (stmt->objtype == OBJECT_INDEX &&
14517  relForm->relkind != RELKIND_INDEX &&
14518  relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
14519  (stmt->objtype == OBJECT_MATVIEW &&
14520  relForm->relkind != RELKIND_MATVIEW))
14521  continue;
14522 
14523  /* Check if we are only moving objects owned by certain roles */
14524  if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
14525  continue;
14526 
14527  /*
14528  * Handle permissions-checking here since we are locking the tables
14529  * and also to avoid doing a bunch of work only to fail part-way. Note
14530  * that permissions will also be checked by AlterTableInternal().
14531  *
14532  * Caller must be considered an owner on the table to move it.
14533  */
14534  if (!pg_class_ownercheck(relOid, GetUserId()))
14536  NameStr(relForm->relname));
14537 
14538  if (stmt->nowait &&
14540  ereport(ERROR,
14541  (errcode(ERRCODE_OBJECT_IN_USE),
14542  errmsg("aborting because lock on relation \"%s.%s\" is not available",
14543  get_namespace_name(relForm->relnamespace),
14544  NameStr(relForm->relname))));
14545  else
14547 
14548  /* Add to our list of objects to move */
14549  relations = lappend_oid(relations, relOid);
14550  }
14551 
14552  table_endscan(scan);
14554 
14555  if (relations == NIL)
14556  ereport(NOTICE,
14557  (errcode(ERRCODE_NO_DATA_FOUND),
14558  errmsg("no matching relations in tablespace \"%s\" found",
14559  orig_tablespaceoid == InvalidOid ? "(database default)" :
14560  get_tablespace_name(orig_tablespaceoid))));
14561 
14562  /* Everything is locked, loop through and move all of the relations. */
14563  foreach(l, relations)
14564  {
14565  List *cmds = NIL;
14567 
14568  cmd->subtype = AT_SetTableSpace;
14569  cmd->name = stmt->new_tablespacename;
14570 
14571  cmds = lappend(cmds, cmd);
14572 
14574  /* OID is set by AlterTableInternal */
14575  AlterTableInternal(lfirst_oid(l), cmds, false);
14577  }
14578 
14579  return new_tablespaceoid;
14580 }
AclResult
Definition: acl.h:178
@ ACLCHECK_OK
Definition: acl.h:179
@ ACLCHECK_NOT_OWNER
Definition: acl.h:181
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4770
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4820
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3308
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1511
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1465
#define OidIsValid(objectId)
Definition: c.h:710
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:201
bool IsCatalogNamespace(Oid namespaceId)
Definition: catalog.c:183
#define NOTICE
Definition: elog.h:29
void EventTriggerAlterTableStart(Node *parsetree)
void EventTriggerAlterTableEnd(void)
Oid MyDatabaseTableSpace
Definition: globals.c:90
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1340
List * lappend(List *list, void *datum)
Definition: list.c:336
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:701
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:152
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:109
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1974
Oid GetUserId(void)
Definition: miscinit.c:495
bool isAnyTempNamespace(Oid namespaceId)
Definition: namespace.c:3240
#define makeNode(_type_)
Definition: nodes.h:587
ObjectType get_relkind_objtype(char relkind)
@ OBJECT_MATVIEW
Definition: parsenodes.h:1812
@ OBJECT_TABLESPACE
Definition: parsenodes.h:1830
@ OBJECT_INDEX
Definition: parsenodes.h:1809
@ OBJECT_TABLE
Definition: parsenodes.h:1829
#define ACL_CREATE
Definition: parsenodes.h:91
#define NIL
Definition: pg_list.h:65
#define lfirst_oid(lc)
Definition: pg_list.h:171
unsigned int Oid
Definition: postgres_ext.h:31
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
@ ForwardScanDirection
Definition: sdir.h:26
#define BTEqualStrategyNumber
Definition: stratnum.h:31
Definition: nodes.h:540
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:993
void AlterTableInternal(Oid relid, List *cmds, bool recurse)
Definition: tablecmds.c:4076
List * roleSpecsToIds(List *memberNames)
Definition: user.c:1349

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

Referenced by ProcessUtilitySlow().

◆ AlterTableNamespace()

ObjectAddress AlterTableNamespace ( AlterObjectSchemaStmt stmt,
Oid oldschema 
)

Definition at line 16309 of file tablecmds.c.

16310 {
16311  Relation rel;
16312  Oid relid;
16313  Oid oldNspOid;
16314  Oid nspOid;
16315  RangeVar *newrv;
16316  ObjectAddresses *objsMoved;
16317  ObjectAddress myself;
16318 
16320  stmt->missing_ok ? RVR_MISSING_OK : 0,
16322  (void *) stmt);
16323 
16324  if (!OidIsValid(relid))
16325  {
16326  ereport(NOTICE,
16327  (errmsg("relation \"%s\" does not exist, skipping",
16328  stmt->relation->relname)));
16329  return InvalidObjectAddress;
16330  }
16331 
16332  rel = relation_open(relid, NoLock);
16333 
16334  oldNspOid = RelationGetNamespace(rel);
16335 
16336  /* If it's an owned sequence, disallow moving it by itself. */
16337  if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
16338  {
16339  Oid tableId;
16340  int32 colId;
16341 
16342  if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
16343  sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
16344  ereport(ERROR,
16345  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
16346  errmsg("cannot move an owned sequence into another schema"),
16347  errdetail("Sequence \"%s\" is linked to table \"%s\".",
16349  get_rel_name(tableId))));
16350  }
16351 
16352  /* Get and lock schema OID and check its permissions. */
16353  newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
16354  nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
16355 
16356  /*
16357  * Check that setting the relation to a different schema won't result in a
16358  * publication having both a schema and the same schema's table, as this
16359  * is not supported.
16360  */
16361  if (stmt->objectType == OBJECT_TABLE)
16362  {
16363  ListCell *lc;
16364  List *schemaPubids = GetSchemaPublications(nspOid);
16365  List *relPubids = GetRelationPublications(RelationGetRelid(rel));
16366 
16367  foreach(lc, relPubids)
16368  {
16369  Oid pubid = lfirst_oid(lc);
16370 
16371  if (list_member_oid(schemaPubids, pubid))
16372  ereport(ERROR,
16373  errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
16374  errmsg("cannot move table \"%s\" to schema \"%s\"",
16375  RelationGetRelationName(rel), stmt->newschema),
16376  errdetail("The schema \"%s\" and same schema's table \"%s\" cannot be part of the same publication \"%s\".",
16377  stmt->newschema,
16379  get_publication_name(pubid, false)));
16380  }
16381  }
16382 
16383  /* common checks on switching namespaces */
16384  CheckSetNamespace(oldNspOid, nspOid);
16385 
16386  objsMoved = new_object_addresses();
16387  AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
16388  free_object_addresses(objsMoved);
16389 
16390  ObjectAddressSet(myself, RelationRelationId, relid);
16391 
16392  if (oldschema)
16393  *oldschema = oldNspOid;
16394 
16395  /* close rel, but keep lock until commit */
16396  relation_close(rel, NoLock);
16397 
16398  return myself;
16399 }
signed int int32
Definition: c.h:429
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2445
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2740
@ DEPENDENCY_AUTO
Definition: dependency.h:34
@ DEPENDENCY_INTERNAL
Definition: dependency.h:35
int errdetail(const char *fmt,...)
Definition: elog.c:1037
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:422
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:535
void CheckSetNamespace(Oid oldNspOid, Oid nspOid)
Definition: namespace.c:3012
const ObjectAddress InvalidObjectAddress
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
bool sequenceIsOwned(Oid seqId, char deptype, Oid *tableId, int32 *colId)
Definition: pg_depend.c:770
List * GetSchemaPublications(Oid schemaid)
List * GetRelationPublications(Oid relid)
char * get_publication_name(Oid pubid, bool missing_ok)
#define RelationGetRelid(relation)
Definition: rel.h:478
#define RelationGetRelationName(relation)
Definition: rel.h:512
#define RelationGetNamespace(relation)
Definition: rel.h:519
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
char * relname
Definition: primnodes.h:68
Form_pg_class rd_rel
Definition: rel.h:109
void AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:16407

References AccessExclusiveLock, AlterTableNamespaceInternal(), CheckSetNamespace(), DEPENDENCY_AUTO, DEPENDENCY_INTERNAL, ereport, errcode(), errdetail(), errmsg(), ERROR, free_object_addresses(), get_publication_name(), get_rel_name(), GetRelationPublications(), GetSchemaPublications(), InvalidObjectAddress, lfirst_oid, list_member_oid(), makeRangeVar(), AlterObjectSchemaStmt::missing_ok, new_object_addresses(), AlterObjectSchemaStmt::newschema, NoLock, NOTICE, OBJECT_TABLE, ObjectAddressSet, AlterObjectSchemaStmt::objectType, OidIsValid, RangeVarCallbackForAlterRelation(), RangeVarGetAndCheckCreationNamespace(), RangeVarGetRelidExtended(), RelationData::rd_rel, AlterObjectSchemaStmt::relation, relation_close(), relation_open(), RelationGetNamespace, RelationGetRelationName, RelationGetRelid, RangeVar::relname, RVR_MISSING_OK, and sequenceIsOwned().

Referenced by ExecAlterObjectSchemaStmt().

◆ AlterTableNamespaceInternal()

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

Definition at line 16407 of file tablecmds.c.

16409 {
16410  Relation classRel;
16411 
16412  Assert(objsMoved != NULL);
16413 
16414  /* OK, modify the pg_class row and pg_depend entry */
16415  classRel = table_open(RelationRelationId, RowExclusiveLock);
16416 
16417  AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
16418  nspOid, true, objsMoved);
16419 
16420  /* Fix the table's row type too, if it has one */
16421  if (OidIsValid(rel->rd_rel->reltype))
16422  AlterTypeNamespaceInternal(rel->rd_rel->reltype,
16423  nspOid, false, false, objsMoved);
16424 
16425  /* Fix other dependent stuff */
16426  if (rel->rd_rel->relkind == RELKIND_RELATION ||
16427  rel->rd_rel->relkind == RELKIND_MATVIEW ||
16428  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
16429  {
16430  AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
16431  AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
16432  objsMoved, AccessExclusiveLock);
16433  AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
16434  false, objsMoved);
16435  }
16436 
16437  table_close(classRel, RowExclusiveLock);
16438 }
#define RowExclusiveLock
Definition: lockdefs.h:38
void AlterConstraintNamespaces(Oid ownerId, Oid oldNspId, Oid newNspId, bool isType, ObjectAddresses *objsMoved)
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
Definition: tablecmds.c:16446
static void AlterSeqNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved, LOCKMODE lockmode)
Definition: tablecmds.c:16561
static void AlterIndexNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:16516
Oid AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid, bool isImplicitArray, bool errorOnTableType, ObjectAddresses *objsMoved)
Definition: typecmds.c:3957

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

Referenced by AlterObjectNamespace_oid(), and AlterTableNamespace().

◆ AtEOSubXact_on_commit_actions()

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

Definition at line 16837 of file tablecmds.c.

16839 {
16840  ListCell *cur_item;
16841 
16842  foreach(cur_item, on_commits)
16843  {
16844  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
16845 
16846  if (!isCommit && oc->creating_subid == mySubid)
16847  {
16848  /* cur_item must be removed */
16850  pfree(oc);
16851  }
16852  else
16853  {
16854  /* cur_item must be preserved */
16855  if (oc->creating_subid == mySubid)
16856  oc->creating_subid = parentSubid;
16857  if (oc->deleting_subid == mySubid)
16858  oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
16859  }
16860  }
16861 }
#define InvalidSubTransactionId
Definition: c.h:593
void pfree(void *pointer)
Definition: mcxt.c:1169
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:369
SubTransactionId creating_subid
Definition: tablecmds.c:119
SubTransactionId deleting_subid
Definition: tablecmds.c:120
static List * on_commits
Definition: tablecmds.c:123

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

Referenced by AbortSubTransaction(), and CommitSubTransaction().

◆ AtEOXact_on_commit_actions()

void AtEOXact_on_commit_actions ( bool  isCommit)

Definition at line 16805 of file tablecmds.c.

16806 {
16807  ListCell *cur_item;
16808 
16809  foreach(cur_item, on_commits)
16810  {
16811  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
16812 
16813  if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
16815  {
16816  /* cur_item must be removed */
16818  pfree(oc);
16819  }
16820  else
16821  {
16822  /* cur_item must be preserved */
16825  }
16826  }
16827 }

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

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

◆ ATExecChangeOwner()

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

Definition at line 13620 of file tablecmds.c.

13621 {
13622  Relation target_rel;
13623  Relation class_rel;
13624  HeapTuple tuple;
13625  Form_pg_class tuple_class;
13626 
13627  /*
13628  * Get exclusive lock till end of transaction on the target table. Use
13629  * relation_open so that we can work on indexes and sequences.
13630  */
13631  target_rel = relation_open(relationOid, lockmode);
13632 
13633  /* Get its pg_class tuple, too */
13634  class_rel = table_open(RelationRelationId, RowExclusiveLock);
13635 
13636  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
13637  if (!HeapTupleIsValid(tuple))
13638  elog(ERROR, "cache lookup failed for relation %u", relationOid);
13639  tuple_class = (Form_pg_class) GETSTRUCT(tuple);
13640 
13641  /* Can we change the ownership of this tuple? */
13642  switch (tuple_class->relkind)
13643  {
13644  case RELKIND_RELATION:
13645  case RELKIND_VIEW:
13646  case RELKIND_MATVIEW:
13647  case RELKIND_FOREIGN_TABLE:
13648  case RELKIND_PARTITIONED_TABLE:
13649  /* ok to change owner */
13650  break;
13651  case RELKIND_INDEX:
13652  if (!recursing)
13653  {
13654  /*
13655  * Because ALTER INDEX OWNER used to be allowed, and in fact
13656  * is generated by old versions of pg_dump, we give a warning
13657  * and do nothing rather than erroring out. Also, to avoid
13658  * unnecessary chatter while restoring those old dumps, say
13659  * nothing at all if the command would be a no-op anyway.
13660  */
13661  if (tuple_class->relowner != newOwnerId)
13662  ereport(WARNING,
13663  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
13664  errmsg("cannot change owner of index \"%s\"",
13665  NameStr(tuple_class->relname)),
13666  errhint("Change the ownership of the index's table, instead.")));
13667  /* quick hack to exit via the no-op path */
13668  newOwnerId = tuple_class->relowner;
13669  }
13670  break;
13671  case RELKIND_PARTITIONED_INDEX:
13672  if (recursing)
13673  break;
13674  ereport(ERROR,
13675  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
13676  errmsg("cannot change owner of index \"%s\"",
13677  NameStr(tuple_class->relname)),
13678  errhint("Change the ownership of the index's table, instead.")));
13679  break;
13680  case RELKIND_SEQUENCE:
13681  if (!recursing &&
13682  tuple_class->relowner != newOwnerId)
13683  {
13684  /* if it's an owned sequence, disallow changing it by itself */
13685  Oid tableId;
13686  int32 colId;
13687 
13688  if (sequenceIsOwned(relationOid, DEPENDENCY_AUTO, &tableId, &colId) ||
13689  sequenceIsOwned(relationOid, DEPENDENCY_INTERNAL, &tableId, &colId))
13690  ereport(ERROR,
13691  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
13692  errmsg("cannot change owner of sequence \"%s\"",
13693  NameStr(tuple_class->relname)),
13694  errdetail("Sequence \"%s\" is linked to table \"%s\".",
13695  NameStr(tuple_class->relname),
13696  get_rel_name(tableId))));
13697  }
13698  break;
13699  case RELKIND_COMPOSITE_TYPE:
13700  if (recursing)
13701  break;
13702  ereport(ERROR,
13703  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
13704  errmsg("\"%s\" is a composite type",
13705  NameStr(tuple_class->relname)),
13706  errhint("Use ALTER TYPE instead.")));
13707  break;
13708  case RELKIND_TOASTVALUE:
13709  if (recursing)
13710  break;
13711  /* FALL THRU */
13712  default:
13713  ereport(ERROR,
13714  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
13715  errmsg("cannot change owner of relation \"%s\"",
13716  NameStr(tuple_class->relname)),
13717  errdetail_relkind_not_supported(tuple_class->relkind)));
13718  }
13719 
13720  /*
13721  * If the new owner is the same as the existing owner, consider the
13722  * command to have succeeded. This is for dump restoration purposes.
13723  */
13724  if (tuple_class->relowner != newOwnerId)
13725  {
13726  Datum repl_val[Natts_pg_class];
13727  bool repl_null[Natts_pg_class];
13728  bool repl_repl[Natts_pg_class];
13729  Acl *newAcl;
13730  Datum aclDatum;
13731  bool isNull;
13732  HeapTuple newtuple;
13733 
13734  /* skip permission checks when recursing to index or toast table */
13735  if (!recursing)
13736  {
13737  /* Superusers can always do it */
13738  if (!superuser())
13739  {
13740  Oid namespaceOid = tuple_class->relnamespace;
13741  AclResult aclresult;
13742 
13743  /* Otherwise, must be owner of the existing object */
13744  if (!pg_class_ownercheck(relationOid, GetUserId()))
13746  RelationGetRelationName(target_rel));
13747 
13748  /* Must be able to become new owner */
13749  check_is_member_of_role(GetUserId(), newOwnerId);
13750 
13751  /* New owner must have CREATE privilege on namespace */
13752  aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
13753  ACL_CREATE);
13754  if (aclresult != ACLCHECK_OK)
13755  aclcheck_error(aclresult, OBJECT_SCHEMA,
13756  get_namespace_name(namespaceOid));
13757  }
13758  }
13759 
13760  memset(repl_null, false, sizeof(repl_null));
13761  memset(repl_repl, false, sizeof(repl_repl));
13762 
13763  repl_repl[Anum_pg_class_relowner - 1] = true;
13764  repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
13765 
13766  /*
13767  * Determine the modified ACL for the new owner. This is only
13768  * necessary when the ACL is non-null.
13769  */
13770  aclDatum = SysCacheGetAttr(RELOID, tuple,
13771  Anum_pg_class_relacl,
13772  &isNull);
13773  if (!isNull)
13774  {
13775  newAcl = aclnewowner(DatumGetAclP(aclDatum),
13776  tuple_class->relowner, newOwnerId);
13777  repl_repl[Anum_pg_class_relacl - 1] = true;
13778  repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
13779  }
13780 
13781  newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
13782 
13783  CatalogTupleUpdate(class_rel, &newtuple->t_self, newtuple);
13784 
13785  heap_freetuple(newtuple);
13786 
13787  /*
13788  * We must similarly update any per-column ACLs to reflect the new
13789  * owner; for neatness reasons that's split out as a subroutine.
13790  */
13791  change_owner_fix_column_acls(relationOid,
13792  tuple_class->relowner,
13793  newOwnerId);
13794 
13795  /*
13796  * Update owner dependency reference, if any. A composite type has
13797  * none, because it's tracked for the pg_type entry instead of here;
13798  * indexes and TOAST tables don't have their own entries either.
13799  */
13800  if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
13801  tuple_class->relkind != RELKIND_INDEX &&
13802  tuple_class->relkind != RELKIND_PARTITIONED_INDEX &&
13803  tuple_class->relkind != RELKIND_TOASTVALUE)
13804  changeDependencyOnOwner(RelationRelationId, relationOid,
13805  newOwnerId);
13806 
13807  /*
13808  * Also change the ownership of the table's row type, if it has one
13809  */
13810  if (OidIsValid(tuple_class->reltype))
13811  AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId);
13812 
13813  /*
13814  * If we are operating on a table or materialized view, also change
13815  * the ownership of any indexes and sequences that belong to the
13816  * relation, as well as its toast table (if it has one).
13817  */
13818  if (tuple_class->relkind == RELKIND_RELATION ||
13819  tuple_class->relkind == RELKIND_PARTITIONED_TABLE ||
13820  tuple_class->relkind == RELKIND_MATVIEW ||
13821  tuple_class->relkind == RELKIND_TOASTVALUE)
13822  {
13823  List *index_oid_list;
13824  ListCell *i;
13825 
13826  /* Find all the indexes belonging to this relation */
13827  index_oid_list = RelationGetIndexList(target_rel);
13828 
13829  /* For each index, recursively change its ownership */
13830  foreach(i, index_oid_list)
13831  ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
13832 
13833  list_free(index_oid_list);
13834  }
13835 
13836  /* If it has a toast table, recurse to change its ownership */
13837  if (tuple_class->reltoastrelid != InvalidOid)
13838  ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
13839  true, lockmode);
13840 
13841  /* If it has dependent sequences, recurse to change them too */
13842  change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
13843  }
13844 
13845  InvokeObjectPostAlterHook(RelationRelationId, relationOid, 0);
13846 
13847  ReleaseSysCache(tuple);
13848  table_close(class_rel, RowExclusiveLock);
13849  relation_close(target_rel, NoLock);
13850 }
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition: acl.c:1037
void check_is_member_of_role(Oid member, Oid role)
Definition: acl.c:4893
#define DatumGetAclP(X)
Definition: acl.h:120
AclResult pg_namespace_aclcheck(Oid nsp_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4758
int errhint(const char *fmt,...)
Definition: elog.c:1151
#define WARNING
Definition: elog.h:30
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
int i
Definition: isn.c:73
void list_free(List *list)
Definition: list.c:1505
@ OBJECT_SCHEMA
Definition: parsenodes.h:1824
int errdetail_relkind_not_supported(char relkind)
Definition: pg_class.c:24
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
Definition: pg_shdepend.c:312
uintptr_t Datum
Definition: postgres.h:411
#define PointerGetDatum(X)
Definition: postgres.h:600
#define RelationGetDescr(relation)
Definition: rel.h:504
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4649
bool superuser(void)
Definition: superuser.c:46
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1198
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1150
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1411
void ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
Definition: tablecmds.c:13620
static void change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
Definition: tablecmds.c:13924
static void change_owner_fix_column_acls(Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
Definition: tablecmds.c:13859
void AlterTypeOwnerInternal(Oid typeOid, Oid newOwnerId)
Definition: typecmds.c:3827

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

Referenced by AlterTypeOwner_oid(), ATExecCmd(), change_owner_recurse_to_sequences(), and shdepReassignOwned().

◆ check_of_type()

void check_of_type ( HeapTuple  typetuple)

Definition at line 6530 of file tablecmds.c.

6531 {
6532  Form_pg_type typ = (Form_pg_type) GETSTRUCT(typetuple);
6533  bool typeOk = false;
6534 
6535  if (typ->typtype == TYPTYPE_COMPOSITE)
6536  {
6537  Relation typeRelation;
6538 
6539  Assert(OidIsValid(typ->typrelid));
6540  typeRelation = relation_open(typ->typrelid, AccessShareLock);
6541  typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
6542 
6543  /*
6544  * Close the parent rel, but keep our AccessShareLock on it until xact
6545  * commit. That will prevent someone else from deleting or ALTERing
6546  * the type before the typed table creation/conversion commits.
6547  */
6548  relation_close(typeRelation, NoLock);
6549  }
6550  if (!typeOk)
6551  ereport(ERROR,
6552  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6553  errmsg("type %s is not a composite type",
6554  format_type_be(typ->oid))));
6555 }
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261

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

Referenced by ATExecAddOf(), and transformOfType().

◆ CheckRelationTableSpaceMove()

bool CheckRelationTableSpaceMove ( Relation  rel,
Oid  newTableSpaceId 
)

Definition at line 3248 of file tablecmds.c.

3249 {
3250  Oid oldTableSpaceId;
3251 
3252  /*
3253  * No work if no change in tablespace. Note that MyDatabaseTableSpace is
3254  * stored as 0.
3255  */
3256  oldTableSpaceId = rel->rd_rel->reltablespace;
3257  if (newTableSpaceId == oldTableSpaceId ||
3258  (newTableSpaceId == MyDatabaseTableSpace && oldTableSpaceId == 0))
3259  return false;
3260 
3261  /*
3262  * We cannot support moving mapped relations into different tablespaces.
3263  * (In particular this eliminates all shared catalogs.)
3264  */
3265  if (RelationIsMapped(rel))
3266  ereport(ERROR,
3267  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3268  errmsg("cannot move system relation \"%s\"",
3269  RelationGetRelationName(rel))));
3270 
3271  /* Cannot move a non-shared relation into pg_global */
3272  if (newTableSpaceId == GLOBALTABLESPACE_OID)
3273  ereport(ERROR,
3274  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3275  errmsg("only shared relations can be placed in pg_global tablespace")));
3276 
3277  /*
3278  * Do not allow moving temp tables of other backends ... their local
3279  * buffer manager is not going to cope.
3280  */
3281  if (RELATION_IS_OTHER_TEMP(rel))
3282  ereport(ERROR,
3283  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3284  errmsg("cannot move temporary tables of other sessions")));
3285 
3286  return true;
3287 }
#define RelationIsMapped(relation)
Definition: rel.h:527
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:632

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

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

◆ CheckTableNotInUse()

void CheckTableNotInUse ( Relation  rel,
const char *  stmt 
)

Definition at line 3963 of file tablecmds.c.

3964 {
3965  int expected_refcnt;
3966 
3967  expected_refcnt = rel->rd_isnailed ? 2 : 1;
3968  if (rel->rd_refcnt != expected_refcnt)
3969  ereport(ERROR,
3970  (errcode(ERRCODE_OBJECT_IN_USE),
3971  /* translator: first %s is a SQL command, eg ALTER TABLE */
3972  errmsg("cannot %s \"%s\" because it is being used by active queries in this session",
3973  stmt, RelationGetRelationName(rel))));
3974 
3975  if (rel->rd_rel->relkind != RELKIND_INDEX &&
3976  rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
3978  ereport(ERROR,
3979  (errcode(ERRCODE_OBJECT_IN_USE),
3980  /* translator: first %s is a SQL command, eg ALTER TABLE */
3981  errmsg("cannot %s \"%s\" because it has pending trigger events",
3982  stmt, RelationGetRelationName(rel))));
3983 }
int rd_refcnt
Definition: rel.h:58
bool rd_isnailed
Definition: rel.h:61
bool AfterTriggerPendingOnRel(Oid relid)
Definition: trigger.c:5608

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

Referenced by addFkRecurseReferencing(), AlterTable(), ATAddCheckConstraint(), ATCheckPartitionsNotInUse(), ATExecAddColumn(), ATExecDropColumn(), ATExecDropConstraint(), ATPrepAlterColumnType(), ATSimpleRecursion(), ATTypedTableRecursion(), cluster_rel(), DefineIndex(), DefineVirtualRelation(), ExecRefreshMatView(), heap_drop_with_catalog(), index_drop(), MergeAttributes(), reindex_index(), and truncate_check_activity().

◆ DefineRelation()

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

Definition at line 649 of file tablecmds.c.

651 {
652  char relname[NAMEDATALEN];
653  Oid namespaceId;
654  Oid relationId;
655  Oid tablespaceId;
656  Relation rel;
658  List *inheritOids;
659  List *old_constraints;
660  List *rawDefaults;
661  List *cookedDefaults;
662  Datum reloptions;
663  ListCell *listptr;
665  bool partitioned;
666  static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
667  Oid ofTypeId;
668  ObjectAddress address;
669  LOCKMODE parentLockmode;
670  const char *accessMethod = NULL;
671  Oid accessMethodId = InvalidOid;
672 
673  /*
674  * Truncate relname to appropriate length (probably a waste of time, as
675  * parser should have done this already).
676  */
678 
679  /*
680  * Check consistency of arguments
681  */
682  if (stmt->oncommit != ONCOMMIT_NOOP
683  && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
684  ereport(ERROR,
685  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
686  errmsg("ON COMMIT can only be used on temporary tables")));
687 
688  if (stmt->partspec != NULL)
689  {
690  if (relkind != RELKIND_RELATION)
691  elog(ERROR, "unexpected relkind: %d", (int) relkind);
692 
693  relkind = RELKIND_PARTITIONED_TABLE;
694  partitioned = true;
695  }
696  else
697  partitioned = false;
698 
699  /*
700  * Look up the namespace in which we are supposed to create the relation,
701  * check we have permission to create there, lock it against concurrent
702  * drop, and mark stmt->relation as RELPERSISTENCE_TEMP if a temporary
703  * namespace is selected.
704  */
705  namespaceId =
707 
708  /*
709  * Security check: disallow creating temp tables from security-restricted
710  * code. This is needed because calling code might not expect untrusted
711  * tables to appear in pg_temp at the front of its search path.
712  */
713  if (stmt->relation->relpersistence == RELPERSISTENCE_TEMP
715  ereport(ERROR,
716  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
717  errmsg("cannot create temporary table within security-restricted operation")));
718 
719  /*
720  * Determine the lockmode to use when scanning parents. A self-exclusive
721  * lock is needed here.
722  *
723  * For regular inheritance, if two backends attempt to add children to the
724  * same parent simultaneously, and that parent has no pre-existing
725  * children, then both will attempt to update the parent's relhassubclass
726  * field, leading to a "tuple concurrently updated" error. Also, this
727  * interlocks against a concurrent ANALYZE on the parent table, which
728  * might otherwise be attempting to clear the parent's relhassubclass
729  * field, if its previous children were recently dropped.
730  *
731  * If the child table is a partition, then we instead grab an exclusive
732  * lock on the parent because its partition descriptor will be changed by
733  * addition of the new partition.
734  */
735  parentLockmode = (stmt->partbound != NULL ? AccessExclusiveLock :
737 
738  /* Determine the list of OIDs of the parents. */
739  inheritOids = NIL;
740  foreach(listptr, stmt->inhRelations)
741  {
742  RangeVar *rv = (RangeVar *) lfirst(listptr);
743  Oid parentOid;
744 
745  parentOid = RangeVarGetRelid(rv, parentLockmode, false);
746 
747  /*
748  * Reject duplications in the list of parents.
749  */
750  if (list_member_oid(inheritOids, parentOid))
751  ereport(ERROR,
752  (errcode(ERRCODE_DUPLICATE_TABLE),
753  errmsg("relation \"%s\" would be inherited from more than once",
754  get_rel_name(parentOid))));
755 
756  inheritOids = lappend_oid(inheritOids, parentOid);
757  }
758 
759  /*
760  * Select tablespace to use: an explicitly indicated one, or (in the case
761  * of a partitioned table) the parent's, if it has one.
762  */
763  if (stmt->tablespacename)
764  {
765  tablespaceId = get_tablespace_oid(stmt->tablespacename, false);
766 
767  if (partitioned && tablespaceId == MyDatabaseTableSpace)
768  ereport(ERROR,
769  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
770  errmsg("cannot specify default tablespace for partitioned relations")));
771  }
772  else if (stmt->partbound)
773  {
774  /*
775  * For partitions, when no other tablespace is specified, we default
776  * the tablespace to the parent partitioned table's.
777  */
778  Assert(list_length(inheritOids) == 1);
779  tablespaceId = get_rel_tablespace(linitial_oid(inheritOids));
780  }
781  else
782  tablespaceId = InvalidOid;
783 
784  /* still nothing? use the default */
785  if (!OidIsValid(tablespaceId))
786  tablespaceId = GetDefaultTablespace(stmt->relation->relpersistence,
787  partitioned);
788 
789  /* Check permissions except when using database's default */
790  if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
791  {
792  AclResult aclresult;
793 
794  aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
795  ACL_CREATE);
796  if (aclresult != ACLCHECK_OK)
798  get_tablespace_name(tablespaceId));
799  }
800 
801  /* In all cases disallow placing user relations in pg_global */
802  if (tablespaceId == GLOBALTABLESPACE_OID)
803  ereport(ERROR,
804  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
805  errmsg("only shared relations can be placed in pg_global tablespace")));
806 
807  /* Identify user ID that will own the table */
808  if (!OidIsValid(ownerId))
809  ownerId = GetUserId();
810 
811  /*
812  * Parse and validate reloptions, if any.
813  */
814  reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, validnsps,
815  true, false);
816 
817  switch (relkind)
818  {
819  case RELKIND_VIEW:
820  (void) view_reloptions(reloptions, true);
821  break;
822  case RELKIND_PARTITIONED_TABLE:
823  (void) partitioned_table_reloptions(reloptions, true);
824  break;
825  default:
826  (void) heap_reloptions(relkind, reloptions, true);
827  }
828 
829  if (stmt->ofTypename)
830  {
831  AclResult aclresult;
832 
833  ofTypeId = typenameTypeId(NULL, stmt->ofTypename);
834 
835  aclresult = pg_type_aclcheck(ofTypeId, GetUserId(), ACL_USAGE);
836  if (aclresult != ACLCHECK_OK)
837  aclcheck_error_type(aclresult, ofTypeId);
838  }
839  else
840  ofTypeId = InvalidOid;
841 
842  /*
843  * Look up inheritance ancestors and generate relation schema, including
844  * inherited attributes. (Note that stmt->tableElts is destructively
845  * modified by MergeAttributes.)
846  */
847  stmt->tableElts =
848  MergeAttributes(stmt->tableElts, inheritOids,
849  stmt->relation->relpersistence,
850  stmt->partbound != NULL,
851  &old_constraints);
852 
853  /*
854  * Create a tuple descriptor from the relation schema. Note that this
855  * deals with column names, types, and NOT NULL constraints, but not
856  * default values or CHECK constraints; we handle those below.
857  */
859 
860  /*
861  * Find columns with default values and prepare for insertion of the
862  * defaults. Pre-cooked (that is, inherited) defaults go into a list of
863  * CookedConstraint structs that we'll pass to heap_create_with_catalog,
864  * while raw defaults go into a list of RawColumnDefault structs that will
865  * be processed by AddRelationNewConstraints. (We can't deal with raw
866  * expressions until we can do transformExpr.)
867  *
868  * We can set the atthasdef flags now in the tuple descriptor; this just
869  * saves StoreAttrDefault from having to do an immediate update of the
870  * pg_attribute rows.
871  */
872  rawDefaults = NIL;
873  cookedDefaults = NIL;
874  attnum = 0;
875 
876  foreach(listptr, stmt->tableElts)
877  {
878  ColumnDef *colDef = lfirst(listptr);
879  Form_pg_attribute attr;
880 
881  attnum++;
882  attr = TupleDescAttr(descriptor, attnum - 1);
883 
884  if (colDef->raw_default != NULL)
885  {
886  RawColumnDefault *rawEnt;
887 
888  Assert(colDef->cooked_default == NULL);
889 
890  rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
891  rawEnt->attnum = attnum;
892  rawEnt->raw_default = colDef->raw_default;
893  rawEnt->missingMode = false;
894  rawEnt->generated = colDef->generated;
895  rawDefaults = lappend(rawDefaults, rawEnt);
896  attr->atthasdef = true;
897  }
898  else if (colDef->cooked_default != NULL)
899  {
900  CookedConstraint *cooked;
901 
902  cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
903  cooked->contype = CONSTR_DEFAULT;
904  cooked->conoid = InvalidOid; /* until created */
905  cooked->name = NULL;
906  cooked->attnum = attnum;
907  cooked->expr = colDef->cooked_default;
908  cooked->skip_validation = false;
909  cooked->is_local = true; /* not used for defaults */
910  cooked->inhcount = 0; /* ditto */
911  cooked->is_no_inherit = false;
912  cookedDefaults = lappend(cookedDefaults, cooked);
913  attr->atthasdef = true;
914  }
915 
916  if (colDef->identity)
917  attr->attidentity = colDef->identity;
918 
919  if (colDef->generated)
920  attr->attgenerated = colDef->generated;
921 
922  if (colDef->compression)
923  attr->attcompression = GetAttributeCompression(attr->atttypid,
924  colDef->compression);
925  }
926 
927  /*
928  * If the statement hasn't specified an access method, but we're defining
929  * a type of relation that needs one, use the default.
930  */
931  if (stmt->accessMethod != NULL)
932  {
933  accessMethod = stmt->accessMethod;
934 
935  if (partitioned)
936  ereport(ERROR,
937  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
938  errmsg("specifying a table access method is not supported on a partitioned table")));
939 
940  }
941  else if (RELKIND_HAS_TABLE_AM(relkind))
942  accessMethod = default_table_access_method;
943 
944  /* look up the access method, verify it is for a table */
945  if (accessMethod != NULL)
946  accessMethodId = get_table_am_oid(accessMethod, false);
947 
948  /*
949  * Create the relation. Inherited defaults and constraints are passed in
950  * for immediate handling --- since they don't need parsing, they can be
951  * stored immediately.
952  */
953  relationId = heap_create_with_catalog(relname,
954  namespaceId,
955  tablespaceId,
956  InvalidOid,
957  InvalidOid,
958  ofTypeId,
959  ownerId,
960  accessMethodId,
961  descriptor,
962  list_concat(cookedDefaults,
963  old_constraints),
964  relkind,
965  stmt->relation->relpersistence,
966  false,
967  false,
968  stmt->oncommit,
969  reloptions,
970  true,
972  false,
973  InvalidOid,
974  typaddress);
975 
976  /*
977  * We must bump the command counter to make the newly-created relation
978  * tuple visible for opening.
979  */
981 
982  /*
983  * Open the new relation and acquire exclusive lock on it. This isn't
984  * really necessary for locking out other backends (since they can't see
985  * the new rel anyway until we commit), but it keeps the lock manager from
986  * complaining about deadlock risks.
987  */
988  rel = relation_open(relationId, AccessExclusiveLock);
989 
990  /*
991  * Now add any newly specified column default and generation expressions
992  * to the new relation. These are passed to us in the form of raw
993  * parsetrees; we need to transform them to executable expression trees
994  * before they can be added. The most convenient way to do that is to
995  * apply the parser's transformExpr routine, but transformExpr doesn't
996  * work unless we have a pre-existing relation. So, the transformation has
997  * to be postponed to this final step of CREATE TABLE.
998  *
999  * This needs to be before processing the partitioning clauses because
1000  * those could refer to generated columns.
1001  */
1002  if (rawDefaults)
1003  AddRelationNewConstraints(rel, rawDefaults, NIL,
1004  true, true, false, queryString);
1005 
1006  /*
1007  * Make column generation expressions visible for use by partitioning.
1008  */
1010 
1011  /* Process and store partition bound, if any. */
1012  if (stmt->partbound)
1013  {
1014  PartitionBoundSpec *bound;
1015  ParseState *pstate;
1016  Oid parentId = linitial_oid(inheritOids),
1017  defaultPartOid;
1018  Relation parent,
1019  defaultRel = NULL;
1020  ParseNamespaceItem *nsitem;
1021 
1022  /* Already have strong enough lock on the parent */
1023  parent = table_open(parentId, NoLock);
1024 
1025  /*
1026  * We are going to try to validate the partition bound specification
1027  * against the partition key of parentRel, so it better have one.
1028  */
1029  if (parent->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
1030  ereport(ERROR,
1031  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1032  errmsg("\"%s\" is not partitioned",
1033  RelationGetRelationName(parent))));
1034 
1035  /*
1036  * The partition constraint of the default partition depends on the
1037  * partition bounds of every other partition. It is possible that
1038  * another backend might be about to execute a query on the default
1039  * partition table, and that the query relies on previously cached
1040  * default partition constraints. We must therefore take a table lock
1041  * strong enough to prevent all queries on the default partition from
1042  * proceeding until we commit and send out a shared-cache-inval notice
1043  * that will make them update their index lists.
1044  *
1045  * Order of locking: The relation being added won't be visible to
1046  * other backends until it is committed, hence here in
1047  * DefineRelation() the order of locking the default partition and the
1048  * relation being added does not matter. But at all other places we
1049  * need to lock the default relation before we lock the relation being
1050  * added or removed i.e. we should take the lock in same order at all
1051  * the places such that lock parent, lock default partition and then
1052  * lock the partition so as to avoid a deadlock.
1053  */
1054  defaultPartOid =
1056  true));
1057  if (OidIsValid(defaultPartOid))
1058  defaultRel = table_open(defaultPartOid, AccessExclusiveLock);
1059 
1060  /* Transform the bound values */
1061  pstate = make_parsestate(NULL);
1062  pstate->p_sourcetext = queryString;
1063 
1064  /*
1065  * Add an nsitem containing this relation, so that transformExpr
1066  * called on partition bound expressions is able to report errors
1067  * using a proper context.
1068  */
1069  nsitem = addRangeTableEntryForRelation(pstate, rel, AccessShareLock,
1070  NULL, false, false);
1071  addNSItemToQuery(pstate, nsitem, false, true, true);
1072 
1073  bound = transformPartitionBound(pstate, parent, stmt->partbound);
1074 
1075  /*
1076  * Check first that the new partition's bound is valid and does not
1077  * overlap with any of existing partitions of the parent.
1078  */
1079  check_new_partition_bound(relname, parent, bound, pstate);
1080 
1081  /*
1082  * If the default partition exists, its partition constraints will
1083  * change after the addition of this new partition such that it won't
1084  * allow any row that qualifies for this new partition. So, check that
1085  * the existing data in the default partition satisfies the constraint
1086  * as it will exist after adding this partition.
1087  */
1088  if (OidIsValid(defaultPartOid))
1089  {
1090  check_default_partition_contents(parent, defaultRel, bound);
1091  /* Keep the lock until commit. */
1092  table_close(defaultRel, NoLock);
1093  }
1094 
1095  /* Update the pg_class entry. */
1096  StorePartitionBound(rel, parent, bound);
1097 
1098  table_close(parent, NoLock);
1099  }
1100 
1101  /* Store inheritance information for new rel. */
1102  StoreCatalogInheritance(relationId, inheritOids, stmt->partbound != NULL);
1103 
1104  /*
1105  * Process the partitioning specification (if any) and store the partition
1106  * key information into the catalog.
1107  */
1108  if (partitioned)
1109  {
1110  ParseState *pstate;
1111  char strategy;
1112  int partnatts;
1113  AttrNumber partattrs[PARTITION_MAX_KEYS];
1114  Oid partopclass[PARTITION_MAX_KEYS];
1115  Oid partcollation[PARTITION_MAX_KEYS];
1116  List *partexprs = NIL;
1117 
1118  pstate = make_parsestate(NULL);
1119  pstate->p_sourcetext = queryString;
1120 
1121  partnatts = list_length(stmt->partspec->partParams);
1122 
1123  /* Protect fixed-size arrays here and in executor */
1124  if (partnatts > PARTITION_MAX_KEYS)
1125  ereport(ERROR,
1126  (errcode(ERRCODE_TOO_MANY_COLUMNS),
1127  errmsg("cannot partition using more than %d columns",
1128  PARTITION_MAX_KEYS)));
1129 
1130  /*
1131  * We need to transform the raw parsetrees corresponding to partition
1132  * expressions into executable expression trees. Like column defaults
1133  * and CHECK constraints, we could not have done the transformation
1134  * earlier.
1135  */
1136  stmt->partspec = transformPartitionSpec(rel, stmt->partspec,
1137  &strategy);
1138 
1139  ComputePartitionAttrs(pstate, rel, stmt->partspec->partParams,
1140  partattrs, &partexprs, partopclass,
1141  partcollation, strategy);
1142 
1143  StorePartitionKey(rel, strategy, partnatts, partattrs, partexprs,
1144  partopclass, partcollation);
1145 
1146  /* make it all visible */
1148  }
1149 
1150  /*
1151  * If we're creating a partition, create now all the indexes, triggers,
1152  * FKs defined in the parent.
1153  *
1154  * We can't do it earlier, because DefineIndex wants to know the partition
1155  * key which we just stored.
1156  */
1157  if (stmt->partbound)
1158  {
1159  Oid parentId = linitial_oid(inheritOids);
1160  Relation parent;
1161  List *idxlist;
1162  ListCell *cell;
1163 
1164  /* Already have strong enough lock on the parent */
1165  parent = table_open(parentId, NoLock);
1166  idxlist = RelationGetIndexList(parent);
1167 
1168  /*
1169  * For each index in the parent table, create one in the partition
1170  */
1171  foreach(cell, idxlist)
1172  {
1173  Relation idxRel = index_open(lfirst_oid(cell), AccessShareLock);
1174  AttrMap *attmap;
1175  IndexStmt *idxstmt;
1176  Oid constraintOid;
1177 
1178  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1179  {
1180  if (idxRel->rd_index->indisunique)
1181  ereport(ERROR,
1182  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1183  errmsg("cannot create foreign partition of partitioned table \"%s\"",
1184  RelationGetRelationName(parent)),
1185  errdetail("Table \"%s\" contains indexes that are unique.",
1186  RelationGetRelationName(parent))));
1187  else
1188  {
1189  index_close(idxRel, AccessShareLock);
1190  continue;
1191  }
1192  }
1193 
1195  RelationGetDescr(parent));
1196  idxstmt =
1197  generateClonedIndexStmt(NULL, idxRel,
1198  attmap, &constraintOid);
1200  idxstmt,
1201  InvalidOid,
1202  RelationGetRelid(idxRel),
1203  constraintOid,
1204  false, false, false, false, false);
1205 
1206  index_close(idxRel, AccessShareLock);
1207  }
1208 
1209  list_free(idxlist);
1210 
1211  /*
1212  * If there are any row-level triggers, clone them to the new
1213  * partition.
1214  */
1215  if (parent->trigdesc != NULL)
1216  CloneRowTriggersToPartition(parent, rel);
1217 
1218  /*
1219  * And foreign keys too. Note that because we're freshly creating the
1220  * table, there is no need to verify these new constraints.
1221  */
1222  CloneForeignKeyConstraints(NULL, parent, rel);
1223 
1224  table_close(parent, NoLock);
1225  }
1226 
1227  /*
1228  * Now add any newly specified CHECK constraints to the new relation. Same
1229  * as for defaults above, but these need to come after partitioning is set
1230  * up.
1231  */
1232  if (stmt->constraints)
1234  true, true, false, queryString);
1235 
1236  ObjectAddressSet(address, RelationRelationId, relationId);
1237 
1238  /*
1239  * Clean up. We keep lock on new relation (although it shouldn't be
1240  * visible to anyone else anyway, until commit).
1241  */
1242  relation_close(rel, NoLock);
1243 
1244  return address;
1245 }
AclResult pg_type_aclcheck(Oid type_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4808
void aclcheck_error_type(AclResult aclerr, Oid typeOid)
Definition: aclchk.c:3623
Oid get_table_am_oid(const char *amname, bool missing_ok)
Definition: amcmds.c:173
AttrMap * build_attrmap_by_name(TupleDesc indesc, TupleDesc outdesc)
Definition: attmap.c:174
int16 AttrNumber
Definition: attnum.h:21
Oid GetDefaultTablespace(char relpersistence, bool partitioned)
Definition: tablespace.c:1182
bool allowSystemTableMods
Definition: globals.c:123
void StorePartitionKey(Relation rel, char strategy, int16 partnatts, AttrNumber *partattrs, List *partexprs, Oid *partopclass, Oid *partcollation)
Definition: heap.c:3631
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:1102
void StorePartitionBound(Relation rel, Relation parent, PartitionBoundSpec *bound)
Definition: heap.c:3789
List * AddRelationNewConstraints(Relation rel, List *newColDefaults, List *newConstraints, bool allow_merge, bool is_local, bool is_internal, const char *queryString)
Definition: heap.c:2576
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
ObjectAddress DefineIndex(Oid relationId, IndexStmt *stmt, Oid indexRelationId, Oid parentIndexId, Oid parentConstraintId, bool is_alter_table, bool check_rights, bool check_not_in_use, bool skip_build, bool quiet)
Definition: indexcmds.c:506
List * list_concat(List *list1, const List *list2)
Definition: list.c:540
Oid get_rel_tablespace(Oid relid)
Definition: lsyscache.c:2025
void * palloc(Size size)
Definition: mcxt.c:1062
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:627
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:79
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:291
IndexStmt * generateClonedIndexStmt(RangeVar *heapRel, Relation source_idx, const AttrMap *attmap, Oid *constraintOid)
PartitionBoundSpec * transformPartitionBound(ParseState *pstate, Relation parent, PartitionBoundSpec *spec)
#define ACL_USAGE
Definition: parsenodes.h:90
@ CONSTR_DEFAULT
Definition: parsenodes.h:2235
void check_new_partition_bound(char *relname, Relation parent, PartitionBoundSpec *spec, ParseState *pstate)
Definition: partbounds.c:2908
void check_default_partition_contents(Relation parent, Relation default_rel, PartitionBoundSpec *new_spec)
Definition: partbounds.c:3267
PartitionDesc RelationGetPartitionDesc(Relation rel, bool omit_detached)
Definition: partdesc.c:72
Oid get_default_oid_from_partdesc(PartitionDesc partdesc)
Definition: partdesc.c:455
int16 attnum
Definition: pg_attribute.h:83
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
NameData relname
Definition: pg_class.h:38
#define PARTITION_MAX_KEYS
#define NAMEDATALEN
static int list_length(const List *l)
Definition: pg_list.h:149
#define linitial_oid(l)
Definition: pg_list.h:176
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
@ ONCOMMIT_NOOP
Definition: primnodes.h:49
Datum transformRelOptions(Datum oldOptions, List *defList, const char *namspace, char *validnsps[], bool acceptOidsOff, bool isReset)
Definition: reloptions.c:1149
bytea * heap_reloptions(char relkind, Datum reloptions, bool validate)
Definition: reloptions.c:2013
bytea * view_reloptions(Datum reloptions, bool validate)
Definition: reloptions.c:1994
bytea * partitioned_table_reloptions(Datum reloptions, bool validate)
Definition: reloptions.c:1979
#define HEAP_RELOPT_NAMESPACES
Definition: reloptions.h:61
Definition: attmap.h:35
char identity
Definition: parsenodes.h:680
Node * cooked_default
Definition: parsenodes.h:679
char generated
Definition: parsenodes.h:683
Node * raw_default
Definition: parsenodes.h:678
char * compression
Definition: parsenodes.h:672
Oid conoid
Definition: heap.h:38
char * name
Definition: heap.h:39
AttrNumber attnum
Definition: heap.h:40
bool skip_validation
Definition: heap.h:42
bool is_no_inherit
Definition: heap.h:45
int inhcount
Definition: heap.h:44
bool is_local
Definition: heap.h:43
ConstrType contype
Definition: heap.h:37
Node * expr
Definition: heap.h:41
List * tableElts
Definition: parsenodes.h:2185
TypeName * ofTypename
Definition: parsenodes.h:2190
OnCommitAction oncommit
Definition: parsenodes.h:2193
List * options
Definition: parsenodes.h:2192
List * inhRelations
Definition: parsenodes.h:2186
RangeVar * relation
Definition: parsenodes.h:2184
char * tablespacename
Definition: parsenodes.h:2194
PartitionSpec * partspec
Definition: parsenodes.h:2189
PartitionBoundSpec * partbound
Definition: parsenodes.h:2188
char * accessMethod
Definition: parsenodes.h:2195
List * constraints
Definition: parsenodes.h:2191
const char * p_sourcetext
Definition: parse_node.h:181
List * partParams
Definition: parsenodes.h:821
char relpersistence
Definition: primnodes.h:71
Node * raw_default
Definition: heap.h:30
AttrNumber attnum
Definition: heap.h:29
char generated
Definition: heap.h:32
bool missingMode
Definition: heap.h:31
TriggerDesc * trigdesc
Definition: rel.h:115
Form_pg_index rd_index
Definition: rel.h:188
char * default_table_access_method
Definition: tableam.c:48
static PartitionSpec * transformPartitionSpec(Relation rel, PartitionSpec *partspec, char *strategy)
Definition: tablecmds.c:17097
static char GetAttributeCompression(Oid atttypid, char *compression)
Definition: tablecmds.c:19208
static List * MergeAttributes(List *schema, List *supers, char relpersistence, bool is_partition, List **supconstr)
Definition: tablecmds.c:2286
static void CloneRowTriggersToPartition(Relation parent, Relation partition)
Definition: tablecmds.c:18087
static void ComputePartitionAttrs(ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs, List **partexprs, Oid *partopclass, Oid *partcollation, char strategy)
Definition: tablecmds.c:17168
static void StoreCatalogInheritance(Oid relationId, List *supers, bool child_is_partition)
Definition: tablecmds.c:3086
static void CloneForeignKeyConstraints(List **wqueue, Relation parentRel, Relation partitionRel)
Definition: tablecmds.c:9923
TupleDesc BuildDescForRelation(List *schema)
Definition: tupdesc.c:777
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
void CommandCounterIncrement(void)
Definition: xact.c:1073

References AccessExclusiveLock, CreateStmt::accessMethod, AccessShareLock, ACL_CREATE, ACL_USAGE, aclcheck_error(), aclcheck_error_type(), ACLCHECK_OK, addNSItemToQuery(), addRangeTableEntryForRelation(), AddRelationNewConstraints(), allowSystemTableMods, Assert(), RawColumnDefault::attnum, CookedConstraint::attnum, attnum, build_attrmap_by_name(), BuildDescForRelation(), check_default_partition_contents(), check_new_partition_bound(), CloneForeignKeyConstraints(), CloneRowTriggersToPartition(), CommandCounterIncrement(), ColumnDef::compression, ComputePartitionAttrs(), CookedConstraint::conoid, CONSTR_DEFAULT, CreateStmt::constraints, CookedConstraint::contype, ColumnDef::cooked_default, default_table_access_method, DefineIndex(), elog, ereport, errcode(), errdetail(), errmsg(), ERROR, CookedConstraint::expr, generateClonedIndexStmt(), RawColumnDefault::generated, ColumnDef::generated, get_default_oid_from_partdesc(), get_rel_name(), get_rel_tablespace(), get_table_am_oid(), get_tablespace_name(), get_tablespace_oid(), GetAttributeCompression(), GetDefaultTablespace(), GetUserId(), heap_create_with_catalog(), HEAP_RELOPT_NAMESPACES, heap_reloptions(), ColumnDef::identity, index_close(), index_open(), CookedConstraint::inhcount, CreateStmt::inhRelations, InSecurityRestrictedOperation(), InvalidOid, CookedConstraint::is_local, CookedConstraint::is_no_inherit, lappend(), lappend_oid(), lfirst, lfirst_oid, linitial_oid, list_concat(), list_free(), list_length(), list_member_oid(), make_parsestate(), MergeAttributes(), RawColumnDefault::missingMode, MyDatabaseTableSpace, CookedConstraint::name, NAMEDATALEN, NIL, NoLock, OBJECT_TABLESPACE, ObjectAddressSet, CreateStmt::ofTypename, OidIsValid, CreateStmt::oncommit, ONCOMMIT_NOOP, CreateStmt::options, ParseState::p_sourcetext, palloc(), CreateStmt::partbound, PARTITION_MAX_KEYS, partitioned_table_reloptions(), PartitionSpec::partParams, CreateStmt::partspec, pg_tablespace_aclcheck(), pg_type_aclcheck(), RangeVarGetAndCheckCreationNamespace(), RangeVarGetRelid, RawColumnDefault::raw_default, ColumnDef::raw_default, RelationData::rd_index, RelationData::rd_rel, CreateStmt::relation, relation_close(), relation_open(), RelationGetDescr, RelationGetIndexList(), RelationGetPartitionDesc(), RelationGetRelationName, RelationGetRelid, relname, RangeVar::relname, RangeVar::relpersistence, ShareUpdateExclusiveLock, CookedConstraint::skip_validation, StoreCatalogInheritance(), StorePartitionBound(), StorePartitionKey(), strlcpy(), table_close(), table_open(), CreateStmt::tableElts, CreateStmt::tablespacename, transformPartitionBound(), transformPartitionSpec(), transformRelOptions(), RelationData::trigdesc, TupleDescAttr, typenameTypeId(), and view_reloptions().

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

◆ ExecuteTruncate()

void ExecuteTruncate ( TruncateStmt stmt)

Definition at line 1631 of file tablecmds.c.

1632 {
1633  List *rels = NIL;
1634  List *relids = NIL;
1635  List *relids_logged = NIL;
1636  ListCell *cell;
1637 
1638  /*
1639  * Open, exclusive-lock, and check all the explicitly-specified relations
1640  */
1641  foreach(cell, stmt->relations)
1642  {
1643  RangeVar *rv = lfirst(cell);
1644  Relation rel;
1645  bool recurse = rv->inh;
1646  Oid myrelid;
1647  LOCKMODE lockmode = AccessExclusiveLock;
1648 
1649  myrelid = RangeVarGetRelidExtended(rv, lockmode,
1651  NULL);
1652 
1653  /* don't throw error for "TRUNCATE foo, foo" */
1654  if (list_member_oid(relids, myrelid))
1655  continue;
1656 
1657  /* open the relation, we already hold a lock on it */
1658  rel = table_open(myrelid, NoLock);
1659 
1660  /*
1661  * RangeVarGetRelidExtended() has done most checks with its callback,
1662  * but other checks with the now-opened Relation remain.
1663  */
1665 
1666  rels = lappend(rels, rel);
1667  relids = lappend_oid(relids, myrelid);
1668 
1669  /* Log this relation only if needed for logical decoding */
1670  if (RelationIsLogicallyLogged(rel))
1671  relids_logged = lappend_oid(relids_logged, myrelid);
1672 
1673  if (recurse)
1674  {
1675  ListCell *child;
1676  List *children;
1677 
1678  children = find_all_inheritors(myrelid, lockmode, NULL);
1679 
1680  foreach(child, children)
1681  {
1682  Oid childrelid = lfirst_oid(child);
1683 
1684  if (list_member_oid(relids, childrelid))
1685  continue;
1686 
1687  /* find_all_inheritors already got lock */
1688  rel = table_open(childrelid, NoLock);
1689 
1690  /*
1691  * It is possible that the parent table has children that are
1692  * temp tables of other backends. We cannot safely access
1693  * such tables (because of buffering issues), and the best
1694  * thing to do is to silently ignore them. Note that this
1695  * check is the same as one of the checks done in
1696  * truncate_check_activity() called below, still it is kept
1697  * here for simplicity.
1698  */
1699  if (RELATION_IS_OTHER_TEMP(rel))
1700  {
1701  table_close(rel, lockmode);
1702  continue;
1703  }
1704 
1705  /*
1706  * Inherited TRUNCATE commands perform access permission
1707  * checks on the parent table only. So we skip checking the
1708  * children's permissions and don't call
1709  * truncate_check_perms() here.
1710  */
1713 
1714  rels = lappend(rels, rel);
1715  relids = lappend_oid(relids, childrelid);
1716 
1717  /* Log this relation only if needed for logical decoding */
1718  if (RelationIsLogicallyLogged(rel))
1719  relids_logged = lappend_oid(relids_logged, childrelid);
1720  }
1721  }
1722  else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1723  ereport(ERROR,
1724  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1725  errmsg("cannot truncate only a partitioned table"),
1726  errhint("Do not specify the ONLY keyword, or use TRUNCATE ONLY on the partitions directly.")));
1727  }
1728 
1729  ExecuteTruncateGuts(rels, relids, relids_logged,
1730  stmt->behavior, stmt->restart_seqs);
1731 
1732  /* And close the rels */
1733  foreach(cell, rels)
1734  {
1735  Relation rel = (Relation) lfirst(cell);
1736 
1737  table_close(rel, NoLock);
1738  }
1739 }
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:256
#define RelationIsLogicallyLogged(relation)
Definition: rel.h:675
struct RelationData * Relation
Definition: relcache.h:26
List * relations
Definition: parsenodes.h:2782
DropBehavior behavior
Definition: parsenodes.h:2784
bool restart_seqs
Definition: parsenodes.h:2783
static void truncate_check_activity(Relation rel)
Definition: tablecmds.c:2188
static void truncate_check_rel(Oid relid, Form_pg_class reltuple)
Definition: tablecmds.c:2130
void ExecuteTruncateGuts(List *explicit_rels, List *relids, List *relids_logged, DropBehavior behavior, bool restart_seqs)
Definition: tablecmds.c:1755
static void RangeVarCallbackForTruncate(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:16904

References AccessExclusiveLock, TruncateStmt::behavior, ereport, errcode(), errhint(), errmsg(), ERROR, ExecuteTruncateGuts(), find_all_inheritors(), RangeVar::inh, lappend(), lappend_oid(), lfirst, lfirst_oid, list_member_oid(), NIL, NoLock, RangeVarCallbackForTruncate(), RangeVarGetRelidExtended(), RelationData::rd_rel, RELATION_IS_OTHER_TEMP, RelationGetRelid, RelationIsLogicallyLogged, TruncateStmt::relations, TruncateStmt::restart_seqs, 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 
)

Definition at line 1755 of file tablecmds.c.

1759 {
1760  List *rels;
1761  List *seq_relids = NIL;
1762  HTAB *ft_htab = NULL;
1763  EState *estate;
1764  ResultRelInfo *resultRelInfos;
1765  ResultRelInfo *resultRelInfo;
1766  SubTransactionId mySubid;
1767  ListCell *cell;
1768  Oid *logrelids;
1769 
1770  /*
1771  * Check the explicitly-specified relations.
1772  *
1773  * In CASCADE mode, suck in all referencing relations as well. This
1774  * requires multiple iterations to find indirectly-dependent relations. At
1775  * each phase, we need to exclusive-lock new rels before looking for their
1776  * dependencies, else we might miss something. Also, we check each rel as
1777  * soon as we open it, to avoid a faux pas such as holding lock for a long
1778  * time on a rel we have no permissions for.
1779  */
1780  rels = list_copy(explicit_rels);
1781  if (behavior == DROP_CASCADE)
1782  {
1783  for (;;)
1784  {
1785  List *newrelids;
1786 
1787  newrelids = heap_truncate_find_FKs(relids);
1788  if (newrelids == NIL)
1789  break; /* nothing else to add */
1790 
1791  foreach(cell, newrelids)
1792  {
1793  Oid relid = lfirst_oid(cell);
1794  Relation rel;
1795 
1796  rel = table_open(relid, AccessExclusiveLock);
1797  ereport(NOTICE,
1798  (errmsg("truncate cascades to table \"%s\"",
1799  RelationGetRelationName(rel))));
1800  truncate_check_rel(relid, rel->rd_rel);
1801  truncate_check_perms(relid, rel->rd_rel);
1803  rels = lappend(rels, rel);
1804  relids = lappend_oid(relids, relid);
1805 
1806  /* Log this relation only if needed for logical decoding */
1807  if (RelationIsLogicallyLogged(rel))
1808  relids_logged = lappend_oid(relids_logged, relid);
1809  }
1810  }
1811  }
1812 
1813  /*
1814  * Check foreign key references. In CASCADE mode, this should be
1815  * unnecessary since we just pulled in all the references; but as a
1816  * cross-check, do it anyway if in an Assert-enabled build.
1817  */
1818 #ifdef USE_ASSERT_CHECKING
1819  heap_truncate_check_FKs(rels, false);
1820 #else
1821  if (behavior == DROP_RESTRICT)
1822  heap_truncate_check_FKs(rels, false);
1823 #endif
1824 
1825  /*
1826  * If we are asked to restart sequences, find all the sequences, lock them
1827  * (we need AccessExclusiveLock for ResetSequence), and check permissions.
1828  * We want to do this early since it's pointless to do all the truncation
1829  * work only to fail on sequence permissions.
1830  */
1831  if (restart_seqs)
1832  {
1833  foreach(cell, rels)
1834  {
1835  Relation rel = (Relation) lfirst(cell);
1836  List *seqlist = getOwnedSequences(RelationGetRelid(rel));
1837  ListCell *seqcell;
1838 
1839  foreach(seqcell, seqlist)
1840  {
1841  Oid seq_relid = lfirst_oid(seqcell);
1842  Relation seq_rel;
1843 
1844  seq_rel = relation_open(seq_relid, AccessExclusiveLock);
1845 
1846  /* This check must match AlterSequence! */
1847  if (!pg_class_ownercheck(seq_relid, GetUserId()))
1849  RelationGetRelationName(seq_rel));
1850 
1851  seq_relids = lappend_oid(seq_relids, seq_relid);
1852 
1853  relation_close(seq_rel, NoLock);
1854  }
1855  }
1856  }
1857 
1858  /* Prepare to catch AFTER triggers. */
1860 
1861  /*
1862  * To fire triggers, we'll need an EState as well as a ResultRelInfo for
1863  * each relation. We don't need to call ExecOpenIndices, though.
1864  *
1865  * We put the ResultRelInfos in the es_opened_result_relations list, even
1866  * though we don't have a range table and don't populate the
1867  * es_result_relations array. That's a bit bogus, but it's enough to make
1868  * ExecGetTriggerResultRel() find them.
1869  */
1870  estate = CreateExecutorState();
1871  resultRelInfos = (ResultRelInfo *)
1872  palloc(list_length(rels) * sizeof(ResultRelInfo));
1873  resultRelInfo = resultRelInfos;
1874  foreach(cell, rels)
1875  {
1876  Relation rel = (Relation) lfirst(cell);
1877 
1878  InitResultRelInfo(resultRelInfo,
1879  rel,
1880  0, /* dummy rangetable index */
1881  NULL,
1882  0);
1883  estate->es_opened_result_relations =
1884  lappend(estate->es_opened_result_relations, resultRelInfo);
1885  resultRelInfo++;
1886  }
1887 
1888  /*
1889  * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
1890  * truncating (this is because one of them might throw an error). Also, if
1891  * we were to allow them to prevent statement execution, that would need
1892  * to be handled here.
1893  */
1894  resultRelInfo = resultRelInfos;
1895  foreach(cell, rels)
1896  {
1897  ExecBSTruncateTriggers(estate, resultRelInfo);
1898  resultRelInfo++;
1899  }
1900 
1901  /*
1902  * OK, truncate each table.
1903  */
1904  mySubid = GetCurrentSubTransactionId();
1905 
1906  foreach(cell, rels)
1907  {
1908  Relation rel = (Relation) lfirst(cell);
1909 
1910  /* Skip partitioned tables as there is nothing to do */
1911  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1912  continue;
1913 
1914  /*
1915  * Build the lists of foreign tables belonging to each foreign server
1916  * and pass each list to the foreign data wrapper's callback function,
1917  * so that each server can truncate its all foreign tables in bulk.
1918  * Each list is saved as a single entry in a hash table that uses the
1919  * server OID as lookup key.
1920  */
1921  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1922  {
1924  bool found;
1925  ForeignTruncateInfo *ft_info;
1926 
1927  /* First time through, initialize hashtable for foreign tables */
1928  if (!ft_htab)
1929  {
1930  HASHCTL hctl;
1931 
1932  memset(&hctl, 0, sizeof(HASHCTL));
1933  hctl.keysize = sizeof(Oid);
1934  hctl.entrysize = sizeof(ForeignTruncateInfo);
1935  hctl.hcxt = CurrentMemoryContext;
1936 
1937  ft_htab = hash_create("TRUNCATE for Foreign Tables",
1938  32, /* start small and extend */
1939  &hctl,
1941  }
1942 
1943  /* Find or create cached entry for the foreign table */
1944  ft_info = hash_search(ft_htab, &serverid, HASH_ENTER, &found);
1945  if (!found)
1946  {
1947  ft_info->serverid = serverid;
1948  ft_info->rels = NIL;
1949  }
1950 
1951  /*
1952  * Save the foreign table in the entry of the server that the
1953  * foreign table belongs to.
1954  */
1955  ft_info->rels = lappend(ft_info->rels, rel);
1956  continue;
1957  }
1958 
1959  /*
1960  * Normally, we need a transaction-safe truncation here. However, if
1961  * the table was either created in the current (sub)transaction or has
1962  * a new relfilenode in the current (sub)transaction, then we can just
1963  * truncate it in-place, because a rollback would cause the whole
1964  * table or the current physical file to be thrown away anyway.
1965  */
1966  if (rel->rd_createSubid == mySubid ||
1967  rel->rd_newRelfilenodeSubid == mySubid)
1968  {
1969  /* Immediate, non-rollbackable truncation is OK */
1970  heap_truncate_one_rel(rel);
1971  }
1972  else
1973  {
1974  Oid heap_relid;
1975  Oid toast_relid;
1976  ReindexParams reindex_params = {0};
1977 
1978  /*
1979  * This effectively deletes all rows in the table, and may be done
1980  * in a serializable transaction. In that case we must record a
1981  * rw-conflict in to this transaction from each transaction
1982  * holding a predicate lock on the table.
1983  */
1985 
1986  /*
1987  * Need the full transaction-safe pushups.
1988  *
1989  * Create a new empty storage file for the relation, and assign it
1990  * as the relfilenode value. The old storage file is scheduled for
1991  * deletion at commit.
1992  */
1993  RelationSetNewRelfilenode(rel, rel->rd_rel->relpersistence);
1994 
1995  heap_relid = RelationGetRelid(rel);
1996 
1997  /*
1998  * The same for the toast table, if any.
1999  */
2000  toast_relid = rel->rd_rel->reltoastrelid;
2001  if (OidIsValid(toast_relid))
2002  {
2003  Relation toastrel = relation_open(toast_relid,
2005 
2006  RelationSetNewRelfilenode(toastrel,
2007  toastrel->rd_rel->relpersistence);
2008  table_close(toastrel, NoLock);
2009  }
2010 
2011  /*
2012  * Reconstruct the indexes to match, and we're done.
2013  */
2015  &reindex_params);
2016  }
2017 
2018  pgstat_count_truncate(rel);
2019  }
2020 
2021  /* Now go through the hash table, and truncate foreign tables */
2022  if (ft_htab)
2023  {
2024  ForeignTruncateInfo *ft_info;
2025  HASH_SEQ_STATUS seq;
2026 
2027  hash_seq_init(&seq, ft_htab);
2028 
2029  PG_TRY();
2030  {
2031  while ((ft_info = hash_seq_search(&seq)) != NULL)
2032  {
2033  FdwRoutine *routine = GetFdwRoutineByServerId(ft_info->serverid);
2034 
2035  /* truncate_check_rel() has checked that already */
2036  Assert(routine->ExecForeignTruncate != NULL);
2037 
2038  routine->ExecForeignTruncate(ft_info->rels,
2039  behavior,
2040  restart_seqs);
2041  }
2042  }
2043  PG_FINALLY();
2044  {
2045  hash_destroy(ft_htab);
2046  }
2047  PG_END_TRY();
2048  }
2049 
2050  /*
2051  * Restart owned sequences if we were asked to.
2052  */
2053  foreach(cell, seq_relids)
2054  {
2055  Oid seq_relid = lfirst_oid(cell);
2056 
2057  ResetSequence(seq_relid);
2058  }
2059 
2060  /*
2061  * Write a WAL record to allow this set of actions to be logically
2062  * decoded.
2063  *
2064  * Assemble an array of relids so we can write a single WAL record for the
2065  * whole action.
2066  */
2067  if (list_length(relids_logged) > 0)
2068  {
2069  xl_heap_truncate xlrec;
2070  int i = 0;
2071 
2072  /* should only get here if wal_level >= logical */
2074 
2075  logrelids = palloc(list_length(relids_logged) * sizeof(Oid));
2076  foreach(cell, relids_logged)
2077  logrelids[i++] = lfirst_oid(cell);
2078 
2079  xlrec.dbId = MyDatabaseId;
2080  xlrec.nrelids = list_length(relids_logged);
2081  xlrec.flags = 0;
2082  if (behavior == DROP_CASCADE)
2083  xlrec.flags |= XLH_TRUNCATE_CASCADE;
2084  if (restart_seqs)
2086 
2087  XLogBeginInsert();
2088  XLogRegisterData((char *) &xlrec, SizeOfHeapTruncate);
2089  XLogRegisterData((char *) logrelids, list_length(relids_logged) * sizeof(Oid));
2090 
2092 
2093  (void) XLogInsert(RM_HEAP_ID, XLOG_HEAP_TRUNCATE);
2094  }
2095 
2096  /*
2097  * Process all AFTER STATEMENT TRUNCATE triggers.
2098  */
2099  resultRelInfo = resultRelInfos;
2100  foreach(cell, rels)
2101  {
2102  ExecASTruncateTriggers(estate, resultRelInfo);
2103  resultRelInfo++;
2104  }
2105 
2106  /* Handle queued AFTER triggers */
2107  AfterTriggerEndQuery(estate);
2108 
2109  /* We can clean up the EState now */
2110  FreeExecutorState(estate);
2111 
2112  /*
2113  * Close any rels opened by CASCADE (can't do this while EState still
2114  * holds refs)
2115  */
2116  rels = list_difference_ptr(rels, explicit_rels);
2117  foreach(cell, rels)
2118  {
2119  Relation rel = (Relation) lfirst(cell);
2120 
2121  table_close(rel, NoLock);
2122  }
2123 }
uint32 SubTransactionId
Definition: c.h:591
void hash_destroy(HTAB *hashp)
Definition: dynahash.c:862
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:349
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1436
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1426
#define PG_END_TRY()
Definition: elog.h:324
#define PG_TRY()
Definition: elog.h:299
#define PG_FINALLY()
Definition: elog.h:316
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, ResultRelInfo *partition_root_rri, int instrument_options)
Definition: execMain.c:1193
EState * CreateExecutorState(void)
Definition: execUtils.c:90
void FreeExecutorState(EState *estate)
Definition: execUtils.c:186
struct ResultRelInfo ResultRelInfo
Oid GetForeignServerIdByRelId(Oid relid)
Definition: foreign.c:340
FdwRoutine * GetFdwRoutineByServerId(Oid serverid)
Definition: foreign.c:362
Oid MyDatabaseId
Definition: globals.c:88
List * heap_truncate_find_FKs(List *relationIds)
Definition: heap.c:3503
void heap_truncate_check_FKs(List *relations, bool tempTables)
Definition: heap.c:3408
void heap_truncate_one_rel(Relation rel)
Definition: heap.c:3364
#define XLOG_HEAP_TRUNCATE
Definition: heapam_xlog.h:35
#define XLH_TRUNCATE_RESTART_SEQS
Definition: heapam_xlog.h:121
#define SizeOfHeapTruncate
Definition: heapam_xlog.h:136
#define XLH_TRUNCATE_CASCADE
Definition: heapam_xlog.h:120
@ 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(Oid relid, int flags, ReindexParams *params)
Definition: index.c:3826
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:155
List * list_difference_ptr(const List *list1, const List *list2)
Definition: list.c:1222
List * list_copy(const List *oldlist)
Definition: list.c:1532
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
@ DROP_CASCADE
Definition: parsenodes.h:1862
@ DROP_RESTRICT
Definition: parsenodes.h:1861
@ OBJECT_SEQUENCE
Definition: parsenodes.h:1825
List * getOwnedSequences(Oid relid)
Definition: pg_depend.c:878
void pgstat_count_truncate(Relation rel)
Definition: pgstat.c:2462
void CheckTableForSerializableConflictIn(Relation relation)
Definition: predicate.c:4531
void RelationSetNewRelfilenode(Relation relation, char persistence)
Definition: relcache.c:3674
void ResetSequence(Oid seq_relid)
Definition: sequence.c:270
List * es_opened_result_relations
Definition: execnodes.h:583
ExecForeignTruncate_function ExecForeignTruncate
Definition: fdwapi.h:263
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76
MemoryContext hcxt
Definition: hsearch.h:86
Definition: dynahash.c:220
SubTransactionId rd_newRelfilenodeSubid
Definition: rel.h:103
SubTransactionId rd_createSubid
Definition: rel.h:102
struct ForeignTruncateInfo ForeignTruncateInfo
static void truncate_check_perms(Oid relid, Form_pg_class reltuple)
Definition: tablecmds.c:2170
void ExecBSTruncateTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:3165
void ExecASTruncateTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:3212
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:4771
void AfterTriggerBeginQuery(void)
Definition: trigger.c:4751
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:775
#define XLogLogicalInfoActive()
Definition: xlog.h:181
#define XLOG_INCLUDE_ORIGIN
Definition: xlog.h:209
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:429
void XLogSetRecordFlags(uint8 flags)
Definition: xloginsert.c:411
void XLogBeginInsert(void)
Definition: xloginsert.c:136
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:337

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

Referenced by apply_handle_truncate(), and ExecuteTruncate().

◆ find_composite_type_dependencies()

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

Definition at line 6363 of file tablecmds.c.

6365 {
6366  Relation depRel;
6367  ScanKeyData key[2];
6368  SysScanDesc depScan;
6369  HeapTuple depTup;
6370 
6371  /* since this function recurses, it could be driven to stack overflow */
6373 
6374  /*
6375  * We scan pg_depend to find those things that depend on the given type.
6376  * (We assume we can ignore refobjsubid for a type.)
6377  */
6378  depRel = table_open(DependRelationId, AccessShareLock);
6379 
6380  ScanKeyInit(&key[0],
6381  Anum_pg_depend_refclassid,
6382  BTEqualStrategyNumber, F_OIDEQ,
6383  ObjectIdGetDatum(TypeRelationId));
6384  ScanKeyInit(&key[1],
6385  Anum_pg_depend_refobjid,
6386  BTEqualStrategyNumber, F_OIDEQ,
6387  ObjectIdGetDatum(typeOid));
6388 
6389  depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
6390  NULL, 2, key);
6391 
6392  while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
6393  {
6394  Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
6395  Relation rel;
6396  Form_pg_attribute att;
6397 
6398  /* Check for directly dependent types */
6399  if (pg_depend->classid == TypeRelationId)
6400  {
6401  /*
6402  * This must be an array, domain, or range containing the given
6403  * type, so recursively check for uses of this type. Note that
6404  * any error message will mention the original type not the
6405  * container; this is intentional.
6406  */
6407  find_composite_type_dependencies(pg_depend->objid,
6408  origRelation, origTypeName);
6409  continue;
6410  }
6411 
6412  /* Else, ignore dependees that aren't user columns of relations */
6413  /* (we assume system columns are never of interesting types) */
6414  if (pg_depend->classid != RelationRelationId ||
6415  pg_depend->objsubid <= 0)
6416  continue;
6417 
6418  rel = relation_open(pg_depend->objid, AccessShareLock);
6419  att = TupleDescAttr(rel->rd_att, pg_depend->objsubid - 1);
6420 
6421  if (rel->rd_rel->relkind == RELKIND_RELATION ||
6422  rel->rd_rel->relkind == RELKIND_MATVIEW ||
6423  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
6424  {
6425  if (origTypeName)
6426  ereport(ERROR,
6427  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6428  errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
6429  origTypeName,
6431  NameStr(att->attname))));
6432  else if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
6433  ereport(ERROR,
6434  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6435  errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
6436  RelationGetRelationName(origRelation),
6438  NameStr(att->attname))));
6439  else if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
6440  ereport(ERROR,
6441  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6442  errmsg("cannot alter foreign table \"%s\" because column \"%s.%s\" uses its row type",
6443  RelationGetRelationName(origRelation),
6445  NameStr(att->attname))));
6446  else
6447  ereport(ERROR,
6448  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6449  errmsg("cannot alter table \"%s\" because column \"%s.%s\" uses its row type",
6450  RelationGetRelationName(origRelation),
6452  NameStr(att->attname))));
6453  }
6454  else if (OidIsValid(rel->rd_rel->reltype))
6455  {
6456  /*
6457  * A view or composite type itself isn't a problem, but we must
6458  * recursively check for indirect dependencies via its rowtype.
6459  */
6461  origRelation, origTypeName);
6462  }
6463 
6465  }
6466 
6467  systable_endscan(depScan);
6468 
6470 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:598
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:505
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:386
FormData_pg_depend * Form_pg_depend
Definition: pg_depend.h:72
void check_stack_depth(void)
Definition: postgres.c:3470
TupleDesc rd_att
Definition: rel.h:110
void find_composite_type_dependencies(Oid typeOid, Relation origRelation, const char *origTypeName)
Definition: tablecmds.c:6363

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

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

◆ PartConstraintImpliedByRelConstraint()

bool PartConstraintImpliedByRelConstraint ( Relation  scanrel,
List partConstraint 
)

Definition at line 17425 of file tablecmds.c.

17427 {
17428  List *existConstraint = NIL;
17429  TupleConstr *constr = RelationGetDescr(scanrel)->constr;
17430  int i;
17431 
17432  if (constr && constr->has_not_null)
17433  {
17434  int natts = scanrel->rd_att->natts;
17435 
17436  for (i = 1; i <= natts; i++)
17437  {
17438  Form_pg_attribute att = TupleDescAttr(scanrel->rd_att, i - 1);
17439 
17440  if (att->attnotnull && !att->attisdropped)
17441  {
17442  NullTest *ntest = makeNode(NullTest);
17443 
17444  ntest->arg = (Expr *) makeVar(1,
17445  i,
17446  att->atttypid,
17447  att->atttypmod,
17448  att->attcollation,
17449  0);
17450  ntest->nulltesttype = IS_NOT_NULL;
17451 
17452  /*
17453  * argisrow=false is correct even for a composite column,
17454  * because attnotnull does not represent a SQL-spec IS NOT
17455  * NULL test in such a case, just IS DISTINCT FROM NULL.
17456  */
17457  ntest->argisrow = false;
17458  ntest->location = -1;
17459  existConstraint = lappend(existConstraint, ntest);
17460  }
17461  }
17462  }
17463 
17464  return ConstraintImpliedByRelConstraint(scanrel, partConstraint, existConstraint);
17465 }
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
@ IS_NOT_NULL
Definition: primnodes.h:1259
NullTestType nulltesttype
Definition: primnodes.h:1266
int location
Definition: primnodes.h:1268
bool argisrow
Definition: primnodes.h:1267
Expr * arg
Definition: primnodes.h:1265
bool has_not_null
Definition: tupdesc.h:44
static bool ConstraintImpliedByRelConstraint(Relation scanrel, List *testConstraint, List *provenConstraint)
Definition: tablecmds.c:17478

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

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

◆ PreCommit_on_commit_actions()

void PreCommit_on_commit_actions ( void  )

Definition at line 16705 of file tablecmds.c.

16706 {
16707  ListCell *l;
16708  List *oids_to_truncate = NIL;
16709  List *oids_to_drop = NIL;
16710 
16711  foreach(l, on_commits)
16712  {
16713  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
16714 
16715  /* Ignore entry if already dropped in this xact */
16717  continue;
16718 
16719  switch (oc->oncommit)
16720  {
16721  case ONCOMMIT_NOOP:
16723  /* Do nothing (there shouldn't be such entries, actually) */
16724  break;
16725  case ONCOMMIT_DELETE_ROWS:
16726 
16727  /*
16728  * If this transaction hasn't accessed any temporary
16729  * relations, we can skip truncating ON COMMIT DELETE ROWS
16730  * tables, as they must still be empty.
16731  */
16733  oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
16734  break;
16735  case ONCOMMIT_DROP:
16736  oids_to_drop = lappend_oid(oids_to_drop, oc->relid);
16737  break;
16738  }
16739  }
16740 
16741  /*
16742  * Truncate relations before dropping so that all dependencies between
16743  * relations are removed after they are worked on. Doing it like this
16744  * might be a waste as it is possible that a relation being truncated will
16745  * be dropped anyway due to its parent being dropped, but this makes the
16746  * code more robust because of not having to re-check that the relation
16747  * exists at truncation time.
16748  */
16749  if (oids_to_truncate != NIL)
16750  heap_truncate(oids_to_truncate);
16751 
16752  if (oids_to_drop != NIL)
16753  {
16754  ObjectAddresses *targetObjects = new_object_addresses();
16755  ListCell *l;
16756 
16757  foreach(l, oids_to_drop)
16758  {
16759  ObjectAddress object;
16760 
16761  object.classId = RelationRelationId;
16762  object.objectId = lfirst_oid(l);
16763  object.objectSubId = 0;
16764 
16765  Assert(!object_address_present(&object, targetObjects));
16766 
16767  add_exact_object_address(&object, targetObjects);
16768  }
16769 
16770  /*
16771  * Since this is an automatic drop, rather than one directly initiated
16772  * by the user, we pass the PERFORM_DELETION_INTERNAL flag.
16773  */
16774  performMultipleDeletions(targetObjects, DROP_CASCADE,
16776 
16777 #ifdef USE_ASSERT_CHECKING
16778 
16779  /*
16780  * Note that table deletion will call remove_on_commit_action, so the
16781  * entry should get marked as deleted.
16782  */
16783  foreach(l, on_commits)
16784  {
16785  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
16786 
16787  if (oc->oncommit != ONCOMMIT_DROP)
16788  continue;
16789 
16791  }
16792 #endif
16793  }
16794 }
void performMultipleDeletions(const ObjectAddresses *objects, DropBehavior behavior, int flags)
Definition: dependency.c:374
#define PERFORM_DELETION_QUIETLY
Definition: dependency.h:136
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:134
void heap_truncate(List *relids)
Definition: heap.c:3323
@ ONCOMMIT_DELETE_ROWS
Definition: primnodes.h:51
@ ONCOMMIT_PRESERVE_ROWS
Definition: primnodes.h:50
@ ONCOMMIT_DROP
Definition: primnodes.h:52
OnCommitAction oncommit
Definition: tablecmds.c:110
int MyXactFlags
Definition: xact.c:134
#define XACT_FLAGS_ACCESSEDTEMPNAMESPACE
Definition: xact.h:102

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

Referenced by CommitTransaction(), and PrepareTransaction().

◆ RangeVarCallbackOwnsRelation()

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

Definition at line 16928 of file tablecmds.c.

16930 {
16931  HeapTuple tuple;
16932 
16933  /* Nothing to do if the relation was not found. */
16934  if (!OidIsValid(relId))
16935  return;
16936 
16937  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
16938  if (!HeapTupleIsValid(tuple)) /* should not happen */
16939  elog(ERROR, "cache lookup failed for relation %u", relId);
16940 
16941  if (!pg_class_ownercheck(relId, GetUserId()))
16943  relation->relname);
16944 
16945  if (!allowSystemTableMods &&
16946  IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
16947  ereport(ERROR,
16948  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
16949  errmsg("permission denied: \"%s\" is a system catalog",
16950  relation->relname)));
16951 
16952  ReleaseSysCache(tuple);
16953 }
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
Definition: catalog.c:86

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

Referenced by AlterSequence(), and ProcessUtilitySlow().

◆ RangeVarCallbackOwnsTable()

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

Definition at line 16872 of file tablecmds.c.

16874 {
16875  char relkind;
16876 
16877  /* Nothing to do if the relation was not found. */
16878  if (!OidIsValid(relId))
16879  return;
16880 
16881  /*
16882  * If the relation does exist, check whether it's an index. But note that
16883  * the relation might have been dropped between the time we did the name
16884  * lookup and now. In that case, there's nothing to do.
16885  */
16886  relkind = get_rel_relkind(relId);
16887  if (!relkind)
16888  return;
16889  if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
16890  relkind != RELKIND_MATVIEW && relkind != RELKIND_PARTITIONED_TABLE)
16891  ereport(ERROR,
16892  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16893  errmsg("\"%s\" is not a table or materialized view", relation->relname)));
16894 
16895  /* Check permissions */
16896  if (!pg_class_ownercheck(relId, GetUserId()))
16898 }

References aclcheck_error(), ACLCHECK_NOT_OWNER, ereport, errcode(), errmsg(), ERROR, get_rel_relkind(), get_relkind_objtype(), GetUserId(), OidIsValid, pg_class_ownercheck(), DropRelationCallbackState::relkind, and RangeVar::relname.

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

◆ register_on_commit_action()

void register_on_commit_action ( Oid  relid,
OnCommitAction  action 
)

Definition at line 16646 of file tablecmds.c.

16647 {
16648  OnCommitItem *oc;
16649  MemoryContext oldcxt;
16650 
16651  /*
16652  * We needn't bother registering the relation unless there is an ON COMMIT
16653  * action we need to take.
16654  */
16656  return;
16657 
16659 
16660  oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
16661  oc->relid = relid;
16662  oc->oncommit = action;
16665 
16666  /*
16667  * We use lcons() here so that ON COMMIT actions are processed in reverse
16668  * order of registration. That might not be essential but it seems
16669  * reasonable.
16670  */
16671  on_commits = lcons(oc, on_commits);
16672 
16673  MemoryContextSwitchTo(oldcxt);
16674 }
List * lcons(void *datum, List *list)
Definition: list.c:474
MemoryContext CacheMemoryContext
Definition: mcxt.c:51
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109

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

Referenced by heap_create_with_catalog().

◆ remove_on_commit_action()

void remove_on_commit_action ( Oid  relid)

Definition at line 16682 of file tablecmds.c.

16683 {
16684  ListCell *l;
16685 
16686  foreach(l, on_commits)
16687  {
16688  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
16689 
16690  if (oc->relid == relid)
16691  {
16693  break;
16694  }
16695  }
16696 }

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

Referenced by heap_drop_with_catalog().

◆ RemoveRelations()

void RemoveRelations ( DropStmt drop)

Definition at line 1327 of file tablecmds.c.

1328 {
1329  ObjectAddresses *objects;
1330  char relkind;
1331  ListCell *cell;
1332  int flags = 0;
1333  LOCKMODE lockmode = AccessExclusiveLock;
1334 
1335  /* DROP CONCURRENTLY uses a weaker lock, and has some restrictions */
1336  if (drop->concurrent)
1337  {
1338  /*
1339  * Note that for temporary relations this lock may get upgraded later
1340  * on, but as no other session can access a temporary relation, this
1341  * is actually fine.
1342  */
1343  lockmode = ShareUpdateExclusiveLock;
1344  Assert(drop->removeType == OBJECT_INDEX);
1345  if (list_length(drop->objects) != 1)
1346  ereport(ERROR,
1347  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1348  errmsg("DROP INDEX CONCURRENTLY does not support dropping multiple objects")));
1349  if (drop->behavior == DROP_CASCADE)
1350  ereport(ERROR,
1351  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1352  errmsg("DROP INDEX CONCURRENTLY does not support CASCADE")));
1353  }
1354 
1355  /*
1356  * First we identify all the relations, then we delete them in a single
1357  * performMultipleDeletions() call. This is to avoid unwanted DROP
1358  * RESTRICT errors if one of the relations depends on another.
1359  */
1360 
1361  /* Determine required relkind */
1362  switch (drop->removeType)
1363  {
1364  case OBJECT_TABLE:
1365  relkind = RELKIND_RELATION;
1366  break;
1367 
1368  case OBJECT_INDEX:
1369  relkind = RELKIND_INDEX;
1370  break;
1371 
1372  case OBJECT_SEQUENCE:
1373  relkind = RELKIND_SEQUENCE;
1374  break;
1375 
1376  case OBJECT_VIEW:
1377  relkind = RELKIND_VIEW;
1378  break;
1379 
1380  case OBJECT_MATVIEW:
1381  relkind = RELKIND_MATVIEW;
1382  break;
1383 
1384  case OBJECT_FOREIGN_TABLE:
1385  relkind = RELKIND_FOREIGN_TABLE;
1386  break;
1387 
1388  default:
1389  elog(ERROR, "unrecognized drop object type: %d",
1390  (int) drop->removeType);
1391  relkind = 0; /* keep compiler quiet */
1392  break;
1393  }
1394 
1395  /* Lock and validate each relation; build a list of object addresses */
1396  objects = new_object_addresses();
1397 
1398  foreach(cell, drop->objects)
1399  {
1400  RangeVar *rel = makeRangeVarFromNameList((List *) lfirst(cell));
1401  Oid relOid;
1402  ObjectAddress obj;
1404 
1405  /*
1406  * These next few steps are a great deal like relation_openrv, but we
1407  * don't bother building a relcache entry since we don't need it.
1408  *
1409  * Check for shared-cache-inval messages before trying to access the
1410  * relation. This is needed to cover the case where the name
1411  * identifies a rel that has been dropped and recreated since the
1412  * start of our transaction: if we don't flush the old syscache entry,
1413  * then we'll latch onto that entry and suffer an error later.
1414  */
1416 
1417  /* Look up the appropriate relation using namespace search. */
1418  state.relkind = relkind;
1419  state.heapOid = InvalidOid;
1420  state.partParentOid = InvalidOid;
1421  state.concurrent = drop->concurrent;
1422  relOid = RangeVarGetRelidExtended(rel, lockmode, RVR_MISSING_OK,
1424  (void *) &state);
1425 
1426  /* Not there? */
1427  if (!OidIsValid(relOid))
1428  {
1430  continue;
1431  }
1432 
1433  /*
1434  * Decide if concurrent mode needs to be used here or not. The
1435  * relation persistence cannot be known without its OID.
1436  */
1437  if (drop->concurrent &&
1438  get_rel_persistence(relOid) != RELPERSISTENCE_TEMP)
1439  {
1440  Assert(list_length(drop->objects) == 1 &&
1441  drop->removeType == OBJECT_INDEX);
1443  }
1444 
1445  /*
1446  * Concurrent index drop cannot be used with partitioned indexes,
1447  * either.
1448  */
1449  if ((flags & PERFORM_DELETION_CONCURRENTLY) != 0 &&
1450  get_rel_relkind(relOid) == RELKIND_PARTITIONED_INDEX)
1451  ereport(ERROR,
1452  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1453  errmsg("cannot drop partitioned index \"%s\" concurrently",
1454  rel->relname)));
1455 
1456  /* OK, we're ready to delete this one */
1457  obj.classId = RelationRelationId;
1458  obj.objectId = relOid;
1459  obj.objectSubId = 0;
1460 
1461  add_exact_object_address(&obj, objects);
1462  }
1463 
1464  performMultipleDeletions(objects, drop->behavior, flags);
1465 
1466  free_object_addresses(objects);
1467 }
#define PERFORM_DELETION_CONCURRENTLY
Definition: dependency.h:135
void AcceptInvalidationMessages(void)
Definition: inval.c:745
char get_rel_persistence(Oid relid)
Definition: lsyscache.c:2049
RangeVar * makeRangeVarFromNameList(List *names)
Definition: namespace.c:3107
@ OBJECT_FOREIGN_TABLE
Definition: parsenodes.h:1807
@ OBJECT_VIEW
Definition: parsenodes.h:1839
bool missing_ok
Definition: parsenodes.h:2771
List * objects
Definition: parsenodes.h:2768
ObjectType removeType
Definition: parsenodes.h:2769
bool concurrent
Definition: parsenodes.h:2772
DropBehavior behavior
Definition: parsenodes.h:2770
Definition: regguts.h:318
static void DropErrorMsgNonExistent(RangeVar *rel, char rightkind, bool missing_ok)
Definition: tablecmds.c:1252
static void RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid, Oid oldRelOid, void *arg)
Definition: tablecmds.c:1476

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

Referenced by ExecDropStmt().

◆ renameatt()

ObjectAddress renameatt ( RenameStmt stmt)

Definition at line 3561 of file tablecmds.c.

3562 {
3563  Oid relid;
3565  ObjectAddress address;
3566 
3567  /* lock level taken here should match renameatt_internal */
3569  stmt->missing_ok ? RVR_MISSING_OK : 0,
3571  NULL);
3572 
3573  if (!OidIsValid(relid))
3574  {
3575  ereport(NOTICE,
3576  (errmsg("relation \"%s\" does not exist, skipping",
3577  stmt->relation->relname)));
3578  return InvalidObjectAddress;
3579  }
3580 
3581  attnum =
3582  renameatt_internal(relid,
3583  stmt->subname, /* old att name */
3584  stmt->newname, /* new att name */
3585  stmt->relation->inh, /* recursive? */
3586  false, /* recursing? */
3587  0, /* expected inhcount */
3588  stmt->behavior);
3589 
3590  ObjectAddressSubSet(address, RelationRelationId, relid, attnum);
3591 
3592  return address;
3593 }
#define ObjectAddressSubSet(addr, class_id, object_id, object_sub_id)
Definition: objectaddress.h:33
RangeVar * relation
Definition: parsenodes.h:3059
bool missing_ok
Definition: parsenodes.h:3065
DropBehavior behavior
Definition: parsenodes.h:3064
char * newname
Definition: parsenodes.h:3063
char * subname
Definition: parsenodes.h:3061
static AttrNumber renameatt_internal(Oid myrelid, const char *oldattname, const char *newattname, bool recurse, bool recursing, int expected_parents, DropBehavior behavior)
Definition: tablecmds.c:3396
static void RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:3541

References AccessExclusiveLock, attnum, RenameStmt::behavior, ereport, errmsg(), RangeVar::inh, InvalidObjectAddress, RenameStmt::missing_ok, RenameStmt::newname, NOTICE, ObjectAddressSubSet, OidIsValid, RangeVarCallbackForRenameAttribute(), RangeVarGetRelidExtended(), RenameStmt::relation, RangeVar::relname, renameatt_internal(), RVR_MISSING_OK, and RenameStmt::subname.

Referenced by ExecRenameStmt().

◆ RenameConstraint()

ObjectAddress RenameConstraint ( RenameStmt stmt)

Definition at line 3705 of file tablecmds.c.

3706 {
3707  Oid relid = InvalidOid;
3708  Oid typid = InvalidOid;
3709 
3710  if (stmt->renameType == OBJECT_DOMCONSTRAINT)
3711  {
3712  Relation rel;
3713  HeapTuple tup;
3714 
3716  rel = table_open(TypeRelationId, RowExclusiveLock);
3717  tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
3718  if (!HeapTupleIsValid(tup))
3719  elog(ERROR, "cache lookup failed for type %u", typid);
3720  checkDomainOwner(tup);
3721  ReleaseSysCache(tup);
3722  table_close(rel, NoLock);
3723  }
3724  else
3725  {
3726  /* lock level taken here should match rename_constraint_internal */
3728  stmt->missing_ok ? RVR_MISSING_OK : 0,
3730  NULL);
3731  if (!OidIsValid(relid))
3732  {
3733  ereport(NOTICE,
3734  (errmsg("relation \"%s\" does not exist, skipping",
3735  stmt->relation->relname)));
3736  return InvalidObjectAddress;
3737  }
3738  }
3739 
3740  return
3741  rename_constraint_internal(relid, typid,
3742  stmt->subname,
3743  stmt->newname,
3744  (stmt->relation &&
3745  stmt->relation->inh), /* recursive? */
3746  false, /* recursing? */
3747  0 /* expected inhcount */ );
3748 
3749 }
TypeName * makeTypeNameFromNameList(List *names)
Definition: makefuncs.c:456
#define castNode(_type_, nodeptr)
Definition: nodes.h:608
@ OBJECT_DOMCONSTRAINT
Definition: parsenodes.h:1802
ObjectType renameType
Definition: parsenodes.h:3057
Node * object
Definition: parsenodes.h:3060
@ TYPEOID
Definition: syscache.h:112
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:3599
void checkDomainOwner(HeapTuple tup)
Definition: typecmds.c:3425

References AccessExclusiveLock, castNode, checkDomainOwner(), elog, ereport, errmsg(), ERROR, HeapTupleIsValid, RangeVar::inh, InvalidObjectAddress, InvalidOid, makeTypeNameFromNameList(), RenameStmt::missing_ok, RenameStmt::newname, NoLock, NOTICE, RenameStmt::object, OBJECT_DOMCONSTRAINT, ObjectIdGetDatum, OidIsValid, RangeVarCallbackForRenameAttribute(), RangeVarGetRelidExtended(), RenameStmt::relation, ReleaseSysCache(), RangeVar::relname, rename_constraint_internal(), RenameStmt::renameType, RowExclusiveLock, RVR_MISSING_OK, SearchSysCache1(), RenameStmt::subname, table_close(), table_open(), typenameTypeId(), and TYPEOID.

Referenced by ExecRenameStmt().

◆ RenameRelation()

ObjectAddress RenameRelation ( RenameStmt stmt)

Definition at line 3756 of file tablecmds.c.

3757 {
3758  bool is_index_stmt = stmt->renameType == OBJECT_INDEX;
3759  Oid relid;
3760  ObjectAddress address;
3761 
3762  /*
3763  * Grab an exclusive lock on the target table, index, sequence, view,
3764  * materialized view, or foreign table, which we will NOT release until
3765  * end of transaction.
3766  *
3767  * Lock level used here should match RenameRelationInternal, to avoid lock
3768  * escalation. However, because ALTER INDEX can be used with any relation
3769  * type, we mustn't believe without verification.
3770  */
3771  for (;;)
3772  {
3773  LOCKMODE lockmode;
3774  char relkind;
3775  bool obj_is_index;
3776 
3777  lockmode = is_index_stmt ? ShareUpdateExclusiveLock : AccessExclusiveLock;
3778 
3779  relid = RangeVarGetRelidExtended(stmt->relation, lockmode,
3780  stmt->missing_ok ? RVR_MISSING_OK : 0,
3782  (void *) stmt);
3783 
3784  if (!OidIsValid(relid))
3785  {
3786  ereport(NOTICE,
3787  (errmsg("relation \"%s\" does not exist, skipping",
3788  stmt->relation->relname)));
3789  return InvalidObjectAddress;
3790  }
3791 
3792  /*
3793  * We allow mismatched statement and object types (e.g., ALTER INDEX
3794  * to rename a table), but we might've used the wrong lock level. If
3795  * that happens, retry with the correct lock level. We don't bother
3796  * if we already acquired AccessExclusiveLock with an index, however.
3797  */
3798  relkind = get_rel_relkind(relid);
3799  obj_is_index = (relkind == RELKIND_INDEX ||
3800  relkind == RELKIND_PARTITIONED_INDEX);
3801  if (obj_is_index || is_index_stmt == obj_is_index)
3802  break;
3803 
3804  UnlockRelationOid(relid, lockmode);
3805  is_index_stmt = obj_is_index;
3806  }
3807 
3808  /* Do the work */
3809  RenameRelationInternal(relid, stmt->newname, false, is_index_stmt);
3810 
3811  ObjectAddressSet(address, RelationRelationId, relid);
3812 
3813  return address;
3814 }
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:200
void RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
Definition: tablecmds.c:3820

References AccessExclusiveLock, ereport, errmsg(), get_rel_relkind(), InvalidObjectAddress, RenameStmt::missing_ok, RenameStmt::newname, NOTICE, OBJECT_INDEX, ObjectAddressSet, OidIsValid, RangeVarCallbackForAlterRelation(), RangeVarGetRelidExtended(), RenameStmt::relation, DropRelationCallbackState::relkind, RenameRelationInternal(), RenameStmt::renameType, RVR_MISSING_OK, ShareUpdateExclusiveLock, and UnlockRelationOid().

Referenced by ExecRenameStmt().

◆ RenameRelationInternal()

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

Definition at line 3820 of file tablecmds.c.

3821 {
3822  Relation targetrelation;
3823  Relation relrelation; /* for RELATION relation */
3824  HeapTuple reltup;
3825  Form_pg_class relform;
3826  Oid namespaceId;
3827 
3828  /*
3829  * Grab a lock on the target relation, which we will NOT release until end
3830  * of transaction. We need at least a self-exclusive lock so that
3831  * concurrent DDL doesn't overwrite the rename if they start updating
3832  * while still seeing the old version. The lock also guards against
3833  * triggering relcache reloads in concurrent sessions, which might not
3834  * handle this information changing under them. For indexes, we can use a
3835  * reduced lock level because RelationReloadIndexInfo() handles indexes
3836  * specially.
3837  */
3838  targetrelation = relation_open(myrelid, is_index ? ShareUpdateExclusiveLock : AccessExclusiveLock);
3839  namespaceId = RelationGetNamespace(targetrelation);
3840 
3841  /*
3842  * Find relation's pg_class tuple, and make sure newrelname isn't in use.
3843  */
3844  relrelation = table_open(RelationRelationId, RowExclusiveLock);
3845 
3846  reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
3847  if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
3848  elog(ERROR, "cache lookup failed for relation %u", myrelid);
3849  relform = (Form_pg_class) GETSTRUCT(reltup);
3850 
3851  if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
3852  ereport(ERROR,
3853  (errcode(ERRCODE_DUPLICATE_TABLE),
3854  errmsg("relation \"%s\" already exists",
3855  newrelname)));
3856 
3857  /*
3858  * RenameRelation is careful not to believe the caller's idea of the
3859  * relation kind being handled. We don't have to worry about this, but
3860  * let's not be totally oblivious to it. We can process an index as
3861  * not-an-index, but not the other way around.
3862  */
3863  Assert(!is_index ||
3864  is_index == (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
3865  targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX));
3866 
3867  /*
3868  * Update pg_class tuple with new relname. (Scribbling on reltup is OK
3869  * because it's a copy...)
3870  */
3871  namestrcpy(&(relform->relname), newrelname);
3872 
3873  CatalogTupleUpdate(relrelation, &reltup->t_self, reltup);
3874 
3875  InvokeObjectPostAlterHookArg(RelationRelationId, myrelid, 0,
3876  InvalidOid, is_internal);
3877 
3878  heap_freetuple(reltup);
3879  table_close(relrelation, RowExclusiveLock);
3880 
3881  /*
3882  * Also rename the associated type, if any.
3883  */
3884  if (OidIsValid(targetrelation->rd_rel->reltype))
3885  RenameTypeInternal(targetrelation->rd_rel->reltype,
3886  newrelname, namespaceId);
3887 
3888  /*
3889  * Also rename the associated constraint, if any.
3890  */
3891  if (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
3892  targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
3893  {
3894  Oid constraintId = get_index_constraint(myrelid);
3895 
3896  if (OidIsValid(constraintId))
3897  RenameConstraintById(constraintId, newrelname);
3898  }
3899 
3900  /*
3901  * Close rel, but keep lock!
3902  */
3903  relation_close(targetrelation, NoLock);
3904 }
void namestrcpy(Name name, const char *str)
Definition: name.c:233
#define InvokeObjectPostAlterHookArg(classId, objectId, subId, auxiliaryId, is_internal)
Definition: objectaccess.h:178
void RenameConstraintById(Oid conId, const char *newname)
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:911
void RenameTypeInternal(Oid typeOid, const char *newTypeName, Oid typeNamespace)
Definition: pg_type.c:741

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

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

◆ ResetRelRewrite()

void ResetRelRewrite ( Oid  myrelid)

Definition at line 3910 of file tablecmds.c.

3911 {
3912  Relation relrelation; /* for RELATION relation */
3913  HeapTuple reltup;
3914  Form_pg_class relform;
3915 
3916  /*
3917  * Find relation's pg_class tuple.
3918  */
3919  relrelation = table_open(RelationRelationId, RowExclusiveLock);
3920 
3921  reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
3922  if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
3923  elog(ERROR, "cache lookup failed for relation %u", myrelid);
3924  relform = (Form_pg_class) GETSTRUCT(reltup);
3925 
3926  /*
3927  * Update pg_class tuple.
3928  */
3929  relform->relrewrite = InvalidOid;
3930 
3931  CatalogTupleUpdate(relrelation, &reltup->t_self, reltup);
3932 
3933  heap_freetuple(reltup);
3934  table_close(relrelation, RowExclusiveLock);
3935 }

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

Referenced by finish_heap_swap().

◆ SetRelationHasSubclass()

void SetRelationHasSubclass ( Oid  relationId,
bool  relhassubclass 
)

Definition at line 3207 of file tablecmds.c.

3208 {
3209  Relation relationRelation;
3210  HeapTuple tuple;
3211  Form_pg_class classtuple;
3212 
3213  /*
3214  * Fetch a modifiable copy of the tuple, modify it, update pg_class.
3215  */
3216  relationRelation = table_open(RelationRelationId, RowExclusiveLock);
3217  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
3218  if (!HeapTupleIsValid(tuple))
3219  elog(ERROR, "cache lookup failed for relation %u", relationId);
3220  classtuple = (Form_pg_class) GETSTRUCT(tuple);
3221 
3222  if (classtuple->relhassubclass != relhassubclass)
3223  {
3224  classtuple->relhassubclass = relhassubclass;
3225  CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
3226  }
3227  else
3228  {
3229  /* no need to change tuple, but force relcache rebuild anyway */
3231  }
3232 
3233  heap_freetuple(tuple);
3234  table_close(relationRelation, RowExclusiveLock);
3235 }
void CacheInvalidateRelcacheByTuple(HeapTuple classTuple)
Definition: inval.c:1398

References CacheInvalidateRelcacheByTuple(), CatalogTupleUpdate(), elog, ERROR, GETSTRUCT, heap_freetuple(), HeapTupleIsValid, ObjectIdGetDatum, RELOID, RowExclusiveLock, SearchSysCacheCopy1, 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,
Oid  newRelFileNode 
)

Definition at line 3305 of file tablecmds.c.

3308 {
3309  Relation pg_class;
3310  HeapTuple tuple;
3311  Form_pg_class rd_rel;
3312  Oid reloid = RelationGetRelid(rel);
3313 
3314  Assert(CheckRelationTableSpaceMove(rel, newTableSpaceId));
3315 
3316  /* Get a modifiable copy of the relation's pg_class row. */
3317  pg_class = table_open(RelationRelationId, RowExclusiveLock);
3318 
3319  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(reloid));
3320  if (!HeapTupleIsValid(tuple))
3321  elog(ERROR, "cache lookup failed for relation %u", reloid);
3322  rd_rel = (Form_pg_class) GETSTRUCT(tuple);
3323 
3324  /* Update the pg_class row. */
3325  rd_rel->reltablespace = (newTableSpaceId == MyDatabaseTableSpace) ?
3326  InvalidOid : newTableSpaceId;
3327  if (OidIsValid(newRelFileNode))
3328  rd_rel->relfilenode = newRelFileNode;
3329  CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
3330 
3331  /*
3332  * Record dependency on tablespace. This is only required for relations
3333  * that have no physical storage.
3334  */
3335  if (!RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
3336  changeDependencyOnTablespace(RelationRelationId, reloid,
3337  rd_rel->reltablespace);
3338 
3339  heap_freetuple(tuple);
3340  table_close(pg_class, RowExclusiveLock);
3341 }
void changeDependencyOnTablespace(Oid classId, Oid objectId, Oid newTablespaceId)
Definition: pg_shdepend.c:381
bool CheckRelationTableSpaceMove(Relation rel, Oid newTableSpaceId)
Definition: tablecmds.c:3248

References Assert(), CatalogTupleUpdate(), changeDependencyOnTablespace(), CheckRelationTableSpaceMove(), elog, ERROR, GETSTRUCT, heap_freetuple(), HeapTupleIsValid, InvalidOid, MyDatabaseTableSpace, ObjectIdGetDatum, OidIsValid, RelationData::rd_rel, RelationGetRelid, RELOID, RowExclusiveLock, SearchSysCacheCopy1, HeapTupleData::t_self, table_close(), and table_open().

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