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

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

15925 {
15926  HeapTuple classTup;
15927  Form_pg_class classForm;
15928  ObjectAddress thisobj;
15929  bool already_done = false;
15930 
15931  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
15932  if (!HeapTupleIsValid(classTup))
15933  elog(ERROR, "cache lookup failed for relation %u", relOid);
15934  classForm = (Form_pg_class) GETSTRUCT(classTup);
15935 
15936  Assert(classForm->relnamespace == oldNspOid);
15937 
15938  thisobj.classId = RelationRelationId;
15939  thisobj.objectId = relOid;
15940  thisobj.objectSubId = 0;
15941 
15942  /*
15943  * If the object has already been moved, don't move it again. If it's
15944  * already in the right place, don't move it, but still fire the object
15945  * access hook.
15946  */
15947  already_done = object_address_present(&thisobj, objsMoved);
15948  if (!already_done && oldNspOid != newNspOid)
15949  {
15950  /* check for duplicate name (more friendly than unique-index failure) */
15951  if (get_relname_relid(NameStr(classForm->relname),
15952  newNspOid) != InvalidOid)
15953  ereport(ERROR,
15954  (errcode(ERRCODE_DUPLICATE_TABLE),
15955  errmsg("relation \"%s\" already exists in schema \"%s\"",
15956  NameStr(classForm->relname),
15957  get_namespace_name(newNspOid))));
15958 
15959  /* classTup is a copy, so OK to scribble on */
15960  classForm->relnamespace = newNspOid;
15961 
15962  CatalogTupleUpdate(classRel, &classTup->t_self, classTup);
15963 
15964  /* Update dependency on schema if caller said so */
15965  if (hasDependEntry &&
15966  changeDependencyFor(RelationRelationId,
15967  relOid,
15968  NamespaceRelationId,
15969  oldNspOid,
15970  newNspOid) != 1)
15971  elog(ERROR, "failed to change schema dependency for relation \"%s\"",
15972  NameStr(classForm->relname));
15973  }
15974  if (!already_done)
15975  {
15976  add_exact_object_address(&thisobj, objsMoved);
15977 
15978  InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
15979  }
15980 
15981  heap_freetuple(classTup);
15982 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2552
int errcode(int sqlerrcode)
Definition: elog.c:698
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2492
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
ItemPointerData t_self
Definition: htup.h:65
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1856
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:175
int errmsg(const char *fmt,...)
Definition: elog.c:909
long changeDependencyFor(Oid classId, Oid objectId, Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition: pg_depend.c:388
#define elog(elevel,...)
Definition: elog.h:232
#define NameStr(name)
Definition: c.h:681

◆ AlterTable()

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

Definition at line 4013 of file tablecmds.c.

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

Referenced by ProcessUtilitySlow().

4015 {
4016  Relation rel;
4017 
4018  /* Caller is required to provide an adequate lock. */
4019  rel = relation_open(context->relid, NoLock);
4020 
4021  CheckTableNotInUse(rel, "ALTER TABLE");
4022 
4023  ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
4024 }
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:4357
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define NoLock
Definition: lockdefs.h:34
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3929
bool inh
Definition: primnodes.h:69
RangeVar * relation
Definition: parsenodes.h:1859

◆ AlterTableGetLockLevel()

LOCKMODE AlterTableGetLockLevel ( List cmds)

Definition at line 4087 of file tablecmds.c.

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

4088 {
4089  /*
4090  * This only works if we read catalog tables using MVCC snapshots.
4091  */
4092  ListCell *lcmd;
4094 
4095  foreach(lcmd, cmds)
4096  {
4097  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
4098  LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
4099 
4100  switch (cmd->subtype)
4101  {
4102  /*
4103  * These subcommands rewrite the heap, so require full locks.
4104  */
4105  case AT_AddColumn: /* may rewrite heap, in some cases and visible
4106  * to SELECT */
4107  case AT_SetTableSpace: /* must rewrite heap */
4108  case AT_AlterColumnType: /* must rewrite heap */
4109  cmd_lockmode = AccessExclusiveLock;
4110  break;
4111 
4112  /*
4113  * These subcommands may require addition of toast tables. If
4114  * we add a toast table to a table currently being scanned, we
4115  * might miss data added to the new toast table by concurrent
4116  * insert transactions.
4117  */
4118  case AT_SetStorage: /* may add toast tables, see
4119  * ATRewriteCatalogs() */
4120  cmd_lockmode = AccessExclusiveLock;
4121  break;
4122 
4123  /*
4124  * Removing constraints can affect SELECTs that have been
4125  * optimized assuming the constraint holds true. See also
4126  * CloneFkReferenced.
4127  */
4128  case AT_DropConstraint: /* as DROP INDEX */
4129  case AT_DropNotNull: /* may change some SQL plans */
4130  cmd_lockmode = AccessExclusiveLock;
4131  break;
4132 
4133  /*
4134  * Subcommands that may be visible to concurrent SELECTs
4135  */
4136  case AT_DropColumn: /* change visible to SELECT */
4137  case AT_AddColumnToView: /* CREATE VIEW */
4138  case AT_DropOids: /* used to equiv to DropColumn */
4139  case AT_EnableAlwaysRule: /* may change SELECT rules */
4140  case AT_EnableReplicaRule: /* may change SELECT rules */
4141  case AT_EnableRule: /* may change SELECT rules */
4142  case AT_DisableRule: /* may change SELECT rules */
4143  cmd_lockmode = AccessExclusiveLock;
4144  break;
4145 
4146  /*
4147  * Changing owner may remove implicit SELECT privileges
4148  */
4149  case AT_ChangeOwner: /* change visible to SELECT */
4150  cmd_lockmode = AccessExclusiveLock;
4151  break;
4152 
4153  /*
4154  * Changing foreign table options may affect optimization.
4155  */
4156  case AT_GenericOptions:
4158  cmd_lockmode = AccessExclusiveLock;
4159  break;
4160 
4161  /*
4162  * These subcommands affect write operations only.
4163  */
4164  case AT_EnableTrig:
4165  case AT_EnableAlwaysTrig:
4166  case AT_EnableReplicaTrig:
4167  case AT_EnableTrigAll:
4168  case AT_EnableTrigUser:
4169  case AT_DisableTrig:
4170  case AT_DisableTrigAll:
4171  case AT_DisableTrigUser:
4172  cmd_lockmode = ShareRowExclusiveLock;
4173  break;
4174 
4175  /*
4176  * These subcommands affect write operations only. XXX
4177  * Theoretically, these could be ShareRowExclusiveLock.
4178  */
4179  case AT_ColumnDefault:
4181  case AT_AlterConstraint:
4182  case AT_AddIndex: /* from ADD CONSTRAINT */
4183  case AT_AddIndexConstraint:
4184  case AT_ReplicaIdentity:
4185  case AT_SetNotNull:
4186  case AT_EnableRowSecurity:
4187  case AT_DisableRowSecurity:
4188  case AT_ForceRowSecurity:
4189  case AT_NoForceRowSecurity:
4190  case AT_AddIdentity:
4191  case AT_DropIdentity:
4192  case AT_SetIdentity:
4193  case AT_DropExpression:
4194  case AT_SetCompression:
4195  cmd_lockmode = AccessExclusiveLock;
4196  break;
4197 
4198  case AT_AddConstraint:
4199  case AT_AddConstraintRecurse: /* becomes AT_AddConstraint */
4200  case AT_ReAddConstraint: /* becomes AT_AddConstraint */
4201  case AT_ReAddDomainConstraint: /* becomes AT_AddConstraint */
4202  if (IsA(cmd->def, Constraint))
4203  {
4204  Constraint *con = (Constraint *) cmd->def;
4205 
4206  switch (con->contype)
4207  {
4208  case CONSTR_EXCLUSION:
4209  case CONSTR_PRIMARY:
4210  case CONSTR_UNIQUE:
4211 
4212  /*
4213  * Cases essentially the same as CREATE INDEX. We
4214  * could reduce the lock strength to ShareLock if
4215  * we can work out how to allow concurrent catalog
4216  * updates. XXX Might be set down to
4217  * ShareRowExclusiveLock but requires further
4218  * analysis.
4219  */
4220  cmd_lockmode = AccessExclusiveLock;
4221  break;
4222  case CONSTR_FOREIGN:
4223 
4224  /*
4225  * We add triggers to both tables when we add a
4226  * Foreign Key, so the lock level must be at least
4227  * as strong as CREATE TRIGGER.
4228  */
4229  cmd_lockmode = ShareRowExclusiveLock;
4230  break;
4231 
4232  default:
4233  cmd_lockmode = AccessExclusiveLock;
4234  }
4235  }
4236  break;
4237 
4238  /*
4239  * These subcommands affect inheritance behaviour. Queries
4240  * started before us will continue to see the old inheritance
4241  * behaviour, while queries started after we commit will see
4242  * new behaviour. No need to prevent reads or writes to the
4243  * subtable while we hook it up though. Changing the TupDesc
4244  * may be a problem, so keep highest lock.
4245  */
4246  case AT_AddInherit:
4247  case AT_DropInherit:
4248  cmd_lockmode = AccessExclusiveLock;
4249  break;
4250 
4251  /*
4252  * These subcommands affect implicit row type conversion. They
4253  * have affects similar to CREATE/DROP CAST on queries. don't
4254  * provide for invalidating parse trees as a result of such
4255  * changes, so we keep these at AccessExclusiveLock.
4256  */
4257  case AT_AddOf:
4258  case AT_DropOf:
4259  cmd_lockmode = AccessExclusiveLock;
4260  break;
4261 
4262  /*
4263  * Only used by CREATE OR REPLACE VIEW which must conflict
4264  * with an SELECTs currently using the view.
4265  */
4266  case AT_ReplaceRelOptions:
4267  cmd_lockmode = AccessExclusiveLock;
4268  break;
4269 
4270  /*
4271  * These subcommands affect general strategies for performance
4272  * and maintenance, though don't change the semantic results
4273  * from normal data reads and writes. Delaying an ALTER TABLE
4274  * behind currently active writes only delays the point where
4275  * the new strategy begins to take effect, so there is no
4276  * benefit in waiting. In this case the minimum restriction
4277  * applies: we don't currently allow concurrent catalog
4278  * updates.
4279  */
4280  case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
4281  case AT_ClusterOn: /* Uses MVCC in getIndexes() */
4282  case AT_DropCluster: /* Uses MVCC in getIndexes() */
4283  case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
4284  case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
4285  cmd_lockmode = ShareUpdateExclusiveLock;
4286  break;
4287 
4288  case AT_SetLogged:
4289  case AT_SetUnLogged:
4290  cmd_lockmode = AccessExclusiveLock;
4291  break;
4292 
4293  case AT_ValidateConstraint: /* Uses MVCC in getConstraints() */
4294  cmd_lockmode = ShareUpdateExclusiveLock;
4295  break;
4296 
4297  /*
4298  * Rel options are more complex than first appears. Options
4299  * are set here for tables, views and indexes; for historical
4300  * reasons these can all be used with ALTER TABLE, so we can't
4301  * decide between them using the basic grammar.
4302  */
4303  case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
4304  * getTables() */
4305  case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
4306  * getTables() */
4307  cmd_lockmode = AlterTableGetRelOptionsLockLevel((List *) cmd->def);
4308  break;
4309 
4310  case AT_AttachPartition:
4311  cmd_lockmode = ShareUpdateExclusiveLock;
4312  break;
4313 
4314  case AT_DetachPartition:
4315  if (((PartitionCmd *) cmd->def)->concurrent)
4316  cmd_lockmode = ShareUpdateExclusiveLock;
4317  else
4318  cmd_lockmode = AccessExclusiveLock;
4319  break;
4320 
4322  cmd_lockmode = ShareUpdateExclusiveLock;
4323  break;
4324 
4325  case AT_CheckNotNull:
4326 
4327  /*
4328  * This only examines the table's schema; but lock must be
4329  * strong enough to prevent concurrent DROP NOT NULL.
4330  */
4331  cmd_lockmode = AccessShareLock;
4332  break;
4333 
4334  default: /* oops */
4335  elog(ERROR, "unrecognized alter table type: %d",
4336  (int) cmd->subtype);
4337  break;
4338  }
4339 
4340  /*
4341  * Take the greatest lockmode from any subcommand
4342  */
4343  if (cmd_lockmode > lockmode)
4344  lockmode = cmd_lockmode;
4345  }
4346 
4347  return lockmode;
4348 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
int LOCKMODE
Definition: lockdefs.h:26
#define AccessShareLock
Definition: lockdefs.h:36
AlterTableType subtype
Definition: parsenodes.h:1949
#define ERROR
Definition: elog.h:46
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define lfirst(lc)
Definition: pg_list.h:169
#define ShareRowExclusiveLock
Definition: lockdefs.h:42
LOCKMODE AlterTableGetRelOptionsLockLevel(List *defList)
Definition: reloptions.c:2084
#define AccessExclusiveLock
Definition: lockdefs.h:45
#define elog(elevel,...)
Definition: elog.h:232
ConstrType contype
Definition: parsenodes.h:2239
Definition: pg_list.h:50

◆ AlterTableInternal()

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

Definition at line 4042 of file tablecmds.c.

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

Referenced by AlterTableMoveAll(), and DefineVirtualRelation().

4043 {
4044  Relation rel;
4045  LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
4046 
4047  rel = relation_open(relid, lockmode);
4048 
4050 
4051  ATController(NULL, rel, cmds, recurse, lockmode, NULL);
4052 }
int LOCKMODE
Definition: lockdefs.h:26
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:4357
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
LOCKMODE AlterTableGetLockLevel(List *cmds)
Definition: tablecmds.c:4087
void EventTriggerAlterTableRelid(Oid objectId)

◆ AlterTableLookupRelation()

Oid AlterTableLookupRelation ( AlterTableStmt stmt,
LOCKMODE  lockmode 
)

Definition at line 3957 of file tablecmds.c.

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

Referenced by ProcessUtilitySlow().

3958 {
3959  return RangeVarGetRelidExtended(stmt->relation, lockmode,
3960  stmt->missing_ok ? RVR_MISSING_OK : 0,
3962  (void *) stmt);
3963 }
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:16435
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:236
RangeVar * relation
Definition: parsenodes.h:1859

◆ AlterTableMoveAll()

Oid AlterTableMoveAll ( AlterTableMoveAllStmt stmt)

Definition at line 13921 of file tablecmds.c.

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

13922 {
13923  List *relations = NIL;
13924  ListCell *l;
13925  ScanKeyData key[1];
13926  Relation rel;
13927  TableScanDesc scan;
13928  HeapTuple tuple;
13929  Oid orig_tablespaceoid;
13930  Oid new_tablespaceoid;
13931  List *role_oids = roleSpecsToIds(stmt->roles);
13932 
13933  /* Ensure we were not asked to move something we can't */
13934  if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
13935  stmt->objtype != OBJECT_MATVIEW)
13936  ereport(ERROR,
13937  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
13938  errmsg("only tables, indexes, and materialized views exist in tablespaces")));
13939 
13940  /* Get the orig and new tablespace OIDs */
13941  orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
13942  new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
13943 
13944  /* Can't move shared relations in to or out of pg_global */
13945  /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
13946  if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
13947  new_tablespaceoid == GLOBALTABLESPACE_OID)
13948  ereport(ERROR,
13949  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
13950  errmsg("cannot move relations in to or out of pg_global tablespace")));
13951 
13952  /*
13953  * Must have CREATE rights on the new tablespace, unless it is the
13954  * database default tablespace (which all users implicitly have CREATE
13955  * rights on).
13956  */
13957  if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
13958  {
13959  AclResult aclresult;
13960 
13961  aclresult = pg_tablespace_aclcheck(new_tablespaceoid, GetUserId(),
13962  ACL_CREATE);
13963  if (aclresult != ACLCHECK_OK)
13964  aclcheck_error(aclresult, OBJECT_TABLESPACE,
13965  get_tablespace_name(new_tablespaceoid));
13966  }
13967 
13968  /*
13969  * Now that the checks are done, check if we should set either to
13970  * InvalidOid because it is our database's default tablespace.
13971  */
13972  if (orig_tablespaceoid == MyDatabaseTableSpace)
13973  orig_tablespaceoid = InvalidOid;
13974 
13975  if (new_tablespaceoid == MyDatabaseTableSpace)
13976  new_tablespaceoid = InvalidOid;
13977 
13978  /* no-op */
13979  if (orig_tablespaceoid == new_tablespaceoid)
13980  return new_tablespaceoid;
13981 
13982  /*
13983  * Walk the list of objects in the tablespace and move them. This will
13984  * only find objects in our database, of course.
13985  */
13986  ScanKeyInit(&key[0],
13987  Anum_pg_class_reltablespace,
13988  BTEqualStrategyNumber, F_OIDEQ,
13989  ObjectIdGetDatum(orig_tablespaceoid));
13990 
13991  rel = table_open(RelationRelationId, AccessShareLock);
13992  scan = table_beginscan_catalog(rel, 1, key);
13993  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
13994  {
13995  Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
13996  Oid relOid = relForm->oid;
13997 
13998  /*
13999  * Do not move objects in pg_catalog as part of this, if an admin
14000  * really wishes to do so, they can issue the individual ALTER
14001  * commands directly.
14002  *
14003  * Also, explicitly avoid any shared tables, temp tables, or TOAST
14004  * (TOAST will be moved with the main table).
14005  */
14006  if (IsCatalogNamespace(relForm->relnamespace) ||
14007  relForm->relisshared ||
14008  isAnyTempNamespace(relForm->relnamespace) ||
14009  IsToastNamespace(relForm->relnamespace))
14010  continue;
14011 
14012  /* Only move the object type requested */
14013  if ((stmt->objtype == OBJECT_TABLE &&
14014  relForm->relkind != RELKIND_RELATION &&
14015  relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
14016  (stmt->objtype == OBJECT_INDEX &&
14017  relForm->relkind != RELKIND_INDEX &&
14018  relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
14019  (stmt->objtype == OBJECT_MATVIEW &&
14020  relForm->relkind != RELKIND_MATVIEW))
14021  continue;
14022 
14023  /* Check if we are only moving objects owned by certain roles */
14024  if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
14025  continue;
14026 
14027  /*
14028  * Handle permissions-checking here since we are locking the tables
14029  * and also to avoid doing a bunch of work only to fail part-way. Note
14030  * that permissions will also be checked by AlterTableInternal().
14031  *
14032  * Caller must be considered an owner on the table to move it.
14033  */
14034  if (!pg_class_ownercheck(relOid, GetUserId()))
14036  NameStr(relForm->relname));
14037 
14038  if (stmt->nowait &&
14040  ereport(ERROR,
14041  (errcode(ERRCODE_OBJECT_IN_USE),
14042  errmsg("aborting because lock on relation \"%s.%s\" is not available",
14043  get_namespace_name(relForm->relnamespace),
14044  NameStr(relForm->relname))));
14045  else
14047 
14048  /* Add to our list of objects to move */
14049  relations = lappend_oid(relations, relOid);
14050  }
14051 
14052  table_endscan(scan);
14054 
14055  if (relations == NIL)
14056  ereport(NOTICE,
14057  (errcode(ERRCODE_NO_DATA_FOUND),
14058  errmsg("no matching relations in tablespace \"%s\" found",
14059  orig_tablespaceoid == InvalidOid ? "(database default)" :
14060  get_tablespace_name(orig_tablespaceoid))));
14061 
14062  /* Everything is locked, loop through and move all of the relations. */
14063  foreach(l, relations)
14064  {
14065  List *cmds = NIL;
14067 
14068  cmd->subtype = AT_SetTableSpace;
14069  cmd->name = stmt->new_tablespacename;
14070 
14071  cmds = lappend(cmds, cmd);
14072 
14074  /* OID is set by AlterTableInternal */
14075  AlterTableInternal(lfirst_oid(l), cmds, false);
14077  }
14078 
14079  return new_tablespaceoid;
14080 }
#define NIL
Definition: pg_list.h:65
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:152
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1433
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4773
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
Oid GetUserId(void)
Definition: miscinit.c:478
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1974
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:539
int errcode(int sqlerrcode)
Definition: elog.c:698
AlterTableType subtype
Definition: parsenodes.h:1949
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:200
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
#define OidIsValid(objectId)
Definition: c.h:710
Oid MyDatabaseTableSpace
Definition: globals.c:90
void EventTriggerAlterTableStart(Node *parsetree)
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3313
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
#define ACL_CREATE
Definition: parsenodes.h:92
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1340
List * lappend(List *list, void *datum)
Definition: list.c:336
AclResult
Definition: acl.h:177
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
#define NOTICE
Definition: elog.h:37
#define makeNode(_type_)
Definition: nodes.h:587
List * roleSpecsToIds(List *memberNames)
Definition: user.c:1436
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:689
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4823
bool IsCatalogNamespace(Oid namespaceId)
Definition: catalog.c:182
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:991
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
void AlterTableInternal(Oid relid, List *cmds, bool recurse)
Definition: tablecmds.c:4042
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:909
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1479
ObjectType get_relkind_objtype(char relkind)
#define NameStr(name)
Definition: c.h:681
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
bool isAnyTempNamespace(Oid namespaceId)
Definition: namespace.c:3194
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:109
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define lfirst_oid(lc)
Definition: pg_list.h:171
void EventTriggerAlterTableEnd(void)

◆ AlterTableNamespace()

ObjectAddress AlterTableNamespace ( AlterObjectSchemaStmt stmt,
Oid oldschema 
)

Definition at line 15811 of file tablecmds.c.

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

Referenced by ExecAlterObjectSchemaStmt().

15812 {
15813  Relation rel;
15814  Oid relid;
15815  Oid oldNspOid;
15816  Oid nspOid;
15817  RangeVar *newrv;
15818  ObjectAddresses *objsMoved;
15819  ObjectAddress myself;
15820 
15822  stmt->missing_ok ? RVR_MISSING_OK : 0,
15824  (void *) stmt);
15825 
15826  if (!OidIsValid(relid))
15827  {
15828  ereport(NOTICE,
15829  (errmsg("relation \"%s\" does not exist, skipping",
15830  stmt->relation->relname)));
15831  return InvalidObjectAddress;
15832  }
15833 
15834  rel = relation_open(relid, NoLock);
15835 
15836  oldNspOid = RelationGetNamespace(rel);
15837 
15838  /* If it's an owned sequence, disallow moving it by itself. */
15839  if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
15840  {
15841  Oid tableId;
15842  int32 colId;
15843 
15844  if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
15845  sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
15846  ereport(ERROR,
15847  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15848  errmsg("cannot move an owned sequence into another schema"),
15849  errdetail("Sequence \"%s\" is linked to table \"%s\".",
15851  get_rel_name(tableId))));
15852  }
15853 
15854  /* Get and lock schema OID and check its permissions. */
15855  newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
15856  nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
15857 
15858  /* common checks on switching namespaces */
15859  CheckSetNamespace(oldNspOid, nspOid);
15860 
15861  objsMoved = new_object_addresses();
15862  AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
15863  free_object_addresses(objsMoved);
15864 
15865  ObjectAddressSet(myself, RelationRelationId, relid);
15866 
15867  if (oldschema)
15868  *oldschema = oldNspOid;
15869 
15870  /* close rel, but keep lock until commit */
15871  relation_close(rel, NoLock);
15872 
15873  return myself;
15874 }
bool sequenceIsOwned(Oid seqId, char deptype, Oid *tableId, int32 *colId)
Definition: pg_depend.c:797
int errcode(int sqlerrcode)
Definition: elog.c:698
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2437
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2732
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
signed int int32
Definition: c.h:429
char * relname
Definition: primnodes.h:68
#define ERROR
Definition: elog.h:46
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
void AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:15882
#define NoLock
Definition: lockdefs.h:34
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:16435
int errdetail(const char *fmt,...)
Definition: elog.c:1042
#define RelationGetRelationName(relation)
Definition: rel.h:503
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:236
void CheckSetNamespace(Oid oldNspOid, Oid nspOid)
Definition: namespace.c:2966
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:534
#define ereport(elevel,...)
Definition: elog.h:157
#define NOTICE
Definition: elog.h:37
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define AccessExclusiveLock
Definition: lockdefs.h:45
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:909
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:422
#define RelationGetNamespace(relation)
Definition: rel.h:510

