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

16042 {
16043  HeapTuple classTup;
16044  Form_pg_class classForm;
16045  ObjectAddress thisobj;
16046  bool already_done = false;
16047 
16048  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
16049  if (!HeapTupleIsValid(classTup))
16050  elog(ERROR, "cache lookup failed for relation %u", relOid);
16051  classForm = (Form_pg_class) GETSTRUCT(classTup);
16052 
16053  Assert(classForm->relnamespace == oldNspOid);
16054 
16055  thisobj.classId = RelationRelationId;
16056  thisobj.objectId = relOid;
16057  thisobj.objectSubId = 0;
16058 
16059  /*
16060  * If the object has already been moved, don't move it again. If it's
16061  * already in the right place, don't move it, but still fire the object
16062  * access hook.
16063  */
16064  already_done = object_address_present(&thisobj, objsMoved);
16065  if (!already_done && oldNspOid != newNspOid)
16066  {
16067  /* check for duplicate name (more friendly than unique-index failure) */
16068  if (get_relname_relid(NameStr(classForm->relname),
16069  newNspOid) != InvalidOid)
16070  ereport(ERROR,
16071  (errcode(ERRCODE_DUPLICATE_TABLE),
16072  errmsg("relation \"%s\" already exists in schema \"%s\"",
16073  NameStr(classForm->relname),
16074  get_namespace_name(newNspOid))));
16075 
16076  /* classTup is a copy, so OK to scribble on */
16077  classForm->relnamespace = newNspOid;
16078 
16079  CatalogTupleUpdate(classRel, &classTup->t_self, classTup);
16080 
16081  /* Update dependency on schema if caller said so */
16082  if (hasDependEntry &&
16083  changeDependencyFor(RelationRelationId,
16084  relOid,
16085  NamespaceRelationId,
16086  oldNspOid,
16087  newNspOid) != 1)
16088  elog(ERROR, "failed to change schema dependency for relation \"%s\"",
16089  NameStr(classForm->relname));
16090  }
16091  if (!already_done)
16092  {
16093  add_exact_object_address(&thisobj, objsMoved);
16094 
16095  InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
16096  }
16097 
16098  heap_freetuple(classTup);
16099 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2542
int errcode(int sqlerrcode)
Definition: elog.c:698
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2482
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:392
#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 4007 of file tablecmds.c.

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

Referenced by ProcessUtilitySlow().

4009 {
4010  Relation rel;
4011 
4012  /* Caller is required to provide an adequate lock. */
4013  rel = relation_open(context->relid, NoLock);
4014 
4015  CheckTableNotInUse(rel, "ALTER TABLE");
4016 
4017  ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
4018 }
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:4352
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:3923
bool inh
Definition: primnodes.h:69
RangeVar * relation
Definition: parsenodes.h:1859

◆ AlterTableGetLockLevel()

LOCKMODE AlterTableGetLockLevel ( List cmds)

Definition at line 4081 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_SetAccessMethod, AT_SetCompression, AT_SetIdentity, AT_SetLogged, AT_SetNotNull, AT_SetOptions, AT_SetRelOptions, AT_SetStatistics, AT_SetStorage, AT_SetTableSpace, AT_SetUnLogged, AT_ValidateConstraint, CONSTR_EXCLUSION, CONSTR_FOREIGN, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, AlterTableCmd::def, elog, ERROR, IsA, lfirst, ShareRowExclusiveLock, ShareUpdateExclusiveLock, and AlterTableCmd::subtype.

Referenced by AlterTableInternal(), and ProcessUtilitySlow().

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

◆ AlterTableInternal()

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

Definition at line 4036 of file tablecmds.c.

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

Referenced by AlterTableMoveAll(), and DefineVirtualRelation().

4037 {
4038  Relation rel;
4039  LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
4040 
4041  rel = relation_open(relid, lockmode);
4042 
4044 
4045  ATController(NULL, rel, cmds, recurse, lockmode, NULL);
4046 }
int LOCKMODE
Definition: lockdefs.h:26
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:4352
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
LOCKMODE AlterTableGetLockLevel(List *cmds)
Definition: tablecmds.c:4081
void EventTriggerAlterTableRelid(Oid objectId)

◆ AlterTableLookupRelation()

Oid AlterTableLookupRelation ( AlterTableStmt stmt,
LOCKMODE  lockmode 
)

Definition at line 3951 of file tablecmds.c.

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

Referenced by ProcessUtilitySlow().

3952 {
3953  return RangeVarGetRelidExtended(stmt->relation, lockmode,
3954  stmt->missing_ok ? RVR_MISSING_OK : 0,
3956  (void *) stmt);
3957 }
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:16552
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:237
RangeVar * relation
Definition: parsenodes.h:1859

◆ AlterTableMoveAll()

Oid AlterTableMoveAll ( AlterTableMoveAllStmt stmt)

Definition at line 14043 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().

14044 {
14045  List *relations = NIL;
14046  ListCell *l;
14047  ScanKeyData key[1];
14048  Relation rel;
14049  TableScanDesc scan;
14050  HeapTuple tuple;
14051  Oid orig_tablespaceoid;
14052  Oid new_tablespaceoid;
14053  List *role_oids = roleSpecsToIds(stmt->roles);
14054 
14055  /* Ensure we were not asked to move something we can't */
14056  if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
14057  stmt->objtype != OBJECT_MATVIEW)
14058  ereport(ERROR,
14059  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
14060  errmsg("only tables, indexes, and materialized views exist in tablespaces")));
14061 
14062  /* Get the orig and new tablespace OIDs */
14063  orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
14064  new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
14065 
14066  /* Can't move shared relations in to or out of pg_global */
14067  /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
14068  if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
14069  new_tablespaceoid == GLOBALTABLESPACE_OID)
14070  ereport(ERROR,
14071  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
14072  errmsg("cannot move relations in to or out of pg_global tablespace")));
14073 
14074  /*
14075  * Must have CREATE rights on the new tablespace, unless it is the
14076  * database default tablespace (which all users implicitly have CREATE
14077  * rights on).
14078  */
14079  if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
14080  {
14081  AclResult aclresult;
14082 
14083  aclresult = pg_tablespace_aclcheck(new_tablespaceoid, GetUserId(),
14084  ACL_CREATE);
14085  if (aclresult != ACLCHECK_OK)
14086  aclcheck_error(aclresult, OBJECT_TABLESPACE,
14087  get_tablespace_name(new_tablespaceoid));
14088  }
14089 
14090  /*
14091  * Now that the checks are done, check if we should set either to
14092  * InvalidOid because it is our database's default tablespace.
14093  */
14094  if (orig_tablespaceoid == MyDatabaseTableSpace)
14095  orig_tablespaceoid = InvalidOid;
14096 
14097  if (new_tablespaceoid == MyDatabaseTableSpace)
14098  new_tablespaceoid = InvalidOid;
14099 
14100  /* no-op */
14101  if (orig_tablespaceoid == new_tablespaceoid)
14102  return new_tablespaceoid;
14103 
14104  /*
14105  * Walk the list of objects in the tablespace and move them. This will
14106  * only find objects in our database, of course.
14107  */
14108  ScanKeyInit(&key[0],
14109  Anum_pg_class_reltablespace,
14110  BTEqualStrategyNumber, F_OIDEQ,
14111  ObjectIdGetDatum(orig_tablespaceoid));
14112 
14113  rel = table_open(RelationRelationId, AccessShareLock);
14114  scan = table_beginscan_catalog(rel, 1, key);
14115  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
14116  {
14117  Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
14118  Oid relOid = relForm->oid;
14119 
14120  /*
14121  * Do not move objects in pg_catalog as part of this, if an admin
14122  * really wishes to do so, they can issue the individual ALTER
14123  * commands directly.
14124  *
14125  * Also, explicitly avoid any shared tables, temp tables, or TOAST
14126  * (TOAST will be moved with the main table).
14127  */
14128  if (IsCatalogNamespace(relForm->relnamespace) ||
14129  relForm->relisshared ||
14130  isAnyTempNamespace(relForm->relnamespace) ||
14131  IsToastNamespace(relForm->relnamespace))
14132  continue;
14133 
14134  /* Only move the object type requested */
14135  if ((stmt->objtype == OBJECT_TABLE &&
14136  relForm->relkind != RELKIND_RELATION &&
14137  relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
14138  (stmt->objtype == OBJECT_INDEX &&
14139  relForm->relkind != RELKIND_INDEX &&
14140  relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
14141  (stmt->objtype == OBJECT_MATVIEW &&
14142  relForm->relkind != RELKIND_MATVIEW))
14143  continue;
14144 
14145  /* Check if we are only moving objects owned by certain roles */
14146  if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
14147  continue;
14148 
14149  /*
14150  * Handle permissions-checking here since we are locking the tables
14151  * and also to avoid doing a bunch of work only to fail part-way. Note
14152  * that permissions will also be checked by AlterTableInternal().
14153  *
14154  * Caller must be considered an owner on the table to move it.
14155  */
14156  if (!pg_class_ownercheck(relOid, GetUserId()))
14158  NameStr(relForm->relname));
14159 
14160  if (stmt->nowait &&
14162  ereport(ERROR,
14163  (errcode(ERRCODE_OBJECT_IN_USE),
14164  errmsg("aborting because lock on relation \"%s.%s\" is not available",
14165  get_namespace_name(relForm->relnamespace),
14166  NameStr(relForm->relname))));
14167  else
14169 
14170  /* Add to our list of objects to move */
14171  relations = lappend_oid(relations, relOid);
14172  }
14173 
14174  table_endscan(scan);
14176 
14177  if (relations == NIL)
14178  ereport(NOTICE,
14179  (errcode(ERRCODE_NO_DATA_FOUND),
14180  errmsg("no matching relations in tablespace \"%s\" found",
14181  orig_tablespaceoid == InvalidOid ? "(database default)" :
14182  get_tablespace_name(orig_tablespaceoid))));
14183 
14184  /* Everything is locked, loop through and move all of the relations. */
14185  foreach(l, relations)
14186  {
14187  List *cmds = NIL;
14189 
14190  cmd->subtype = AT_SetTableSpace;
14191  cmd->name = stmt->new_tablespacename;
14192 
14193  cmds = lappend(cmds, cmd);
14194 
14196  /* OID is set by AlterTableInternal */
14197  AlterTableInternal(lfirst_oid(l), cmds, false);
14199  }
14200 
14201  return new_tablespaceoid;
14202 }
#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:1431
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4768
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:1950
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:201
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:3308
#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:1376
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:4818
bool IsCatalogNamespace(Oid namespaceId)
Definition: catalog.c:183
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:4036
#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:1477
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:3240
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 15928 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().

15929 {
15930  Relation rel;
15931  Oid relid;
15932  Oid oldNspOid;
15933  Oid nspOid;
15934  RangeVar *newrv;
15935  ObjectAddresses *objsMoved;
15936  ObjectAddress myself;
15937 
15939  stmt->missing_ok ? RVR_MISSING_OK : 0,
15941  (void *) stmt);
15942 
15943  if (!OidIsValid(relid))
15944  {
15945  ereport(NOTICE,
15946  (errmsg("relation \"%s\" does not exist, skipping",
15947  stmt->relation->relname)));
15948  return InvalidObjectAddress;
15949  }
15950 
15951  rel = relation_open(relid, NoLock);
15952 
15953  oldNspOid = RelationGetNamespace(rel);
15954 
15955  /* If it's an owned sequence, disallow moving it by itself. */
15956  if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
15957  {
15958  Oid tableId;
15959  int32 colId;
15960 
15961  if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
15962  sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
15963  ereport(ERROR,
15964  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15965  errmsg("cannot move an owned sequence into another schema"),
15966  errdetail("Sequence \"%s\" is linked to table \"%s\".",
15968  get_rel_name(tableId))));
15969  }
15970 
15971  /* Get and lock schema OID and check its permissions. */
15972  newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
15973  nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
15974 
15975  /* common checks on switching namespaces */
15976  CheckSetNamespace(oldNspOid, nspOid);
15977 
15978  objsMoved = new_object_addresses();
15979  AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
15980  free_object_addresses(objsMoved);
15981 
15982  ObjectAddressSet(myself, RelationRelationId, relid);
15983 
15984  if (oldschema)
15985  *oldschema = oldNspOid;
15986 
15987  /* close rel, but keep lock until commit */
15988  relation_close(rel, NoLock);
15989 
15990  return myself;
15991 }
bool sequenceIsOwned(Oid seqId, char deptype, Oid *tableId, int32 *colId)
Definition: pg_depend.c:763
int errcode(int sqlerrcode)
Definition: elog.c:698
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2427
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2722
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:15999
#define NoLock
Definition: lockdefs.h:34
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:16552
int errdetail(const char *fmt,...)
Definition: elog.c:1042
#define RelationGetRelationName(relation)
Definition: rel.h:511
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:237
void CheckSetNamespace(Oid oldNspOid, Oid nspOid)
Definition: namespace.c:3012
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:535
#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:518

