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)
 
TupleDesc BuildDescForRelation (const List *columns)
 
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, bool run_as_table_owner)
 
void SetRelationHasSubclass (Oid relationId, bool relhassubclass)
 
bool CheckRelationTableSpaceMove (Relation rel, Oid newTableSpaceId)
 
void SetRelationTableSpace (Relation rel, Oid newTableSpaceId, RelFileNumber newRelFilenumber)
 
ObjectAddress renameatt (RenameStmt *stmt)
 
ObjectAddress RenameConstraint (RenameStmt *stmt)
 
ObjectAddress RenameRelation (RenameStmt *stmt)
 
void RenameRelationInternal (Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
 
void ResetRelRewrite (Oid myrelid)
 
void find_composite_type_dependencies (Oid typeOid, Relation origRelation, const char *origTypeName)
 
void check_of_type (HeapTuple typetuple)
 
void register_on_commit_action (Oid relid, OnCommitAction action)
 
void remove_on_commit_action (Oid relid)
 
void PreCommit_on_commit_actions (void)
 
void AtEOXact_on_commit_actions (bool isCommit)
 
void AtEOSubXact_on_commit_actions (bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
 
void RangeVarCallbackMaintainsTable (const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
 
void RangeVarCallbackOwnsRelation (const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
 
bool PartConstraintImpliedByRelConstraint (Relation scanrel, List *partConstraint)
 

Function Documentation

◆ AlterRelationNamespaceInternal()

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

Definition at line 17672 of file tablecmds.c.

17676 {
17677  HeapTuple classTup;
17678  Form_pg_class classForm;
17679  ObjectAddress thisobj;
17680  bool already_done = false;
17681 
17682  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
17683  if (!HeapTupleIsValid(classTup))
17684  elog(ERROR, "cache lookup failed for relation %u", relOid);
17685  classForm = (Form_pg_class) GETSTRUCT(classTup);
17686 
17687  Assert(classForm->relnamespace == oldNspOid);
17688 
17689  thisobj.classId = RelationRelationId;
17690  thisobj.objectId = relOid;
17691  thisobj.objectSubId = 0;
17692 
17693  /*
17694  * If the object has already been moved, don't move it again. If it's
17695  * already in the right place, don't move it, but still fire the object
17696  * access hook.
17697  */
17698  already_done = object_address_present(&thisobj, objsMoved);
17699  if (!already_done && oldNspOid != newNspOid)
17700  {
17701  /* check for duplicate name (more friendly than unique-index failure) */
17702  if (get_relname_relid(NameStr(classForm->relname),
17703  newNspOid) != InvalidOid)
17704  ereport(ERROR,
17705  (errcode(ERRCODE_DUPLICATE_TABLE),
17706  errmsg("relation \"%s\" already exists in schema \"%s\"",
17707  NameStr(classForm->relname),
17708  get_namespace_name(newNspOid))));
17709 
17710  /* classTup is a copy, so OK to scribble on */
17711  classForm->relnamespace = newNspOid;
17712 
17713  CatalogTupleUpdate(classRel, &classTup->t_self, classTup);
17714 
17715  /* Update dependency on schema if caller said so */
17716  if (hasDependEntry &&
17717  changeDependencyFor(RelationRelationId,
17718  relOid,
17719  NamespaceRelationId,
17720  oldNspOid,
17721  newNspOid) != 1)
17722  elog(ERROR, "could not change schema dependency for relation \"%s\"",
17723  NameStr(classForm->relname));
17724  }
17725  if (!already_done)
17726  {
17727  add_exact_object_address(&thisobj, objsMoved);
17728 
17729  InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
17730  }
17731 
17732  heap_freetuple(classTup);
17733 }
#define NameStr(name)
Definition: c.h:733
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2589
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2529
int errcode(int sqlerrcode)
Definition: elog.c:859
int errmsg(const char *fmt,...)
Definition: elog.c:1072
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:224
#define ereport(elevel,...)
Definition: elog.h:149
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1434
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:313
Assert(fmt[strlen(fmt) - 1] !='\n')
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3322
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1863
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:197
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
long changeDependencyFor(Oid classId, Oid objectId, Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition: pg_depend.c:456
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
#define InvalidOid
Definition: postgres_ext.h:36
ItemPointerData t_self
Definition: htup.h:65
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:86

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, SearchSysCacheCopy1, and HeapTupleData::t_self.

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

◆ AlterTable()

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

Definition at line 4419 of file tablecmds.c.

4421 {
4422  Relation rel;
4423 
4424  /* Caller is required to provide an adequate lock. */
4425  rel = relation_open(context->relid, NoLock);
4426 
4427  CheckTableNotInUse(rel, "ALTER TABLE");
4428 
4429  ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
4430 }
#define stmt
Definition: indent_codes.h:59
#define NoLock
Definition: lockdefs.h:34
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:47
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:4332
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:4756

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

Referenced by ProcessUtilitySlow().

◆ AlterTableGetLockLevel()

LOCKMODE AlterTableGetLockLevel ( List cmds)

Definition at line 4493 of file tablecmds.c.

4494 {
4495  /*
4496  * This only works if we read catalog tables using MVCC snapshots.
4497  */
4498  ListCell *lcmd;
4500 
4501  foreach(lcmd, cmds)
4502  {
4503  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
4504  LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
4505 
4506  switch (cmd->subtype)
4507  {
4508  /*
4509  * These subcommands rewrite the heap, so require full locks.
4510  */
4511  case AT_AddColumn: /* may rewrite heap, in some cases and visible
4512  * to SELECT */
4513  case AT_SetAccessMethod: /* must rewrite heap */
4514  case AT_SetTableSpace: /* must rewrite heap */
4515  case AT_AlterColumnType: /* must rewrite heap */
4516  cmd_lockmode = AccessExclusiveLock;
4517  break;
4518 
4519  /*
4520  * These subcommands may require addition of toast tables. If
4521  * we add a toast table to a table currently being scanned, we
4522  * might miss data added to the new toast table by concurrent
4523  * insert transactions.
4524  */
4525  case AT_SetStorage: /* may add toast tables, see
4526  * ATRewriteCatalogs() */
4527  cmd_lockmode = AccessExclusiveLock;
4528  break;
4529 
4530  /*
4531  * Removing constraints can affect SELECTs that have been
4532  * optimized assuming the constraint holds true. See also
4533  * CloneFkReferenced.
4534  */
4535  case AT_DropConstraint: /* as DROP INDEX */
4536  case AT_DropNotNull: /* may change some SQL plans */
4537  cmd_lockmode = AccessExclusiveLock;
4538  break;
4539 
4540  /*
4541  * Subcommands that may be visible to concurrent SELECTs
4542  */
4543  case AT_DropColumn: /* change visible to SELECT */
4544  case AT_AddColumnToView: /* CREATE VIEW */
4545  case AT_DropOids: /* used to equiv to DropColumn */
4546  case AT_EnableAlwaysRule: /* may change SELECT rules */
4547  case AT_EnableReplicaRule: /* may change SELECT rules */
4548  case AT_EnableRule: /* may change SELECT rules */
4549  case AT_DisableRule: /* may change SELECT rules */
4550  cmd_lockmode = AccessExclusiveLock;
4551  break;
4552 
4553  /*
4554  * Changing owner may remove implicit SELECT privileges
4555  */
4556  case AT_ChangeOwner: /* change visible to SELECT */
4557  cmd_lockmode = AccessExclusiveLock;
4558  break;
4559 
4560  /*
4561  * Changing foreign table options may affect optimization.
4562  */
4563  case AT_GenericOptions:
4565  cmd_lockmode = AccessExclusiveLock;
4566  break;
4567 
4568  /*
4569  * These subcommands affect write operations only.
4570  */
4571  case AT_EnableTrig:
4572  case AT_EnableAlwaysTrig:
4573  case AT_EnableReplicaTrig:
4574  case AT_EnableTrigAll:
4575  case AT_EnableTrigUser:
4576  case AT_DisableTrig:
4577  case AT_DisableTrigAll:
4578  case AT_DisableTrigUser:
4579  cmd_lockmode = ShareRowExclusiveLock;
4580  break;
4581 
4582  /*
4583  * These subcommands affect write operations only. XXX
4584  * Theoretically, these could be ShareRowExclusiveLock.
4585  */
4586  case AT_ColumnDefault:
4588  case AT_AlterConstraint:
4589  case AT_AddIndex: /* from ADD CONSTRAINT */
4590  case AT_AddIndexConstraint:
4591  case AT_ReplicaIdentity:
4592  case AT_SetNotNull:
4593  case AT_SetAttNotNull:
4594  case AT_EnableRowSecurity:
4595  case AT_DisableRowSecurity:
4596  case AT_ForceRowSecurity:
4597  case AT_NoForceRowSecurity:
4598  case AT_AddIdentity:
4599  case AT_DropIdentity:
4600  case AT_SetIdentity:
4601  case AT_SetExpression:
4602  case AT_DropExpression:
4603  case AT_SetCompression:
4604  cmd_lockmode = AccessExclusiveLock;
4605  break;
4606 
4607  case AT_AddConstraint:
4608  case AT_ReAddConstraint: /* becomes AT_AddConstraint */
4609  case AT_ReAddDomainConstraint: /* becomes AT_AddConstraint */
4610  if (IsA(cmd->def, Constraint))
4611  {
4612  Constraint *con = (Constraint *) cmd->def;
4613 
4614  switch (con->contype)
4615  {
4616  case CONSTR_EXCLUSION:
4617  case CONSTR_PRIMARY:
4618  case CONSTR_UNIQUE:
4619 
4620  /*
4621  * Cases essentially the same as CREATE INDEX. We
4622  * could reduce the lock strength to ShareLock if
4623  * we can work out how to allow concurrent catalog
4624  * updates. XXX Might be set down to
4625  * ShareRowExclusiveLock but requires further
4626  * analysis.
4627  */
4628  cmd_lockmode = AccessExclusiveLock;
4629  break;
4630  case CONSTR_FOREIGN:
4631 
4632  /*
4633  * We add triggers to both tables when we add a
4634  * Foreign Key, so the lock level must be at least
4635  * as strong as CREATE TRIGGER.
4636  */
4637  cmd_lockmode = ShareRowExclusiveLock;
4638  break;
4639 
4640  default:
4641  cmd_lockmode = AccessExclusiveLock;
4642  }
4643  }
4644  break;
4645 
4646  /*
4647  * These subcommands affect inheritance behaviour. Queries
4648  * started before us will continue to see the old inheritance
4649  * behaviour, while queries started after we commit will see
4650  * new behaviour. No need to prevent reads or writes to the
4651  * subtable while we hook it up though. Changing the TupDesc
4652  * may be a problem, so keep highest lock.
4653  */
4654  case AT_AddInherit:
4655  case AT_DropInherit:
4656  cmd_lockmode = AccessExclusiveLock;
4657  break;
4658 
4659  /*
4660  * These subcommands affect implicit row type conversion. They
4661  * have affects similar to CREATE/DROP CAST on queries. don't
4662  * provide for invalidating parse trees as a result of such
4663  * changes, so we keep these at AccessExclusiveLock.
4664  */
4665  case AT_AddOf:
4666  case AT_DropOf:
4667  cmd_lockmode = AccessExclusiveLock;
4668  break;
4669 
4670  /*
4671  * Only used by CREATE OR REPLACE VIEW which must conflict
4672  * with an SELECTs currently using the view.
4673  */
4674  case AT_ReplaceRelOptions:
4675  cmd_lockmode = AccessExclusiveLock;
4676  break;
4677 
4678  /*
4679  * These subcommands affect general strategies for performance
4680  * and maintenance, though don't change the semantic results
4681  * from normal data reads and writes. Delaying an ALTER TABLE
4682  * behind currently active writes only delays the point where
4683  * the new strategy begins to take effect, so there is no
4684  * benefit in waiting. In this case the minimum restriction
4685  * applies: we don't currently allow concurrent catalog
4686  * updates.
4687  */
4688  case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
4689  case AT_ClusterOn: /* Uses MVCC in getIndexes() */
4690  case AT_DropCluster: /* Uses MVCC in getIndexes() */
4691  case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
4692  case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
4693  cmd_lockmode = ShareUpdateExclusiveLock;
4694  break;
4695 
4696  case AT_SetLogged:
4697  case AT_SetUnLogged:
4698  cmd_lockmode = AccessExclusiveLock;
4699  break;
4700 
4701  case AT_ValidateConstraint: /* Uses MVCC in getConstraints() */
4702  cmd_lockmode = ShareUpdateExclusiveLock;
4703  break;
4704 
4705  /*
4706  * Rel options are more complex than first appears. Options
4707  * are set here for tables, views and indexes; for historical
4708  * reasons these can all be used with ALTER TABLE, so we can't
4709  * decide between them using the basic grammar.
4710  */
4711  case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
4712  * getTables() */
4713  case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
4714  * getTables() */
4715  cmd_lockmode = AlterTableGetRelOptionsLockLevel((List *) cmd->def);
4716  break;
4717 
4718  case AT_AttachPartition:
4719  cmd_lockmode = ShareUpdateExclusiveLock;
4720  break;
4721 
4722  case AT_DetachPartition:
4723  if (((PartitionCmd *) cmd->def)->concurrent)
4724  cmd_lockmode = ShareUpdateExclusiveLock;
4725  else
4726  cmd_lockmode = AccessExclusiveLock;
4727  break;
4728 
4730  cmd_lockmode = ShareUpdateExclusiveLock;
4731  break;
4732 
4733  default: /* oops */
4734  elog(ERROR, "unrecognized alter table type: %d",
4735  (int) cmd->subtype);
4736  break;
4737  }
4738 
4739  /*
4740  * Take the greatest lockmode from any subcommand
4741  */
4742  if (cmd_lockmode > lockmode)
4743  lockmode = cmd_lockmode;
4744  }
4745 
4746  return lockmode;
4747 }
int LOCKMODE
Definition: lockdefs.h:26
#define AccessExclusiveLock
Definition: lockdefs.h:43
#define ShareRowExclusiveLock
Definition: lockdefs.h:41
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
@ CONSTR_FOREIGN
Definition: parsenodes.h:2561
@ CONSTR_UNIQUE
Definition: parsenodes.h:2559
@ CONSTR_EXCLUSION
Definition: parsenodes.h:2560
@ CONSTR_PRIMARY
Definition: parsenodes.h:2558
@ AT_AddIndexConstraint
Definition: parsenodes.h:2223
@ AT_DropOf
Definition: parsenodes.h:2254
@ AT_SetOptions
Definition: parsenodes.h:2211
@ AT_DropIdentity
Definition: parsenodes.h:2266
@ AT_SetAttNotNull
Definition: parsenodes.h:2207
@ AT_DisableTrigUser
Definition: parsenodes.h:2246
@ AT_DropNotNull
Definition: parsenodes.h:2205
@ AT_AddOf
Definition: parsenodes.h:2253
@ AT_ResetOptions
Definition: parsenodes.h:2212
@ AT_ReplicaIdentity
Definition: parsenodes.h:2255
@ AT_ReplaceRelOptions
Definition: parsenodes.h:2238
@ AT_EnableRowSecurity
Definition: parsenodes.h:2256
@ AT_AddColumnToView
Definition: parsenodes.h:2202
@ AT_ResetRelOptions
Definition: parsenodes.h:2237
@ AT_EnableReplicaTrig
Definition: parsenodes.h:2241
@ AT_DropOids
Definition: parsenodes.h:2233
@ AT_SetIdentity
Definition: parsenodes.h:2265
@ AT_SetUnLogged
Definition: parsenodes.h:2232
@ AT_DisableTrig
Definition: parsenodes.h:2242
@ AT_SetCompression
Definition: parsenodes.h:2214
@ AT_DropExpression
Definition: parsenodes.h:2209
@ AT_AddIndex
Definition: parsenodes.h:2216
@ AT_EnableReplicaRule
Definition: parsenodes.h:2249
@ AT_DropConstraint
Definition: parsenodes.h:2224
@ AT_SetNotNull
Definition: parsenodes.h:2206
@ AT_ClusterOn
Definition: parsenodes.h:2229
@ AT_AddIdentity
Definition: parsenodes.h:2264
@ AT_ForceRowSecurity
Definition: parsenodes.h:2258
@ AT_EnableAlwaysRule
Definition: parsenodes.h:2248
@ AT_SetAccessMethod
Definition: parsenodes.h:2234
@ AT_AlterColumnType
Definition: parsenodes.h:2226
@ AT_DetachPartitionFinalize
Definition: parsenodes.h:2263
@ AT_AddInherit
Definition: parsenodes.h:2251
@ AT_ReAddDomainConstraint
Definition: parsenodes.h:2220
@ AT_EnableTrig
Definition: parsenodes.h:2239
@ AT_DropColumn
Definition: parsenodes.h:2215
@ AT_AlterColumnGenericOptions
Definition: parsenodes.h:2227
@ AT_DisableTrigAll
Definition: parsenodes.h:2244
@ AT_EnableRule
Definition: parsenodes.h:2247
@ AT_NoForceRowSecurity
Definition: parsenodes.h:2259
@ AT_DetachPartition
Definition: parsenodes.h:2262
@ AT_SetStatistics
Definition: parsenodes.h:2210
@ AT_AttachPartition
Definition: parsenodes.h:2261
@ AT_AddConstraint
Definition: parsenodes.h:2218
@ AT_DropInherit
Definition: parsenodes.h:2252
@ AT_EnableAlwaysTrig
Definition: parsenodes.h:2240
@ AT_SetLogged
Definition: parsenodes.h:2231
@ AT_SetStorage
Definition: parsenodes.h:2213
@ AT_DisableRule
Definition: parsenodes.h:2250
@ AT_DisableRowSecurity
Definition: parsenodes.h:2257
@ AT_SetRelOptions
Definition: parsenodes.h:2236
@ AT_ChangeOwner
Definition: parsenodes.h:2228
@ AT_EnableTrigUser
Definition: parsenodes.h:2245
@ AT_SetExpression
Definition: parsenodes.h:2208
@ AT_ReAddConstraint
Definition: parsenodes.h:2219
@ AT_SetTableSpace
Definition: parsenodes.h:2235
@ AT_GenericOptions
Definition: parsenodes.h:2260
@ AT_ColumnDefault
Definition: parsenodes.h:2203
@ AT_CookedColumnDefault
Definition: parsenodes.h:2204
@ AT_AlterConstraint
Definition: parsenodes.h:2221
@ AT_EnableTrigAll
Definition: parsenodes.h:2243
@ AT_DropCluster
Definition: parsenodes.h:2230
@ AT_ValidateConstraint
Definition: parsenodes.h:2222
@ AT_AddColumn
Definition: parsenodes.h:2201
#define lfirst(lc)
Definition: pg_list.h:172
LOCKMODE AlterTableGetRelOptionsLockLevel(List *defList)
Definition: reloptions.c:2108
AlterTableType subtype
Definition: parsenodes.h:2280
ConstrType contype
Definition: parsenodes.h:2583
Definition: pg_list.h:54

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

Referenced by AlterTableInternal(), and ProcessUtilitySlow().

◆ AlterTableInternal()

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

Definition at line 4448 of file tablecmds.c.

4449 {
4450  Relation rel;
4451  LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
4452 
4453  rel = relation_open(relid, lockmode);
4454 
4456 
4457  ATController(NULL, rel, cmds, recurse, lockmode, NULL);
4458 }
void EventTriggerAlterTableRelid(Oid objectId)
LOCKMODE AlterTableGetLockLevel(List *cmds)
Definition: tablecmds.c:4493

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

Referenced by AlterTableMoveAll(), and DefineVirtualRelation().

◆ AlterTableLookupRelation()

Oid AlterTableLookupRelation ( AlterTableStmt stmt,
LOCKMODE  lockmode 
)

Definition at line 4360 of file tablecmds.c.

4361 {
4362  return RangeVarGetRelidExtended(stmt->relation, lockmode,
4363  stmt->missing_ok ? RVR_MISSING_OK : 0,
4365  (void *) stmt);
4366 }
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:426
@ RVR_MISSING_OK
Definition: namespace.h:72
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:18197

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

Referenced by ProcessUtilitySlow().

◆ AlterTableMoveAll()

Oid AlterTableMoveAll ( AlterTableMoveAllStmt stmt)

Definition at line 15594 of file tablecmds.c.

15595 {
15596  List *relations = NIL;
15597  ListCell *l;
15598  ScanKeyData key[1];
15599  Relation rel;
15600  TableScanDesc scan;
15601  HeapTuple tuple;
15602  Oid orig_tablespaceoid;
15603  Oid new_tablespaceoid;
15604  List *role_oids = roleSpecsToIds(stmt->roles);
15605 
15606  /* Ensure we were not asked to move something we can't */
15607  if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
15608  stmt->objtype != OBJECT_MATVIEW)
15609  ereport(ERROR,
15610  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
15611  errmsg("only tables, indexes, and materialized views exist in tablespaces")));
15612 
15613  /* Get the orig and new tablespace OIDs */
15614  orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
15615  new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
15616 
15617  /* Can't move shared relations in to or out of pg_global */
15618  /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
15619  if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
15620  new_tablespaceoid == GLOBALTABLESPACE_OID)
15621  ereport(ERROR,
15622  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
15623  errmsg("cannot move relations in to or out of pg_global tablespace")));
15624 
15625  /*
15626  * Must have CREATE rights on the new tablespace, unless it is the
15627  * database default tablespace (which all users implicitly have CREATE
15628  * rights on).
15629  */
15630  if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
15631  {
15632  AclResult aclresult;
15633 
15634  aclresult = object_aclcheck(TableSpaceRelationId, new_tablespaceoid, GetUserId(),
15635  ACL_CREATE);
15636  if (aclresult != ACLCHECK_OK)
15637  aclcheck_error(aclresult, OBJECT_TABLESPACE,
15638  get_tablespace_name(new_tablespaceoid));
15639  }
15640 
15641  /*
15642  * Now that the checks are done, check if we should set either to
15643  * InvalidOid because it is our database's default tablespace.
15644  */
15645  if (orig_tablespaceoid == MyDatabaseTableSpace)
15646  orig_tablespaceoid = InvalidOid;
15647 
15648  if (new_tablespaceoid == MyDatabaseTableSpace)
15649  new_tablespaceoid = InvalidOid;
15650 
15651  /* no-op */
15652  if (orig_tablespaceoid == new_tablespaceoid)
15653  return new_tablespaceoid;
15654 
15655  /*
15656  * Walk the list of objects in the tablespace and move them. This will
15657  * only find objects in our database, of course.
15658  */
15659  ScanKeyInit(&key[0],
15660  Anum_pg_class_reltablespace,
15661  BTEqualStrategyNumber, F_OIDEQ,
15662  ObjectIdGetDatum(orig_tablespaceoid));
15663 
15664  rel = table_open(RelationRelationId, AccessShareLock);
15665  scan = table_beginscan_catalog(rel, 1, key);
15666  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
15667  {
15668  Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
15669  Oid relOid = relForm->oid;
15670 
15671  /*
15672  * Do not move objects in pg_catalog as part of this, if an admin
15673  * really wishes to do so, they can issue the individual ALTER
15674  * commands directly.
15675  *
15676  * Also, explicitly avoid any shared tables, temp tables, or TOAST
15677  * (TOAST will be moved with the main table).
15678  */
15679  if (IsCatalogNamespace(relForm->relnamespace) ||
15680  relForm->relisshared ||
15681  isAnyTempNamespace(relForm->relnamespace) ||
15682  IsToastNamespace(relForm->relnamespace))
15683  continue;
15684 
15685  /* Only move the object type requested */
15686  if ((stmt->objtype == OBJECT_TABLE &&
15687  relForm->relkind != RELKIND_RELATION &&
15688  relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
15689  (stmt->objtype == OBJECT_INDEX &&
15690  relForm->relkind != RELKIND_INDEX &&
15691  relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
15692  (stmt->objtype == OBJECT_MATVIEW &&
15693  relForm->relkind != RELKIND_MATVIEW))
15694  continue;
15695 
15696  /* Check if we are only moving objects owned by certain roles */
15697  if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
15698  continue;
15699 
15700  /*
15701  * Handle permissions-checking here since we are locking the tables
15702  * and also to avoid doing a bunch of work only to fail part-way. Note
15703  * that permissions will also be checked by AlterTableInternal().
15704  *
15705  * Caller must be considered an owner on the table to move it.
15706  */
15707  if (!object_ownercheck(RelationRelationId, relOid, GetUserId()))
15709  NameStr(relForm->relname));
15710 
15711  if (stmt->nowait &&
15713  ereport(ERROR,
15714  (errcode(ERRCODE_OBJECT_IN_USE),
15715  errmsg("aborting because lock on relation \"%s.%s\" is not available",
15716  get_namespace_name(relForm->relnamespace),
15717  NameStr(relForm->relname))));
15718  else
15720 
15721  /* Add to our list of objects to move */
15722  relations = lappend_oid(relations, relOid);
15723  }
15724 
15725  table_endscan(scan);
15727 
15728  if (relations == NIL)
15729  ereport(NOTICE,
15730  (errcode(ERRCODE_NO_DATA_FOUND),
15731  errmsg("no matching relations in tablespace \"%s\" found",
15732  orig_tablespaceoid == InvalidOid ? "(database default)" :
15733  get_tablespace_name(orig_tablespaceoid))));
15734 
15735  /* Everything is locked, loop through and move all of the relations. */
15736  foreach(l, relations)
15737  {
15738  List *cmds = NIL;
15740 
15741  cmd->subtype = AT_SetTableSpace;
15742  cmd->name = stmt->new_tablespacename;
15743 
15744  cmds = lappend(cmds, cmd);
15745 
15747  /* OID is set by AlterTableInternal */
15748  AlterTableInternal(lfirst_oid(l), cmds, false);
15750  }
15751 
15752  return new_tablespaceoid;
15753 }
AclResult
Definition: acl.h:182
@ ACLCHECK_OK
Definition: acl.h:183
@ ACLCHECK_NOT_OWNER
Definition: acl.h:185
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2688
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:3876
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4130
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1472
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1426
List * roleSpecsToIds(List *memberNames)
Definition: user.c:1652
#define OidIsValid(objectId)
Definition: c.h:762
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:200
bool IsCatalogNamespace(Oid namespaceId)
Definition: catalog.c:182
#define NOTICE
Definition: elog.h:35
void EventTriggerAlterTableStart(Node *parsetree)
void EventTriggerAlterTableEnd(void)
Oid MyDatabaseTableSpace
Definition: globals.c:93
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1082
List * lappend(List *list, void *datum)
Definition: list.c:339
List * lappend_oid(List *list, Oid datum)
Definition: list.c:375
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:722
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:151
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:108
#define AccessShareLock
Definition: lockdefs.h:36
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1981
Oid GetUserId(void)
Definition: miscinit.c:514
bool isAnyTempNamespace(Oid namespaceId)
Definition: namespace.c:3672
#define makeNode(_type_)
Definition: nodes.h:155
ObjectType get_relkind_objtype(char relkind)
@ OBJECT_MATVIEW
Definition: parsenodes.h:2132
@ OBJECT_TABLESPACE
Definition: parsenodes.h:2151
@ OBJECT_INDEX
Definition: parsenodes.h:2129
@ OBJECT_TABLE
Definition: parsenodes.h:2150
#define ACL_CREATE
Definition: parsenodes.h:85
#define NIL
Definition: pg_list.h:68
#define lfirst_oid(lc)
Definition: pg_list.h:174
unsigned int Oid
Definition: postgres_ext.h:31
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
@ ForwardScanDirection
Definition: sdir.h:28
#define BTEqualStrategyNumber
Definition: stratnum.h:31
Definition: nodes.h:129
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:1009
void AlterTableInternal(Oid relid, List *cmds, bool recurse)
Definition: tablecmds.c:4448

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

Referenced by ProcessUtilitySlow().

◆ AlterTableNamespace()

ObjectAddress AlterTableNamespace ( AlterObjectSchemaStmt stmt,
Oid oldschema 
)

Definition at line 17562 of file tablecmds.c.

17563 {
17564  Relation rel;
17565  Oid relid;
17566  Oid oldNspOid;
17567  Oid nspOid;
17568  RangeVar *newrv;
17569  ObjectAddresses *objsMoved;
17570  ObjectAddress myself;
17571 
17573  stmt->missing_ok ? RVR_MISSING_OK : 0,
17575  (void *) stmt);
17576 
17577  if (!OidIsValid(relid))
17578  {
17579  ereport(NOTICE,
17580  (errmsg("relation \"%s\" does not exist, skipping",
17581  stmt->relation->relname)));
17582  return InvalidObjectAddress;
17583  }
17584 
17585  rel = relation_open(relid, NoLock);
17586 
17587  oldNspOid = RelationGetNamespace(rel);
17588 
17589  /* If it's an owned sequence, disallow moving it by itself. */
17590  if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
17591  {
17592  Oid tableId;
17593  int32 colId;
17594 
17595  if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
17596  sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
17597  ereport(ERROR,
17598  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
17599  errmsg("cannot move an owned sequence into another schema"),
17600  errdetail("Sequence \"%s\" is linked to table \"%s\".",
17602  get_rel_name(tableId))));
17603  }
17604 
17605  /* Get and lock schema OID and check its permissions. */
17606  newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
17607  nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
17608 
17609  /* common checks on switching namespaces */
17610  CheckSetNamespace(oldNspOid, nspOid);
17611 
17612  objsMoved = new_object_addresses();
17613  AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
17614  free_object_addresses(objsMoved);
17615 
17616  ObjectAddressSet(myself, RelationRelationId, relid);
17617 
17618  if (oldschema)
17619  *oldschema = oldNspOid;
17620 
17621  /* close rel, but keep lock until commit */
17622  relation_close(rel, NoLock);
17623 
17624  return myself;
17625 }
signed int int32
Definition: c.h:481
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2483
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2769
@ DEPENDENCY_AUTO
Definition: dependency.h:34
@ DEPENDENCY_INTERNAL
Definition: dependency.h:35
int errdetail(const char *fmt,...)
Definition: elog.c:1205
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1906
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:424
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:724
void CheckSetNamespace(Oid oldNspOid, Oid nspOid)
Definition: namespace.c:3444
const ObjectAddress InvalidObjectAddress
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
bool sequenceIsOwned(Oid seqId, char deptype, Oid *tableId, int32 *colId)
Definition: pg_depend.c:827
#define RelationGetRelationName(relation)
Definition: rel.h:539
#define RelationGetNamespace(relation)
Definition: rel.h:546
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:205
Form_pg_class rd_rel
Definition: rel.h:111
void AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:17633

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

Referenced by ExecAlterObjectSchemaStmt().

◆ AlterTableNamespaceInternal()

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

Definition at line 17633 of file tablecmds.c.

17635 {
17636  Relation classRel;
17637 
17638  Assert(objsMoved != NULL);
17639 
17640  /* OK, modify the pg_class row and pg_depend entry */
17641  classRel = table_open(RelationRelationId, RowExclusiveLock);
17642 
17643  AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
17644  nspOid, true, objsMoved);
17645 
17646  /* Fix the table's row type too, if it has one */
17647  if (OidIsValid(rel->rd_rel->reltype))
17648  AlterTypeNamespaceInternal(rel->rd_rel->reltype,
17649  nspOid, false, false, objsMoved);
17650 
17651  /* Fix other dependent stuff */
17652  if (rel->rd_rel->relkind == RELKIND_RELATION ||
17653  rel->rd_rel->relkind == RELKIND_MATVIEW ||
17654  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
17655  {
17656  AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
17657  AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
17658  objsMoved, AccessExclusiveLock);
17659  AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
17660  false, objsMoved);
17661  }
17662 
17663  table_close(classRel, RowExclusiveLock);
17664 }
#define RowExclusiveLock
Definition: lockdefs.h:38
void AlterConstraintNamespaces(Oid ownerId, Oid oldNspId, Oid newNspId, bool isType, ObjectAddresses *objsMoved)
#define RelationGetRelid(relation)
Definition: rel.h:505
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
Definition: tablecmds.c:17672
static void AlterSeqNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved, LOCKMODE lockmode)
Definition: tablecmds.c:17787
static void AlterIndexNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:17742
Oid AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid, bool isImplicitArray, bool errorOnTableType, ObjectAddresses *objsMoved)
Definition: typecmds.c:3981

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