◆ AlterTableNamespaceInternal()

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

Definition at line 15882 of file tablecmds.c.

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

15884 {
15885  Relation classRel;
15886 
15887  Assert(objsMoved != NULL);
15888 
15889  /* OK, modify the pg_class row and pg_depend entry */
15890  classRel = table_open(RelationRelationId, RowExclusiveLock);
15891 
15892  AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
15893  nspOid, true, objsMoved);
15894 
15895  /* Fix the table's row type too, if it has one */
15896  if (OidIsValid(rel->rd_rel->reltype))
15897  AlterTypeNamespaceInternal(rel->rd_rel->reltype,
15898  nspOid, false, false, objsMoved);
15899 
15900  /* Fix other dependent stuff */
15901  if (rel->rd_rel->relkind == RELKIND_RELATION ||
15902  rel->rd_rel->relkind == RELKIND_MATVIEW ||
15903  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
15904  {
15905  AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
15906  AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
15907  objsMoved, AccessExclusiveLock);
15908  AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
15909  false, objsMoved);
15910  }
15911 
15912  table_close(classRel, RowExclusiveLock);
15913 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Oid AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid, bool isImplicitArray, bool errorOnTableType, ObjectAddresses *objsMoved)
Definition: typecmds.c:3970
Form_pg_class rd_rel
Definition: rel.h:109
#define OidIsValid(objectId)
Definition: c.h:710
static void AlterIndexNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:15991
void AlterConstraintNamespaces(Oid ownerId, Oid oldNspId, Oid newNspId, bool isType, ObjectAddresses *objsMoved)
static void AlterSeqNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved, LOCKMODE lockmode)
Definition: tablecmds.c:16036
#define RowExclusiveLock
Definition: lockdefs.h:38
#define Assert(condition)
Definition: c.h:804
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
Definition: tablecmds.c:15921
#define AccessExclusiveLock
Definition: lockdefs.h:45
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define RelationGetRelid(relation)
Definition: rel.h:469