◆ AlterTableNamespaceInternal()

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

Definition at line 15999 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().

16001 {
16002  Relation classRel;
16003 
16004  Assert(objsMoved != NULL);
16005 
16006  /* OK, modify the pg_class row and pg_depend entry */
16007  classRel = table_open(RelationRelationId, RowExclusiveLock);
16008 
16009  AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
16010  nspOid, true, objsMoved);
16011 
16012  /* Fix the table's row type too, if it has one */
16013  if (OidIsValid(rel->rd_rel->reltype))
16014  AlterTypeNamespaceInternal(rel->rd_rel->reltype,
16015  nspOid, false, false, objsMoved);
16016 
16017  /* Fix other dependent stuff */
16018  if (rel->rd_rel->relkind == RELKIND_RELATION ||
16019  rel->rd_rel->relkind == RELKIND_MATVIEW ||
16020  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
16021  {
16022  AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
16023  AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
16024  objsMoved, AccessExclusiveLock);
16025  AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
16026  false, objsMoved);
16027  }
16028 
16029  table_close(classRel, RowExclusiveLock);
16030 }
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:3955
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:16108
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:16153
#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:16038
#define AccessExclusiveLock
Definition: lockdefs.h:45
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define RelationGetRelid(relation)
Definition: rel.h:477