Referenced by AlterObjectNamespace_oid(), and AlterTableNamespace().

◆ AtEOSubXact_on_commit_actions()

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

Definition at line 18070 of file tablecmds.c.

18072 {
18073  ListCell *cur_item;
18074 
18075  foreach(cur_item, on_commits)
18076  {
18077  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
18078 
18079  if (!isCommit && oc->creating_subid == mySubid)
18080  {
18081  /* cur_item must be removed */
18083  pfree(oc);
18084  }
18085  else
18086  {
18087  /* cur_item must be preserved */
18088  if (oc->creating_subid == mySubid)
18089  oc->creating_subid = parentSubid;
18090  if (oc->deleting_subid == mySubid)
18091  oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
18092  }
18093  }
18094 }
#define InvalidSubTransactionId
Definition: c.h:645
void pfree(void *pointer)
Definition: mcxt.c:1508
#define foreach_delete_current(lst, var_or_cell)
Definition: pg_list.h:391
SubTransactionId creating_subid
Definition: tablecmds.c:121
SubTransactionId deleting_subid
Definition: tablecmds.c:122
static List * on_commits
Definition: tablecmds.c:125

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

Referenced by AbortSubTransaction(), and CommitSubTransaction().

◆ AtEOXact_on_commit_actions()

void AtEOXact_on_commit_actions ( bool  isCommit)