◆ AtEOSubXact_on_commit_actions()

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

Definition at line 16312 of file tablecmds.c.

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

Referenced by AbortSubTransaction(), and CommitSubTransaction().

16314 {
16315  ListCell *cur_item;
16316 
16317  foreach(cur_item, on_commits)
16318  {
16319  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
16320 
16321  if (!isCommit && oc->creating_subid == mySubid)
16322  {
16323  /* cur_item must be removed */
16325  pfree(oc);
16326  }
16327  else
16328  {
16329  /* cur_item must be preserved */
16330  if (oc->creating_subid == mySubid)
16331  oc->creating_subid = parentSubid;
16332  if (oc->deleting_subid == mySubid)
16333  oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
16334  }
16335  }
16336 }
SubTransactionId creating_subid
Definition: tablecmds.c:119
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:369
void pfree(void *pointer)
Definition: mcxt.c:1169
static List * on_commits
Definition: tablecmds.c:123
SubTransactionId deleting_subid
Definition: tablecmds.c:120
#define lfirst(lc)
Definition: pg_list.h:169
#define InvalidSubTransactionId
Definition: c.h:593

◆ AtEOXact_on_commit_actions()

void AtEOXact_on_commit_actions ( bool  isCommit)

Definition at line 16280 of file tablecmds.c.

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

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

16281 {
16282  ListCell *cur_item;
16283 
16284  foreach(cur_item, on_commits)
16285  {
16286  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
16287 
16288  if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
16290  {
16291  /* cur_item must be removed */
16293  pfree(oc);
16294  }
16295  else
16296  {
16297  /* cur_item must be preserved */
16300  }
16301  }
16302 }
SubTransactionId creating_subid
Definition: tablecmds.c:119
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:369
void pfree(void *pointer)
Definition: mcxt.c:1169
static List * on_commits
Definition: tablecmds.c:123
SubTransactionId deleting_subid
Definition: tablecmds.c:120
#define lfirst(lc)
Definition: pg_list.h:169
#define InvalidSubTransactionId
Definition: c.h:593

◆ ATExecChangeOwner()

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

Definition at line 13142 of file tablecmds.c.

References ACL_CREATE, aclcheck_error(), ACLCHECK_NOT_OWNER, ACLCHECK_OK, aclnewowner(), AlterTypeOwnerInternal(), ATExecChangeOwner(), CatalogTupleUpdate(), change_owner_fix_column_acls(), change_owner_recurse_to_sequences(), changeDependencyOnOwner(), check_is_member_of_role(), DatumGetAclP, DEPENDENCY_AUTO, DEPENDENCY_INTERNAL, elog, ereport, errcode(), errdetail(), 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(), ATExecChangeOwner(), ATExecCmd(), change_owner_recurse_to_sequences(), and shdepReassignOwned().