◆ AtEOSubXact_on_commit_actions()

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

Definition at line 16429 of file tablecmds.c.

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

Referenced by AbortSubTransaction(), and CommitSubTransaction().

16431 {
16432  ListCell *cur_item;
16433 
16434  foreach(cur_item, on_commits)
16435  {
16436  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
16437 
16438  if (!isCommit && oc->creating_subid == mySubid)
16439  {
16440  /* cur_item must be removed */
16442  pfree(oc);
16443  }
16444  else
16445  {
16446  /* cur_item must be preserved */
16447  if (oc->creating_subid == mySubid)
16448  oc->creating_subid = parentSubid;
16449  if (oc->deleting_subid == mySubid)
16450  oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
16451  }
16452  }
16453 }
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 16397 of file tablecmds.c.

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

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

16398 {
16399  ListCell *cur_item;
16400 
16401  foreach(cur_item, on_commits)
16402  {
16403  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
16404 
16405  if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
16407  {
16408  /* cur_item must be removed */
16410  pfree(oc);
16411  }
16412  else
16413  {
16414  /* cur_item must be preserved */
16417  }
16418  }
16419 }
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 13240 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(), errdetail_relkind_not_supported(), errhint(), errmsg(), ERROR, get_namespace_name(), get_rel_name(), get_rel_relkind(), get_relkind_objtype(), GETSTRUCT, GetUserId(), heap_freetuple(), heap_modify_tuple(), HeapTupleIsValid, i, InvalidOid, InvokeObjectPostAlterHook, lfirst_oid, list_free(), NameStr, NoLock, OBJECT_SCHEMA, ObjectIdGetDatum, OidIsValid, pg_class_ownercheck(), pg_namespace_aclcheck(), PointerGetDatum, relation_close(), relation_open(), RelationGetDescr, RelationGetIndexList(), RelationGetRelationName, ReleaseSysCache(), RELOID, RowExclusiveLock, SearchSysCache1(), sequenceIsOwned(), superuser(), SysCacheGetAttr(), HeapTupleData::t_self, table_close(), table_open(), and WARNING.

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