Definition at line 18038 of file tablecmds.c.

18039 {
18040  ListCell *cur_item;
18041 
18042  foreach(cur_item, on_commits)
18043  {
18044  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
18045 
18046  if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
18048  {
18049  /* cur_item must be removed */
18051  pfree(oc);
18052  }
18053  else
18054  {
18055  /* cur_item must be preserved */
18058  }
18059  }
18060 }

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

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

◆ ATExecChangeOwner()

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

Definition at line 14789 of file tablecmds.c.

14790 {
14791  Relation target_rel;
14792  Relation class_rel;
14793  HeapTuple tuple;
14794  Form_pg_class tuple_class;
14795 
14796  /*
14797  * Get exclusive lock till end of transaction on the target table. Use
14798  * relation_open so that we can work on indexes and sequences.
14799  */
14800  target_rel = relation_open(relationOid, lockmode);
14801 
14802  /* Get its pg_class tuple, too */
14803  class_rel = table_open(RelationRelationId, RowExclusiveLock);
14804 
14805  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
14806  if (!HeapTupleIsValid(tuple))
14807  elog(ERROR, "cache lookup failed for relation %u", relationOid);
14808  tuple_class = (Form_pg_class) GETSTRUCT(tuple);
14809 
14810  /* Can we change the ownership of this tuple? */
14811  switch (tuple_class->relkind)
14812  {
14813  case RELKIND_RELATION:
14814  case RELKIND_VIEW:
14815  case RELKIND_MATVIEW:
14816  case RELKIND_FOREIGN_TABLE:
14817  case RELKIND_PARTITIONED_TABLE:
14818  /* ok to change owner */
14819  break;
14820  case RELKIND_INDEX:
14821  if (!recursing)
14822  {
14823  /*
14824  * Because ALTER INDEX OWNER used to be allowed, and in fact
14825  * is generated by old versions of pg_dump, we give a warning
14826  * and do nothing rather than erroring out. Also, to avoid
14827  * unnecessary chatter while restoring those old dumps, say
14828  * nothing at all if the command would be a no-op anyway.
14829  */
14830  if (tuple_class->relowner != newOwnerId)
14831  ereport(WARNING,
14832  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
14833  errmsg("cannot change owner of index \"%s\"",
14834  NameStr(tuple_class->relname)),
14835  errhint("Change the ownership of the index's table instead.")));
14836  /* quick hack to exit via the no-op path */
14837  newOwnerId = tuple_class->relowner;
14838  }
14839  break;
14840  case RELKIND_PARTITIONED_INDEX:
14841  if (recursing)
14842  break;
14843  ereport(ERROR,
14844  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
14845  errmsg("cannot change owner of index \"%s\"",
14846  NameStr(tuple_class->relname)),
14847  errhint("Change the ownership of the index's table instead.")));
14848  break;
14849  case RELKIND_SEQUENCE:
14850  if (!recursing &&
14851  tuple_class->relowner != newOwnerId)
14852  {
14853  /* if it's an owned sequence, disallow changing it by itself */
14854  Oid tableId;
14855  int32 colId;
14856 
14857  if (sequenceIsOwned(relationOid, DEPENDENCY_AUTO, &tableId, &colId) ||
14858  sequenceIsOwned(relationOid, DEPENDENCY_INTERNAL, &tableId, &colId))
14859  ereport(ERROR,
14860  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
14861  errmsg("cannot change owner of sequence \"%s\"",
14862  NameStr(tuple_class->relname)),
14863  errdetail("Sequence \"%s\" is linked to table \"%s\".",
14864  NameStr(tuple_class->relname),
14865  get_rel_name(tableId))));
14866  }
14867  break;
14868  case RELKIND_COMPOSITE_TYPE:
14869  if (recursing)
14870  break;
14871  ereport(ERROR,
14872  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
14873  errmsg("\"%s\" is a composite type",
14874  NameStr(tuple_class->relname)),
14875  /* translator: %s is an SQL ALTER command */
14876  errhint("Use %s instead.",
14877  "ALTER TYPE")));
14878  break;
14879  case RELKIND_TOASTVALUE:
14880  if (recursing)
14881  break;
14882  /* FALL THRU */
14883  default:
14884  ereport(ERROR,
14885  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
14886  errmsg("cannot change owner of relation \"%s\"",
14887  NameStr(tuple_class->relname)),
14888  errdetail_relkind_not_supported(tuple_class->relkind)));
14889  }
14890 
14891  /*
14892  * If the new owner is the same as the existing owner, consider the
14893  * command to have succeeded. This is for dump restoration purposes.
14894  */
14895  if (tuple_class->relowner != newOwnerId)
14896  {
14897  Datum repl_val[Natts_pg_class];
14898  bool repl_null[Natts_pg_class];
14899  bool repl_repl[Natts_pg_class];
14900  Acl *newAcl;
14901  Datum aclDatum;
14902  bool isNull;
14903  HeapTuple newtuple;
14904 
14905  /* skip permission checks when recursing to index or toast table */
14906  if (!recursing)
14907  {
14908  /* Superusers can always do it */
14909  if (!superuser())
14910  {
14911  Oid namespaceOid = tuple_class->relnamespace;
14912  AclResult aclresult;
14913 
14914  /* Otherwise, must be owner of the existing object */
14915  if (!object_ownercheck(RelationRelationId, relationOid, GetUserId()))
14917  RelationGetRelationName(target_rel));
14918 
14919  /* Must be able to become new owner */
14920  check_can_set_role(GetUserId(), newOwnerId);
14921 
14922  /* New owner must have CREATE privilege on namespace */
14923  aclresult = object_aclcheck(NamespaceRelationId, namespaceOid, newOwnerId,
14924  ACL_CREATE);
14925  if (aclresult != ACLCHECK_OK)
14926  aclcheck_error(aclresult, OBJECT_SCHEMA,
14927  get_namespace_name(namespaceOid));
14928  }
14929  }
14930 
14931  memset(repl_null, false, sizeof(repl_null));
14932  memset(repl_repl, false, sizeof(repl_repl));
14933 
14934  repl_repl[Anum_pg_class_relowner - 1] = true;
14935  repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
14936 
14937  /*
14938  * Determine the modified ACL for the new owner. This is only
14939  * necessary when the ACL is non-null.
14940  */
14941  aclDatum = SysCacheGetAttr(RELOID, tuple,
14942  Anum_pg_class_relacl,
14943  &isNull);
14944  if (!isNull)
14945  {
14946  newAcl = aclnewowner(DatumGetAclP(aclDatum),
14947  tuple_class->relowner, newOwnerId);
14948  repl_repl[Anum_pg_class_relacl - 1] = true;
14949  repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
14950  }
14951 
14952  newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
14953 
14954  CatalogTupleUpdate(class_rel, &newtuple->t_self, newtuple);
14955 
14956  heap_freetuple(newtuple);
14957 
14958  /*
14959  * We must similarly update any per-column ACLs to reflect the new
14960  * owner; for neatness reasons that's split out as a subroutine.
14961  */
14962  change_owner_fix_column_acls(relationOid,
14963  tuple_class->relowner,
14964  newOwnerId);
14965 
14966  /*
14967  * Update owner dependency reference, if any. A composite type has
14968  * none, because it's tracked for the pg_type entry instead of here;
14969  * indexes and TOAST tables don't have their own entries either.
14970  */
14971  if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
14972  tuple_class->relkind != RELKIND_INDEX &&
14973  tuple_class->relkind != RELKIND_PARTITIONED_INDEX &&
14974  tuple_class->relkind != RELKIND_TOASTVALUE)
14975  changeDependencyOnOwner(RelationRelationId, relationOid,
14976  newOwnerId);
14977 
14978  /*
14979  * Also change the ownership of the table's row type, if it has one
14980  */
14981  if (OidIsValid(tuple_class->reltype))
14982  AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId);
14983 
14984  /*
14985  * If we are operating on a table or materialized view, also change
14986  * the ownership of any indexes and sequences that belong to the
14987  * relation, as well as its toast table (if it has one).
14988  */
14989  if (tuple_class->relkind == RELKIND_RELATION ||
14990  tuple_class->relkind == RELKIND_PARTITIONED_TABLE ||
14991  tuple_class->relkind == RELKIND_MATVIEW ||
14992  tuple_class->relkind == RELKIND_TOASTVALUE)
14993  {
14994  List *index_oid_list;
14995  ListCell *i;
14996 
14997  /* Find all the indexes belonging to this relation */
14998  index_oid_list = RelationGetIndexList(target_rel);
14999 
15000  /* For each index, recursively change its ownership */
15001  foreach(i, index_oid_list)
15002  ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
15003 
15004  list_free(index_oid_list);
15005  }
15006 
15007  /* If it has a toast table, recurse to change its ownership */
15008  if (tuple_class->reltoastrelid != InvalidOid)
15009  ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
15010  true, lockmode);
15011 
15012  /* If it has dependent sequences, recurse to change them too */
15013  change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
15014  }
15015 
15016  InvokeObjectPostAlterHook(RelationRelationId, relationOid, 0);
15017 
15018  ReleaseSysCache(tuple);
15019  table_close(class_rel, RowExclusiveLock);
15020  relation_close(target_rel, NoLock);
15021 }
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition: acl.c:1088
void check_can_set_role(Oid member, Oid role)
Definition: acl.c:5123
#define DatumGetAclP(X)
Definition: acl.h:120
int errhint(const char *fmt,...)
Definition: elog.c:1319
#define WARNING
Definition: elog.h:36
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition: heaptuple.c:1209
int i
Definition: isn.c:73
void list_free(List *list)
Definition: list.c:1546
@ OBJECT_SCHEMA
Definition: parsenodes.h:2145
int errdetail_relkind_not_supported(char relkind)
Definition: pg_class.c:24
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
Definition: pg_shdepend.c:308
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
uintptr_t Datum
Definition: postgres.h:64
#define RelationGetDescr(relation)
Definition: rel.h:531
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4749
bool superuser(void)
Definition: superuser.c:46
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:266
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:218
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:479
void ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
Definition: tablecmds.c:14789
static void change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
Definition: tablecmds.c:15095
static void change_owner_fix_column_acls(Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
Definition: tablecmds.c:15030
void AlterTypeOwnerInternal(Oid typeOid, Oid newOwnerId)
Definition: typecmds.c:3838

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

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

◆ BuildDescForRelation()

TupleDesc BuildDescForRelation ( const List columns)

Definition at line 1293 of file tablecmds.c.

1294 {
1295  int natts;
1297  ListCell *l;
1298  TupleDesc desc;
1299  bool has_not_null;
1300  char *attname;
1301  Oid atttypid;
1302  int32 atttypmod;
1303  Oid attcollation;
1304  int attdim;
1305 
1306  /*
1307  * allocate a new tuple descriptor
1308  */
1309  natts = list_length(columns);
1310  desc = CreateTemplateTupleDesc(natts);
1311  has_not_null = false;
1312 
1313  attnum = 0;
1314 
1315  foreach(l, columns)
1316  {
1317  ColumnDef *entry = lfirst(l);
1318  AclResult aclresult;
1319  Form_pg_attribute att;
1320 
1321  /*
1322  * for each entry in the list, get the name and type information from
1323  * the list and have TupleDescInitEntry fill in the attribute
1324  * information we need.
1325  */
1326  attnum++;
1327 
1328  attname = entry->colname;
1329  typenameTypeIdAndMod(NULL, entry->typeName, &atttypid, &atttypmod);
1330 
1331  aclresult = object_aclcheck(TypeRelationId, atttypid, GetUserId(), ACL_USAGE);
1332  if (aclresult != ACLCHECK_OK)
1333  aclcheck_error_type(aclresult, atttypid);
1334 
1335  attcollation = GetColumnDefCollation(NULL, entry, atttypid);
1336  attdim = list_length(entry->typeName->arrayBounds);
1337  if (attdim > PG_INT16_MAX)
1338  ereport(ERROR,
1339  errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1340  errmsg("too many array dimensions"));
1341 
1342  if (entry->typeName->setof)
1343  ereport(ERROR,
1344  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1345  errmsg("column \"%s\" cannot be declared SETOF",
1346  attname)));
1347 
1349  atttypid, atttypmod, attdim);
1350  att = TupleDescAttr(desc, attnum - 1);
1351 
1352  /* Override TupleDescInitEntry's settings as requested */
1353  TupleDescInitEntryCollation(desc, attnum, attcollation);
1354 
1355  /* Fill in additional stuff not handled by TupleDescInitEntry */
1356  att->attnotnull = entry->is_not_null;
1357  has_not_null |= entry->is_not_null;
1358  att->attislocal = entry->is_local;
1359  att->attinhcount = entry->inhcount;
1360  att->attidentity = entry->identity;
1361  att->attgenerated = entry->generated;
1362  att->attcompression = GetAttributeCompression(att->atttypid, entry->compression);
1363  if (entry->storage)
1364  att->attstorage = entry->storage;
1365  else if (entry->storage_name)
1366  att->attstorage = GetAttributeStorage(att->atttypid, entry->storage_name);
1367  }
1368 
1369  if (has_not_null)
1370  {
1371  TupleConstr *constr = (TupleConstr *) palloc0(sizeof(TupleConstr));
1372 
1373  constr->has_not_null = true;
1374  constr->has_generated_stored = false;
1375  constr->defval = NULL;
1376  constr->missing = NULL;
1377  constr->num_defval = 0;
1378  constr->check = NULL;
1379  constr->num_check = 0;
1380  desc->constr = constr;
1381  }
1382  else
1383  {
1384  desc->constr = NULL;
1385  }
1386 
1387  return desc;
1388 }
void aclcheck_error_type(AclResult aclerr, Oid typeOid)
Definition: aclchk.c:3007
int16 AttrNumber
Definition: attnum.h:21
#define PG_INT16_MAX
Definition: c.h:573
void * palloc0(Size size)
Definition: mcxt.c:1334
void typenameTypeIdAndMod(ParseState *pstate, const TypeName *typeName, Oid *typeid_p, int32 *typmod_p)
Definition: parse_type.c:310
Oid GetColumnDefCollation(ParseState *pstate, const ColumnDef *coldef, Oid typeOid)
Definition: parse_type.c:540
#define ACL_USAGE
Definition: parsenodes.h:84
NameData attname
Definition: pg_attribute.h:41
int16 attnum
Definition: pg_attribute.h:74
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
static int list_length(const List *l)
Definition: pg_list.h:152
bool is_not_null
Definition: parsenodes.h:727
char identity
Definition: parsenodes.h:733
char * storage_name
Definition: parsenodes.h:730
int inhcount
Definition: parsenodes.h:725
char * colname
Definition: parsenodes.h:722
TypeName * typeName
Definition: parsenodes.h:723
char generated
Definition: parsenodes.h:736
char storage
Definition: parsenodes.h:729
bool is_local
Definition: parsenodes.h:726
char * compression
Definition: parsenodes.h:724
bool has_not_null
Definition: tupdesc.h:44
AttrDefault * defval
Definition: tupdesc.h:39
bool has_generated_stored
Definition: tupdesc.h:45
struct AttrMissing * missing
Definition: tupdesc.h:41
ConstrCheck * check
Definition: tupdesc.h:40
uint16 num_defval
Definition: tupdesc.h:42
uint16 num_check
Definition: tupdesc.h:43
TupleConstr * constr
Definition: tupdesc.h:85
bool setof
Definition: parsenodes.h:269
List * arrayBounds
Definition: parsenodes.h:273
static char GetAttributeCompression(Oid atttypid, const char *compression)
Definition: tablecmds.c:20533
static char GetAttributeStorage(Oid atttypid, const char *storagemode)
Definition: tablecmds.c:20571
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:67
void TupleDescInitEntryCollation(TupleDesc desc, AttrNumber attributeNumber, Oid collationid)
Definition: tupdesc.c:833
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:651
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