13143 {
13144  Relation target_rel;
13145  Relation class_rel;
13146  HeapTuple tuple;
13147  Form_pg_class tuple_class;
13148 
13149  /*
13150  * Get exclusive lock till end of transaction on the target table. Use
13151  * relation_open so that we can work on indexes and sequences.
13152  */
13153  target_rel = relation_open(relationOid, lockmode);
13154 
13155  /* Get its pg_class tuple, too */
13156  class_rel = table_open(RelationRelationId, RowExclusiveLock);
13157 
13158  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
13159  if (!HeapTupleIsValid(tuple))
13160  elog(ERROR, "cache lookup failed for relation %u", relationOid);
13161  tuple_class = (Form_pg_class) GETSTRUCT(tuple);
13162 
13163  /* Can we change the ownership of this tuple? */
13164  switch (tuple_class->relkind)
13165  {
13166  case RELKIND_RELATION:
13167  case RELKIND_VIEW:
13168  case RELKIND_MATVIEW:
13169  case RELKIND_FOREIGN_TABLE:
13170  case RELKIND_PARTITIONED_TABLE:
13171  /* ok to change owner */
13172  break;
13173  case RELKIND_INDEX:
13174  if (!recursing)
13175  {
13176  /*
13177  * Because ALTER INDEX OWNER used to be allowed, and in fact
13178  * is generated by old versions of pg_dump, we give a warning
13179  * and do nothing rather than erroring out. Also, to avoid
13180  * unnecessary chatter while restoring those old dumps, say
13181  * nothing at all if the command would be a no-op anyway.
13182  */
13183  if (tuple_class->relowner != newOwnerId)
13184  ereport(WARNING,
13185  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
13186  errmsg("cannot change owner of index \"%s\"",
13187  NameStr(tuple_class->relname)),
13188  errhint("Change the ownership of the index's table, instead.")));
13189  /* quick hack to exit via the no-op path */
13190  newOwnerId = tuple_class->relowner;
13191  }
13192  break;
13193  case RELKIND_PARTITIONED_INDEX:
13194  if (recursing)
13195  break;
13196  ereport(ERROR,
13197  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
13198  errmsg("cannot change owner of index \"%s\"",
13199  NameStr(tuple_class->relname)),
13200  errhint("Change the ownership of the index's table, instead.")));
13201  break;
13202  case RELKIND_SEQUENCE:
13203  if (!recursing &&
13204  tuple_class->relowner != newOwnerId)
13205  {
13206  /* if it's an owned sequence, disallow changing it by itself */
13207  Oid tableId;
13208  int32 colId;
13209 
13210  if (sequenceIsOwned(relationOid, DEPENDENCY_AUTO, &tableId, &colId) ||
13211  sequenceIsOwned(relationOid, DEPENDENCY_INTERNAL, &tableId, &colId))
13212  ereport(ERROR,
13213  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
13214  errmsg("cannot change owner of sequence \"%s\"",
13215  NameStr(tuple_class->relname)),
13216  errdetail("Sequence \"%s\" is linked to table \"%s\".",
13217  NameStr(tuple_class->relname),
13218  get_rel_name(tableId))));
13219  }
13220  break;
13221  case RELKIND_COMPOSITE_TYPE:
13222  if (recursing)
13223  break;
13224  ereport(ERROR,
13225  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
13226  errmsg("\"%s\" is a composite type",
13227  NameStr(tuple_class->relname)),
13228  errhint("Use ALTER TYPE instead.")));
13229  break;
13230  case RELKIND_TOASTVALUE:
13231  if (recursing)
13232  break;
13233  /* FALL THRU */
13234  default:
13235  ereport(ERROR,
13236  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
13237  errmsg("\"%s\" is not a table, view, sequence, or foreign table",
13238  NameStr(tuple_class->relname))));
13239  }
13240 
13241  /*
13242  * If the new owner is the same as the existing owner, consider the
13243  * command to have succeeded. This is for dump restoration purposes.
13244  */
13245  if (tuple_class->relowner != newOwnerId)
13246  {
13247  Datum repl_val[Natts_pg_class];
13248  bool repl_null[Natts_pg_class];
13249  bool repl_repl[Natts_pg_class];
13250  Acl *newAcl;
13251  Datum aclDatum;
13252  bool isNull;
13253  HeapTuple newtuple;
13254 
13255  /* skip permission checks when recursing to index or toast table */
13256  if (!recursing)
13257  {
13258  /* Superusers can always do it */
13259  if (!superuser())
13260  {
13261  Oid namespaceOid = tuple_class->relnamespace;
13262  AclResult aclresult;
13263 
13264  /* Otherwise, must be owner of the existing object */
13265  if (!pg_class_ownercheck(relationOid, GetUserId()))
13267  RelationGetRelationName(target_rel));
13268 
13269  /* Must be able to become new owner */
13270  check_is_member_of_role(GetUserId(), newOwnerId);
13271 
13272  /* New owner must have CREATE privilege on namespace */
13273  aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
13274  ACL_CREATE);
13275  if (aclresult != ACLCHECK_OK)
13276  aclcheck_error(aclresult, OBJECT_SCHEMA,
13277  get_namespace_name(namespaceOid));
13278  }
13279  }
13280 
13281  memset(repl_null, false, sizeof(repl_null));
13282  memset(repl_repl, false, sizeof(repl_repl));
13283 
13284  repl_repl[Anum_pg_class_relowner - 1] = true;
13285  repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
13286 
13287  /*
13288  * Determine the modified ACL for the new owner. This is only
13289  * necessary when the ACL is non-null.
13290  */
13291  aclDatum = SysCacheGetAttr(RELOID, tuple,
13292  Anum_pg_class_relacl,
13293  &isNull);
13294  if (!isNull)
13295  {
13296  newAcl = aclnewowner(DatumGetAclP(aclDatum),
13297  tuple_class->relowner, newOwnerId);
13298  repl_repl[Anum_pg_class_relacl - 1] = true;
13299  repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
13300  }
13301 
13302  newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
13303 
13304  CatalogTupleUpdate(class_rel, &newtuple->t_self, newtuple);
13305 
13306  heap_freetuple(newtuple);
13307 
13308  /*
13309  * We must similarly update any per-column ACLs to reflect the new
13310  * owner; for neatness reasons that's split out as a subroutine.
13311  */
13312  change_owner_fix_column_acls(relationOid,
13313  tuple_class->relowner,
13314  newOwnerId);
13315 
13316  /*
13317  * Update owner dependency reference, if any. A composite type has
13318  * none, because it's tracked for the pg_type entry instead of here;
13319  * indexes and TOAST tables don't have their own entries either.
13320  */
13321  if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
13322  tuple_class->relkind != RELKIND_INDEX &&
13323  tuple_class->relkind != RELKIND_PARTITIONED_INDEX &&
13324  tuple_class->relkind != RELKIND_TOASTVALUE)
13325  changeDependencyOnOwner(RelationRelationId, relationOid,
13326  newOwnerId);
13327 
13328  /*
13329  * Also change the ownership of the table's row type, if it has one
13330  */
13331  if (OidIsValid(tuple_class->reltype))
13332  AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId);
13333 
13334  /*
13335  * If we are operating on a table or materialized view, also change
13336  * the ownership of any indexes and sequences that belong to the
13337  * relation, as well as its toast table (if it has one).
13338  */
13339  if (tuple_class->relkind == RELKIND_RELATION ||
13340  tuple_class->relkind == RELKIND_PARTITIONED_TABLE ||
13341  tuple_class->relkind == RELKIND_MATVIEW ||
13342  tuple_class->relkind == RELKIND_TOASTVALUE)
13343  {
13344  List *index_oid_list;
13345  ListCell *i;
13346 
13347  /* Find all the indexes belonging to this relation */
13348  index_oid_list = RelationGetIndexList(target_rel);
13349 
13350  /* For each index, recursively change its ownership */
13351  foreach(i, index_oid_list)
13352  ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
13353 
13354  list_free(index_oid_list);
13355  }
13356 
13357  /* If it has a toast table, recurse to change its ownership */
13358  if (tuple_class->reltoastrelid != InvalidOid)
13359  ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
13360  true, lockmode);
13361 
13362  /* If it has dependent sequences, recurse to change them too */
13363  change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
13364  }
13365 
13366  InvokeObjectPostAlterHook(RelationRelationId, relationOid, 0);
13367 
13368  ReleaseSysCache(tuple);
13369  table_close(class_rel, RowExclusiveLock);
13370  relation_close(target_rel, NoLock);
13371 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
int errhint(const char *fmt,...)
Definition: elog.c:1156
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
bool sequenceIsOwned(Oid seqId, char deptype, Oid *tableId, int32 *colId)
Definition: pg_depend.c:797
#define RelationGetDescr(relation)
Definition: rel.h:495
Oid GetUserId(void)
Definition: miscinit.c:478
#define DatumGetAclP(X)
Definition: acl.h:120
#define PointerGetDatum(X)
Definition: postgres.h:600
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1974
int errcode(int sqlerrcode)
Definition: elog.c:698
bool superuser(void)
Definition: superuser.c:46
void AlterTypeOwnerInternal(Oid typeOid, Oid newOwnerId)
Definition: typecmds.c:3840
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
AclResult pg_namespace_aclcheck(Oid nsp_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4761
signed int int32
Definition: c.h:429
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
Definition: pg_shdepend.c:313
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3313
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
#define ACL_CREATE
Definition: parsenodes.h:92
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
ItemPointerData t_self
Definition: htup.h:65
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:1042
#define RelationGetRelationName(relation)
Definition: rel.h:503
void check_is_member_of_role(Oid member, Oid role)
Definition: acl.c:4893
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
void ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
Definition: tablecmds.c:13142
#define WARNING
Definition: elog.h:40
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
AclResult
Definition: acl.h:177
uintptr_t Datum
Definition: postgres.h:411
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1388
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4823
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
static void change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
Definition: tablecmds.c:13445
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4570
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
static void change_owner_fix_column_acls(Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
Definition: tablecmds.c:13380
int errmsg(const char *fmt,...)
Definition: elog.c:909
void list_free(List *list)
Definition: list.c:1391
#define elog(elevel,...)
Definition: elog.h:232
int i
ObjectType get_relkind_objtype(char relkind)
#define NameStr(name)
Definition: c.h:681
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
Definition: pg_list.h:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition: acl.c:1037
#define lfirst_oid(lc)
Definition: pg_list.h:171

◆ check_of_type()

void check_of_type ( HeapTuple  typetuple)

Definition at line 6363 of file tablecmds.c.

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

6364 {
6365  Form_pg_type typ = (Form_pg_type) GETSTRUCT(typetuple);
6366  bool typeOk = false;
6367 
6368  if (typ->typtype == TYPTYPE_COMPOSITE)
6369  {
6370  Relation typeRelation;
6371 
6372  Assert(OidIsValid(typ->typrelid));
6373  typeRelation = relation_open(typ->typrelid, AccessShareLock);
6374  typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
6375 
6376  /*
6377  * Close the parent rel, but keep our AccessShareLock on it until xact
6378  * commit. That will prevent someone else from deleting or ALTERing
6379  * the type before the typed table creation/conversion commits.
6380  */
6381  relation_close(typeRelation, NoLock);
6382  }
6383  if (!typeOk)
6384  ereport(ERROR,
6385  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6386  errmsg("type %s is not a composite type",
6387  format_type_be(typ->oid))));
6388 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:698
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
Form_pg_class rd_rel
Definition: rel.h:109
#define OidIsValid(objectId)
Definition: c.h:710
#define ERROR
Definition: elog.h:46
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define NoLock
Definition: lockdefs.h:34
#define ereport(elevel,...)
Definition: elog.h:157
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define Assert(condition)
Definition: c.h:804
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ CheckRelationTableSpaceMove()

bool CheckRelationTableSpaceMove ( Relation  rel,
Oid  newTableSpaceId 
)

Definition at line 3280 of file tablecmds.c.

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

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

3281 {
3282  Oid oldTableSpaceId;
3283 
3284  /*
3285  * No work if no change in tablespace. Note that MyDatabaseTableSpace is
3286  * stored as 0.
3287  */
3288  oldTableSpaceId = rel->rd_rel->reltablespace;
3289  if (newTableSpaceId == oldTableSpaceId ||
3290  (newTableSpaceId == MyDatabaseTableSpace && oldTableSpaceId == 0))
3291  return false;
3292 
3293  /*
3294  * We cannot support moving mapped relations into different tablespaces.
3295  * (In particular this eliminates all shared catalogs.)
3296  */
3297  if (RelationIsMapped(rel))
3298  ereport(ERROR,
3299  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3300  errmsg("cannot move system relation \"%s\"",
3301  RelationGetRelationName(rel))));
3302 
3303  /* Cannot move a non-shared relation into pg_global */
3304  if (newTableSpaceId == GLOBALTABLESPACE_OID)
3305  ereport(ERROR,
3306  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3307  errmsg("only shared relations can be placed in pg_global tablespace")));
3308 
3309  /*
3310  * Do not allow moving temp tables of other backends ... their local
3311  * buffer manager is not going to cope.
3312  */
3313  if (RELATION_IS_OTHER_TEMP(rel))
3314  ereport(ERROR,
3315  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3316  errmsg("cannot move temporary tables of other sessions")));
3317 
3318  return true;
3319 }
int errcode(int sqlerrcode)
Definition: elog.c:698
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
Oid MyDatabaseTableSpace
Definition: globals.c:90
#define ERROR
Definition: elog.h:46
#define RelationGetRelationName(relation)
Definition: rel.h:503
#define RelationIsMapped(relation)
Definition: rel.h:518
#define ereport(elevel,...)
Definition: elog.h:157
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:612
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ CheckTableNotInUse()