13241 {
13242  Relation target_rel;
13243  Relation class_rel;
13244  HeapTuple tuple;
13245  Form_pg_class tuple_class;
13246 
13247  /*
13248  * Get exclusive lock till end of transaction on the target table. Use
13249  * relation_open so that we can work on indexes and sequences.
13250  */
13251  target_rel = relation_open(relationOid, lockmode);
13252 
13253  /* Get its pg_class tuple, too */
13254  class_rel = table_open(RelationRelationId, RowExclusiveLock);
13255 
13256  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
13257  if (!HeapTupleIsValid(tuple))
13258  elog(ERROR, "cache lookup failed for relation %u", relationOid);
13259  tuple_class = (Form_pg_class) GETSTRUCT(tuple);
13260 
13261  /* Can we change the ownership of this tuple? */
13262  switch (tuple_class->relkind)
13263  {
13264  case RELKIND_RELATION:
13265  case RELKIND_VIEW:
13266  case RELKIND_MATVIEW:
13267  case RELKIND_FOREIGN_TABLE:
13268  case RELKIND_PARTITIONED_TABLE:
13269  /* ok to change owner */
13270  break;
13271  case RELKIND_INDEX:
13272  if (!recursing)
13273  {
13274  /*
13275  * Because ALTER INDEX OWNER used to be allowed, and in fact
13276  * is generated by old versions of pg_dump, we give a warning
13277  * and do nothing rather than erroring out. Also, to avoid
13278  * unnecessary chatter while restoring those old dumps, say
13279  * nothing at all if the command would be a no-op anyway.
13280  */
13281  if (tuple_class->relowner != newOwnerId)
13282  ereport(WARNING,
13283  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
13284  errmsg("cannot change owner of index \"%s\"",
13285  NameStr(tuple_class->relname)),
13286  errhint("Change the ownership of the index's table, instead.")));
13287  /* quick hack to exit via the no-op path */
13288  newOwnerId = tuple_class->relowner;
13289  }
13290  break;
13291  case RELKIND_PARTITIONED_INDEX:
13292  if (recursing)
13293  break;
13294  ereport(ERROR,
13295  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
13296  errmsg("cannot change owner of index \"%s\"",
13297  NameStr(tuple_class->relname)),
13298  errhint("Change the ownership of the index's table, instead.")));
13299  break;
13300  case RELKIND_SEQUENCE:
13301  if (!recursing &&
13302  tuple_class->relowner != newOwnerId)
13303  {
13304  /* if it's an owned sequence, disallow changing it by itself */
13305  Oid tableId;
13306  int32 colId;
13307 
13308  if (sequenceIsOwned(relationOid, DEPENDENCY_AUTO, &tableId, &colId) ||
13309  sequenceIsOwned(relationOid, DEPENDENCY_INTERNAL, &tableId, &colId))
13310  ereport(ERROR,
13311  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
13312  errmsg("cannot change owner of sequence \"%s\"",
13313  NameStr(tuple_class->relname)),
13314  errdetail("Sequence \"%s\" is linked to table \"%s\".",
13315  NameStr(tuple_class->relname),
13316  get_rel_name(tableId))));
13317  }
13318  break;
13319  case RELKIND_COMPOSITE_TYPE:
13320  if (recursing)
13321  break;
13322  ereport(ERROR,
13323  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
13324  errmsg("\"%s\" is a composite type",
13325  NameStr(tuple_class->relname)),
13326  errhint("Use ALTER TYPE instead.")));
13327  break;
13328  case RELKIND_TOASTVALUE:
13329  if (recursing)
13330  break;
13331  /* FALL THRU */
13332  default:
13333  ereport(ERROR,
13334  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
13335  errmsg("cannot change owner of relation \"%s\"",
13336  NameStr(tuple_class->relname)),
13337  errdetail_relkind_not_supported(tuple_class->relkind)));
13338  }
13339 
13340  /*
13341  * If the new owner is the same as the existing owner, consider the
13342  * command to have succeeded. This is for dump restoration purposes.
13343  */
13344  if (tuple_class->relowner != newOwnerId)
13345  {
13346  Datum repl_val[Natts_pg_class];
13347  bool repl_null[Natts_pg_class];
13348  bool repl_repl[Natts_pg_class];
13349  Acl *newAcl;
13350  Datum aclDatum;
13351  bool isNull;
13352  HeapTuple newtuple;
13353 
13354  /* skip permission checks when recursing to index or toast table */
13355  if (!recursing)
13356  {
13357  /* Superusers can always do it */
13358  if (!superuser())
13359  {
13360  Oid namespaceOid = tuple_class->relnamespace;
13361  AclResult aclresult;
13362 
13363  /* Otherwise, must be owner of the existing object */
13364  if (!pg_class_ownercheck(relationOid, GetUserId()))
13366  RelationGetRelationName(target_rel));
13367 
13368  /* Must be able to become new owner */
13369  check_is_member_of_role(GetUserId(), newOwnerId);
13370 
13371  /* New owner must have CREATE privilege on namespace */
13372  aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
13373  ACL_CREATE);
13374  if (aclresult != ACLCHECK_OK)
13375  aclcheck_error(aclresult, OBJECT_SCHEMA,
13376  get_namespace_name(namespaceOid));
13377  }
13378  }
13379 
13380  memset(repl_null, false, sizeof(repl_null));
13381  memset(repl_repl, false, sizeof(repl_repl));
13382 
13383  repl_repl[Anum_pg_class_relowner - 1] = true;
13384  repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
13385 
13386  /*
13387  * Determine the modified ACL for the new owner. This is only
13388  * necessary when the ACL is non-null.
13389  */
13390  aclDatum = SysCacheGetAttr(RELOID, tuple,
13391  Anum_pg_class_relacl,
13392  &isNull);
13393  if (!isNull)
13394  {
13395  newAcl = aclnewowner(DatumGetAclP(aclDatum),
13396  tuple_class->relowner, newOwnerId);
13397  repl_repl[Anum_pg_class_relacl - 1] = true;
13398  repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
13399  }
13400 
13401  newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
13402 
13403  CatalogTupleUpdate(class_rel, &newtuple->t_self, newtuple);
13404 
13405  heap_freetuple(newtuple);
13406 
13407  /*
13408  * We must similarly update any per-column ACLs to reflect the new
13409  * owner; for neatness reasons that's split out as a subroutine.
13410  */
13411  change_owner_fix_column_acls(relationOid,
13412  tuple_class->relowner,
13413  newOwnerId);
13414 
13415  /*
13416  * Update owner dependency reference, if any. A composite type has
13417  * none, because it's tracked for the pg_type entry instead of here;
13418  * indexes and TOAST tables don't have their own entries either.
13419  */
13420  if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
13421  tuple_class->relkind != RELKIND_INDEX &&
13422  tuple_class->relkind != RELKIND_PARTITIONED_INDEX &&
13423  tuple_class->relkind != RELKIND_TOASTVALUE)
13424  changeDependencyOnOwner(RelationRelationId, relationOid,
13425  newOwnerId);
13426 
13427  /*
13428  * Also change the ownership of the table's row type, if it has one
13429  */
13430  if (OidIsValid(tuple_class->reltype))
13431  AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId);
13432 
13433  /*
13434  * If we are operating on a table or materialized view, also change
13435  * the ownership of any indexes and sequences that belong to the
13436  * relation, as well as its toast table (if it has one).
13437  */
13438  if (tuple_class->relkind == RELKIND_RELATION ||
13439  tuple_class->relkind == RELKIND_PARTITIONED_TABLE ||
13440  tuple_class->relkind == RELKIND_MATVIEW ||
13441  tuple_class->relkind == RELKIND_TOASTVALUE)
13442  {
13443  List *index_oid_list;
13444  ListCell *i;
13445 
13446  /* Find all the indexes belonging to this relation */
13447  index_oid_list = RelationGetIndexList(target_rel);
13448 
13449  /* For each index, recursively change its ownership */
13450  foreach(i, index_oid_list)
13451  ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
13452 
13453  list_free(index_oid_list);
13454  }
13455 
13456  /* If it has a toast table, recurse to change its ownership */
13457  if (tuple_class->reltoastrelid != InvalidOid)
13458  ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
13459  true, lockmode);
13460 
13461  /* If it has dependent sequences, recurse to change them too */
13462  change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
13463  }
13464 
13465  InvokeObjectPostAlterHook(RelationRelationId, relationOid, 0);
13466 
13467  ReleaseSysCache(tuple);
13468  table_close(class_rel, RowExclusiveLock);
13469  relation_close(target_rel, NoLock);
13470 }
int errdetail_relkind_not_supported(char relkind)
Definition: pg_class.c:24
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:763
#define RelationGetDescr(relation)
Definition: rel.h:503
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:3825
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:4756
signed int int32
Definition: c.h:429
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
Definition: pg_shdepend.c:311
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3308
#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:511
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:13240
#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:4818
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:13544
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4573
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:13479
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 6488 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().

6489 {
6490  Form_pg_type typ = (Form_pg_type) GETSTRUCT(typetuple);
6491  bool typeOk = false;
6492 
6493  if (typ->typtype == TYPTYPE_COMPOSITE)
6494  {
6495  Relation typeRelation;
6496 
6497  Assert(OidIsValid(typ->typrelid));
6498  typeRelation = relation_open(typ->typrelid, AccessShareLock);
6499  typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
6500 
6501  /*
6502  * Close the parent rel, but keep our AccessShareLock on it until xact
6503  * commit. That will prevent someone else from deleting or ALTERing
6504  * the type before the typed table creation/conversion commits.
6505  */
6506  relation_close(typeRelation, NoLock);
6507  }
6508  if (!typeOk)
6509  ereport(ERROR,
6510  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6511  errmsg("type %s is not a composite type",
6512  format_type_be(typ->oid))));
6513 }
#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 3273 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().

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

◆ CheckTableNotInUse()

void CheckTableNotInUse ( Relation  rel,
const char *  stmt 
)

Definition at line 3923 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().