References ACL_USAGE, aclcheck_error_type(), ACLCHECK_OK, TypeName::arrayBounds, attname, attnum, TupleConstr::check, ColumnDef::colname, ColumnDef::compression, TupleDescData::constr, CreateTemplateTupleDesc(), TupleConstr::defval, ereport, errcode(), errmsg(), ERROR, ColumnDef::generated, GetAttributeCompression(), GetAttributeStorage(), GetColumnDefCollation(), GetUserId(), TupleConstr::has_generated_stored, TupleConstr::has_not_null, ColumnDef::identity, ColumnDef::inhcount, ColumnDef::is_local, ColumnDef::is_not_null, lfirst, list_length(), TupleConstr::missing, TupleConstr::num_check, TupleConstr::num_defval, object_aclcheck(), palloc0(), PG_INT16_MAX, TypeName::setof, ColumnDef::storage, ColumnDef::storage_name, TupleDescAttr, TupleDescInitEntry(), TupleDescInitEntryCollation(), ColumnDef::typeName, and typenameTypeIdAndMod().

Referenced by ATExecAddColumn(), DefineRelation(), and DefineVirtualRelation().

◆ check_of_type()

void check_of_type ( HeapTuple  typetuple)

Definition at line 6959 of file tablecmds.c.

6960 {
6961  Form_pg_type typ = (Form_pg_type) GETSTRUCT(typetuple);
6962  bool typeOk = false;
6963 
6964  if (typ->typtype == TYPTYPE_COMPOSITE)
6965  {
6966  Relation typeRelation;
6967 
6968  Assert(OidIsValid(typ->typrelid));
6969  typeRelation = relation_open(typ->typrelid, AccessShareLock);
6970  typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
6971 
6972  /*
6973  * Close the parent rel, but keep our AccessShareLock on it until xact
6974  * commit. That will prevent someone else from deleting or ALTERing
6975  * the type before the typed table creation/conversion commits.
6976  */
6977  relation_close(typeRelation, NoLock);
6978  }
6979  if (!typeOk)
6980  ereport(ERROR,
6981  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6982  errmsg("type %s is not a composite type",
6983  format_type_be(typ->oid))));
6984 }
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261

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

Referenced by ATExecAddOf(), and transformOfType().

◆ CheckRelationTableSpaceMove()

bool CheckRelationTableSpaceMove ( Relation  rel,
Oid  newTableSpaceId 
)

Definition at line 3615 of file tablecmds.c.

3616 {
3617  Oid oldTableSpaceId;
3618 
3619  /*
3620  * No work if no change in tablespace. Note that MyDatabaseTableSpace is
3621  * stored as 0.
3622  */
3623  oldTableSpaceId = rel->rd_rel->reltablespace;
3624  if (newTableSpaceId == oldTableSpaceId ||
3625  (newTableSpaceId == MyDatabaseTableSpace && oldTableSpaceId == 0))
3626  return false;
3627 
3628  /*
3629  * We cannot support moving mapped relations into different tablespaces.
3630  * (In particular this eliminates all shared catalogs.)
3631  */
3632  if (RelationIsMapped(rel))
3633  ereport(ERROR,
3634  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3635  errmsg("cannot move system relation \"%s\"",
3636  RelationGetRelationName(rel))));
3637 
3638  /* Cannot move a non-shared relation into pg_global */
3639  if (newTableSpaceId == GLOBALTABLESPACE_OID)
3640  ereport(ERROR,
3641  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3642  errmsg("only shared relations can be placed in pg_global tablespace")));
3643 
3644  /*
3645  * Do not allow moving temp tables of other backends ... their local
3646  * buffer manager is not going to cope.
3647  */
3648  if (RELATION_IS_OTHER_TEMP(rel))
3649  ereport(ERROR,
3650  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3651  errmsg("cannot move temporary tables of other sessions")));
3652 
3653  return true;
3654 }
#define RelationIsMapped(relation)
Definition: rel.h:554
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:658

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

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

◆ CheckTableNotInUse()

void CheckTableNotInUse ( Relation  rel,
const char *  stmt 
)

Definition at line 4332 of file tablecmds.c.