void CheckTableNotInUse ( Relation  rel,
const char *  stmt 
)

Definition at line 3929 of file tablecmds.c.

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

3930 {
3931  int expected_refcnt;
3932 
3933  expected_refcnt = rel->rd_isnailed ? 2 : 1;
3934  if (rel->rd_refcnt != expected_refcnt)
3935  ereport(ERROR,
3936  (errcode(ERRCODE_OBJECT_IN_USE),
3937  /* translator: first %s is a SQL command, eg ALTER TABLE */
3938  errmsg("cannot %s \"%s\" because it is being used by active queries in this session",
3939  stmt, RelationGetRelationName(rel))));
3940 
3941  if (rel->rd_rel->relkind != RELKIND_INDEX &&
3942  rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
3944  ereport(ERROR,
3945  (errcode(ERRCODE_OBJECT_IN_USE),
3946  /* translator: first %s is a SQL command, eg ALTER TABLE */
3947  errmsg("cannot %s \"%s\" because it has pending trigger events",
3948  stmt, RelationGetRelationName(rel))));
3949 }
bool rd_isnailed
Definition: rel.h:61
int errcode(int sqlerrcode)
Definition: elog.c:698
Form_pg_class rd_rel
Definition: rel.h:109
#define ERROR
Definition: elog.h:46
#define RelationGetRelationName(relation)
Definition: rel.h:503
#define ereport(elevel,...)
Definition: elog.h:157
bool AfterTriggerPendingOnRel(Oid relid)
Definition: trigger.c:5376
int errmsg(const char *fmt,...)
Definition: elog.c:909
int rd_refcnt
Definition: rel.h:58
#define RelationGetRelid(relation)
Definition: rel.h:469

◆ DefineRelation()

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

Definition at line 627 of file tablecmds.c.

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

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

◆ ExecuteTruncate()

void ExecuteTruncate ( TruncateStmt stmt)

Definition at line 1619 of file tablecmds.c.

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

1620 {
1621  List *rels = NIL;
1622  List *relids = NIL;
1623  List *relids_logged = NIL;
1624  ListCell *cell;
1625 
1626  /*
1627  * Open, exclusive-lock, and check all the explicitly-specified relations
1628  */
1629  foreach(cell, stmt->relations)
1630  {
1631  RangeVar *rv = lfirst(cell);
1632  Relation rel;
1633  bool recurse = rv->inh;
1634  Oid myrelid;
1635  LOCKMODE lockmode = AccessExclusiveLock;
1636 
1637  myrelid = RangeVarGetRelidExtended(rv, lockmode,
1639  NULL);
1640 
1641  /* don't throw error for "TRUNCATE foo, foo" */
1642  if (list_member_oid(relids, myrelid))
1643  continue;
1644 
1645  /* open the relation, we already hold a lock on it */
1646  rel = table_open(myrelid, NoLock);
1647 
1648  /*
1649  * RangeVarGetRelidExtended() has done most checks with its callback,
1650  * but other checks with the now-opened Relation remain.
1651  */
1653 
1654  rels = lappend(rels, rel);
1655  relids = lappend_oid(relids, myrelid);
1656 
1657  /* Log this relation only if needed for logical decoding */
1658  if (RelationIsLogicallyLogged(rel))
1659  relids_logged = lappend_oid(relids_logged, myrelid);
1660 
1661  if (recurse)
1662  {
1663  ListCell *child;
1664  List *children;
1665 
1666  children = find_all_inheritors(myrelid, lockmode, NULL);
1667 
1668  foreach(child, children)
1669  {
1670  Oid childrelid = lfirst_oid(child);
1671 
1672  if (list_member_oid(relids, childrelid))
1673  continue;
1674 
1675  /* find_all_inheritors already got lock */
1676  rel = table_open(childrelid, NoLock);
1677 
1678  /*
1679  * It is possible that the parent table has children that are
1680  * temp tables of other backends. We cannot safely access
1681  * such tables (because of buffering issues), and the best
1682  * thing to do is to silently ignore them. Note that this
1683  * check is the same as one of the checks done in
1684  * truncate_check_activity() called below, still it is kept
1685  * here for simplicity.
1686  */
1687  if (RELATION_IS_OTHER_TEMP(rel))
1688  {
1689  table_close(rel, lockmode);
1690  continue;
1691  }
1692 
1693  /*
1694  * Inherited TRUNCATE commands perform access permission
1695  * checks on the parent table only. So we skip checking the
1696  * children's permissions and don't call
1697  * truncate_check_perms() here.
1698  */
1701 
1702  rels = lappend(rels, rel);
1703  relids = lappend_oid(relids, childrelid);
1704 
1705  /* Log this relation only if needed for logical decoding */
1706  if (RelationIsLogicallyLogged(rel))
1707  relids_logged = lappend_oid(relids_logged, childrelid);
1708  }
1709  }
1710  else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1711  ereport(ERROR,
1712  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1713  errmsg("cannot truncate only a partitioned table"),
1714  errhint("Do not specify the ONLY keyword, or use TRUNCATE ONLY on the partitions directly.")));
1715  }
1716 
1717  ExecuteTruncateGuts(rels, relids, relids_logged,
1718  stmt->behavior, stmt->restart_seqs);
1719 
1720  /* And close the rels */
1721  foreach(cell, rels)
1722  {
1723  Relation rel = (Relation) lfirst(cell);
1724 
1725  table_close(rel, NoLock);
1726  }
1727 }
#define NIL
Definition: pg_list.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
int errhint(const char *fmt,...)
Definition: elog.c:1156
int LOCKMODE
Definition: lockdefs.h:26
static void RangeVarCallbackForTruncate(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:16379
int errcode(int sqlerrcode)
Definition: elog.c:698
#define RelationIsLogicallyLogged(relation)
Definition: rel.h:655
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
DropBehavior behavior
Definition: parsenodes.h:2758
struct RelationData * Relation
Definition: relcache.h:27
#define ERROR
Definition: elog.h:46
void ExecuteTruncateGuts(List *explicit_rels, List *relids, List *relids_logged, DropBehavior behavior, bool restart_seqs)
Definition: tablecmds.c:1743
List * relations
Definition: parsenodes.h:2756
#define NoLock
Definition: lockdefs.h:34
bool restart_seqs
Definition: parsenodes.h:2757
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:236
bool inh
Definition: primnodes.h:69
List * lappend(List *list, void *datum)
Definition: list.c:336
#define ereport(elevel,...)
Definition: elog.h:157
static void truncate_check_activity(Relation rel)
Definition: tablecmds.c:2186
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:689
#define lfirst(lc)
Definition: pg_list.h:169
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:612
static void truncate_check_rel(Oid relid, Form_pg_class reltuple)
Definition: tablecmds.c:2128
#define AccessExclusiveLock
Definition: lockdefs.h:45
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:256
int errmsg(const char *fmt,...)
Definition: elog.c:909
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:469
#define lfirst_oid(lc)
Definition: pg_list.h:171

◆ ExecuteTruncateGuts()

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

Definition at line 1743 of file tablecmds.c.

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(), OnCommitItem::relid, ForeignTruncateInfo::rels, ResetSequence(), ForeignTruncateInfo::serverid, SizeOfHeapTruncate, table_close(), table_open(), truncate_check_activity(), truncate_check_perms(), truncate_check_rel(), truncate_update_partedrel_stats(), 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().

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

◆ find_composite_type_dependencies()

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

Definition at line 6196 of file tablecmds.c.

References AccessShareLock, BTEqualStrategyNumber, check_stack_depth(), DependReferenceIndexId, ereport, errcode(), errmsg(), ERROR, find_composite_type_dependencies(), 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(), find_composite_type_dependencies(), and get_rels_with_domain().

6198 {
6199  Relation depRel;
6200  ScanKeyData key[2];
6201  SysScanDesc depScan;
6202  HeapTuple depTup;
6203 
6204  /* since this function recurses, it could be driven to stack overflow */
6206 
6207  /*
6208  * We scan pg_depend to find those things that depend on the given type.
6209  * (We assume we can ignore refobjsubid for a type.)
6210  */
6211  depRel = table_open(DependRelationId, AccessShareLock);
6212 
6213  ScanKeyInit(&key[0],
6214  Anum_pg_depend_refclassid,
6215  BTEqualStrategyNumber, F_OIDEQ,
6216  ObjectIdGetDatum(TypeRelationId));
6217  ScanKeyInit(&key[1],
6218  Anum_pg_depend_refobjid,
6219  BTEqualStrategyNumber, F_OIDEQ,
6220  ObjectIdGetDatum(typeOid));
6221 
6222  depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
6223  NULL, 2, key);
6224 
6225  while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
6226  {
6227  Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
6228  Relation rel;
6229  Form_pg_attribute att;
6230 
6231  /* Check for directly dependent types */
6232  if (pg_depend->classid == TypeRelationId)
6233  {
6234  /*
6235  * This must be an array, domain, or range containing the given
6236  * type, so recursively check for uses of this type. Note that
6237  * any error message will mention the original type not the
6238  * container; this is intentional.
6239  */
6240  find_composite_type_dependencies(pg_depend->objid,
6241  origRelation, origTypeName);
6242  continue;
6243  }
6244 
6245  /* Else, ignore dependees that aren't user columns of relations */
6246  /* (we assume system columns are never of interesting types) */
6247  if (pg_depend->classid != RelationRelationId ||
6248  pg_depend->objsubid <= 0)
6249  continue;
6250 
6251  rel = relation_open(pg_depend->objid, AccessShareLock);
6252  att = TupleDescAttr(rel->rd_att, pg_depend->objsubid - 1);
6253 
6254  if (rel->rd_rel->relkind == RELKIND_RELATION ||
6255  rel->rd_rel->relkind == RELKIND_MATVIEW ||
6256  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
6257  {
6258  if (origTypeName)
6259  ereport(ERROR,
6260  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6261  errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
6262  origTypeName,
6264  NameStr(att->attname))));
6265  else if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
6266  ereport(ERROR,
6267  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6268  errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
6269  RelationGetRelationName(origRelation),
6271  NameStr(att->attname))));
6272  else if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
6273  ereport(ERROR,
6274  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6275  errmsg("cannot alter foreign table \"%s\" because column \"%s.%s\" uses its row type",
6276  RelationGetRelationName(origRelation),
6278  NameStr(att->attname))));
6279  else
6280  ereport(ERROR,
6281  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6282  errmsg("cannot alter table \"%s\" because column \"%s.%s\" uses its row type",
6283  RelationGetRelationName(origRelation),
6285  NameStr(att->attname))));
6286  }
6287  else if (OidIsValid(rel->rd_rel->reltype))
6288  {
6289  /*
6290  * A view or composite type itself isn't a problem, but we must
6291  * recursively check for indirect dependencies via its rowtype.
6292  */
6294  origRelation, origTypeName);
6295  }
6296 
6298  }
6299 
6300  systable_endscan(depScan);
6301 
6303 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:595
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
void find_composite_type_dependencies(Oid typeOid, Relation origRelation, const char *origTypeName)
Definition: tablecmds.c:6196
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:698
Form_pg_class rd_rel
Definition: rel.h:109
#define OidIsValid(objectId)
Definition: c.h:710
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:383
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:502
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
void check_stack_depth(void)
Definition: postgres.c:3469
#define RelationGetRelationName(relation)
Definition: rel.h:503
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:203
FormData_pg_depend * Form_pg_depend
Definition: pg_depend.h:73
#define DependReferenceIndexId
Definition: pg_depend.h:78
TupleDesc rd_att
Definition: rel.h:110
#define ereport(elevel,...)
Definition: elog.h:157
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define NameStr(name)
Definition: c.h:681
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ PartConstraintImpliedByRelConstraint()