3924 {
3925  int expected_refcnt;
3926 
3927  expected_refcnt = rel->rd_isnailed ? 2 : 1;
3928  if (rel->rd_refcnt != expected_refcnt)
3929  ereport(ERROR,
3930  (errcode(ERRCODE_OBJECT_IN_USE),
3931  /* translator: first %s is a SQL command, eg ALTER TABLE */
3932  errmsg("cannot %s \"%s\" because it is being used by active queries in this session",
3933  stmt, RelationGetRelationName(rel))));
3934 
3935  if (rel->rd_rel->relkind != RELKIND_INDEX &&
3936  rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
3938  ereport(ERROR,
3939  (errcode(ERRCODE_OBJECT_IN_USE),
3940  /* translator: first %s is a SQL command, eg ALTER TABLE */
3941  errmsg("cannot %s \"%s\" because it has pending trigger events",
3942  stmt, RelationGetRelationName(rel))));
3943 }
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:511
#define ereport(elevel,...)
Definition: elog.h:157
bool AfterTriggerPendingOnRel(Oid relid)
Definition: trigger.c:5527
int errmsg(const char *fmt,...)
Definition: elog.c:909
int rd_refcnt
Definition: rel.h:58
#define RelationGetRelid(relation)
Definition: rel.h:477

◆ DefineRelation()

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

Definition at line 628 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(), 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().

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

1613 {
1614  List *rels = NIL;
1615  List *relids = NIL;
1616  List *relids_logged = NIL;
1617  ListCell *cell;
1618 
1619  /*
1620  * Open, exclusive-lock, and check all the explicitly-specified relations
1621  */
1622  foreach(cell, stmt->relations)
1623  {
1624  RangeVar *rv = lfirst(cell);
1625  Relation rel;
1626  bool recurse = rv->inh;
1627  Oid myrelid;
1628  LOCKMODE lockmode = AccessExclusiveLock;
1629 
1630  myrelid = RangeVarGetRelidExtended(rv, lockmode,
1632  NULL);
1633 
1634  /* don't throw error for "TRUNCATE foo, foo" */
1635  if (list_member_oid(relids, myrelid))
1636  continue;
1637 
1638  /* open the relation, we already hold a lock on it */
1639  rel = table_open(myrelid, NoLock);
1640 
1641  /*
1642  * RangeVarGetRelidExtended() has done most checks with its callback,
1643  * but other checks with the now-opened Relation remain.
1644  */
1646 
1647  rels = lappend(rels, rel);
1648  relids = lappend_oid(relids, myrelid);
1649 
1650  /* Log this relation only if needed for logical decoding */
1651  if (RelationIsLogicallyLogged(rel))
1652  relids_logged = lappend_oid(relids_logged, myrelid);
1653 
1654  if (recurse)
1655  {
1656  ListCell *child;
1657  List *children;
1658 
1659  children = find_all_inheritors(myrelid, lockmode, NULL);
1660 
1661  foreach(child, children)
1662  {
1663  Oid childrelid = lfirst_oid(child);
1664 
1665  if (list_member_oid(relids, childrelid))
1666  continue;
1667 
1668  /* find_all_inheritors already got lock */
1669  rel = table_open(childrelid, NoLock);
1670 
1671  /*
1672  * It is possible that the parent table has children that are
1673  * temp tables of other backends. We cannot safely access
1674  * such tables (because of buffering issues), and the best
1675  * thing to do is to silently ignore them. Note that this
1676  * check is the same as one of the checks done in
1677  * truncate_check_activity() called below, still it is kept
1678  * here for simplicity.
1679  */
1680  if (RELATION_IS_OTHER_TEMP(rel))
1681  {
1682  table_close(rel, lockmode);
1683  continue;
1684  }
1685 
1686  /*
1687  * Inherited TRUNCATE commands perform access permission
1688  * checks on the parent table only. So we skip checking the
1689  * children's permissions and don't call
1690  * truncate_check_perms() here.
1691  */
1694 
1695  rels = lappend(rels, rel);
1696  relids = lappend_oid(relids, childrelid);
1697 
1698  /* Log this relation only if needed for logical decoding */
1699  if (RelationIsLogicallyLogged(rel))
1700  relids_logged = lappend_oid(relids_logged, childrelid);
1701  }
1702  }
1703  else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1704  ereport(ERROR,
1705  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1706  errmsg("cannot truncate only a partitioned table"),
1707  errhint("Do not specify the ONLY keyword, or use TRUNCATE ONLY on the partitions directly.")));
1708  }
1709 
1710  ExecuteTruncateGuts(rels, relids, relids_logged,
1711  stmt->behavior, stmt->restart_seqs);
1712 
1713  /* And close the rels */
1714  foreach(cell, rels)
1715  {
1716  Relation rel = (Relation) lfirst(cell);
1717 
1718  table_close(rel, NoLock);
1719  }
1720 }
#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:16496
int errcode(int sqlerrcode)
Definition: elog.c:698
#define RelationIsLogicallyLogged(relation)
Definition: rel.h:674
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:2770
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:1736
List * relations
Definition: parsenodes.h:2768
#define NoLock
Definition: lockdefs.h:34
bool restart_seqs
Definition: parsenodes.h:2769
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:237
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:2179
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:631
static void truncate_check_rel(Oid relid, Form_pg_class reltuple)
Definition: tablecmds.c:2121
#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:477
#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 1736 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().

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

References AccessShareLock, BTEqualStrategyNumber, check_stack_depth(), 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().