4333 {
4334  int expected_refcnt;
4335 
4336  expected_refcnt = rel->rd_isnailed ? 2 : 1;
4337  if (rel->rd_refcnt != expected_refcnt)
4338  ereport(ERROR,
4339  (errcode(ERRCODE_OBJECT_IN_USE),
4340  /* translator: first %s is a SQL command, eg ALTER TABLE */
4341  errmsg("cannot %s \"%s\" because it is being used by active queries in this session",
4342  stmt, RelationGetRelationName(rel))));
4343 
4344  if (rel->rd_rel->relkind != RELKIND_INDEX &&
4345  rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
4347  ereport(ERROR,
4348  (errcode(ERRCODE_OBJECT_IN_USE),
4349  /* translator: first %s is a SQL command, eg ALTER TABLE */
4350  errmsg("cannot %s \"%s\" because it has pending trigger events",
4351  stmt, RelationGetRelationName(rel))));
4352 }
int rd_refcnt
Definition: rel.h:59
bool rd_isnailed
Definition: rel.h:62
bool AfterTriggerPendingOnRel(Oid relid)
Definition: trigger.c:5974

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

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

◆ DefineRelation()

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

Definition at line 683 of file tablecmds.c.

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

References AccessExclusiveLock, AccessShareLock, ACL_CREATE, ACL_USAGE, aclcheck_error(), aclcheck_error_type(), ACLCHECK_OK, addNSItemToQuery(), addRangeTableEntryForRelation(), AddRelationNewConstraints(), AddRelationNotNullConstraints(), allowSystemTableMods, Assert(), RawColumnDefault::attnum, CookedConstraint::attnum, attnum, build_attrmap_by_name(), BuildDescForRelation(), check_default_partition_contents(), check_new_partition_bound(), CloneForeignKeyConstraints(), CloneRowTriggersToPartition(), CommandCounterIncrement(), ComputePartitionAttrs(), CookedConstraint::conoid, CONSTR_DEFAULT, CookedConstraint::contype, ColumnDef::cooked_default, default_table_access_method, DefineIndex(), elog, ereport, errcode(), errdetail(), errmsg(), ERROR, CookedConstraint::expr, 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(), GetDefaultTablespace(), GetUserId(), heap_create_with_catalog(), HEAP_RELOPT_NAMESPACES, heap_reloptions(), index_close(), index_open(), CookedConstraint::inhcount, InSecurityRestrictedOperation(), InvalidOid, CookedConstraint::is_local, CookedConstraint::is_no_inherit, lappend(), lappend_oid(), lfirst, lfirst_int, 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_aclcheck(), OBJECT_TABLESPACE, ObjectAddressSet, OidIsValid, ONCOMMIT_NOOP, ParseState::p_sourcetext, palloc(), PARTITION_MAX_KEYS, partitioned_table_reloptions(), RangeVarGetAndCheckCreationNamespace(), RangeVarGetRelid, RawColumnDefault::raw_default, ColumnDef::raw_default, RelationData::rd_index, RelationData::rd_rel, relation_close(), relation_open(), RelationGetDescr, RelationGetIndexList(), RelationGetPartitionDesc(), RelationGetRelationName, RelationGetRelid, relname, set_attnotnull(), ShareUpdateExclusiveLock, CookedConstraint::skip_validation, stmt, StoreCatalogInheritance(), StorePartitionBound(), StorePartitionKey(), strlcpy(), table_close(), table_open(), transformPartitionBound(), transformPartitionSpec(), transformRelOptions(), RelationData::trigdesc, TupleDescAttr, typenameTypeId(), and view_reloptions().

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

◆ ExecuteTruncate()

void ExecuteTruncate ( TruncateStmt stmt)

Definition at line 1793 of file tablecmds.c.

1794 {
1795  List *rels = NIL;
1796  List *relids = NIL;
1797  List *relids_logged = NIL;
1798  ListCell *cell;
1799 
1800  /*
1801  * Open, exclusive-lock, and check all the explicitly-specified relations
1802  */
1803  foreach(cell, stmt->relations)
1804  {
1805  RangeVar *rv = lfirst(cell);
1806  Relation rel;
1807  bool recurse = rv->inh;
1808  Oid myrelid;
1809  LOCKMODE lockmode = AccessExclusiveLock;
1810 
1811  myrelid = RangeVarGetRelidExtended(rv, lockmode,
1813  NULL);
1814 
1815  /* don't throw error for "TRUNCATE foo, foo" */
1816  if (list_member_oid(relids, myrelid))
1817  continue;
1818 
1819  /* open the relation, we already hold a lock on it */
1820  rel = table_open(myrelid, NoLock);
1821 
1822  /*
1823  * RangeVarGetRelidExtended() has done most checks with its callback,
1824  * but other checks with the now-opened Relation remain.
1825  */
1827 
1828  rels = lappend(rels, rel);
1829  relids = lappend_oid(relids, myrelid);
1830 
1831  /* Log this relation only if needed for logical decoding */
1832  if (RelationIsLogicallyLogged(rel))
1833  relids_logged = lappend_oid(relids_logged, myrelid);
1834 
1835  if (recurse)
1836  {
1837  ListCell *child;
1838  List *children;
1839 
1840  children = find_all_inheritors(myrelid, lockmode, NULL);
1841 
1842  foreach(child, children)
1843  {
1844  Oid childrelid = lfirst_oid(child);
1845 
1846  if (list_member_oid(relids, childrelid))
1847  continue;
1848 
1849  /* find_all_inheritors already got lock */
1850  rel = table_open(childrelid, NoLock);
1851 
1852  /*
1853  * It is possible that the parent table has children that are
1854  * temp tables of other backends. We cannot safely access
1855  * such tables (because of buffering issues), and the best
1856  * thing to do is to silently ignore them. Note that this
1857  * check is the same as one of the checks done in
1858  * truncate_check_activity() called below, still it is kept
1859  * here for simplicity.
1860  */
1861  if (RELATION_IS_OTHER_TEMP(rel))
1862  {
1863  table_close(rel, lockmode);
1864  continue;
1865  }
1866 
1867  /*
1868  * Inherited TRUNCATE commands perform access permission
1869  * checks on the parent table only. So we skip checking the
1870  * children's permissions and don't call
1871  * truncate_check_perms() here.
1872  */
1875 
1876  rels = lappend(rels, rel);
1877  relids = lappend_oid(relids, childrelid);
1878 
1879  /* Log this relation only if needed for logical decoding */
1880  if (RelationIsLogicallyLogged(rel))
1881  relids_logged = lappend_oid(relids_logged, childrelid);
1882  }
1883  }
1884  else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1885  ereport(ERROR,
1886  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1887  errmsg("cannot truncate only a partitioned table"),
1888  errhint("Do not specify the ONLY keyword, or use TRUNCATE ONLY on the partitions directly.")));
1889  }
1890 
1891  ExecuteTruncateGuts(rels, relids, relids_logged,
1892  stmt->behavior, stmt->restart_seqs, false);
1893 
1894  /* And close the rels */
1895  foreach(cell, rels)
1896  {
1897  Relation rel = (Relation) lfirst(cell);
1898 
1899  table_close(rel, NoLock);
1900  }
1901 }
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:255
#define RelationIsLogicallyLogged(relation)
Definition: rel.h:701
struct RelationData * Relation
Definition: relcache.h:27
bool inh
Definition: primnodes.h:85
static void truncate_check_activity(Relation rel)
Definition: tablecmds.c:2370
static void truncate_check_rel(Oid relid, Form_pg_class reltuple)
Definition: tablecmds.c:2304
static void RangeVarCallbackForTruncate(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:18141
void ExecuteTruncateGuts(List *explicit_rels, List *relids, List *relids_logged, DropBehavior behavior, bool restart_seqs, bool run_as_table_owner)
Definition: tablecmds.c:1917

References AccessExclusiveLock, ereport, errcode(), errhint(), errmsg(), ERROR, ExecuteTruncateGuts(), find_all_inheritors(), RangeVar::inh, lappend(), lappend_oid(), lfirst, lfirst_oid, list_member_oid(), NIL, NoLock, RangeVarCallbackForTruncate(), RangeVarGetRelidExtended(), RelationData::rd_rel, RELATION_IS_OTHER_TEMP, RelationGetRelid, RelationIsLogicallyLogged, stmt, table_close(), table_open(), truncate_check_activity(), and truncate_check_rel().

Referenced by standard_ProcessUtility().

◆ ExecuteTruncateGuts()

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

Definition at line 1917 of file tablecmds.c.

1922 {
1923  List *rels;
1924  List *seq_relids = NIL;
1925  HTAB *ft_htab = NULL;
1926  EState *estate;
1927  ResultRelInfo *resultRelInfos;
1928  ResultRelInfo *resultRelInfo;
1929  SubTransactionId mySubid;
1930  ListCell *cell;
1931  Oid *logrelids;
1932 
1933  /*
1934  * Check the explicitly-specified relations.
1935  *
1936  * In CASCADE mode, suck in all referencing relations as well. This
1937  * requires multiple iterations to find indirectly-dependent relations. At
1938  * each phase, we need to exclusive-lock new rels before looking for their
1939  * dependencies, else we might miss something. Also, we check each rel as
1940  * soon as we open it, to avoid a faux pas such as holding lock for a long
1941  * time on a rel we have no permissions for.
1942  */
1943  rels = list_copy(explicit_rels);
1944  if (behavior == DROP_CASCADE)
1945  {
1946  for (;;)
1947  {
1948  List *newrelids;
1949 
1950  newrelids = heap_truncate_find_FKs(relids);
1951  if (newrelids == NIL)
1952  break; /* nothing else to add */
1953 
1954  foreach(cell, newrelids)
1955  {
1956  Oid relid = lfirst_oid(cell);
1957  Relation rel;
1958 
1959  rel = table_open(relid, AccessExclusiveLock);
1960  ereport(NOTICE,
1961  (errmsg("truncate cascades to table \"%s\"",
1962  RelationGetRelationName(rel))));
1963  truncate_check_rel(relid, rel->rd_rel);
1964  truncate_check_perms(relid, rel->rd_rel);
1966  rels = lappend(rels, rel);
1967  relids = lappend_oid(relids, relid);
1968 
1969  /* Log this relation only if needed for logical decoding */
1970  if (RelationIsLogicallyLogged(rel))
1971  relids_logged = lappend_oid(relids_logged, relid);
1972  }
1973  }
1974  }
1975 
1976  /*
1977  * Check foreign key references. In CASCADE mode, this should be
1978  * unnecessary since we just pulled in all the references; but as a
1979  * cross-check, do it anyway if in an Assert-enabled build.
1980  */
1981 #ifdef USE_ASSERT_CHECKING
1982  heap_truncate_check_FKs(rels, false);
1983 #else
1984  if (behavior == DROP_RESTRICT)
1985  heap_truncate_check_FKs(rels, false);
1986 #endif
1987 
1988  /*
1989  * If we are asked to restart sequences, find all the sequences, lock them
1990  * (we need AccessExclusiveLock for ResetSequence), and check permissions.
1991  * We want to do this early since it's pointless to do all the truncation
1992  * work only to fail on sequence permissions.
1993  */
1994  if (restart_seqs)
1995  {
1996  foreach(cell, rels)
1997  {
1998  Relation rel = (Relation) lfirst(cell);
1999  List *seqlist = getOwnedSequences(RelationGetRelid(rel));
2000  ListCell *seqcell;
2001 
2002  foreach(seqcell, seqlist)
2003  {
2004  Oid seq_relid = lfirst_oid(seqcell);
2005  Relation seq_rel;
2006 
2007  seq_rel = relation_open(seq_relid, AccessExclusiveLock);
2008 
2009  /* This check must match AlterSequence! */
2010  if (!object_ownercheck(RelationRelationId, seq_relid, GetUserId()))
2012  RelationGetRelationName(seq_rel));
2013 
2014  seq_relids = lappend_oid(seq_relids, seq_relid);
2015 
2016  relation_close(seq_rel, NoLock);
2017  }
2018  }
2019  }
2020 
2021  /* Prepare to catch AFTER triggers. */
2023 
2024  /*
2025  * To fire triggers, we'll need an EState as well as a ResultRelInfo for
2026  * each relation. We don't need to call ExecOpenIndices, though.
2027  *
2028  * We put the ResultRelInfos in the es_opened_result_relations list, even
2029  * though we don't have a range table and don't populate the
2030  * es_result_relations array. That's a bit bogus, but it's enough to make
2031  * ExecGetTriggerResultRel() find them.
2032  */
2033  estate = CreateExecutorState();
2034  resultRelInfos = (ResultRelInfo *)
2035  palloc(list_length(rels) * sizeof(ResultRelInfo));
2036  resultRelInfo = resultRelInfos;
2037  foreach(cell, rels)
2038  {
2039  Relation rel = (Relation) lfirst(cell);
2040 
2041  InitResultRelInfo(resultRelInfo,
2042  rel,
2043  0, /* dummy rangetable index */
2044  NULL,
2045  0);
2046  estate->es_opened_result_relations =
2047  lappend(estate->es_opened_result_relations, resultRelInfo);
2048  resultRelInfo++;
2049  }
2050 
2051  /*
2052  * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
2053  * truncating (this is because one of them might throw an error). Also, if
2054  * we were to allow them to prevent statement execution, that would need
2055  * to be handled here.
2056  */
2057  resultRelInfo = resultRelInfos;
2058  foreach(cell, rels)
2059  {
2060  UserContext ucxt;
2061 
2062  if (run_as_table_owner)
2063  SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
2064  &ucxt);
2065  ExecBSTruncateTriggers(estate, resultRelInfo);
2066  if (run_as_table_owner)
2067  RestoreUserContext(&ucxt);
2068  resultRelInfo++;
2069  }
2070 
2071  /*
2072  * OK, truncate each table.
2073  */
2074  mySubid = GetCurrentSubTransactionId();
2075 
2076  foreach(cell, rels)
2077  {
2078  Relation rel = (Relation) lfirst(cell);
2079 
2080  /* Skip partitioned tables as there is nothing to do */
2081  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2082  continue;
2083 
2084  /*
2085  * Build the lists of foreign tables belonging to each foreign server
2086  * and pass each list to the foreign data wrapper's callback function,
2087  * so that each server can truncate its all foreign tables in bulk.
2088  * Each list is saved as a single entry in a hash table that uses the
2089  * server OID as lookup key.
2090  */
2091  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2092  {
2094  bool found;
2095  ForeignTruncateInfo *ft_info;
2096 
2097  /* First time through, initialize hashtable for foreign tables */
2098  if (!ft_htab)
2099  {
2100  HASHCTL hctl;
2101 
2102  memset(&hctl, 0, sizeof(HASHCTL));
2103  hctl.keysize = sizeof(Oid);
2104  hctl.entrysize = sizeof(ForeignTruncateInfo);
2105  hctl.hcxt = CurrentMemoryContext;
2106 
2107  ft_htab = hash_create("TRUNCATE for Foreign Tables",
2108  32, /* start small and extend */
2109  &hctl,
2111  }
2112 
2113  /* Find or create cached entry for the foreign table */
2114  ft_info = hash_search(ft_htab, &serverid, HASH_ENTER, &found);
2115  if (!found)
2116  ft_info->rels = NIL;
2117 
2118  /*
2119  * Save the foreign table in the entry of the server that the
2120  * foreign table belongs to.
2121  */
2122  ft_info->rels = lappend(ft_info->rels, rel);
2123  continue;
2124  }
2125 
2126  /*
2127  * Normally, we need a transaction-safe truncation here. However, if
2128  * the table was either created in the current (sub)transaction or has
2129  * a new relfilenumber in the current (sub)transaction, then we can
2130  * just truncate it in-place, because a rollback would cause the whole
2131  * table or the current physical file to be thrown away anyway.
2132  */
2133  if (rel->rd_createSubid == mySubid ||
2134  rel->rd_newRelfilelocatorSubid == mySubid)
2135  {
2136  /* Immediate, non-rollbackable truncation is OK */
2137  heap_truncate_one_rel(rel);
2138  }
2139  else
2140  {
2141  Oid heap_relid;
2142  Oid toast_relid;
2143  ReindexParams reindex_params = {0};
2144 
2145  /*
2146  * This effectively deletes all rows in the table, and may be done
2147  * in a serializable transaction. In that case we must record a
2148  * rw-conflict in to this transaction from each transaction
2149  * holding a predicate lock on the table.
2150  */
2152 
2153  /*
2154  * Need the full transaction-safe pushups.
2155  *
2156  * Create a new empty storage file for the relation, and assign it
2157  * as the relfilenumber value. The old storage file is scheduled
2158  * for deletion at commit.
2159  */
2160  RelationSetNewRelfilenumber(rel, rel->rd_rel->relpersistence);
2161 
2162  heap_relid = RelationGetRelid(rel);
2163 
2164  /*
2165  * The same for the toast table, if any.
2166  */
2167  toast_relid = rel->rd_rel->reltoastrelid;
2168  if (OidIsValid(toast_relid))
2169  {
2170  Relation toastrel = relation_open(toast_relid,
2172 
2173  RelationSetNewRelfilenumber(toastrel,
2174  toastrel->rd_rel->relpersistence);
2175  table_close(toastrel, NoLock);
2176  }
2177 
2178  /*
2179  * Reconstruct the indexes to match, and we're done.
2180  */
2181  reindex_relation(NULL, heap_relid, REINDEX_REL_PROCESS_TOAST,
2182  &reindex_params);
2183  }
2184 
2185  pgstat_count_truncate(rel);
2186  }
2187 
2188  /* Now go through the hash table, and truncate foreign tables */
2189  if (ft_htab)
2190  {
2191  ForeignTruncateInfo *ft_info;
2192  HASH_SEQ_STATUS seq;
2193 
2194  hash_seq_init(&seq, ft_htab);
2195 
2196  PG_TRY();
2197  {
2198  while ((ft_info = hash_seq_search(&seq)) != NULL)
2199  {
2200  FdwRoutine *routine = GetFdwRoutineByServerId(ft_info->serverid);
2201 
2202  /* truncate_check_rel() has checked that already */
2203  Assert(routine->ExecForeignTruncate != NULL);
2204 
2205  routine->ExecForeignTruncate(ft_info->rels,
2206  behavior,
2207  restart_seqs);
2208  }
2209  }
2210  PG_FINALLY();
2211  {
2212  hash_destroy(ft_htab);
2213  }
2214  PG_END_TRY();
2215  }
2216 
2217  /*
2218  * Restart owned sequences if we were asked to.
2219  */
2220  foreach(cell, seq_relids)
2221  {
2222  Oid seq_relid = lfirst_oid(cell);
2223 
2224  ResetSequence(seq_relid);
2225  }
2226 
2227  /*
2228  * Write a WAL record to allow this set of actions to be logically
2229  * decoded.
2230  *
2231  * Assemble an array of relids so we can write a single WAL record for the
2232  * whole action.
2233  */
2234  if (relids_logged != NIL)
2235  {
2236  xl_heap_truncate xlrec;
2237  int i = 0;
2238 
2239  /* should only get here if wal_level >= logical */
2241 
2242  logrelids = palloc(list_length(relids_logged) * sizeof(Oid));
2243  foreach(cell, relids_logged)
2244  logrelids[i++] = lfirst_oid(cell);
2245 
2246  xlrec.dbId = MyDatabaseId;
2247  xlrec.nrelids = list_length(relids_logged);
2248  xlrec.flags = 0;
2249  if (behavior == DROP_CASCADE)
2250  xlrec.flags |= XLH_TRUNCATE_CASCADE;
2251  if (restart_seqs)
2253 
2254  XLogBeginInsert();
2255  XLogRegisterData((char *) &xlrec, SizeOfHeapTruncate);
2256  XLogRegisterData((char *) logrelids, list_length(relids_logged) * sizeof(Oid));
2257 
2259 
2260  (void) XLogInsert(RM_HEAP_ID, XLOG_HEAP_TRUNCATE);
2261  }
2262 
2263  /*
2264  * Process all AFTER STATEMENT TRUNCATE triggers.
2265  */
2266  resultRelInfo = resultRelInfos;
2267  foreach(cell, rels)
2268  {
2269  UserContext ucxt;
2270 
2271  if (run_as_table_owner)
2272  SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
2273  &ucxt);
2274  ExecASTruncateTriggers(estate, resultRelInfo);
2275  if (run_as_table_owner)
2276  RestoreUserContext(&ucxt);
2277  resultRelInfo++;
2278  }
2279 
2280  /* Handle queued AFTER triggers */
2281  AfterTriggerEndQuery(estate);
2282 
2283  /* We can clean up the EState now */
2284  FreeExecutorState(estate);
2285 
2286  /*
2287  * Close any rels opened by CASCADE (can't do this while EState still
2288  * holds refs)
2289  */
2290  rels = list_difference_ptr(rels, explicit_rels);
2291  foreach(cell, rels)
2292  {
2293  Relation rel = (Relation) lfirst(cell);
2294 
2295  table_close(rel, NoLock);
2296  }
2297 }
uint32 SubTransactionId
Definition: c.h:643
void ResetSequence(Oid seq_relid)
Definition: sequence.c:262
void hash_destroy(HTAB *hashp)
Definition: dynahash.c:865
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:955
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:352
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1395
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1385
#define PG_TRY(...)
Definition: elog.h:370
#define PG_END_TRY(...)
Definition: elog.h:395
#define PG_FINALLY(...)
Definition: elog.h:387
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, ResultRelInfo *partition_root_rri, int instrument_options)
Definition: execMain.c:1199
EState * CreateExecutorState(void)
Definition: execUtils.c:88
void FreeExecutorState(EState *estate)
Definition: execUtils.c:189
struct ResultRelInfo ResultRelInfo
Oid GetForeignServerIdByRelId(Oid relid)
Definition: foreign.c:345
FdwRoutine * GetFdwRoutineByServerId(Oid serverid)
Definition: foreign.c:367
Oid MyDatabaseId
Definition: globals.c:91
List * heap_truncate_find_FKs(List *relationIds)
Definition: heap.c:3529
void heap_truncate_check_FKs(List *relations, bool tempTables)
Definition: heap.c:3434
void heap_truncate_one_rel(Relation rel)
Definition: heap.c:3390
#define XLOG_HEAP_TRUNCATE
Definition: heapam_xlog.h:35
#define XLH_TRUNCATE_RESTART_SEQS
Definition: heapam_xlog.h:121
#define SizeOfHeapTruncate
Definition: heapam_xlog.h:136
#define XLH_TRUNCATE_CASCADE
Definition: heapam_xlog.h:120
@ HASH_ENTER
Definition: hsearch.h:114
#define HASH_CONTEXT
Definition: hsearch.h:102
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params)
Definition: index.c:3885
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:159
List * list_difference_ptr(const List *list1, const List *list2)
Definition: list.c:1263
List * list_copy(const List *oldlist)
Definition: list.c:1573
MemoryContext CurrentMemoryContext
Definition: mcxt.c:131
@ DROP_CASCADE
Definition: parsenodes.h:2183
@ DROP_RESTRICT
Definition: parsenodes.h:2182
@ OBJECT_SEQUENCE
Definition: parsenodes.h:2146
List * getOwnedSequences(Oid relid)
Definition: pg_depend.c:935
void pgstat_count_truncate(Relation rel)
void CheckTableForSerializableConflictIn(Relation relation)
Definition: predicate.c:4399
void RelationSetNewRelfilenumber(Relation relation, char persistence)
Definition: relcache.c:3719
List * es_opened_result_relations
Definition: execnodes.h:643
ExecForeignTruncate_function ExecForeignTruncate
Definition: fdwapi.h:263
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76
MemoryContext hcxt
Definition: hsearch.h:86
Definition: dynahash.c:220
SubTransactionId rd_newRelfilelocatorSubid
Definition: rel.h:104
SubTransactionId rd_createSubid
Definition: rel.h:103
Relation ri_RelationDesc
Definition: execnodes.h:456
struct ForeignTruncateInfo ForeignTruncateInfo
static void truncate_check_perms(Oid relid, Form_pg_class reltuple)
Definition: tablecmds.c:2352
void ExecBSTruncateTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:3222
void ExecASTruncateTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:3269
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:5038
void AfterTriggerBeginQuery(void)
Definition: trigger.c:5018
void SwitchToUntrustedUser(Oid userid, UserContext *context)
Definition: usercontext.c:33
void RestoreUserContext(UserContext *context)
Definition: usercontext.c:87
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:781
#define XLogLogicalInfoActive()
Definition: xlog.h:124
#define XLOG_INCLUDE_ORIGIN
Definition: xlog.h:152
void XLogRegisterData(char *data, uint32 len)
Definition: xloginsert.c:364
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:474
void XLogSetRecordFlags(uint8 flags)
Definition: xloginsert.c:456
void XLogBeginInsert(void)
Definition: xloginsert.c:149

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