bool PartConstraintImpliedByRelConstraint ( Relation  scanrel,
List partConstraint 
)

Definition at line 16890 of file tablecmds.c.

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

16892 {
16893  List *existConstraint = NIL;
16894  TupleConstr *constr = RelationGetDescr(scanrel)->constr;
16895  int i;
16896 
16897  if (constr && constr->has_not_null)
16898  {
16899  int natts = scanrel->rd_att->natts;
16900 
16901  for (i = 1; i <= natts; i++)
16902  {
16903  Form_pg_attribute att = TupleDescAttr(scanrel->rd_att, i - 1);
16904 
16905  if (att->attnotnull && !att->attisdropped)
16906  {
16907  NullTest *ntest = makeNode(NullTest);
16908 
16909  ntest->arg = (Expr *) makeVar(1,
16910  i,
16911  att->atttypid,
16912  att->atttypmod,
16913  att->attcollation,
16914  0);
16915  ntest->nulltesttype = IS_NOT_NULL;
16916 
16917  /*
16918  * argisrow=false is correct even for a composite column,
16919  * because attnotnull does not represent a SQL-spec IS NOT
16920  * NULL test in such a case, just IS DISTINCT FROM NULL.
16921  */
16922  ntest->argisrow = false;
16923  ntest->location = -1;
16924  existConstraint = lappend(existConstraint, ntest);
16925  }
16926  }
16927  }
16928 
16929  return ConstraintImpliedByRelConstraint(scanrel, partConstraint, existConstraint);
16930 }
#define NIL
Definition: pg_list.h:65
#define RelationGetDescr(relation)
Definition: rel.h:495
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
Expr * arg
Definition: primnodes.h:1255
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:203
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
List * lappend(List *list, void *datum)
Definition: list.c:336
TupleDesc rd_att
Definition: rel.h:110
NullTestType nulltesttype
Definition: primnodes.h:1256
#define makeNode(_type_)
Definition: nodes.h:587
static bool ConstraintImpliedByRelConstraint(Relation scanrel, List *testConstraint, List *provenConstraint)
Definition: tablecmds.c:16943
int location
Definition: primnodes.h:1258
int i
bool argisrow
Definition: primnodes.h:1257
bool has_not_null
Definition: tupdesc.h:44
Definition: pg_list.h:50

◆ PreCommit_on_commit_actions()

void PreCommit_on_commit_actions ( void  )

Definition at line 16180 of file tablecmds.c.

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

16181 {
16182  ListCell *l;
16183  List *oids_to_truncate = NIL;
16184  List *oids_to_drop = NIL;
16185 
16186  foreach(l, on_commits)
16187  {
16188  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
16189 
16190  /* Ignore entry if already dropped in this xact */
16192  continue;
16193 
16194  switch (oc->oncommit)
16195  {
16196  case ONCOMMIT_NOOP:
16198  /* Do nothing (there shouldn't be such entries, actually) */
16199  break;
16200  case ONCOMMIT_DELETE_ROWS:
16201 
16202  /*
16203  * If this transaction hasn't accessed any temporary
16204  * relations, we can skip truncating ON COMMIT DELETE ROWS
16205  * tables, as they must still be empty.
16206  */
16208  oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
16209  break;
16210  case ONCOMMIT_DROP:
16211  oids_to_drop = lappend_oid(oids_to_drop, oc->relid);
16212  break;
16213  }
16214  }
16215 
16216  /*
16217  * Truncate relations before dropping so that all dependencies between
16218  * relations are removed after they are worked on. Doing it like this
16219  * might be a waste as it is possible that a relation being truncated will
16220  * be dropped anyway due to its parent being dropped, but this makes the
16221  * code more robust because of not having to re-check that the relation
16222  * exists at truncation time.
16223  */
16224  if (oids_to_truncate != NIL)
16225  heap_truncate(oids_to_truncate);
16226 
16227  if (oids_to_drop != NIL)
16228  {
16229  ObjectAddresses *targetObjects = new_object_addresses();
16230  ListCell *l;
16231 
16232  foreach(l, oids_to_drop)
16233  {
16234  ObjectAddress object;
16235 
16236  object.classId = RelationRelationId;
16237  object.objectId = lfirst_oid(l);
16238  object.objectSubId = 0;
16239 
16240  Assert(!object_address_present(&object, targetObjects));
16241 
16242  add_exact_object_address(&object, targetObjects);
16243  }
16244 
16245  /*
16246  * Since this is an automatic drop, rather than one directly initiated
16247  * by the user, we pass the PERFORM_DELETION_INTERNAL flag.
16248  */
16249  performMultipleDeletions(targetObjects, DROP_CASCADE,
16251 
16252 #ifdef USE_ASSERT_CHECKING
16253 
16254  /*
16255  * Note that table deletion will call remove_on_commit_action, so the
16256  * entry should get marked as deleted.
16257  */
16258  foreach(l, on_commits)
16259  {
16260  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
16261 
16262  if (oc->oncommit != ONCOMMIT_DROP)
16263  continue;
16264 
16266  }
16267 #endif
16268  }
16269 }
#define NIL
Definition: pg_list.h:65
OnCommitAction oncommit
Definition: tablecmds.c:110
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2552
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2492
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2437
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
static List * on_commits
Definition: tablecmds.c:123
int MyXactFlags
Definition: xact.c:132
#define XACT_FLAGS_ACCESSEDTEMPNAMESPACE
Definition: xact.h:102
SubTransactionId deleting_subid
Definition: tablecmds.c:120
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
#define PERFORM_DELETION_QUIETLY
Definition: dependency.h:143
void heap_truncate(List *relids)
Definition: heap.c:3312
#define InvalidSubTransactionId
Definition: c.h:593
void performMultipleDeletions(const ObjectAddresses *objects, DropBehavior behavior, int flags)
Definition: dependency.c:371
Definition: pg_list.h:50
#define lfirst_oid(lc)
Definition: pg_list.h:171
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:141

◆ RangeVarCallbackOwnsRelation()

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

Definition at line 16403 of file tablecmds.c.

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

16405 {
16406  HeapTuple tuple;
16407 
16408  /* Nothing to do if the relation was not found. */
16409  if (!OidIsValid(relId))
16410  return;
16411 
16412  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
16413  if (!HeapTupleIsValid(tuple)) /* should not happen */
16414  elog(ERROR, "cache lookup failed for relation %u", relId);
16415 
16416  if (!pg_class_ownercheck(relId, GetUserId()))
16418  relation->relname);
16419 
16420  if (!allowSystemTableMods &&
16421  IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
16422  ereport(ERROR,
16423  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
16424  errmsg("permission denied: \"%s\" is a system catalog",
16425  relation->relname)));
16426 
16427  ReleaseSysCache(tuple);
16428 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
Oid GetUserId(void)
Definition: miscinit.c:478
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1974
int errcode(int sqlerrcode)
Definition: elog.c:698
#define OidIsValid(objectId)
Definition: c.h:710
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
Definition: catalog.c:85
char * relname
Definition: primnodes.h:68
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3313
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
bool allowSystemTableMods
Definition: globals.c:123
#define ereport(elevel,...)
Definition: elog.h:157
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4823
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
ObjectType get_relkind_objtype(char relkind)

◆ RangeVarCallbackOwnsTable()

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

Definition at line 16347 of file tablecmds.c.

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

16349 {
16350  char relkind;
16351 
16352  /* Nothing to do if the relation was not found. */
16353  if (!OidIsValid(relId))
16354  return;
16355 
16356  /*
16357  * If the relation does exist, check whether it's an index. But note that
16358  * the relation might have been dropped between the time we did the name
16359  * lookup and now. In that case, there's nothing to do.
16360  */
16361  relkind = get_rel_relkind(relId);
16362  if (!relkind)
16363  return;
16364  if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
16365  relkind != RELKIND_MATVIEW && relkind != RELKIND_PARTITIONED_TABLE)
16366  ereport(ERROR,
16367  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16368  errmsg("\"%s\" is not a table or materialized view", relation->relname)));
16369 
16370  /* Check permissions */
16371  if (!pg_class_ownercheck(relId, GetUserId()))
16373 }
Oid GetUserId(void)
Definition: miscinit.c:478
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1974
int errcode(int sqlerrcode)
Definition: elog.c:698
#define OidIsValid(objectId)
Definition: c.h:710
char * relname
Definition: primnodes.h:68
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3313
#define ERROR
Definition: elog.h:46
#define ereport(elevel,...)
Definition: elog.h:157
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4823
int errmsg(const char *fmt,...)
Definition: elog.c:909
ObjectType get_relkind_objtype(char relkind)