6323 {
6324  Relation depRel;
6325  ScanKeyData key[2];
6326  SysScanDesc depScan;
6327  HeapTuple depTup;
6328 
6329  /* since this function recurses, it could be driven to stack overflow */
6331 
6332  /*
6333  * We scan pg_depend to find those things that depend on the given type.
6334  * (We assume we can ignore refobjsubid for a type.)
6335  */
6336  depRel = table_open(DependRelationId, AccessShareLock);
6337 
6338  ScanKeyInit(&key[0],
6339  Anum_pg_depend_refclassid,
6340  BTEqualStrategyNumber, F_OIDEQ,
6341  ObjectIdGetDatum(TypeRelationId));
6342  ScanKeyInit(&key[1],
6343  Anum_pg_depend_refobjid,
6344  BTEqualStrategyNumber, F_OIDEQ,
6345  ObjectIdGetDatum(typeOid));
6346 
6347  depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
6348  NULL, 2, key);
6349 
6350  while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
6351  {
6352  Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
6353  Relation rel;
6354  Form_pg_attribute att;
6355 
6356  /* Check for directly dependent types */
6357  if (pg_depend->classid == TypeRelationId)
6358  {
6359  /*
6360  * This must be an array, domain, or range containing the given
6361  * type, so recursively check for uses of this type. Note that
6362  * any error message will mention the original type not the
6363  * container; this is intentional.
6364  */
6365  find_composite_type_dependencies(pg_depend->objid,
6366  origRelation, origTypeName);
6367  continue;
6368  }
6369 
6370  /* Else, ignore dependees that aren't user columns of relations */
6371  /* (we assume system columns are never of interesting types) */
6372  if (pg_depend->classid != RelationRelationId ||
6373  pg_depend->objsubid <= 0)
6374  continue;
6375 
6376  rel = relation_open(pg_depend->objid, AccessShareLock);
6377  att = TupleDescAttr(rel->rd_att, pg_depend->objsubid - 1);
6378 
6379  if (rel->rd_rel->relkind == RELKIND_RELATION ||
6380  rel->rd_rel->relkind == RELKIND_MATVIEW ||
6381  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
6382  {
6383  if (origTypeName)
6384  ereport(ERROR,
6385  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6386  errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
6387  origTypeName,
6389  NameStr(att->attname))));
6390  else if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
6391  ereport(ERROR,
6392  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6393  errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
6394  RelationGetRelationName(origRelation),
6396  NameStr(att->attname))));
6397  else if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
6398  ereport(ERROR,
6399  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6400  errmsg("cannot alter foreign table \"%s\" because column \"%s.%s\" uses its row type",
6401  RelationGetRelationName(origRelation),
6403  NameStr(att->attname))));
6404  else
6405  ereport(ERROR,
6406  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6407  errmsg("cannot alter table \"%s\" because column \"%s.%s\" uses its row type",
6408  RelationGetRelationName(origRelation),
6410  NameStr(att->attname))));
6411  }
6412  else if (OidIsValid(rel->rd_rel->reltype))
6413  {
6414  /*
6415  * A view or composite type itself isn't a problem, but we must
6416  * recursively check for indirect dependencies via its rowtype.
6417  */
6419  origRelation, origTypeName);
6420  }
6421 
6423  }
6424 
6425  systable_endscan(depScan);
6426 
6428 }
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:6321
#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:511
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
FormData_pg_depend * Form_pg_depend
Definition: pg_depend.h:72
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 17017 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().

17019 {
17020  List *existConstraint = NIL;
17021  TupleConstr *constr = RelationGetDescr(scanrel)->constr;
17022  int i;
17023 
17024  if (constr && constr->has_not_null)
17025  {
17026  int natts = scanrel->rd_att->natts;
17027 
17028  for (i = 1; i <= natts; i++)
17029  {
17030  Form_pg_attribute att = TupleDescAttr(scanrel->rd_att, i - 1);
17031 
17032  if (att->attnotnull && !att->attisdropped)
17033  {
17034  NullTest *ntest = makeNode(NullTest);
17035 
17036  ntest->arg = (Expr *) makeVar(1,
17037  i,
17038  att->atttypid,
17039  att->atttypmod,
17040  att->attcollation,
17041  0);
17042  ntest->nulltesttype = IS_NOT_NULL;
17043 
17044  /*
17045  * argisrow=false is correct even for a composite column,
17046  * because attnotnull does not represent a SQL-spec IS NOT
17047  * NULL test in such a case, just IS DISTINCT FROM NULL.
17048  */
17049  ntest->argisrow = false;
17050  ntest->location = -1;
17051  existConstraint = lappend(existConstraint, ntest);
17052  }
17053  }
17054  }
17055 
17056  return ConstraintImpliedByRelConstraint(scanrel, partConstraint, existConstraint);
17057 }
#define NIL
Definition: pg_list.h:65
#define RelationGetDescr(relation)
Definition: rel.h:503
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
Expr * arg
Definition: primnodes.h:1265
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
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:1266
#define makeNode(_type_)
Definition: nodes.h:587
static bool ConstraintImpliedByRelConstraint(Relation scanrel, List *testConstraint, List *provenConstraint)
Definition: tablecmds.c:17070
int location
Definition: primnodes.h:1268
int i
bool argisrow
Definition: primnodes.h:1267
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 16297 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().

16298 {
16299  ListCell *l;
16300  List *oids_to_truncate = NIL;
16301  List *oids_to_drop = NIL;
16302 
16303  foreach(l, on_commits)
16304  {
16305  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
16306 
16307  /* Ignore entry if already dropped in this xact */
16309  continue;
16310 
16311  switch (oc->oncommit)
16312  {
16313  case ONCOMMIT_NOOP:
16315  /* Do nothing (there shouldn't be such entries, actually) */
16316  break;
16317  case ONCOMMIT_DELETE_ROWS:
16318 
16319  /*
16320  * If this transaction hasn't accessed any temporary
16321  * relations, we can skip truncating ON COMMIT DELETE ROWS
16322  * tables, as they must still be empty.
16323  */
16325  oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
16326  break;
16327  case ONCOMMIT_DROP:
16328  oids_to_drop = lappend_oid(oids_to_drop, oc->relid);
16329  break;
16330  }
16331  }
16332 
16333  /*
16334  * Truncate relations before dropping so that all dependencies between
16335  * relations are removed after they are worked on. Doing it like this
16336  * might be a waste as it is possible that a relation being truncated will
16337  * be dropped anyway due to its parent being dropped, but this makes the
16338  * code more robust because of not having to re-check that the relation
16339  * exists at truncation time.
16340  */
16341  if (oids_to_truncate != NIL)
16342  heap_truncate(oids_to_truncate);
16343 
16344  if (oids_to_drop != NIL)
16345  {
16346  ObjectAddresses *targetObjects = new_object_addresses();
16347  ListCell *l;
16348 
16349  foreach(l, oids_to_drop)
16350  {
16351  ObjectAddress object;
16352 
16353  object.classId = RelationRelationId;
16354  object.objectId = lfirst_oid(l);
16355  object.objectSubId = 0;
16356 
16357  Assert(!object_address_present(&object, targetObjects));
16358 
16359  add_exact_object_address(&object, targetObjects);
16360  }
16361 
16362  /*
16363  * Since this is an automatic drop, rather than one directly initiated
16364  * by the user, we pass the PERFORM_DELETION_INTERNAL flag.
16365  */
16366  performMultipleDeletions(targetObjects, DROP_CASCADE,
16368 
16369 #ifdef USE_ASSERT_CHECKING
16370 
16371  /*
16372  * Note that table deletion will call remove_on_commit_action, so the
16373  * entry should get marked as deleted.
16374  */
16375  foreach(l, on_commits)
16376  {
16377  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
16378 
16379  if (oc->oncommit != ONCOMMIT_DROP)
16380  continue;
16381 
16383  }
16384 #endif
16385  }
16386 }
#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:2542
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2482
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2427
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:135
void heap_truncate(List *relids)
Definition: heap.c:3328
#define InvalidSubTransactionId
Definition: c.h:593
void performMultipleDeletions(const ObjectAddresses *objects, DropBehavior behavior, int flags)
Definition: dependency.c:372
Definition: pg_list.h:50
#define lfirst_oid(lc)
Definition: pg_list.h:171
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:133

◆ RangeVarCallbackOwnsRelation()

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

Definition at line 16520 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().

16522 {
16523  HeapTuple tuple;
16524 
16525  /* Nothing to do if the relation was not found. */
16526  if (!OidIsValid(relId))
16527  return;
16528 
16529  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
16530  if (!HeapTupleIsValid(tuple)) /* should not happen */
16531  elog(ERROR, "cache lookup failed for relation %u", relId);
16532 
16533  if (!pg_class_ownercheck(relId, GetUserId()))
16535  relation->relname);
16536 
16537  if (!allowSystemTableMods &&
16538  IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
16539  ereport(ERROR,
16540  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
16541  errmsg("permission denied: \"%s\" is a system catalog",
16542  relation->relname)));
16543 
16544  ReleaseSysCache(tuple);
16545 }
#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:86
char * relname
Definition: primnodes.h:68
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3308
#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:4818
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 16464 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().