Referenced by apply_handle_truncate(), and ExecuteTruncate().

◆ find_composite_type_dependencies()

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

Definition at line 6752 of file tablecmds.c.

6754 {
6755  Relation depRel;
6756  ScanKeyData key[2];
6757  SysScanDesc depScan;
6758  HeapTuple depTup;
6759 
6760  /* since this function recurses, it could be driven to stack overflow */
6762 
6763  /*
6764  * We scan pg_depend to find those things that depend on the given type.
6765  * (We assume we can ignore refobjsubid for a type.)
6766  */
6767  depRel = table_open(DependRelationId, AccessShareLock);
6768 
6769  ScanKeyInit(&key[0],
6770  Anum_pg_depend_refclassid,
6771  BTEqualStrategyNumber, F_OIDEQ,
6772  ObjectIdGetDatum(TypeRelationId));
6773  ScanKeyInit(&key[1],
6774  Anum_pg_depend_refobjid,
6775  BTEqualStrategyNumber, F_OIDEQ,
6776  ObjectIdGetDatum(typeOid));
6777 
6778  depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
6779  NULL, 2, key);
6780 
6781  while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
6782  {
6783  Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
6784  Relation rel;
6785  TupleDesc tupleDesc;
6786  Form_pg_attribute att;
6787 
6788  /* Check for directly dependent types */
6789  if (pg_depend->classid == TypeRelationId)
6790  {
6791  /*
6792  * This must be an array, domain, or range containing the given
6793  * type, so recursively check for uses of this type. Note that
6794  * any error message will mention the original type not the
6795  * container; this is intentional.
6796  */
6797  find_composite_type_dependencies(pg_depend->objid,
6798  origRelation, origTypeName);
6799  continue;
6800  }
6801 
6802  /* Else, ignore dependees that aren't relations */
6803  if (pg_depend->classid != RelationRelationId)
6804  continue;
6805 
6806  rel = relation_open(pg_depend->objid, AccessShareLock);
6807  tupleDesc = RelationGetDescr(rel);
6808 
6809  /*
6810  * If objsubid identifies a specific column, refer to that in error
6811  * messages. Otherwise, search to see if there's a user column of the
6812  * type. (We assume system columns are never of interesting types.)
6813  * The search is needed because an index containing an expression
6814  * column of the target type will just be recorded as a whole-relation
6815  * dependency. If we do not find a column of the type, the dependency
6816  * must indicate that the type is transiently referenced in an index
6817  * expression but not stored on disk, which we assume is OK, just as
6818  * we do for references in views. (It could also be that the target
6819  * type is embedded in some container type that is stored in an index
6820  * column, but the previous recursion should catch such cases.)
6821  */
6822  if (pg_depend->objsubid > 0 && pg_depend->objsubid <= tupleDesc->natts)
6823  att = TupleDescAttr(tupleDesc, pg_depend->objsubid - 1);
6824  else
6825  {
6826  att = NULL;
6827  for (int attno = 1; attno <= tupleDesc->natts; attno++)
6828  {
6829  att = TupleDescAttr(tupleDesc, attno - 1);
6830  if (att->atttypid == typeOid && !att->attisdropped)
6831  break;
6832  att = NULL;
6833  }
6834  if (att == NULL)
6835  {
6836  /* No such column, so assume OK */
6838  continue;
6839  }
6840  }
6841 
6842  /*
6843  * We definitely should reject if the relation has storage. If it's
6844  * partitioned, then perhaps we don't have to reject: if there are
6845  * partitions then we'll fail when we find one, else there is no
6846  * stored data to worry about. However, it's possible that the type
6847  * change would affect conclusions about whether the type is sortable
6848  * or hashable and thus (if it's a partitioning column) break the
6849  * partitioning rule. For now, reject for partitioned rels too.
6850  */
6851  if (RELKIND_HAS_STORAGE(rel->rd_rel->relkind) ||
6852  RELKIND_HAS_PARTITIONS(rel->rd_rel->relkind))
6853  {
6854  if (origTypeName)
6855  ereport(ERROR,
6856  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6857  errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
6858  origTypeName,
6860  NameStr(att->attname))));
6861  else if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
6862  ereport(ERROR,
6863  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6864  errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
6865  RelationGetRelationName(origRelation),
6867  NameStr(att->attname))));
6868  else if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
6869  ereport(ERROR,
6870  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6871  errmsg("cannot alter foreign table \"%s\" because column \"%s.%s\" uses its row type",
6872  RelationGetRelationName(origRelation),
6874  NameStr(att->attname))));
6875  else
6876  ereport(ERROR,
6877  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6878  errmsg("cannot alter table \"%s\" because column \"%s.%s\" uses its row type",
6879  RelationGetRelationName(origRelation),
6881  NameStr(att->attname))));
6882  }
6883  else if (OidIsValid(rel->rd_rel->reltype))
6884  {
6885  /*
6886  * A view or composite type itself isn't a problem, but we must
6887  * recursively check for indirect dependencies via its rowtype.
6888  */
6890  origRelation, origTypeName);
6891  }
6892 
6894  }
6895 
6896  systable_endscan(depScan);
6897 
6899 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:596
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:503
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:384
FormData_pg_depend * Form_pg_depend
Definition: pg_depend.h:72
void check_stack_depth(void)
Definition: postgres.c:3531
void find_composite_type_dependencies(Oid typeOid, Relation origRelation, const char *origTypeName)
Definition: tablecmds.c:6752

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

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

◆ PartConstraintImpliedByRelConstraint()

bool PartConstraintImpliedByRelConstraint ( Relation  scanrel,
List partConstraint 
)

Definition at line 18654 of file tablecmds.c.

18656 {
18657  List *existConstraint = NIL;
18658  TupleConstr *constr = RelationGetDescr(scanrel)->constr;
18659  int i;
18660 
18661  if (constr && constr->has_not_null)
18662  {
18663  int natts = scanrel->rd_att->natts;
18664 
18665  for (i = 1; i <= natts; i++)
18666  {
18667  Form_pg_attribute att = TupleDescAttr(scanrel->rd_att, i - 1);
18668 
18669  if (att->attnotnull && !att->attisdropped)
18670  {
18671  NullTest *ntest = makeNode(NullTest);
18672 
18673  ntest->arg = (Expr *) makeVar(1,
18674  i,
18675  att->atttypid,
18676  att->atttypmod,
18677  att->attcollation,
18678  0);
18679  ntest->nulltesttype = IS_NOT_NULL;
18680 
18681  /*
18682  * argisrow=false is correct even for a composite column,
18683  * because attnotnull does not represent a SQL-spec IS NOT
18684  * NULL test in such a case, just IS DISTINCT FROM NULL.
18685  */
18686  ntest->argisrow = false;
18687  ntest->location = -1;
18688  existConstraint = lappend(existConstraint, ntest);
18689  }
18690  }
18691  }
18692 
18693  return ConstraintImpliedByRelConstraint(scanrel, partConstraint, existConstraint);
18694 }
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
@ IS_NOT_NULL
Definition: primnodes.h:1715
NullTestType nulltesttype
Definition: primnodes.h:1722
int location
Definition: primnodes.h:1725
Expr * arg
Definition: primnodes.h:1721
TupleDesc rd_att
Definition: rel.h:112
static bool ConstraintImpliedByRelConstraint(Relation scanrel, List *testConstraint, List *provenConstraint)
Definition: tablecmds.c:18707

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

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

◆ PreCommit_on_commit_actions()