◆ register_on_commit_action()

void register_on_commit_action ( Oid  relid,
OnCommitAction  action 
)

Definition at line 16121 of file tablecmds.c.

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

Referenced by heap_create_with_catalog().

16122 {
16123  OnCommitItem *oc;
16124  MemoryContext oldcxt;
16125 
16126  /*
16127  * We needn't bother registering the relation unless there is an ON COMMIT
16128  * action we need to take.
16129  */
16131  return;
16132 
16134 
16135  oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
16136  oc->relid = relid;
16137  oc->oncommit = action;
16140 
16141  /*
16142  * We use lcons() here so that ON COMMIT actions are processed in reverse
16143  * order of registration. That might not be essential but it seems
16144  * reasonable.
16145  */
16146  on_commits = lcons(oc, on_commits);
16147 
16148  MemoryContextSwitchTo(oldcxt);
16149 }
OnCommitAction oncommit
Definition: tablecmds.c:110
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
SubTransactionId creating_subid
Definition: tablecmds.c:119
static List * on_commits
Definition: tablecmds.c:123
SubTransactionId deleting_subid
Definition: tablecmds.c:120
List * lcons(void *datum, List *list)
Definition: list.c:468
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:723
#define InvalidSubTransactionId
Definition: c.h:593
void * palloc(Size size)
Definition: mcxt.c:1062
MemoryContext CacheMemoryContext
Definition: mcxt.c:51

◆ remove_on_commit_action()

void remove_on_commit_action ( Oid  relid)

Definition at line 16157 of file tablecmds.c.

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

Referenced by heap_drop_with_catalog().

16158 {
16159  ListCell *l;
16160 
16161  foreach(l, on_commits)
16162  {
16163  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
16164 
16165  if (oc->relid == relid)
16166  {
16168  break;
16169  }
16170  }
16171 }
static List * on_commits
Definition: tablecmds.c:123
SubTransactionId deleting_subid
Definition: tablecmds.c:120
#define lfirst(lc)
Definition: pg_list.h:169
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:723

◆ RemoveRelations()

void RemoveRelations ( DropStmt drop)

Definition at line 1315 of file tablecmds.c.

References AcceptInvalidationMessages(), AccessExclusiveLock, add_exact_object_address(), Assert, DropStmt::behavior, ObjectAddress::classId, DropRelationCallbackState::concurrent, DropStmt::concurrent, DROP_CASCADE, DropErrorMsgNonExistent(), elog, ereport, errcode(), errmsg(), ERROR, free_object_addresses(), get_rel_persistence(), get_rel_relkind(), DropRelationCallbackState::heapOid, 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, DropRelationCallbackState::partParentOid, PERFORM_DELETION_CONCURRENTLY, performMultipleDeletions(), RangeVarCallbackForDropRelation(), RangeVarGetRelidExtended(), DropRelationCallbackState::relkind, RangeVar::relname, DropStmt::removeType, RVR_MISSING_OK, and ShareUpdateExclusiveLock.

Referenced by ExecDropStmt().

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

◆ renameatt()

ObjectAddress renameatt ( RenameStmt stmt)

Definition at line 3592 of file tablecmds.c.

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

Referenced by ExecRenameStmt().

3593 {
3594  Oid relid;
3596  ObjectAddress address;
3597 
3598  /* lock level taken here should match renameatt_internal */
3600  stmt->missing_ok ? RVR_MISSING_OK : 0,
3602  NULL);
3603 
3604  if (!OidIsValid(relid))
3605  {
3606  ereport(NOTICE,
3607  (errmsg("relation \"%s\" does not exist, skipping",
3608  stmt->relation->relname)));
3609  return InvalidObjectAddress;
3610  }
3611 
3612  attnum =
3613  renameatt_internal(relid,
3614  stmt->subname, /* old att name */
3615  stmt->newname, /* new att name */
3616  stmt->relation->inh, /* recursive? */
3617  false, /* recursing? */
3618  0, /* expected inhcount */
3619  stmt->behavior);
3620 
3621  ObjectAddressSubSet(address, RelationRelationId, relid, attnum);
3622 
3623  return address;
3624 }
char * subname
Definition: parsenodes.h:3027
char * newname
Definition: parsenodes.h:3029
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
char * relname
Definition: primnodes.h:68
bool missing_ok
Definition: parsenodes.h:3031
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:236
bool inh
Definition: primnodes.h:69
RangeVar * relation
Definition: parsenodes.h:3025
int16 attnum
Definition: pg_attribute.h:83
#define ereport(elevel,...)
Definition: elog.h:157
#define NOTICE
Definition: elog.h:37
static void RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:3572
static AttrNumber renameatt_internal(Oid myrelid, const char *oldattname, const char *newattname, bool recurse, bool recursing, int expected_parents, DropBehavior behavior)
Definition: tablecmds.c:3427
#define ObjectAddressSubSet(addr, class_id, object_id, object_sub_id)
Definition: objectaddress.h:33
#define AccessExclusiveLock
Definition: lockdefs.h:45
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:909
DropBehavior behavior
Definition: parsenodes.h:3030
int16 AttrNumber
Definition: attnum.h:21

◆ RenameConstraint()

ObjectAddress RenameConstraint ( RenameStmt stmt)

Definition at line 3736 of file tablecmds.c.

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(), OnCommitItem::relid, RangeVar::relname, rename_constraint_internal(), RenameStmt::renameType, RowExclusiveLock, RVR_MISSING_OK, SearchSysCache1(), RenameStmt::subname, table_close(), table_open(), typenameTypeId(), and TYPEOID.

Referenced by ExecRenameStmt().

3737 {
3738  Oid relid = InvalidOid;
3739  Oid typid = InvalidOid;
3740 
3741  if (stmt->renameType == OBJECT_DOMCONSTRAINT)
3742  {
3743  Relation rel;
3744  HeapTuple tup;
3745 
3747  rel = table_open(TypeRelationId, RowExclusiveLock);
3748  tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
3749  if (!HeapTupleIsValid(tup))
3750  elog(ERROR, "cache lookup failed for type %u", typid);
3751  checkDomainOwner(tup);
3752  ReleaseSysCache(tup);
3753  table_close(rel, NoLock);
3754  }
3755  else
3756  {
3757  /* lock level taken here should match rename_constraint_internal */
3759  stmt->missing_ok ? RVR_MISSING_OK : 0,
3761  NULL);
3762  if (!OidIsValid(relid))
3763  {
3764  ereport(NOTICE,
3765  (errmsg("relation \"%s\" does not exist, skipping",
3766  stmt->relation->relname)));
3767  return InvalidObjectAddress;
3768  }
3769  }
3770 
3771  return
3772  rename_constraint_internal(relid, typid,
3773  stmt->subname,
3774  stmt->newname,
3775  (stmt->relation &&
3776  stmt->relation->inh), /* recursive? */
3777  false, /* recursing? */
3778  0 /* expected inhcount */ );
3779 
3780 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
char * subname
Definition: parsenodes.h:3027
ObjectType renameType
Definition: parsenodes.h:3023
#define castNode(_type_, nodeptr)
Definition: nodes.h:608
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:3630
char * newname
Definition: parsenodes.h:3029
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
char * relname
Definition: primnodes.h:68
bool missing_ok
Definition: parsenodes.h:3031
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
Node * object
Definition: parsenodes.h:3026
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:236
bool inh
Definition: primnodes.h:69
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
RangeVar * relation
Definition: parsenodes.h:3025
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
#define NOTICE
Definition: elog.h:37
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static void RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:3572
void checkDomainOwner(HeapTuple tup)
Definition: typecmds.c:3440
#define AccessExclusiveLock
Definition: lockdefs.h:45
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
TypeName * makeTypeNameFromNameList(List *names)
Definition: makefuncs.c:456
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:291