16466 {
16467  char relkind;
16468 
16469  /* Nothing to do if the relation was not found. */
16470  if (!OidIsValid(relId))
16471  return;
16472 
16473  /*
16474  * If the relation does exist, check whether it's an index. But note that
16475  * the relation might have been dropped between the time we did the name
16476  * lookup and now. In that case, there's nothing to do.
16477  */
16478  relkind = get_rel_relkind(relId);
16479  if (!relkind)
16480  return;
16481  if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
16482  relkind != RELKIND_MATVIEW && relkind != RELKIND_PARTITIONED_TABLE)
16483  ereport(ERROR,
16484  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16485  errmsg("\"%s\" is not a table or materialized view", relation->relname)));
16486 
16487  /* Check permissions */
16488  if (!pg_class_ownercheck(relId, GetUserId()))
16490 }
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:3308
#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:4818
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 16238 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().

16239 {
16240  OnCommitItem *oc;
16241  MemoryContext oldcxt;
16242 
16243  /*
16244  * We needn't bother registering the relation unless there is an ON COMMIT
16245  * action we need to take.
16246  */
16248  return;
16249 
16251 
16252  oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
16253  oc->relid = relid;
16254  oc->oncommit = action;
16257 
16258  /*
16259  * We use lcons() here so that ON COMMIT actions are processed in reverse
16260  * order of registration. That might not be essential but it seems
16261  * reasonable.
16262  */
16263  on_commits = lcons(oc, on_commits);
16264 
16265  MemoryContextSwitchTo(oldcxt);
16266 }
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 16274 of file tablecmds.c.

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

Referenced by heap_drop_with_catalog().

16275 {
16276  ListCell *l;
16277 
16278  foreach(l, on_commits)
16279  {
16280  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
16281 
16282  if (oc->relid == relid)
16283  {
16285  break;
16286  }
16287  }
16288 }
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 1308 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().

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

◆ renameatt()

ObjectAddress renameatt ( RenameStmt stmt)

Definition at line 3586 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().

3587 {
3588  Oid relid;
3590  ObjectAddress address;
3591 
3592  /* lock level taken here should match renameatt_internal */
3594  stmt->missing_ok ? RVR_MISSING_OK : 0,
3596  NULL);
3597 
3598  if (!OidIsValid(relid))
3599  {
3600  ereport(NOTICE,
3601  (errmsg("relation \"%s\" does not exist, skipping",
3602  stmt->relation->relname)));
3603  return InvalidObjectAddress;
3604  }
3605 
3606  attnum =
3607  renameatt_internal(relid,
3608  stmt->subname, /* old att name */
3609  stmt->newname, /* new att name */
3610  stmt->relation->inh, /* recursive? */
3611  false, /* recursing? */
3612  0, /* expected inhcount */
3613  stmt->behavior);
3614 
3615  ObjectAddressSubSet(address, RelationRelationId, relid, attnum);
3616 
3617  return address;
3618 }
char * subname
Definition: parsenodes.h:3047
char * newname
Definition: parsenodes.h:3049
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:3051
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:237
bool inh
Definition: primnodes.h:69
RangeVar * relation
Definition: parsenodes.h:3045
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:3566
static AttrNumber renameatt_internal(Oid myrelid, const char *oldattname, const char *newattname, bool recurse, bool recursing, int expected_parents, DropBehavior behavior)
Definition: tablecmds.c:3421
#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:3050
int16 AttrNumber
Definition: attnum.h:21

◆ RenameConstraint()

ObjectAddress RenameConstraint ( RenameStmt stmt)

Definition at line 3730 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().

3731 {
3732  Oid relid = InvalidOid;
3733  Oid typid = InvalidOid;
3734 
3735  if (stmt->renameType == OBJECT_DOMCONSTRAINT)
3736  {
3737  Relation rel;
3738  HeapTuple tup;
3739 
3741  rel = table_open(TypeRelationId, RowExclusiveLock);
3742  tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
3743  if (!HeapTupleIsValid(tup))
3744  elog(ERROR, "cache lookup failed for type %u", typid);
3745  checkDomainOwner(tup);
3746  ReleaseSysCache(tup);
3747  table_close(rel, NoLock);
3748  }
3749  else
3750  {
3751  /* lock level taken here should match rename_constraint_internal */
3753  stmt->missing_ok ? RVR_MISSING_OK : 0,
3755  NULL);
3756  if (!OidIsValid(relid))
3757  {
3758  ereport(NOTICE,
3759  (errmsg("relation \"%s\" does not exist, skipping",
3760  stmt->relation->relname)));
3761  return InvalidObjectAddress;
3762  }
3763  }
3764 
3765  return
3766  rename_constraint_internal(relid, typid,
3767  stmt->subname,
3768  stmt->newname,
3769  (stmt->relation &&
3770  stmt->relation->inh), /* recursive? */
3771  false, /* recursing? */
3772  0 /* expected inhcount */ );
3773 
3774 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
char * subname
Definition: parsenodes.h:3047
ObjectType renameType
Definition: parsenodes.h:3043
#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:3624
char * newname
Definition: parsenodes.h:3049
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:3051
#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:3046
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:237
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:3045
#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:3566
void checkDomainOwner(HeapTuple tup)
Definition: typecmds.c:3425
#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 3781 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().