void PreCommit_on_commit_actions ( void  )

Definition at line 17931 of file tablecmds.c.

17932 {
17933  ListCell *l;
17934  List *oids_to_truncate = NIL;
17935  List *oids_to_drop = NIL;
17936 
17937  foreach(l, on_commits)
17938  {
17939  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
17940 
17941  /* Ignore entry if already dropped in this xact */
17943  continue;
17944 
17945  switch (oc->oncommit)
17946  {
17947  case ONCOMMIT_NOOP:
17949  /* Do nothing (there shouldn't be such entries, actually) */
17950  break;
17951  case ONCOMMIT_DELETE_ROWS:
17952 
17953  /*
17954  * If this transaction hasn't accessed any temporary
17955  * relations, we can skip truncating ON COMMIT DELETE ROWS
17956  * tables, as they must still be empty.
17957  */
17959  oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
17960  break;
17961  case ONCOMMIT_DROP:
17962  oids_to_drop = lappend_oid(oids_to_drop, oc->relid);
17963  break;
17964  }
17965  }
17966 
17967  /*
17968  * Truncate relations before dropping so that all dependencies between
17969  * relations are removed after they are worked on. Doing it like this
17970  * might be a waste as it is possible that a relation being truncated will
17971  * be dropped anyway due to its parent being dropped, but this makes the
17972  * code more robust because of not having to re-check that the relation
17973  * exists at truncation time.
17974  */
17975  if (oids_to_truncate != NIL)
17976  heap_truncate(oids_to_truncate);
17977 
17978  if (oids_to_drop != NIL)
17979  {
17980  ObjectAddresses *targetObjects = new_object_addresses();
17981 
17982  foreach(l, oids_to_drop)
17983  {
17984  ObjectAddress object;
17985 
17986  object.classId = RelationRelationId;
17987  object.objectId = lfirst_oid(l);
17988  object.objectSubId = 0;
17989 
17990  Assert(!object_address_present(&object, targetObjects));
17991 
17992  add_exact_object_address(&object, targetObjects);
17993  }
17994 
17995  /*
17996  * Object deletion might involve toast table access (to clean up
17997  * toasted catalog entries), so ensure we have a valid snapshot.
17998  */
18000 
18001  /*
18002  * Since this is an automatic drop, rather than one directly initiated
18003  * by the user, we pass the PERFORM_DELETION_INTERNAL flag.
18004  */
18005  performMultipleDeletions(targetObjects, DROP_CASCADE,
18007 
18009 
18010 #ifdef USE_ASSERT_CHECKING
18011 
18012  /*
18013  * Note that table deletion will call remove_on_commit_action, so the
18014  * entry should get marked as deleted.
18015  */
18016  foreach(l, on_commits)
18017  {
18018  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
18019 
18020  if (oc->oncommit != ONCOMMIT_DROP)
18021  continue;
18022 
18024  }
18025 #endif
18026  }
18027 }
void performMultipleDeletions(const ObjectAddresses *objects, DropBehavior behavior, int flags)
Definition: dependency.c:332
#define PERFORM_DELETION_QUIETLY
Definition: dependency.h:136
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:134
void heap_truncate(List *relids)
Definition: heap.c:3349
@ ONCOMMIT_DELETE_ROWS
Definition: primnodes.h:59
@ ONCOMMIT_PRESERVE_ROWS
Definition: primnodes.h:58
@ ONCOMMIT_DROP
Definition: primnodes.h:60
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:216
void PushActiveSnapshot(Snapshot snapshot)
Definition: snapmgr.c:648
void PopActiveSnapshot(void)
Definition: snapmgr.c:743
OnCommitAction oncommit
Definition: tablecmds.c:112
int MyXactFlags
Definition: xact.c:134
#define XACT_FLAGS_ACCESSEDTEMPNAMESPACE
Definition: xact.h:102

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

Referenced by CommitTransaction(), and PrepareTransaction().

◆ RangeVarCallbackMaintainsTable()

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

Definition at line 18105 of file tablecmds.c.

18107 {
18108  char relkind;
18109  AclResult aclresult;
18110 
18111  /* Nothing to do if the relation was not found. */
18112  if (!OidIsValid(relId))
18113  return;
18114 
18115  /*
18116  * If the relation does exist, check whether it's an index. But note that
18117  * the relation might have been dropped between the time we did the name
18118  * lookup and now. In that case, there's nothing to do.
18119  */
18120  relkind = get_rel_relkind(relId);
18121  if (!relkind)
18122  return;
18123  if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
18124  relkind != RELKIND_MATVIEW && relkind != RELKIND_PARTITIONED_TABLE)
18125  ereport(ERROR,
18126  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18127  errmsg("\"%s\" is not a table or materialized view", relation->relname)));
18128 
18129  /* Check permissions */
18130  aclresult = pg_class_aclcheck(relId, GetUserId(), ACL_MAINTAIN);
18131  if (aclresult != ACLCHECK_OK)
18132  aclcheck_error(aclresult,
18134  relation->relname);
18135 }
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4079
#define ACL_MAINTAIN
Definition: parsenodes.h:90
char * relname
Definition: primnodes.h:82

References ACL_MAINTAIN, aclcheck_error(), ACLCHECK_OK, ereport, errcode(), errmsg(), ERROR, get_rel_relkind(), get_relkind_objtype(), GetUserId(), OidIsValid, pg_class_aclcheck(), and RangeVar::relname.

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

◆ RangeVarCallbackOwnsRelation()

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

Definition at line 18165 of file tablecmds.c.

18167 {
18168  HeapTuple tuple;
18169 
18170  /* Nothing to do if the relation was not found. */
18171  if (!OidIsValid(relId))
18172  return;
18173 
18174  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
18175  if (!HeapTupleIsValid(tuple)) /* should not happen */
18176  elog(ERROR, "cache lookup failed for relation %u", relId);
18177 
18178  if (!object_ownercheck(RelationRelationId, relId, GetUserId()))
18180  relation->relname);
18181 
18182  if (!allowSystemTableMods &&
18183  IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
18184  ereport(ERROR,
18185  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
18186  errmsg("permission denied: \"%s\" is a system catalog",
18187  relation->relname)));
18188 
18189  ReleaseSysCache(tuple);
18190 }
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
Definition: catalog.c:85

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

Referenced by AlterSequence(), and ProcessUtilitySlow().

◆ register_on_commit_action()

void register_on_commit_action ( Oid  relid,
OnCommitAction  action 
)

Definition at line 17872 of file tablecmds.c.

17873 {
17874  OnCommitItem *oc;
17875  MemoryContext oldcxt;
17876 
17877  /*
17878  * We needn't bother registering the relation unless there is an ON COMMIT
17879  * action we need to take.
17880  */
17882  return;
17883 
17885 
17886  oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
17887  oc->relid = relid;
17888  oc->oncommit = action;
17891 
17892  /*
17893  * We use lcons() here so that ON COMMIT actions are processed in reverse
17894  * order of registration. That might not be essential but it seems
17895  * reasonable.
17896  */
17897  on_commits = lcons(oc, on_commits);
17898 
17899  MemoryContextSwitchTo(oldcxt);
17900 }
List * lcons(void *datum, List *list)
Definition: list.c:495
MemoryContext CacheMemoryContext
Definition: mcxt.c:140
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124

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

Referenced by heap_create_with_catalog().

◆ remove_on_commit_action()

void remove_on_commit_action ( Oid  relid)

Definition at line 17908 of file tablecmds.c.

17909 {
17910  ListCell *l;
17911 
17912  foreach(l, on_commits)
17913  {
17914  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
17915 
17916  if (oc->relid == relid)
17917  {
17919  break;
17920  }
17921  }
17922 }

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

Referenced by heap_drop_with_catalog().

◆ RemoveRelations()

void RemoveRelations ( DropStmt drop)

Definition at line 1470 of file tablecmds.c.

1471 {
1472  ObjectAddresses *objects;
1473  char relkind;
1474  ListCell *cell;
1475  int flags = 0;
1476  LOCKMODE lockmode = AccessExclusiveLock;
1477 
1478  /* DROP CONCURRENTLY uses a weaker lock, and has some restrictions */
1479  if (drop->concurrent)
1480  {
1481  /*
1482  * Note that for temporary relations this lock may get upgraded later
1483  * on, but as no other session can access a temporary relation, this
1484  * is actually fine.
1485  */
1486  lockmode = ShareUpdateExclusiveLock;
1487  Assert(drop->removeType == OBJECT_INDEX);
1488  if (list_length(drop->objects) != 1)
1489  ereport(ERROR,
1490  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1491  errmsg("DROP INDEX CONCURRENTLY does not support dropping multiple objects")));
1492  if (drop->behavior == DROP_CASCADE)
1493  ereport(ERROR,
1494  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1495  errmsg("DROP INDEX CONCURRENTLY does not support CASCADE")));
1496  }
1497 
1498  /*
1499  * First we identify all the relations, then we delete them in a single
1500  * performMultipleDeletions() call. This is to avoid unwanted DROP
1501  * RESTRICT errors if one of the relations depends on another.
1502  */
1503 
1504  /* Determine required relkind */
1505  switch (drop->removeType)
1506  {
1507  case OBJECT_TABLE:
1508  relkind = RELKIND_RELATION;
1509  break;
1510 
1511  case OBJECT_INDEX:
1512  relkind = RELKIND_INDEX;
1513  break;
1514 
1515  case OBJECT_SEQUENCE:
1516  relkind = RELKIND_SEQUENCE;
1517  break;
1518 
1519  case OBJECT_VIEW:
1520  relkind = RELKIND_VIEW;
1521  break;
1522 
1523  case OBJECT_MATVIEW:
1524  relkind = RELKIND_MATVIEW;
1525  break;
1526 
1527  case OBJECT_FOREIGN_TABLE:
1528  relkind = RELKIND_FOREIGN_TABLE;
1529  break;
1530 
1531  default:
1532  elog(ERROR, "unrecognized drop object type: %d",
1533  (int) drop->removeType);
1534  relkind = 0; /* keep compiler quiet */
1535  break;
1536  }
1537 
1538  /* Lock and validate each relation; build a list of object addresses */
1539  objects = new_object_addresses();
1540 
1541  foreach(cell, drop->objects)
1542  {
1543  RangeVar *rel = makeRangeVarFromNameList((List *) lfirst(cell));
1544  Oid relOid;
1545  ObjectAddress obj;
1547 
1548  /*
1549  * These next few steps are a great deal like relation_openrv, but we
1550  * don't bother building a relcache entry since we don't need it.
1551  *
1552  * Check for shared-cache-inval messages before trying to access the
1553  * relation. This is needed to cover the case where the name
1554  * identifies a rel that has been dropped and recreated since the
1555  * start of our transaction: if we don't flush the old syscache entry,
1556  * then we'll latch onto that entry and suffer an error later.
1557  */
1559 
1560  /* Look up the appropriate relation using namespace search. */
1561  state.expected_relkind = relkind;
1562  state.heap_lockmode = drop->concurrent ?
1564  /* We must initialize these fields to show that no locks are held: */
1565  state.heapOid = InvalidOid;
1566  state.partParentOid = InvalidOid;
1567 
1568  relOid = RangeVarGetRelidExtended(rel, lockmode, RVR_MISSING_OK,
1570  (void *) &state);
1571 
1572  /* Not there? */
1573  if (!OidIsValid(relOid))
1574  {
1575  DropErrorMsgNonExistent(rel, relkind, drop->missing_ok);
1576  continue;
1577  }
1578 
1579  /*
1580  * Decide if concurrent mode needs to be used here or not. The
1581  * callback retrieved the rel's persistence for us.
1582  */
1583  if (drop->concurrent &&
1584  state.actual_relpersistence != RELPERSISTENCE_TEMP)
1585  {
1586  Assert(list_length(drop->objects) == 1 &&
1587  drop->removeType == OBJECT_INDEX);
1589  }
1590 
1591  /*
1592  * Concurrent index drop cannot be used with partitioned indexes,
1593  * either.
1594  */
1595  if ((flags & PERFORM_DELETION_CONCURRENTLY) != 0 &&
1596  state.actual_relkind == RELKIND_PARTITIONED_INDEX)
1597  ereport(ERROR,
1598  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1599  errmsg("cannot drop partitioned index \"%s\" concurrently",
1600  rel->relname)));
1601 
1602  /*
1603  * If we're told to drop a partitioned index, we must acquire lock on
1604  * all the children of its parent partitioned table before proceeding.
1605  * Otherwise we'd try to lock the child index partitions before their
1606  * tables, leading to potential deadlock against other sessions that
1607  * will lock those objects in the other order.
1608  */
1609  if (state.actual_relkind == RELKIND_PARTITIONED_INDEX)
1610  (void) find_all_inheritors(state.heapOid,
1611  state.heap_lockmode,
1612  NULL);
1613 
1614  /* OK, we're ready to delete this one */
1615  obj.classId = RelationRelationId;
1616  obj.objectId = relOid;
1617  obj.objectSubId = 0;
1618 
1619  add_exact_object_address(&obj, objects);
1620  }
1621 
1622  performMultipleDeletions(objects, drop->behavior, flags);
1623 
1624  free_object_addresses(objects);
1625 }
#define PERFORM_DELETION_CONCURRENTLY
Definition: dependency.h:135
void AcceptInvalidationMessages(void)
Definition: inval.c:806
RangeVar * makeRangeVarFromNameList(const List *names)
Definition: namespace.c:3539
@ OBJECT_FOREIGN_TABLE
Definition: parsenodes.h:2127
@ OBJECT_VIEW
Definition: parsenodes.h:2160
bool missing_ok
Definition: parsenodes.h:3085
List * objects
Definition: parsenodes.h:3082
ObjectType removeType
Definition: parsenodes.h:3083
bool concurrent
Definition: parsenodes.h:3086
DropBehavior behavior
Definition: parsenodes.h:3084
Definition: regguts.h:323
static void DropErrorMsgNonExistent(RangeVar *rel, char rightkind, bool missing_ok)
Definition: tablecmds.c:1395
static void RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid, Oid oldRelOid, void *arg)
Definition: tablecmds.c:1634

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

Referenced by ExecDropStmt().

◆ renameatt()

ObjectAddress renameatt ( RenameStmt stmt)

Definition at line 3928 of file tablecmds.c.