◆ RenameRelation()

ObjectAddress RenameRelation ( RenameStmt stmt)

Definition at line 3787 of file tablecmds.c.

References AccessExclusiveLock, ereport, errmsg(), InvalidObjectAddress, RenameStmt::missing_ok, NOTICE, OBJECT_INDEX, ObjectAddressSet, OidIsValid, RangeVarCallbackForAlterRelation(), RangeVarGetRelidExtended(), RenameStmt::relation, OnCommitItem::relid, RenameRelationInternal(), RenameStmt::renameType, RVR_MISSING_OK, and ShareUpdateExclusiveLock.

Referenced by ExecRenameStmt().

3788 {
3789  bool is_index = stmt->renameType == OBJECT_INDEX;
3790  Oid relid;
3791  ObjectAddress address;
3792 
3793  /*
3794  * Grab an exclusive lock on the target table, index, sequence, view,
3795  * materialized view, or foreign table, which we will NOT release until
3796  * end of transaction.
3797  *
3798  * Lock level used here should match RenameRelationInternal, to avoid lock
3799  * escalation.
3800  */
3801  relid = RangeVarGetRelidExtended(stmt->relation,
3803  stmt->missing_ok ? RVR_MISSING_OK : 0,
3805  (void *) stmt);
3806 
3807  if (!OidIsValid(relid))
3808  {
3809  ereport(NOTICE,
3810  (errmsg("relation \"%s\" does not exist, skipping",
3811  stmt->relation->relname)));
3812  return InvalidObjectAddress;
3813  }
3814 
3815  /* Do the work */
3816  RenameRelationInternal(relid, stmt->newname, false, is_index);
3817 
3818  ObjectAddressSet(address, RelationRelationId, relid);
3819 
3820  return address;
3821 }
ObjectType renameType
Definition: parsenodes.h:3023
char * newname
Definition: parsenodes.h:3029
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
char * relname
Definition: primnodes.h:68
bool missing_ok
Definition: parsenodes.h:3031
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:16435
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:236
RangeVar * relation
Definition: parsenodes.h:3025
#define ereport(elevel,...)
Definition: elog.h:157
#define NOTICE
Definition: elog.h:37
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define AccessExclusiveLock
Definition: lockdefs.h:45
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:909
void RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
Definition: tablecmds.c:3827

◆ RenameRelationInternal()

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

Definition at line 3827 of file tablecmds.c.

References AccessExclusiveLock, 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().

3828 {
3829  Relation targetrelation;
3830  Relation relrelation; /* for RELATION relation */
3831  HeapTuple reltup;
3832  Form_pg_class relform;
3833  Oid namespaceId;
3834 
3835  /*
3836  * Grab a lock on the target relation, which we will NOT release until end
3837  * of transaction. We need at least a self-exclusive lock so that
3838  * concurrent DDL doesn't overwrite the rename if they start updating
3839  * while still seeing the old version. The lock also guards against
3840  * triggering relcache reloads in concurrent sessions, which might not
3841  * handle this information changing under them. For indexes, we can use a
3842  * reduced lock level because RelationReloadIndexInfo() handles indexes
3843  * specially.
3844  */
3845  targetrelation = relation_open(myrelid, is_index ? ShareUpdateExclusiveLock : AccessExclusiveLock);
3846  namespaceId = RelationGetNamespace(targetrelation);
3847 
3848  /*
3849  * Find relation's pg_class tuple, and make sure newrelname isn't in use.
3850  */
3851  relrelation = table_open(RelationRelationId, RowExclusiveLock);
3852 
3853  reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
3854  if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
3855  elog(ERROR, "cache lookup failed for relation %u", myrelid);
3856  relform = (Form_pg_class) GETSTRUCT(reltup);
3857 
3858  if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
3859  ereport(ERROR,
3860  (errcode(ERRCODE_DUPLICATE_TABLE),
3861  errmsg("relation \"%s\" already exists",
3862  newrelname)));
3863 
3864  /*
3865  * Update pg_class tuple with new relname. (Scribbling on reltup is OK
3866  * because it's a copy...)
3867  */
3868  namestrcpy(&(relform->relname), newrelname);
3869 
3870  CatalogTupleUpdate(relrelation, &reltup->t_self, reltup);
3871 
3872  InvokeObjectPostAlterHookArg(RelationRelationId, myrelid, 0,
3873  InvalidOid, is_internal);
3874 
3875  heap_freetuple(reltup);
3876  table_close(relrelation, RowExclusiveLock);
3877 
3878  /*
3879  * Also rename the associated type, if any.
3880  */
3881  if (OidIsValid(targetrelation->rd_rel->reltype))
3882  RenameTypeInternal(targetrelation->rd_rel->reltype,
3883  newrelname, namespaceId);
3884 
3885  /*
3886  * Also rename the associated constraint, if any.
3887  */
3888  if (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
3889  targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
3890  {
3891  Oid constraintId = get_index_constraint(myrelid);
3892 
3893  if (OidIsValid(constraintId))
3894  RenameConstraintById(constraintId, newrelname);
3895  }
3896 
3897  /*
3898  * Close rel, but keep lock!
3899  */
3900  relation_close(targetrelation, NoLock);
3901 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
void namestrcpy(Name name, const char *str)
Definition: name.c:233
int errcode(int sqlerrcode)
Definition: elog.c:698
Form_pg_class rd_rel
Definition: rel.h:109
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
#define InvokeObjectPostAlterHookArg(classId, objectId, subId, auxiliaryId, is_internal)
Definition: objectaccess.h:178
void RenameConstraintById(Oid conId, const char *newname)
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
ItemPointerData t_self
Definition: htup.h:65
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1856
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:938
void RenameTypeInternal(Oid typeOid, const char *newTypeName, Oid typeNamespace)
Definition: pg_type.c:733
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:175
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define RelationGetNamespace(relation)
Definition: rel.h:510

◆ SetRelationHasSubclass()

void SetRelationHasSubclass ( Oid  relationId,
bool  relhassubclass 
)

Definition at line 3239 of file tablecmds.c.

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

3240 {
3241  Relation relationRelation;
3242  HeapTuple tuple;
3243  Form_pg_class classtuple;
3244 
3245  /*
3246  * Fetch a modifiable copy of the tuple, modify it, update pg_class.
3247  */
3248  relationRelation = table_open(RelationRelationId, RowExclusiveLock);
3249  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
3250  if (!HeapTupleIsValid(tuple))
3251  elog(ERROR, "cache lookup failed for relation %u", relationId);
3252  classtuple = (Form_pg_class) GETSTRUCT(tuple);
3253 
3254  if (classtuple->relhassubclass != relhassubclass)
3255  {
3256  classtuple->relhassubclass = relhassubclass;
3257  CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
3258  }
3259  else
3260  {
3261  /* no need to change tuple, but force relcache rebuild anyway */
3263  }
3264 
3265  heap_freetuple(tuple);
3266  table_close(relationRelation, RowExclusiveLock);
3267 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:175
#define elog(elevel,...)
Definition: elog.h:232
void CacheInvalidateRelcacheByTuple(HeapTuple classTuple)
Definition: inval.c:1315
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

◆ SetRelationTableSpace()

void SetRelationTableSpace ( Relation  rel,
Oid  newTableSpaceId,
Oid  newRelFileNode 
)

Definition at line 3337 of file tablecmds.c.

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

3340 {
3341  Relation pg_class;
3342  HeapTuple tuple;
3343  Form_pg_class rd_rel;
3344  Oid reloid = RelationGetRelid(rel);
3345 
3346  Assert(CheckRelationTableSpaceMove(rel, newTableSpaceId));
3347 
3348  /* Get a modifiable copy of the relation's pg_class row. */
3349  pg_class = table_open(RelationRelationId, RowExclusiveLock);
3350 
3351  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(reloid));
3352  if (!HeapTupleIsValid(tuple))
3353  elog(ERROR, "cache lookup failed for relation %u", reloid);
3354  rd_rel = (Form_pg_class) GETSTRUCT(tuple);
3355 
3356  /* Update the pg_class row. */
3357  rd_rel->reltablespace = (newTableSpaceId == MyDatabaseTableSpace) ?
3358  InvalidOid : newTableSpaceId;
3359  if (OidIsValid(newRelFileNode))
3360  rd_rel->relfilenode = newRelFileNode;
3361  CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
3362 
3363  /*
3364  * Record dependency on tablespace. This is only required for relations
3365  * that have no physical storage.
3366  */
3367  if (!RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
3368  changeDependencyOnTablespace(RelationRelationId, reloid,
3369  rd_rel->reltablespace);
3370 
3371  heap_freetuple(tuple);
3372  table_close(pg_class, RowExclusiveLock);
3373 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
Form_pg_class rd_rel
Definition: rel.h:109
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
Oid MyDatabaseTableSpace
Definition: globals.c:90
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
ItemPointerData t_self
Definition: htup.h:65
bool CheckRelationTableSpaceMove(Relation rel, Oid newTableSpaceId)
Definition: tablecmds.c:3280
#define RowExclusiveLock
Definition: lockdefs.h:38
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
void changeDependencyOnTablespace(Oid classId, Oid objectId, Oid newTablespaceId)
Definition: pg_shdepend.c:382
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:175
#define elog(elevel,...)
Definition: elog.h:232
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define RelationGetRelid(relation)
Definition: rel.h:469