3782 {
3783  bool is_index = stmt->renameType == OBJECT_INDEX;
3784  Oid relid;
3785  ObjectAddress address;
3786 
3787  /*
3788  * Grab an exclusive lock on the target table, index, sequence, view,
3789  * materialized view, or foreign table, which we will NOT release until
3790  * end of transaction.
3791  *
3792  * Lock level used here should match RenameRelationInternal, to avoid lock
3793  * escalation.
3794  */
3795  relid = RangeVarGetRelidExtended(stmt->relation,
3797  stmt->missing_ok ? RVR_MISSING_OK : 0,
3799  (void *) stmt);
3800 
3801  if (!OidIsValid(relid))
3802  {
3803  ereport(NOTICE,
3804  (errmsg("relation \"%s\" does not exist, skipping",
3805  stmt->relation->relname)));
3806  return InvalidObjectAddress;
3807  }
3808 
3809  /* Do the work */
3810  RenameRelationInternal(relid, stmt->newname, false, is_index);
3811 
3812  ObjectAddressSet(address, RelationRelationId, relid);
3813 
3814  return address;
3815 }
ObjectType renameType
Definition: parsenodes.h:3043
char * newname
Definition: parsenodes.h:3049
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:3051
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:16552
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:237
RangeVar * relation
Definition: parsenodes.h:3045
#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:3821

◆ RenameRelationInternal()

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

Definition at line 3821 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().

3822 {
3823  Relation targetrelation;
3824  Relation relrelation; /* for RELATION relation */
3825  HeapTuple reltup;
3826  Form_pg_class relform;
3827  Oid namespaceId;
3828 
3829  /*
3830  * Grab a lock on the target relation, which we will NOT release until end
3831  * of transaction. We need at least a self-exclusive lock so that
3832  * concurrent DDL doesn't overwrite the rename if they start updating
3833  * while still seeing the old version. The lock also guards against
3834  * triggering relcache reloads in concurrent sessions, which might not
3835  * handle this information changing under them. For indexes, we can use a
3836  * reduced lock level because RelationReloadIndexInfo() handles indexes
3837  * specially.
3838  */
3839  targetrelation = relation_open(myrelid, is_index ? ShareUpdateExclusiveLock : AccessExclusiveLock);
3840  namespaceId = RelationGetNamespace(targetrelation);
3841 
3842  /*
3843  * Find relation's pg_class tuple, and make sure newrelname isn't in use.
3844  */
3845  relrelation = table_open(RelationRelationId, RowExclusiveLock);
3846 
3847  reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
3848  if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
3849  elog(ERROR, "cache lookup failed for relation %u", myrelid);
3850  relform = (Form_pg_class) GETSTRUCT(reltup);
3851 
3852  if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
3853  ereport(ERROR,
3854  (errcode(ERRCODE_DUPLICATE_TABLE),
3855  errmsg("relation \"%s\" already exists",
3856  newrelname)));
3857 
3858  /*
3859  * Update pg_class tuple with new relname. (Scribbling on reltup is OK
3860  * because it's a copy...)
3861  */
3862  namestrcpy(&(relform->relname), newrelname);
3863 
3864  CatalogTupleUpdate(relrelation, &reltup->t_self, reltup);
3865 
3866  InvokeObjectPostAlterHookArg(RelationRelationId, myrelid, 0,
3867  InvalidOid, is_internal);
3868 
3869  heap_freetuple(reltup);
3870  table_close(relrelation, RowExclusiveLock);
3871 
3872  /*
3873  * Also rename the associated type, if any.
3874  */
3875  if (OidIsValid(targetrelation->rd_rel->reltype))
3876  RenameTypeInternal(targetrelation->rd_rel->reltype,
3877  newrelname, namespaceId);
3878 
3879  /*
3880  * Also rename the associated constraint, if any.
3881  */
3882  if (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
3883  targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
3884  {
3885  Oid constraintId = get_index_constraint(myrelid);
3886 
3887  if (OidIsValid(constraintId))
3888  RenameConstraintById(constraintId, newrelname);
3889  }
3890 
3891  /*
3892  * Close rel, but keep lock!
3893  */
3894  relation_close(targetrelation, NoLock);
3895 }
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:904
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:518

◆ SetRelationHasSubclass()

void SetRelationHasSubclass ( Oid  relationId,
bool  relhassubclass 
)

Definition at line 3232 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().

3233 {
3234  Relation relationRelation;
3235  HeapTuple tuple;
3236  Form_pg_class classtuple;
3237 
3238  /*
3239  * Fetch a modifiable copy of the tuple, modify it, update pg_class.
3240  */
3241  relationRelation = table_open(RelationRelationId, RowExclusiveLock);
3242  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
3243  if (!HeapTupleIsValid(tuple))
3244  elog(ERROR, "cache lookup failed for relation %u", relationId);
3245  classtuple = (Form_pg_class) GETSTRUCT(tuple);
3246 
3247  if (classtuple->relhassubclass != relhassubclass)
3248  {
3249  classtuple->relhassubclass = relhassubclass;
3250  CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
3251  }
3252  else
3253  {
3254  /* no need to change tuple, but force relcache rebuild anyway */
3256  }
3257 
3258  heap_freetuple(tuple);
3259  table_close(relationRelation, RowExclusiveLock);
3260 }
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 3330 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().

3333 {
3334  Relation pg_class;
3335  HeapTuple tuple;
3336  Form_pg_class rd_rel;
3337  Oid reloid = RelationGetRelid(rel);
3338 
3339  Assert(CheckRelationTableSpaceMove(rel, newTableSpaceId));
3340 
3341  /* Get a modifiable copy of the relation's pg_class row. */
3342  pg_class = table_open(RelationRelationId, RowExclusiveLock);
3343 
3344  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(reloid));
3345  if (!HeapTupleIsValid(tuple))
3346  elog(ERROR, "cache lookup failed for relation %u", reloid);
3347  rd_rel = (Form_pg_class) GETSTRUCT(tuple);
3348 
3349  /* Update the pg_class row. */
3350  rd_rel->reltablespace = (newTableSpaceId == MyDatabaseTableSpace) ?
3351  InvalidOid : newTableSpaceId;
3352  if (OidIsValid(newRelFileNode))
3353  rd_rel->relfilenode = newRelFileNode;
3354  CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
3355 
3356  /*
3357  * Record dependency on tablespace. This is only required for relations
3358  * that have no physical storage.
3359  */
3360  if (!RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
3361  changeDependencyOnTablespace(RelationRelationId, reloid,
3362  rd_rel->reltablespace);
3363 
3364  heap_freetuple(tuple);
3365  table_close(pg_class, RowExclusiveLock);
3366 }
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:3273
#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:380
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:477