3929 {
3930  Oid relid;
3932  ObjectAddress address;
3933 
3934  /* lock level taken here should match renameatt_internal */
3936  stmt->missing_ok ? RVR_MISSING_OK : 0,
3938  NULL);
3939 
3940  if (!OidIsValid(relid))
3941  {
3942  ereport(NOTICE,
3943  (errmsg("relation \"%s\" does not exist, skipping",
3944  stmt->relation->relname)));
3945  return InvalidObjectAddress;
3946  }
3947 
3948  attnum =
3949  renameatt_internal(relid,
3950  stmt->subname, /* old att name */
3951  stmt->newname, /* new att name */
3952  stmt->relation->inh, /* recursive? */
3953  false, /* recursing? */
3954  0, /* expected inhcount */
3955  stmt->behavior);
3956 
3957  ObjectAddressSubSet(address, RelationRelationId, relid, attnum);
3958 
3959  return address;
3960 }
#define ObjectAddressSubSet(addr, class_id, object_id, object_sub_id)
Definition: objectaddress.h:33
static AttrNumber renameatt_internal(Oid myrelid, const char *oldattname, const char *newattname, bool recurse, bool recursing, int expected_parents, DropBehavior behavior)
Definition: tablecmds.c:3763
static void RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:3908

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

Referenced by ExecRenameStmt().

◆ RenameConstraint()

ObjectAddress RenameConstraint ( RenameStmt stmt)

Definition at line 4075 of file tablecmds.c.

4076 {
4077  Oid relid = InvalidOid;
4078  Oid typid = InvalidOid;
4079 
4080  if (stmt->renameType == OBJECT_DOMCONSTRAINT)
4081  {
4082  Relation rel;
4083  HeapTuple tup;
4084 
4085  typid = typenameTypeId(NULL, makeTypeNameFromNameList(castNode(List, stmt->object)));
4086  rel = table_open(TypeRelationId, RowExclusiveLock);
4087  tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
4088  if (!HeapTupleIsValid(tup))
4089  elog(ERROR, "cache lookup failed for type %u", typid);
4090  checkDomainOwner(tup);
4091  ReleaseSysCache(tup);
4092  table_close(rel, NoLock);
4093  }
4094  else
4095  {
4096  /* lock level taken here should match rename_constraint_internal */
4098  stmt->missing_ok ? RVR_MISSING_OK : 0,
4100  NULL);
4101  if (!OidIsValid(relid))
4102  {
4103  ereport(NOTICE,
4104  (errmsg("relation \"%s\" does not exist, skipping",
4105  stmt->relation->relname)));
4106  return InvalidObjectAddress;
4107  }
4108  }
4109 
4110  return
4111  rename_constraint_internal(relid, typid,
4112  stmt->subname,
4113  stmt->newname,
4114  (stmt->relation &&
4115  stmt->relation->inh), /* recursive? */
4116  false, /* recursing? */
4117  0 /* expected inhcount */ );
4118 }
TypeName * makeTypeNameFromNameList(List *names)
Definition: makefuncs.c:458
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
@ OBJECT_DOMCONSTRAINT
Definition: parsenodes.h:2122
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:3966
void checkDomainOwner(HeapTuple tup)
Definition: typecmds.c:3415

References AccessExclusiveLock, castNode, checkDomainOwner(), elog, ereport, errmsg(), ERROR, HeapTupleIsValid, InvalidObjectAddress, InvalidOid, makeTypeNameFromNameList(), NoLock, NOTICE, OBJECT_DOMCONSTRAINT, ObjectIdGetDatum(), OidIsValid, RangeVarCallbackForRenameAttribute(), RangeVarGetRelidExtended(), ReleaseSysCache(), rename_constraint_internal(), RowExclusiveLock, RVR_MISSING_OK, SearchSysCache1(), stmt, table_close(), table_open(), and typenameTypeId().

Referenced by ExecRenameStmt().

◆ RenameRelation()

ObjectAddress RenameRelation ( RenameStmt stmt)

Definition at line 4125 of file tablecmds.c.

4126 {
4127  bool is_index_stmt = stmt->renameType == OBJECT_INDEX;
4128  Oid relid;
4129  ObjectAddress address;
4130 
4131  /*
4132  * Grab an exclusive lock on the target table, index, sequence, view,
4133  * materialized view, or foreign table, which we will NOT release until
4134  * end of transaction.
4135  *
4136  * Lock level used here should match RenameRelationInternal, to avoid lock
4137  * escalation. However, because ALTER INDEX can be used with any relation
4138  * type, we mustn't believe without verification.
4139  */
4140  for (;;)
4141  {
4142  LOCKMODE lockmode;
4143  char relkind;
4144  bool obj_is_index;
4145 
4146  lockmode = is_index_stmt ? ShareUpdateExclusiveLock : AccessExclusiveLock;
4147 
4148  relid = RangeVarGetRelidExtended(stmt->relation, lockmode,
4149  stmt->missing_ok ? RVR_MISSING_OK : 0,
4151  (void *) stmt);
4152 
4153  if (!OidIsValid(relid))
4154  {
4155  ereport(NOTICE,
4156  (errmsg("relation \"%s\" does not exist, skipping",
4157  stmt->relation->relname)));
4158  return InvalidObjectAddress;
4159  }
4160 
4161  /*
4162  * We allow mismatched statement and object types (e.g., ALTER INDEX
4163  * to rename a table), but we might've used the wrong lock level. If
4164  * that happens, retry with the correct lock level. We don't bother
4165  * if we already acquired AccessExclusiveLock with an index, however.
4166  */
4167  relkind = get_rel_relkind(relid);
4168  obj_is_index = (relkind == RELKIND_INDEX ||
4169  relkind == RELKIND_PARTITIONED_INDEX);
4170  if (obj_is_index || is_index_stmt == obj_is_index)
4171  break;
4172 
4173  UnlockRelationOid(relid, lockmode);
4174  is_index_stmt = obj_is_index;
4175  }
4176 
4177  /* Do the work */
4178  RenameRelationInternal(relid, stmt->newname, false, is_index_stmt);
4179 
4180  ObjectAddressSet(address, RelationRelationId, relid);
4181 
4182  return address;
4183 }
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:227
void RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
Definition: tablecmds.c:4189

References AccessExclusiveLock, ereport, errmsg(), get_rel_relkind(), InvalidObjectAddress, NOTICE, OBJECT_INDEX, ObjectAddressSet, OidIsValid, RangeVarCallbackForAlterRelation(), RangeVarGetRelidExtended(), RenameRelationInternal(), RVR_MISSING_OK, ShareUpdateExclusiveLock, stmt, and UnlockRelationOid().

Referenced by ExecRenameStmt().

◆ RenameRelationInternal()

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

Definition at line 4189 of file tablecmds.c.

4190 {
4191  Relation targetrelation;
4192  Relation relrelation; /* for RELATION relation */
4193  HeapTuple reltup;
4194  Form_pg_class relform;
4195  Oid namespaceId;
4196 
4197  /*
4198  * Grab a lock on the target relation, which we will NOT release until end
4199  * of transaction. We need at least a self-exclusive lock so that
4200  * concurrent DDL doesn't overwrite the rename if they start updating
4201  * while still seeing the old version. The lock also guards against
4202  * triggering relcache reloads in concurrent sessions, which might not
4203  * handle this information changing under them. For indexes, we can use a
4204  * reduced lock level because RelationReloadIndexInfo() handles indexes
4205  * specially.
4206  */
4207  targetrelation = relation_open(myrelid, is_index ? ShareUpdateExclusiveLock : AccessExclusiveLock);
4208  namespaceId = RelationGetNamespace(targetrelation);
4209 
4210  /*
4211  * Find relation's pg_class tuple, and make sure newrelname isn't in use.
4212  */
4213  relrelation = table_open(RelationRelationId, RowExclusiveLock);
4214 
4215  reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
4216  if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
4217  elog(ERROR, "cache lookup failed for relation %u", myrelid);
4218  relform = (Form_pg_class) GETSTRUCT(reltup);
4219 
4220  if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
4221  ereport(ERROR,
4222  (errcode(ERRCODE_DUPLICATE_TABLE),
4223  errmsg("relation \"%s\" already exists",
4224  newrelname)));
4225 
4226  /*
4227  * RenameRelation is careful not to believe the caller's idea of the
4228  * relation kind being handled. We don't have to worry about this, but
4229  * let's not be totally oblivious to it. We can process an index as
4230  * not-an-index, but not the other way around.
4231  */
4232  Assert(!is_index ||
4233  is_index == (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
4234  targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX));
4235 
4236  /*
4237  * Update pg_class tuple with new relname. (Scribbling on reltup is OK
4238  * because it's a copy...)
4239  */
4240  namestrcpy(&(relform->relname), newrelname);
4241 
4242  CatalogTupleUpdate(relrelation, &reltup->t_self, reltup);
4243 
4244  InvokeObjectPostAlterHookArg(RelationRelationId, myrelid, 0,
4245  InvalidOid, is_internal);
4246 
4247  heap_freetuple(reltup);
4248  table_close(relrelation, RowExclusiveLock);
4249 
4250  /*
4251  * Also rename the associated type, if any.
4252  */
4253  if (OidIsValid(targetrelation->rd_rel->reltype))
4254  RenameTypeInternal(targetrelation->rd_rel->reltype,
4255  newrelname, namespaceId);
4256 
4257  /*
4258  * Also rename the associated constraint, if any.
4259  */
4260  if (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
4261  targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
4262  {
4263  Oid constraintId = get_index_constraint(myrelid);
4264 
4265  if (OidIsValid(constraintId))
4266  RenameConstraintById(constraintId, newrelname);
4267  }
4268 
4269  /*
4270  * Close rel, but keep lock!
4271  */
4272  relation_close(targetrelation, NoLock);
4273 }
void namestrcpy(Name name, const char *str)
Definition: name.c:233
#define InvokeObjectPostAlterHookArg(classId, objectId, subId, auxiliaryId, is_internal)
Definition: objectaccess.h:200
void RenameConstraintById(Oid conId, const char *newname)
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:968
void RenameTypeInternal(Oid typeOid, const char *newTypeName, Oid typeNamespace)
Definition: pg_type.c:765

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

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

◆ ResetRelRewrite()

void ResetRelRewrite ( Oid  myrelid)

Definition at line 4279 of file tablecmds.c.

4280 {
4281  Relation relrelation; /* for RELATION relation */
4282  HeapTuple reltup;
4283  Form_pg_class relform;
4284 
4285  /*
4286  * Find relation's pg_class tuple.
4287  */
4288  relrelation = table_open(RelationRelationId, RowExclusiveLock);
4289 
4290  reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
4291  if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
4292  elog(ERROR, "cache lookup failed for relation %u", myrelid);
4293  relform = (Form_pg_class) GETSTRUCT(reltup);
4294 
4295  /*
4296  * Update pg_class tuple.
4297  */
4298  relform->relrewrite = InvalidOid;
4299 
4300  CatalogTupleUpdate(relrelation, &reltup->t_self, reltup);
4301 
4302  heap_freetuple(reltup);
4303  table_close(relrelation, RowExclusiveLock);
4304 }

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

Referenced by finish_heap_swap().

◆ SetRelationHasSubclass()

void SetRelationHasSubclass ( Oid  relationId,
bool  relhassubclass 
)

Definition at line 3574 of file tablecmds.c.

3575 {
3576  Relation relationRelation;
3577  HeapTuple tuple;
3578  Form_pg_class classtuple;
3579 
3580  /*
3581  * Fetch a modifiable copy of the tuple, modify it, update pg_class.
3582  */
3583  relationRelation = table_open(RelationRelationId, RowExclusiveLock);
3584  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
3585  if (!HeapTupleIsValid(tuple))
3586  elog(ERROR, "cache lookup failed for relation %u", relationId);
3587  classtuple = (Form_pg_class) GETSTRUCT(tuple);
3588 
3589  if (classtuple->relhassubclass != relhassubclass)
3590  {
3591  classtuple->relhassubclass = relhassubclass;
3592  CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
3593  }
3594  else
3595  {
3596  /* no need to change tuple, but force relcache rebuild anyway */
3598  }
3599 
3600  heap_freetuple(tuple);
3601  table_close(relationRelation, RowExclusiveLock);
3602 }
void CacheInvalidateRelcacheByTuple(HeapTuple classTuple)
Definition: inval.c:1396

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

Referenced by acquire_inherited_sample_rows(), index_create(), IndexSetParentIndex(), and StoreCatalogInheritance1().

◆ SetRelationTableSpace()

void SetRelationTableSpace ( Relation  rel,
Oid  newTableSpaceId,
RelFileNumber  newRelFilenumber 
)

Definition at line 3672 of file tablecmds.c.

3675 {
3676  Relation pg_class;
3677  HeapTuple tuple;
3678  Form_pg_class rd_rel;
3679  Oid reloid = RelationGetRelid(rel);
3680 
3681  Assert(CheckRelationTableSpaceMove(rel, newTableSpaceId));
3682 
3683  /* Get a modifiable copy of the relation's pg_class row. */
3684  pg_class = table_open(RelationRelationId, RowExclusiveLock);
3685 
3686  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(reloid));
3687  if (!HeapTupleIsValid(tuple))
3688  elog(ERROR, "cache lookup failed for relation %u", reloid);
3689  rd_rel = (Form_pg_class) GETSTRUCT(tuple);
3690 
3691  /* Update the pg_class row. */
3692  rd_rel->reltablespace = (newTableSpaceId == MyDatabaseTableSpace) ?
3693  InvalidOid : newTableSpaceId;
3694  if (RelFileNumberIsValid(newRelFilenumber))
3695  rd_rel->relfilenode = newRelFilenumber;
3696  CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
3697 
3698  /*
3699  * Record dependency on tablespace. This is only required for relations
3700  * that have no physical storage.
3701  */
3702  if (!RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
3703  changeDependencyOnTablespace(RelationRelationId, reloid,
3704  rd_rel->reltablespace);
3705 
3706  heap_freetuple(tuple);
3707  table_close(pg_class, RowExclusiveLock);
3708 }
void changeDependencyOnTablespace(Oid classId, Oid objectId, Oid newTablespaceId)
Definition: pg_shdepend.c:377
#define RelFileNumberIsValid(relnumber)
Definition: relpath.h:27
bool CheckRelationTableSpaceMove(Relation rel, Oid newTableSpaceId)
Definition: tablecmds.c:3615

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

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