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

17985 {
17986  HeapTuple classTup;
17987  Form_pg_class classForm;
17988  ObjectAddress thisobj;
17989  bool already_done = false;
17990 
17991  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
17992  if (!HeapTupleIsValid(classTup))
17993  elog(ERROR, "cache lookup failed for relation %u", relOid);
17994  classForm = (Form_pg_class) GETSTRUCT(classTup);
17995 
17996  Assert(classForm->relnamespace == oldNspOid);
17997 
17998  thisobj.classId = RelationRelationId;
17999  thisobj.objectId = relOid;
18000  thisobj.objectSubId = 0;
18001 
18002  /*
18003  * If the object has already been moved, don't move it again. If it's
18004  * already in the right place, don't move it, but still fire the object
18005  * access hook.
18006  */
18007  already_done = object_address_present(&thisobj, objsMoved);
18008  if (!already_done && oldNspOid != newNspOid)
18009  {
18010  /* check for duplicate name (more friendly than unique-index failure) */
18011  if (get_relname_relid(NameStr(classForm->relname),
18012  newNspOid) != InvalidOid)
18013  ereport(ERROR,
18014  (errcode(ERRCODE_DUPLICATE_TABLE),
18015  errmsg("relation \"%s\" already exists in schema \"%s\"",
18016  NameStr(classForm->relname),
18017  get_namespace_name(newNspOid))));
18018 
18019  /* classTup is a copy, so OK to scribble on */
18020  classForm->relnamespace = newNspOid;
18021 
18022  CatalogTupleUpdate(classRel, &classTup->t_self, classTup);
18023 
18024  /* Update dependency on schema if caller said so */
18025  if (hasDependEntry &&
18026  changeDependencyFor(RelationRelationId,
18027  relOid,
18028  NamespaceRelationId,
18029  oldNspOid,
18030  newNspOid) != 1)
18031  elog(ERROR, "could not change schema dependency for relation \"%s\"",
18032  NameStr(classForm->relname));
18033  }
18034  if (!already_done)
18035  {
18036  add_exact_object_address(&thisobj, objsMoved);
18037 
18038  InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
18039  }
18040 
18041  heap_freetuple(classTup);
18042 }
#define NameStr(name)
Definition: c.h:746
#define Assert(condition)
Definition: c.h:858
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2591
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2531
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
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3366
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1885
#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 4433 of file tablecmds.c.

4435 {
4436  Relation rel;
4437 
4438  /* Caller is required to provide an adequate lock. */
4439  rel = relation_open(context->relid, NoLock);
4440 
4441  CheckTableNotInUse(rel, "ALTER TABLE");
4442 
4443  ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
4444 }
#define stmt
Definition: indent_codes.h:59
#define NoLock
Definition: lockdefs.h:34
tree context
Definition: radixtree.h:1833
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:47
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:4346
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:4778

References ATController(), CheckTableNotInUse(), context, NoLock, relation_open(), and stmt.

Referenced by ProcessUtilitySlow().

◆ AlterTableGetLockLevel()

LOCKMODE AlterTableGetLockLevel ( List cmds)

Definition at line 4507 of file tablecmds.c.

4508 {
4509  /*
4510  * This only works if we read catalog tables using MVCC snapshots.
4511  */
4512  ListCell *lcmd;
4514 
4515  foreach(lcmd, cmds)
4516  {
4517  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
4518  LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
4519 
4520  switch (cmd->subtype)
4521  {
4522  /*
4523  * These subcommands rewrite the heap, so require full locks.
4524  */
4525  case AT_AddColumn: /* may rewrite heap, in some cases and visible
4526  * to SELECT */
4527  case AT_SetAccessMethod: /* must rewrite heap */
4528  case AT_SetTableSpace: /* must rewrite heap */
4529  case AT_AlterColumnType: /* must rewrite heap */
4530  cmd_lockmode = AccessExclusiveLock;
4531  break;
4532 
4533  /*
4534  * These subcommands may require addition of toast tables. If
4535  * we add a toast table to a table currently being scanned, we
4536  * might miss data added to the new toast table by concurrent
4537  * insert transactions.
4538  */
4539  case AT_SetStorage: /* may add toast tables, see
4540  * ATRewriteCatalogs() */
4541  cmd_lockmode = AccessExclusiveLock;
4542  break;
4543 
4544  /*
4545  * Removing constraints can affect SELECTs that have been
4546  * optimized assuming the constraint holds true. See also
4547  * CloneFkReferenced.
4548  */
4549  case AT_DropConstraint: /* as DROP INDEX */
4550  case AT_DropNotNull: /* may change some SQL plans */
4551  cmd_lockmode = AccessExclusiveLock;
4552  break;
4553 
4554  /*
4555  * Subcommands that may be visible to concurrent SELECTs
4556  */
4557  case AT_DropColumn: /* change visible to SELECT */
4558  case AT_AddColumnToView: /* CREATE VIEW */
4559  case AT_DropOids: /* used to equiv to DropColumn */
4560  case AT_EnableAlwaysRule: /* may change SELECT rules */
4561  case AT_EnableReplicaRule: /* may change SELECT rules */
4562  case AT_EnableRule: /* may change SELECT rules */
4563  case AT_DisableRule: /* may change SELECT rules */
4564  cmd_lockmode = AccessExclusiveLock;
4565  break;
4566 
4567  /*
4568  * Changing owner may remove implicit SELECT privileges
4569  */
4570  case AT_ChangeOwner: /* change visible to SELECT */
4571  cmd_lockmode = AccessExclusiveLock;
4572  break;
4573 
4574  /*
4575  * Changing foreign table options may affect optimization.
4576  */
4577  case AT_GenericOptions:
4579  cmd_lockmode = AccessExclusiveLock;
4580  break;
4581 
4582  /*
4583  * These subcommands affect write operations only.
4584  */
4585  case AT_EnableTrig:
4586  case AT_EnableAlwaysTrig:
4587  case AT_EnableReplicaTrig:
4588  case AT_EnableTrigAll:
4589  case AT_EnableTrigUser:
4590  case AT_DisableTrig:
4591  case AT_DisableTrigAll:
4592  case AT_DisableTrigUser:
4593  cmd_lockmode = ShareRowExclusiveLock;
4594  break;
4595 
4596  /*
4597  * These subcommands affect write operations only. XXX
4598  * Theoretically, these could be ShareRowExclusiveLock.
4599  */
4600  case AT_ColumnDefault:
4602  case AT_AlterConstraint:
4603  case AT_AddIndex: /* from ADD CONSTRAINT */
4604  case AT_AddIndexConstraint:
4605  case AT_ReplicaIdentity:
4606  case AT_SetNotNull:
4607  case AT_SetAttNotNull:
4608  case AT_EnableRowSecurity:
4609  case AT_DisableRowSecurity:
4610  case AT_ForceRowSecurity:
4611  case AT_NoForceRowSecurity:
4612  case AT_AddIdentity:
4613  case AT_DropIdentity:
4614  case AT_SetIdentity:
4615  case AT_SetExpression:
4616  case AT_DropExpression:
4617  case AT_SetCompression:
4618  cmd_lockmode = AccessExclusiveLock;
4619  break;
4620 
4621  case AT_AddConstraint:
4622  case AT_ReAddConstraint: /* becomes AT_AddConstraint */
4623  case AT_ReAddDomainConstraint: /* becomes AT_AddConstraint */
4624  if (IsA(cmd->def, Constraint))
4625  {
4626  Constraint *con = (Constraint *) cmd->def;
4627 
4628  switch (con->contype)
4629  {
4630  case CONSTR_EXCLUSION:
4631  case CONSTR_PRIMARY:
4632  case CONSTR_UNIQUE:
4633 
4634  /*
4635  * Cases essentially the same as CREATE INDEX. We
4636  * could reduce the lock strength to ShareLock if
4637  * we can work out how to allow concurrent catalog
4638  * updates. XXX Might be set down to
4639  * ShareRowExclusiveLock but requires further
4640  * analysis.
4641  */
4642  cmd_lockmode = AccessExclusiveLock;
4643  break;
4644  case CONSTR_FOREIGN:
4645 
4646  /*
4647  * We add triggers to both tables when we add a
4648  * Foreign Key, so the lock level must be at least
4649  * as strong as CREATE TRIGGER.
4650  */
4651  cmd_lockmode = ShareRowExclusiveLock;
4652  break;
4653 
4654  default:
4655  cmd_lockmode = AccessExclusiveLock;
4656  }
4657  }
4658  break;
4659 
4660  /*
4661  * These subcommands affect inheritance behaviour. Queries
4662  * started before us will continue to see the old inheritance
4663  * behaviour, while queries started after we commit will see
4664  * new behaviour. No need to prevent reads or writes to the
4665  * subtable while we hook it up though. Changing the TupDesc
4666  * may be a problem, so keep highest lock.
4667  */
4668  case AT_AddInherit:
4669  case AT_DropInherit:
4670  cmd_lockmode = AccessExclusiveLock;
4671  break;
4672 
4673  /*
4674  * These subcommands affect implicit row type conversion. They
4675  * have affects similar to CREATE/DROP CAST on queries. don't
4676  * provide for invalidating parse trees as a result of such
4677  * changes, so we keep these at AccessExclusiveLock.
4678  */
4679  case AT_AddOf:
4680  case AT_DropOf:
4681  cmd_lockmode = AccessExclusiveLock;
4682  break;
4683 
4684  /*
4685  * Only used by CREATE OR REPLACE VIEW which must conflict
4686  * with an SELECTs currently using the view.
4687  */
4688  case AT_ReplaceRelOptions:
4689  cmd_lockmode = AccessExclusiveLock;
4690  break;
4691 
4692  /*
4693  * These subcommands affect general strategies for performance
4694  * and maintenance, though don't change the semantic results
4695  * from normal data reads and writes. Delaying an ALTER TABLE
4696  * behind currently active writes only delays the point where
4697  * the new strategy begins to take effect, so there is no
4698  * benefit in waiting. In this case the minimum restriction
4699  * applies: we don't currently allow concurrent catalog
4700  * updates.
4701  */
4702  case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
4703  case AT_ClusterOn: /* Uses MVCC in getIndexes() */
4704  case AT_DropCluster: /* Uses MVCC in getIndexes() */
4705  case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
4706  case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
4707  cmd_lockmode = ShareUpdateExclusiveLock;
4708  break;
4709 
4710  case AT_SetLogged:
4711  case AT_SetUnLogged:
4712  cmd_lockmode = AccessExclusiveLock;
4713  break;
4714 
4715  case AT_ValidateConstraint: /* Uses MVCC in getConstraints() */
4716  cmd_lockmode = ShareUpdateExclusiveLock;
4717  break;
4718 
4719  /*
4720  * Rel options are more complex than first appears. Options
4721  * are set here for tables, views and indexes; for historical
4722  * reasons these can all be used with ALTER TABLE, so we can't
4723  * decide between them using the basic grammar.
4724  */
4725  case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
4726  * getTables() */
4727  case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
4728  * getTables() */
4729  cmd_lockmode = AlterTableGetRelOptionsLockLevel((List *) cmd->def);
4730  break;
4731 
4732  case AT_AttachPartition:
4733  cmd_lockmode = ShareUpdateExclusiveLock;
4734  break;
4735 
4736  case AT_DetachPartition:
4737  if (((PartitionCmd *) cmd->def)->concurrent)
4738  cmd_lockmode = ShareUpdateExclusiveLock;
4739  else
4740  cmd_lockmode = AccessExclusiveLock;
4741  break;
4742 
4744  cmd_lockmode = ShareUpdateExclusiveLock;
4745  break;
4746 
4747  case AT_SplitPartition:
4748  cmd_lockmode = AccessExclusiveLock;
4749  break;
4750 
4751  case AT_MergePartitions:
4752  cmd_lockmode = AccessExclusiveLock;
4753  break;
4754 
4755  default: /* oops */
4756  elog(ERROR, "unrecognized alter table type: %d",
4757  (int) cmd->subtype);
4758  break;
4759  }
4760 
4761  /*
4762  * Take the greatest lockmode from any subcommand
4763  */
4764  if (cmd_lockmode > lockmode)
4765  lockmode = cmd_lockmode;
4766  }
4767 
4768  return lockmode;
4769 }
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:2717
@ CONSTR_UNIQUE
Definition: parsenodes.h:2715
@ CONSTR_EXCLUSION
Definition: parsenodes.h:2716
@ CONSTR_PRIMARY
Definition: parsenodes.h:2714
@ AT_AddIndexConstraint
Definition: parsenodes.h:2377
@ AT_MergePartitions
Definition: parsenodes.h:2419
@ AT_DropOf
Definition: parsenodes.h:2408
@ AT_SetOptions
Definition: parsenodes.h:2365
@ AT_DropIdentity
Definition: parsenodes.h:2422
@ AT_SetAttNotNull
Definition: parsenodes.h:2361
@ AT_DisableTrigUser
Definition: parsenodes.h:2400
@ AT_DropNotNull
Definition: parsenodes.h:2359
@ AT_AddOf
Definition: parsenodes.h:2407
@ AT_ResetOptions
Definition: parsenodes.h:2366
@ AT_ReplicaIdentity
Definition: parsenodes.h:2409
@ AT_ReplaceRelOptions
Definition: parsenodes.h:2392
@ AT_EnableRowSecurity
Definition: parsenodes.h:2410
@ AT_AddColumnToView
Definition: parsenodes.h:2356
@ AT_ResetRelOptions
Definition: parsenodes.h:2391
@ AT_EnableReplicaTrig
Definition: parsenodes.h:2395
@ AT_DropOids
Definition: parsenodes.h:2387
@ AT_SetIdentity
Definition: parsenodes.h:2421
@ AT_SetUnLogged
Definition: parsenodes.h:2386
@ AT_DisableTrig
Definition: parsenodes.h:2396
@ AT_SetCompression
Definition: parsenodes.h:2368
@ AT_DropExpression
Definition: parsenodes.h:2363
@ AT_AddIndex
Definition: parsenodes.h:2370
@ AT_EnableReplicaRule
Definition: parsenodes.h:2403
@ AT_DropConstraint
Definition: parsenodes.h:2378
@ AT_SetNotNull
Definition: parsenodes.h:2360
@ AT_ClusterOn
Definition: parsenodes.h:2383
@ AT_AddIdentity
Definition: parsenodes.h:2420
@ AT_ForceRowSecurity
Definition: parsenodes.h:2412
@ AT_EnableAlwaysRule
Definition: parsenodes.h:2402
@ AT_SetAccessMethod
Definition: parsenodes.h:2388
@ AT_AlterColumnType
Definition: parsenodes.h:2380
@ AT_DetachPartitionFinalize
Definition: parsenodes.h:2417
@ AT_AddInherit
Definition: parsenodes.h:2405
@ AT_ReAddDomainConstraint
Definition: parsenodes.h:2374
@ AT_EnableTrig
Definition: parsenodes.h:2393
@ AT_DropColumn
Definition: parsenodes.h:2369
@ AT_AlterColumnGenericOptions
Definition: parsenodes.h:2381
@ AT_DisableTrigAll
Definition: parsenodes.h:2398
@ AT_EnableRule
Definition: parsenodes.h:2401
@ AT_NoForceRowSecurity
Definition: parsenodes.h:2413
@ AT_DetachPartition
Definition: parsenodes.h:2416
@ AT_SetStatistics
Definition: parsenodes.h:2364
@ AT_AttachPartition
Definition: parsenodes.h:2415
@ AT_AddConstraint
Definition: parsenodes.h:2372
@ AT_DropInherit
Definition: parsenodes.h:2406
@ AT_EnableAlwaysTrig
Definition: parsenodes.h:2394
@ AT_SetLogged
Definition: parsenodes.h:2385
@ AT_SetStorage
Definition: parsenodes.h:2367
@ AT_DisableRule
Definition: parsenodes.h:2404
@ AT_DisableRowSecurity
Definition: parsenodes.h:2411
@ AT_SetRelOptions
Definition: parsenodes.h:2390
@ AT_ChangeOwner
Definition: parsenodes.h:2382
@ AT_EnableTrigUser
Definition: parsenodes.h:2399
@ AT_SetExpression
Definition: parsenodes.h:2362
@ AT_ReAddConstraint
Definition: parsenodes.h:2373
@ AT_SetTableSpace
Definition: parsenodes.h:2389
@ AT_GenericOptions
Definition: parsenodes.h:2414
@ AT_ColumnDefault
Definition: parsenodes.h:2357
@ AT_CookedColumnDefault
Definition: parsenodes.h:2358
@ AT_AlterConstraint
Definition: parsenodes.h:2375
@ AT_EnableTrigAll
Definition: parsenodes.h:2397
@ AT_SplitPartition
Definition: parsenodes.h:2418
@ AT_DropCluster
Definition: parsenodes.h:2384
@ AT_ValidateConstraint
Definition: parsenodes.h:2376
@ AT_AddColumn
Definition: parsenodes.h:2355
#define lfirst(lc)
Definition: pg_list.h:172
LOCKMODE AlterTableGetRelOptionsLockLevel(List *defList)
Definition: reloptions.c:2108
AlterTableType subtype
Definition: parsenodes.h:2436
ConstrType contype
Definition: parsenodes.h:2739
Definition: pg_list.h:54

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

Referenced by AlterTableInternal(), and ProcessUtilitySlow().

◆ AlterTableInternal()

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

Definition at line 4462 of file tablecmds.c.

4463 {
4464  Relation rel;
4465  LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
4466 
4467  rel = relation_open(relid, lockmode);
4468 
4470 
4471  ATController(NULL, rel, cmds, recurse, lockmode, NULL);
4472 }
void EventTriggerAlterTableRelid(Oid objectId)
LOCKMODE AlterTableGetLockLevel(List *cmds)
Definition: tablecmds.c:4507

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

Referenced by AlterTableMoveAll(), and DefineVirtualRelation().

◆ AlterTableLookupRelation()

Oid AlterTableLookupRelation ( AlterTableStmt stmt,
LOCKMODE  lockmode 
)

Definition at line 4374 of file tablecmds.c.

4375 {
4376  return RangeVarGetRelidExtended(stmt->relation, lockmode,
4377  stmt->missing_ok ? RVR_MISSING_OK : 0,
4379  (void *) stmt);
4380 }
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:18506

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

Referenced by ProcessUtilitySlow().

◆ AlterTableMoveAll()

Oid AlterTableMoveAll ( AlterTableMoveAllStmt stmt)

Definition at line 15890 of file tablecmds.c.

15891 {
15892  List *relations = NIL;
15893  ListCell *l;
15894  ScanKeyData key[1];
15895  Relation rel;
15896  TableScanDesc scan;
15897  HeapTuple tuple;
15898  Oid orig_tablespaceoid;
15899  Oid new_tablespaceoid;
15900  List *role_oids = roleSpecsToIds(stmt->roles);
15901 
15902  /* Ensure we were not asked to move something we can't */
15903  if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
15904  stmt->objtype != OBJECT_MATVIEW)
15905  ereport(ERROR,
15906  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
15907  errmsg("only tables, indexes, and materialized views exist in tablespaces")));
15908 
15909  /* Get the orig and new tablespace OIDs */
15910  orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
15911  new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
15912 
15913  /* Can't move shared relations in to or out of pg_global */
15914  /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
15915  if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
15916  new_tablespaceoid == GLOBALTABLESPACE_OID)
15917  ereport(ERROR,
15918  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
15919  errmsg("cannot move relations in to or out of pg_global tablespace")));
15920 
15921  /*
15922  * Must have CREATE rights on the new tablespace, unless it is the
15923  * database default tablespace (which all users implicitly have CREATE
15924  * rights on).
15925  */
15926  if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
15927  {
15928  AclResult aclresult;
15929 
15930  aclresult = object_aclcheck(TableSpaceRelationId, new_tablespaceoid, GetUserId(),
15931  ACL_CREATE);
15932  if (aclresult != ACLCHECK_OK)
15933  aclcheck_error(aclresult, OBJECT_TABLESPACE,
15934  get_tablespace_name(new_tablespaceoid));
15935  }
15936 
15937  /*
15938  * Now that the checks are done, check if we should set either to
15939  * InvalidOid because it is our database's default tablespace.
15940  */
15941  if (orig_tablespaceoid == MyDatabaseTableSpace)
15942  orig_tablespaceoid = InvalidOid;
15943 
15944  if (new_tablespaceoid == MyDatabaseTableSpace)
15945  new_tablespaceoid = InvalidOid;
15946 
15947  /* no-op */
15948  if (orig_tablespaceoid == new_tablespaceoid)
15949  return new_tablespaceoid;
15950 
15951  /*
15952  * Walk the list of objects in the tablespace and move them. This will
15953  * only find objects in our database, of course.
15954  */
15955  ScanKeyInit(&key[0],
15956  Anum_pg_class_reltablespace,
15957  BTEqualStrategyNumber, F_OIDEQ,
15958  ObjectIdGetDatum(orig_tablespaceoid));
15959 
15960  rel = table_open(RelationRelationId, AccessShareLock);
15961  scan = table_beginscan_catalog(rel, 1, key);
15962  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
15963  {
15964  Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
15965  Oid relOid = relForm->oid;
15966 
15967  /*
15968  * Do not move objects in pg_catalog as part of this, if an admin
15969  * really wishes to do so, they can issue the individual ALTER
15970  * commands directly.
15971  *
15972  * Also, explicitly avoid any shared tables, temp tables, or TOAST
15973  * (TOAST will be moved with the main table).
15974  */
15975  if (IsCatalogNamespace(relForm->relnamespace) ||
15976  relForm->relisshared ||
15977  isAnyTempNamespace(relForm->relnamespace) ||
15978  IsToastNamespace(relForm->relnamespace))
15979  continue;
15980 
15981  /* Only move the object type requested */
15982  if ((stmt->objtype == OBJECT_TABLE &&
15983  relForm->relkind != RELKIND_RELATION &&
15984  relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
15985  (stmt->objtype == OBJECT_INDEX &&
15986  relForm->relkind != RELKIND_INDEX &&
15987  relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
15988  (stmt->objtype == OBJECT_MATVIEW &&
15989  relForm->relkind != RELKIND_MATVIEW))
15990  continue;
15991 
15992  /* Check if we are only moving objects owned by certain roles */
15993  if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
15994  continue;
15995 
15996  /*
15997  * Handle permissions-checking here since we are locking the tables
15998  * and also to avoid doing a bunch of work only to fail part-way. Note
15999  * that permissions will also be checked by AlterTableInternal().
16000  *
16001  * Caller must be considered an owner on the table to move it.
16002  */
16003  if (!object_ownercheck(RelationRelationId, relOid, GetUserId()))
16005  NameStr(relForm->relname));
16006 
16007  if (stmt->nowait &&
16009  ereport(ERROR,
16010  (errcode(ERRCODE_OBJECT_IN_USE),
16011  errmsg("aborting because lock on relation \"%s.%s\" is not available",
16012  get_namespace_name(relForm->relnamespace),
16013  NameStr(relForm->relname))));
16014  else
16016 
16017  /* Add to our list of objects to move */
16018  relations = lappend_oid(relations, relOid);
16019  }
16020 
16021  table_endscan(scan);
16023 
16024  if (relations == NIL)
16025  ereport(NOTICE,
16026  (errcode(ERRCODE_NO_DATA_FOUND),
16027  errmsg("no matching relations in tablespace \"%s\" found",
16028  orig_tablespaceoid == InvalidOid ? "(database default)" :
16029  get_tablespace_name(orig_tablespaceoid))));
16030 
16031  /* Everything is locked, loop through and move all of the relations. */
16032  foreach(l, relations)
16033  {
16034  List *cmds = NIL;
16036 
16037  cmd->subtype = AT_SetTableSpace;
16038  cmd->name = stmt->new_tablespacename;
16039 
16040  cmds = lappend(cmds, cmd);
16041 
16043  /* OID is set by AlterTableInternal */
16044  AlterTableInternal(lfirst_oid(l), cmds, false);
16046  }
16047 
16048  return new_tablespaceoid;
16049 }
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:775
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:1248
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:2003
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:2286
@ OBJECT_TABLESPACE
Definition: parsenodes.h:2305
@ OBJECT_INDEX
Definition: parsenodes.h:2283
@ OBJECT_TABLE
Definition: parsenodes.h:2304
#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:1029
void AlterTableInternal(Oid relid, List *cmds, bool recurse)
Definition: tablecmds.c:4462

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

17877 {
17878  Relation rel;
17879  Oid relid;
17880  Oid oldNspOid;
17881  Oid nspOid;
17882  RangeVar *newrv;
17883  ObjectAddresses *objsMoved;
17884  ObjectAddress myself;
17885 
17887  stmt->missing_ok ? RVR_MISSING_OK : 0,
17889  (void *) stmt);
17890 
17891  if (!OidIsValid(relid))
17892  {
17893  ereport(NOTICE,
17894  (errmsg("relation \"%s\" does not exist, skipping",
17895  stmt->relation->relname)));
17896  return InvalidObjectAddress;
17897  }
17898 
17899  rel = relation_open(relid, NoLock);
17900 
17901  oldNspOid = RelationGetNamespace(rel);
17902 
17903  /* If it's an owned sequence, disallow moving it by itself. */
17904  if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
17905  {
17906  Oid tableId;
17907  int32 colId;
17908 
17909  if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
17910  sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
17911  ereport(ERROR,
17912  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
17913  errmsg("cannot move an owned sequence into another schema"),
17914  errdetail("Sequence \"%s\" is linked to table \"%s\".",
17916  get_rel_name(tableId))));
17917  }
17918 
17919  /* Get and lock schema OID and check its permissions. */
17920  newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
17921  nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
17922 
17923  /* common checks on switching namespaces */
17924  CheckSetNamespace(oldNspOid, nspOid);
17925 
17926  objsMoved = new_object_addresses();
17927  AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
17928  free_object_addresses(objsMoved);
17929 
17930  ObjectAddressSet(myself, RelationRelationId, relid);
17931 
17932  if (oldschema)
17933  *oldschema = oldNspOid;
17934 
17935  /* close rel, but keep lock until commit */
17936  relation_close(rel, NoLock);
17937 
17938  return myself;
17939 }
signed int int32
Definition: c.h:494
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2485
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2771
@ 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:1928
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:17947

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

17949 {
17950  Relation classRel;
17951 
17952  Assert(objsMoved != NULL);
17953 
17954  /* OK, modify the pg_class row and pg_depend entry */
17955  classRel = table_open(RelationRelationId, RowExclusiveLock);
17956 
17957  AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
17958  nspOid, true, objsMoved);
17959 
17960  /* Fix the table's row type too, if it has one */
17961  if (OidIsValid(rel->rd_rel->reltype))
17962  AlterTypeNamespaceInternal(rel->rd_rel->reltype,
17963  nspOid, false, false, objsMoved);
17964 
17965  /* Fix other dependent stuff */
17966  AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
17967  AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
17968  objsMoved, AccessExclusiveLock);
17969  AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
17970  false, objsMoved);
17971 
17972  table_close(classRel, RowExclusiveLock);
17973 }
#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:17981
static void AlterSeqNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved, LOCKMODE lockmode)
Definition: tablecmds.c:18096
static void AlterIndexNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:18051
Oid AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid, bool isImplicitArray, bool errorOnTableType, ObjectAddresses *objsMoved)
Definition: typecmds.c:4132

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

18381 {
18382  ListCell *cur_item;
18383 
18384  foreach(cur_item, on_commits)
18385  {
18386  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
18387 
18388  if (!isCommit && oc->creating_subid == mySubid)
18389  {
18390  /* cur_item must be removed */
18392  pfree(oc);
18393  }
18394  else
18395  {
18396  /* cur_item must be preserved */
18397  if (oc->creating_subid == mySubid)
18398  oc->creating_subid = parentSubid;
18399  if (oc->deleting_subid == mySubid)
18400  oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
18401  }
18402  }
18403 }
#define InvalidSubTransactionId
Definition: c.h:658
void pfree(void *pointer)
Definition: mcxt.c:1520
#define foreach_delete_current(lst, var_or_cell)
Definition: pg_list.h:391
SubTransactionId creating_subid
Definition: tablecmds.c:124
SubTransactionId deleting_subid
Definition: tablecmds.c:125
static List * on_commits
Definition: tablecmds.c:128

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

18348 {
18349  ListCell *cur_item;
18350 
18351  foreach(cur_item, on_commits)
18352  {
18353  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
18354 
18355  if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
18357  {
18358  /* cur_item must be removed */
18360  pfree(oc);
18361  }
18362  else
18363  {
18364  /* cur_item must be preserved */
18367  }
18368  }
18369 }

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

14983 {
14984  Relation target_rel;
14985  Relation class_rel;
14986  HeapTuple tuple;
14987  Form_pg_class tuple_class;
14988 
14989  /*
14990  * Get exclusive lock till end of transaction on the target table. Use
14991  * relation_open so that we can work on indexes and sequences.
14992  */
14993  target_rel = relation_open(relationOid, lockmode);
14994 
14995  /* Get its pg_class tuple, too */
14996  class_rel = table_open(RelationRelationId, RowExclusiveLock);
14997 
14998  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
14999  if (!HeapTupleIsValid(tuple))
15000  elog(ERROR, "cache lookup failed for relation %u", relationOid);
15001  tuple_class = (Form_pg_class) GETSTRUCT(tuple);
15002 
15003  /* Can we change the ownership of this tuple? */
15004  switch (tuple_class->relkind)
15005  {
15006  case RELKIND_RELATION:
15007  case RELKIND_VIEW:
15008  case RELKIND_MATVIEW:
15009  case RELKIND_FOREIGN_TABLE:
15010  case RELKIND_PARTITIONED_TABLE:
15011  /* ok to change owner */
15012  break;
15013  case RELKIND_INDEX:
15014  if (!recursing)
15015  {
15016  /*
15017  * Because ALTER INDEX OWNER used to be allowed, and in fact
15018  * is generated by old versions of pg_dump, we give a warning
15019  * and do nothing rather than erroring out. Also, to avoid
15020  * unnecessary chatter while restoring those old dumps, say
15021  * nothing at all if the command would be a no-op anyway.
15022  */
15023  if (tuple_class->relowner != newOwnerId)
15024  ereport(WARNING,
15025  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
15026  errmsg("cannot change owner of index \"%s\"",
15027  NameStr(tuple_class->relname)),
15028  errhint("Change the ownership of the index's table instead.")));
15029  /* quick hack to exit via the no-op path */
15030  newOwnerId = tuple_class->relowner;
15031  }
15032  break;
15033  case RELKIND_PARTITIONED_INDEX:
15034  if (recursing)
15035  break;
15036  ereport(ERROR,
15037  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
15038  errmsg("cannot change owner of index \"%s\"",
15039  NameStr(tuple_class->relname)),
15040  errhint("Change the ownership of the index's table instead.")));
15041  break;
15042  case RELKIND_SEQUENCE:
15043  if (!recursing &&
15044  tuple_class->relowner != newOwnerId)
15045  {
15046  /* if it's an owned sequence, disallow changing it by itself */
15047  Oid tableId;
15048  int32 colId;
15049 
15050  if (sequenceIsOwned(relationOid, DEPENDENCY_AUTO, &tableId, &colId) ||
15051  sequenceIsOwned(relationOid, DEPENDENCY_INTERNAL, &tableId, &colId))
15052  ereport(ERROR,
15053  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15054  errmsg("cannot change owner of sequence \"%s\"",
15055  NameStr(tuple_class->relname)),
15056  errdetail("Sequence \"%s\" is linked to table \"%s\".",
15057  NameStr(tuple_class->relname),
15058  get_rel_name(tableId))));
15059  }
15060  break;
15061  case RELKIND_COMPOSITE_TYPE:
15062  if (recursing)
15063  break;
15064  ereport(ERROR,
15065  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
15066  errmsg("\"%s\" is a composite type",
15067  NameStr(tuple_class->relname)),
15068  /* translator: %s is an SQL ALTER command */
15069  errhint("Use %s instead.",
15070  "ALTER TYPE")));
15071  break;
15072  case RELKIND_TOASTVALUE:
15073  if (recursing)
15074  break;
15075  /* FALL THRU */
15076  default:
15077  ereport(ERROR,
15078  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
15079  errmsg("cannot change owner of relation \"%s\"",
15080  NameStr(tuple_class->relname)),
15081  errdetail_relkind_not_supported(tuple_class->relkind)));
15082  }
15083 
15084  /*
15085  * If the new owner is the same as the existing owner, consider the
15086  * command to have succeeded. This is for dump restoration purposes.
15087  */
15088  if (tuple_class->relowner != newOwnerId)
15089  {
15090  Datum repl_val[Natts_pg_class];
15091  bool repl_null[Natts_pg_class];
15092  bool repl_repl[Natts_pg_class];
15093  Acl *newAcl;
15094  Datum aclDatum;
15095  bool isNull;
15096  HeapTuple newtuple;
15097 
15098  /* skip permission checks when recursing to index or toast table */
15099  if (!recursing)
15100  {
15101  /* Superusers can always do it */
15102  if (!superuser())
15103  {
15104  Oid namespaceOid = tuple_class->relnamespace;
15105  AclResult aclresult;
15106 
15107  /* Otherwise, must be owner of the existing object */
15108  if (!object_ownercheck(RelationRelationId, relationOid, GetUserId()))
15110  RelationGetRelationName(target_rel));
15111 
15112  /* Must be able to become new owner */
15113  check_can_set_role(GetUserId(), newOwnerId);
15114 
15115  /* New owner must have CREATE privilege on namespace */
15116  aclresult = object_aclcheck(NamespaceRelationId, namespaceOid, newOwnerId,
15117  ACL_CREATE);
15118  if (aclresult != ACLCHECK_OK)
15119  aclcheck_error(aclresult, OBJECT_SCHEMA,
15120  get_namespace_name(namespaceOid));
15121  }
15122  }
15123 
15124  memset(repl_null, false, sizeof(repl_null));
15125  memset(repl_repl, false, sizeof(repl_repl));
15126 
15127  repl_repl[Anum_pg_class_relowner - 1] = true;
15128  repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
15129 
15130  /*
15131  * Determine the modified ACL for the new owner. This is only
15132  * necessary when the ACL is non-null.
15133  */
15134  aclDatum = SysCacheGetAttr(RELOID, tuple,
15135  Anum_pg_class_relacl,
15136  &isNull);
15137  if (!isNull)
15138  {
15139  newAcl = aclnewowner(DatumGetAclP(aclDatum),
15140  tuple_class->relowner, newOwnerId);
15141  repl_repl[Anum_pg_class_relacl - 1] = true;
15142  repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
15143  }
15144 
15145  newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
15146 
15147  CatalogTupleUpdate(class_rel, &newtuple->t_self, newtuple);
15148 
15149  heap_freetuple(newtuple);
15150 
15151  /*
15152  * We must similarly update any per-column ACLs to reflect the new
15153  * owner; for neatness reasons that's split out as a subroutine.
15154  */
15155  change_owner_fix_column_acls(relationOid,
15156  tuple_class->relowner,
15157  newOwnerId);
15158 
15159  /*
15160  * Update owner dependency reference, if any. A composite type has
15161  * none, because it's tracked for the pg_type entry instead of here;
15162  * indexes and TOAST tables don't have their own entries either.
15163  */
15164  if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
15165  tuple_class->relkind != RELKIND_INDEX &&
15166  tuple_class->relkind != RELKIND_PARTITIONED_INDEX &&
15167  tuple_class->relkind != RELKIND_TOASTVALUE)
15168  changeDependencyOnOwner(RelationRelationId, relationOid,
15169  newOwnerId);
15170 
15171  /*
15172  * Also change the ownership of the table's row type, if it has one
15173  */
15174  if (OidIsValid(tuple_class->reltype))
15175  AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId);
15176 
15177  /*
15178  * If we are operating on a table or materialized view, also change
15179  * the ownership of any indexes and sequences that belong to the
15180  * relation, as well as its toast table (if it has one).
15181  */
15182  if (tuple_class->relkind == RELKIND_RELATION ||
15183  tuple_class->relkind == RELKIND_PARTITIONED_TABLE ||
15184  tuple_class->relkind == RELKIND_MATVIEW ||
15185  tuple_class->relkind == RELKIND_TOASTVALUE)
15186  {
15187  List *index_oid_list;
15188  ListCell *i;
15189 
15190  /* Find all the indexes belonging to this relation */
15191  index_oid_list = RelationGetIndexList(target_rel);
15192 
15193  /* For each index, recursively change its ownership */
15194  foreach(i, index_oid_list)
15195  ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
15196 
15197  list_free(index_oid_list);
15198  }
15199 
15200  /* If it has a toast table, recurse to change its ownership */
15201  if (tuple_class->reltoastrelid != InvalidOid)
15202  ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
15203  true, lockmode);
15204 
15205  /* If it has dependent sequences, recurse to change them too */
15206  change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
15207  }
15208 
15209  InvokeObjectPostAlterHook(RelationRelationId, relationOid, 0);
15210 
15211  ReleaseSysCache(tuple);
15212  table_close(class_rel, RowExclusiveLock);
15213  relation_close(target_rel, NoLock);
15214 }
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition: acl.c:1096
void check_can_set_role(Oid member, Oid role)
Definition: acl.c:5185
#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:2299
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:4760
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:14982
static void change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
Definition: tablecmds.c:15288
static void change_owner_fix_column_acls(Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
Definition: tablecmds.c:15223
void AlterTypeOwnerInternal(Oid typeOid, Oid newOwnerId)
Definition: typecmds.c:3989

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

1308 {
1309  int natts;
1311  ListCell *l;
1312  TupleDesc desc;
1313  bool has_not_null;
1314  char *attname;
1315  Oid atttypid;
1316  int32 atttypmod;
1317  Oid attcollation;
1318  int attdim;
1319 
1320  /*
1321  * allocate a new tuple descriptor
1322  */
1323  natts = list_length(columns);
1324  desc = CreateTemplateTupleDesc(natts);
1325  has_not_null = false;
1326 
1327  attnum = 0;
1328 
1329  foreach(l, columns)
1330  {
1331  ColumnDef *entry = lfirst(l);
1332  AclResult aclresult;
1333  Form_pg_attribute att;
1334 
1335  /*
1336  * for each entry in the list, get the name and type information from
1337  * the list and have TupleDescInitEntry fill in the attribute
1338  * information we need.
1339  */
1340  attnum++;
1341 
1342  attname = entry->colname;
1343  typenameTypeIdAndMod(NULL, entry->typeName, &atttypid, &atttypmod);
1344 
1345  aclresult = object_aclcheck(TypeRelationId, atttypid, GetUserId(), ACL_USAGE);
1346  if (aclresult != ACLCHECK_OK)
1347  aclcheck_error_type(aclresult, atttypid);
1348 
1349  attcollation = GetColumnDefCollation(NULL, entry, atttypid);
1350  attdim = list_length(entry->typeName->arrayBounds);
1351  if (attdim > PG_INT16_MAX)
1352  ereport(ERROR,
1353  errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1354  errmsg("too many array dimensions"));
1355 
1356  if (entry->typeName->setof)
1357  ereport(ERROR,
1358  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1359  errmsg("column \"%s\" cannot be declared SETOF",
1360  attname)));
1361 
1363  atttypid, atttypmod, attdim);
1364  att = TupleDescAttr(desc, attnum - 1);
1365 
1366  /* Override TupleDescInitEntry's settings as requested */
1367  TupleDescInitEntryCollation(desc, attnum, attcollation);
1368 
1369  /* Fill in additional stuff not handled by TupleDescInitEntry */
1370  att->attnotnull = entry->is_not_null;
1371  has_not_null |= entry->is_not_null;
1372  att->attislocal = entry->is_local;
1373  att->attinhcount = entry->inhcount;
1374  att->attidentity = entry->identity;
1375  att->attgenerated = entry->generated;
1376  att->attcompression = GetAttributeCompression(att->atttypid, entry->compression);
1377  if (entry->storage)
1378  att->attstorage = entry->storage;
1379  else if (entry->storage_name)
1380  att->attstorage = GetAttributeStorage(att->atttypid, entry->storage_name);
1381  }
1382 
1383  if (has_not_null)
1384  {
1385  TupleConstr *constr = (TupleConstr *) palloc0(sizeof(TupleConstr));
1386 
1387  constr->has_not_null = true;
1388  constr->has_generated_stored = false;
1389  constr->defval = NULL;
1390  constr->missing = NULL;
1391  constr->num_defval = 0;
1392  constr->check = NULL;
1393  constr->num_check = 0;
1394  desc->constr = constr;
1395  }
1396  else
1397  {
1398  desc->constr = NULL;
1399  }
1400 
1401  return desc;
1402 }
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:586
void * palloc0(Size size)
Definition: mcxt.c:1346
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:731
char identity
Definition: parsenodes.h:737
char * storage_name
Definition: parsenodes.h:734
int inhcount
Definition: parsenodes.h:729
char * colname
Definition: parsenodes.h:726
TypeName * typeName
Definition: parsenodes.h:727
char generated
Definition: parsenodes.h:740
char storage
Definition: parsenodes.h:733
bool is_local
Definition: parsenodes.h:730
char * compression
Definition: parsenodes.h:728
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:270
List * arrayBounds
Definition: parsenodes.h:274
static char GetAttributeCompression(Oid atttypid, const char *compression)
Definition: tablecmds.c:20863
static char GetAttributeStorage(Oid atttypid, const char *storagemode)
Definition: tablecmds.c:20901
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 7014 of file tablecmds.c.

7015 {
7016  Form_pg_type typ = (Form_pg_type) GETSTRUCT(typetuple);
7017  bool typeOk = false;
7018 
7019  if (typ->typtype == TYPTYPE_COMPOSITE)
7020  {
7021  Relation typeRelation;
7022 
7023  Assert(OidIsValid(typ->typrelid));
7024  typeRelation = relation_open(typ->typrelid, AccessShareLock);
7025  typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
7026 
7027  /*
7028  * Close the parent rel, but keep our AccessShareLock on it until xact
7029  * commit. That will prevent someone else from deleting or ALTERing
7030  * the type before the typed table creation/conversion commits.
7031  */
7032  relation_close(typeRelation, NoLock);
7033  }
7034  if (!typeOk)
7035  ereport(ERROR,
7036  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7037  errmsg("type %s is not a composite type",
7038  format_type_be(typ->oid))));
7039 }
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 3629 of file tablecmds.c.

3630 {
3631  Oid oldTableSpaceId;
3632 
3633  /*
3634  * No work if no change in tablespace. Note that MyDatabaseTableSpace is
3635  * stored as 0.
3636  */
3637  oldTableSpaceId = rel->rd_rel->reltablespace;
3638  if (newTableSpaceId == oldTableSpaceId ||
3639  (newTableSpaceId == MyDatabaseTableSpace && oldTableSpaceId == 0))
3640  return false;
3641 
3642  /*
3643  * We cannot support moving mapped relations into different tablespaces.
3644  * (In particular this eliminates all shared catalogs.)
3645  */
3646  if (RelationIsMapped(rel))
3647  ereport(ERROR,
3648  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3649  errmsg("cannot move system relation \"%s\"",
3650  RelationGetRelationName(rel))));
3651 
3652  /* Cannot move a non-shared relation into pg_global */
3653  if (newTableSpaceId == GLOBALTABLESPACE_OID)
3654  ereport(ERROR,
3655  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3656  errmsg("only shared relations can be placed in pg_global tablespace")));
3657 
3658  /*
3659  * Do not allow moving temp tables of other backends ... their local
3660  * buffer manager is not going to cope.
3661  */
3662  if (RELATION_IS_OTHER_TEMP(rel))
3663  ereport(ERROR,
3664  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3665  errmsg("cannot move temporary tables of other sessions")));
3666 
3667  return true;
3668 }
#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 4346 of file tablecmds.c.

4347 {
4348  int expected_refcnt;
4349 
4350  expected_refcnt = rel->rd_isnailed ? 2 : 1;
4351  if (rel->rd_refcnt != expected_refcnt)
4352  ereport(ERROR,
4353  (errcode(ERRCODE_OBJECT_IN_USE),
4354  /* translator: first %s is a SQL command, eg ALTER TABLE */
4355  errmsg("cannot %s \"%s\" because it is being used by active queries in this session",
4356  stmt, RelationGetRelationName(rel))));
4357 
4358  if (rel->rd_rel->relkind != RELKIND_INDEX &&
4359  rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
4361  ereport(ERROR,
4362  (errcode(ERRCODE_OBJECT_IN_USE),
4363  /* translator: first %s is a SQL command, eg ALTER TABLE */
4364  errmsg("cannot %s \"%s\" because it has pending trigger events",
4365  stmt, RelationGetRelationName(rel))));
4366 }
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 700 of file tablecmds.c.

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

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_relam(), get_rel_tablespace(), get_table_am_oid(), get_tablespace_name(), get_tablespace_oid(), GetDefaultTablespace(), GetUserId(), heap_create_with_catalog(), HEAP_RELOPT_NAMESPACES, heap_reloptions(), index_close(), index_open(), 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 1807 of file tablecmds.c.

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

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

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

6809 {
6810  Relation depRel;
6811  ScanKeyData key[2];
6812  SysScanDesc depScan;
6813  HeapTuple depTup;
6814 
6815  /* since this function recurses, it could be driven to stack overflow */
6817 
6818  /*
6819  * We scan pg_depend to find those things that depend on the given type.
6820  * (We assume we can ignore refobjsubid for a type.)
6821  */
6822  depRel = table_open(DependRelationId, AccessShareLock);
6823 
6824  ScanKeyInit(&key[0],
6825  Anum_pg_depend_refclassid,
6826  BTEqualStrategyNumber, F_OIDEQ,
6827  ObjectIdGetDatum(TypeRelationId));
6828  ScanKeyInit(&key[1],
6829  Anum_pg_depend_refobjid,
6830  BTEqualStrategyNumber, F_OIDEQ,
6831  ObjectIdGetDatum(typeOid));
6832 
6833  depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
6834  NULL, 2, key);
6835 
6836  while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
6837  {
6838  Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
6839  Relation rel;
6840  TupleDesc tupleDesc;
6841  Form_pg_attribute att;
6842 
6843  /* Check for directly dependent types */
6844  if (pg_depend->classid == TypeRelationId)
6845  {
6846  /*
6847  * This must be an array, domain, or range containing the given
6848  * type, so recursively check for uses of this type. Note that
6849  * any error message will mention the original type not the
6850  * container; this is intentional.
6851  */
6852  find_composite_type_dependencies(pg_depend->objid,
6853  origRelation, origTypeName);
6854  continue;
6855  }
6856 
6857  /* Else, ignore dependees that aren't relations */
6858  if (pg_depend->classid != RelationRelationId)
6859  continue;
6860 
6861  rel = relation_open(pg_depend->objid, AccessShareLock);
6862  tupleDesc = RelationGetDescr(rel);
6863 
6864  /*
6865  * If objsubid identifies a specific column, refer to that in error
6866  * messages. Otherwise, search to see if there's a user column of the
6867  * type. (We assume system columns are never of interesting types.)
6868  * The search is needed because an index containing an expression
6869  * column of the target type will just be recorded as a whole-relation
6870  * dependency. If we do not find a column of the type, the dependency
6871  * must indicate that the type is transiently referenced in an index
6872  * expression but not stored on disk, which we assume is OK, just as
6873  * we do for references in views. (It could also be that the target
6874  * type is embedded in some container type that is stored in an index
6875  * column, but the previous recursion should catch such cases.)
6876  */
6877  if (pg_depend->objsubid > 0 && pg_depend->objsubid <= tupleDesc->natts)
6878  att = TupleDescAttr(tupleDesc, pg_depend->objsubid - 1);
6879  else
6880  {
6881  att = NULL;
6882  for (int attno = 1; attno <= tupleDesc->natts; attno++)
6883  {
6884  att = TupleDescAttr(tupleDesc, attno - 1);
6885  if (att->atttypid == typeOid && !att->attisdropped)
6886  break;
6887  att = NULL;
6888  }
6889  if (att == NULL)
6890  {
6891  /* No such column, so assume OK */
6893  continue;
6894  }
6895  }
6896 
6897  /*
6898  * We definitely should reject if the relation has storage. If it's
6899  * partitioned, then perhaps we don't have to reject: if there are
6900  * partitions then we'll fail when we find one, else there is no
6901  * stored data to worry about. However, it's possible that the type
6902  * change would affect conclusions about whether the type is sortable
6903  * or hashable and thus (if it's a partitioning column) break the
6904  * partitioning rule. For now, reject for partitioned rels too.
6905  */
6906  if (RELKIND_HAS_STORAGE(rel->rd_rel->relkind) ||
6907  RELKIND_HAS_PARTITIONS(rel->rd_rel->relkind))
6908  {
6909  if (origTypeName)
6910  ereport(ERROR,
6911  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6912  errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
6913  origTypeName,
6915  NameStr(att->attname))));
6916  else if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
6917  ereport(ERROR,
6918  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6919  errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
6920  RelationGetRelationName(origRelation),
6922  NameStr(att->attname))));
6923  else if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
6924  ereport(ERROR,
6925  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6926  errmsg("cannot alter foreign table \"%s\" because column \"%s.%s\" uses its row type",
6927  RelationGetRelationName(origRelation),
6929  NameStr(att->attname))));
6930  else
6931  ereport(ERROR,
6932  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6933  errmsg("cannot alter table \"%s\" because column \"%s.%s\" uses its row type",
6934  RelationGetRelationName(origRelation),
6936  NameStr(att->attname))));
6937  }
6938  else if (OidIsValid(rel->rd_rel->reltype))
6939  {
6940  /*
6941  * A view or composite type itself isn't a problem, but we must
6942  * recursively check for indirect dependencies via its rowtype.
6943  */
6945  origRelation, origTypeName);
6946  }
6947 
6949  }
6950 
6951  systable_endscan(depScan);
6952 
6954 }
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:6807

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

18965 {
18966  List *existConstraint = NIL;
18967  TupleConstr *constr = RelationGetDescr(scanrel)->constr;
18968  int i;
18969 
18970  if (constr && constr->has_not_null)
18971  {
18972  int natts = scanrel->rd_att->natts;
18973 
18974  for (i = 1; i <= natts; i++)
18975  {
18976  Form_pg_attribute att = TupleDescAttr(scanrel->rd_att, i - 1);
18977 
18978  if (att->attnotnull && !att->attisdropped)
18979  {
18980  NullTest *ntest = makeNode(NullTest);
18981 
18982  ntest->arg = (Expr *) makeVar(1,
18983  i,
18984  att->atttypid,
18985  att->atttypmod,
18986  att->attcollation,
18987  0);
18988  ntest->nulltesttype = IS_NOT_NULL;
18989 
18990  /*
18991  * argisrow=false is correct even for a composite column,
18992  * because attnotnull does not represent a SQL-spec IS NOT
18993  * NULL test in such a case, just IS DISTINCT FROM NULL.
18994  */
18995  ntest->argisrow = false;
18996  ntest->location = -1;
18997  existConstraint = lappend(existConstraint, ntest);
18998  }
18999  }
19000  }
19001 
19002  return ConstraintImpliedByRelConstraint(scanrel, partConstraint, existConstraint);
19003 }
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
@ IS_NOT_NULL
Definition: primnodes.h:1924
NullTestType nulltesttype
Definition: primnodes.h:1931
ParseLoc location
Definition: primnodes.h:1934
Expr * arg
Definition: primnodes.h:1930
TupleDesc rd_att
Definition: rel.h:112
static bool ConstraintImpliedByRelConstraint(Relation scanrel, List *testConstraint, List *provenConstraint)
Definition: tablecmds.c:19016

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

18241 {
18242  ListCell *l;
18243  List *oids_to_truncate = NIL;
18244  List *oids_to_drop = NIL;
18245 
18246  foreach(l, on_commits)
18247  {
18248  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
18249 
18250  /* Ignore entry if already dropped in this xact */
18252  continue;
18253 
18254  switch (oc->oncommit)
18255  {
18256  case ONCOMMIT_NOOP:
18258  /* Do nothing (there shouldn't be such entries, actually) */
18259  break;
18260  case ONCOMMIT_DELETE_ROWS:
18261 
18262  /*
18263  * If this transaction hasn't accessed any temporary
18264  * relations, we can skip truncating ON COMMIT DELETE ROWS
18265  * tables, as they must still be empty.
18266  */
18268  oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
18269  break;
18270  case ONCOMMIT_DROP:
18271  oids_to_drop = lappend_oid(oids_to_drop, oc->relid);
18272  break;
18273  }
18274  }
18275 
18276  /*
18277  * Truncate relations before dropping so that all dependencies between
18278  * relations are removed after they are worked on. Doing it like this
18279  * might be a waste as it is possible that a relation being truncated will
18280  * be dropped anyway due to its parent being dropped, but this makes the
18281  * code more robust because of not having to re-check that the relation
18282  * exists at truncation time.
18283  */
18284  if (oids_to_truncate != NIL)
18285  heap_truncate(oids_to_truncate);
18286 
18287  if (oids_to_drop != NIL)
18288  {
18289  ObjectAddresses *targetObjects = new_object_addresses();
18290 
18291  foreach(l, oids_to_drop)
18292  {
18293  ObjectAddress object;
18294 
18295  object.classId = RelationRelationId;
18296  object.objectId = lfirst_oid(l);
18297  object.objectSubId = 0;
18298 
18299  Assert(!object_address_present(&object, targetObjects));
18300 
18301  add_exact_object_address(&object, targetObjects);
18302  }
18303 
18304  /*
18305  * Object deletion might involve toast table access (to clean up
18306  * toasted catalog entries), so ensure we have a valid snapshot.
18307  */
18309 
18310  /*
18311  * Since this is an automatic drop, rather than one directly initiated
18312  * by the user, we pass the PERFORM_DELETION_INTERNAL flag.
18313  */
18314  performMultipleDeletions(targetObjects, DROP_CASCADE,
18316 
18318 
18319 #ifdef USE_ASSERT_CHECKING
18320 
18321  /*
18322  * Note that table deletion will call remove_on_commit_action, so the
18323  * entry should get marked as deleted.
18324  */
18325  foreach(l, on_commits)
18326  {
18327  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
18328 
18329  if (oc->oncommit != ONCOMMIT_DROP)
18330  continue;
18331 
18333  }
18334 #endif
18335  }
18336 }
void performMultipleDeletions(const ObjectAddresses *objects, DropBehavior behavior, int flags)
Definition: dependency.c:332
#define PERFORM_DELETION_QUIETLY
Definition: dependency.h:87
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:85
void heap_truncate(List *relids)
Definition: heap.c:3377
@ 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:115
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 18414 of file tablecmds.c.

18416 {
18417  char relkind;
18418  AclResult aclresult;
18419 
18420  /* Nothing to do if the relation was not found. */
18421  if (!OidIsValid(relId))
18422  return;
18423 
18424  /*
18425  * If the relation does exist, check whether it's an index. But note that
18426  * the relation might have been dropped between the time we did the name
18427  * lookup and now. In that case, there's nothing to do.
18428  */
18429  relkind = get_rel_relkind(relId);
18430  if (!relkind)
18431  return;
18432  if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
18433  relkind != RELKIND_MATVIEW && relkind != RELKIND_PARTITIONED_TABLE)
18434  ereport(ERROR,
18435  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18436  errmsg("\"%s\" is not a table or materialized view", relation->relname)));
18437 
18438  /* Check permissions */
18439  aclresult = pg_class_aclcheck(relId, GetUserId(), ACL_MAINTAIN);
18440  if (aclresult != ACLCHECK_OK)
18441  aclcheck_error(aclresult,
18443  relation->relname);
18444 }
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 18474 of file tablecmds.c.

18476 {
18477  HeapTuple tuple;
18478 
18479  /* Nothing to do if the relation was not found. */
18480  if (!OidIsValid(relId))
18481  return;
18482 
18483  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
18484  if (!HeapTupleIsValid(tuple)) /* should not happen */
18485  elog(ERROR, "cache lookup failed for relation %u", relId);
18486 
18487  if (!object_ownercheck(RelationRelationId, relId, GetUserId()))
18489  relation->relname);
18490 
18491  if (!allowSystemTableMods &&
18492  IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
18493  ereport(ERROR,
18494  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
18495  errmsg("permission denied: \"%s\" is a system catalog",
18496  relation->relname)));
18497 
18498  ReleaseSysCache(tuple);
18499 }
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 18181 of file tablecmds.c.

18182 {
18183  OnCommitItem *oc;
18184  MemoryContext oldcxt;
18185 
18186  /*
18187  * We needn't bother registering the relation unless there is an ON COMMIT
18188  * action we need to take.
18189  */
18191  return;
18192 
18194 
18195  oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
18196  oc->relid = relid;
18197  oc->oncommit = action;
18200 
18201  /*
18202  * We use lcons() here so that ON COMMIT actions are processed in reverse
18203  * order of registration. That might not be essential but it seems
18204  * reasonable.
18205  */
18206  on_commits = lcons(oc, on_commits);
18207 
18208  MemoryContextSwitchTo(oldcxt);
18209 }
List * lcons(void *datum, List *list)
Definition: list.c:495
MemoryContext CacheMemoryContext
Definition: mcxt.c:152
MemoryContextSwitchTo(old_ctx)

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

18218 {
18219  ListCell *l;
18220 
18221  foreach(l, on_commits)
18222  {
18223  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
18224 
18225  if (oc->relid == relid)
18226  {
18228  break;
18229  }
18230  }
18231 }

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

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

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

3943 {
3944  Oid relid;
3946  ObjectAddress address;
3947 
3948  /* lock level taken here should match renameatt_internal */
3950  stmt->missing_ok ? RVR_MISSING_OK : 0,
3952  NULL);
3953 
3954  if (!OidIsValid(relid))
3955  {
3956  ereport(NOTICE,
3957  (errmsg("relation \"%s\" does not exist, skipping",
3958  stmt->relation->relname)));
3959  return InvalidObjectAddress;
3960  }
3961 
3962  attnum =
3963  renameatt_internal(relid,
3964  stmt->subname, /* old att name */
3965  stmt->newname, /* new att name */
3966  stmt->relation->inh, /* recursive? */
3967  false, /* recursing? */
3968  0, /* expected inhcount */
3969  stmt->behavior);
3970 
3971  ObjectAddressSubSet(address, RelationRelationId, relid, attnum);
3972 
3973  return address;
3974 }
#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:3777
static void RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:3922

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

4090 {
4091  Oid relid = InvalidOid;
4092  Oid typid = InvalidOid;
4093 
4094  if (stmt->renameType == OBJECT_DOMCONSTRAINT)
4095  {
4096  Relation rel;
4097  HeapTuple tup;
4098 
4099  typid = typenameTypeId(NULL, makeTypeNameFromNameList(castNode(List, stmt->object)));
4100  rel = table_open(TypeRelationId, RowExclusiveLock);
4101  tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
4102  if (!HeapTupleIsValid(tup))
4103  elog(ERROR, "cache lookup failed for type %u", typid);
4104  checkDomainOwner(tup);
4105  ReleaseSysCache(tup);
4106  table_close(rel, NoLock);
4107  }
4108  else
4109  {
4110  /* lock level taken here should match rename_constraint_internal */
4112  stmt->missing_ok ? RVR_MISSING_OK : 0,
4114  NULL);
4115  if (!OidIsValid(relid))
4116  {
4117  ereport(NOTICE,
4118  (errmsg("relation \"%s\" does not exist, skipping",
4119  stmt->relation->relname)));
4120  return InvalidObjectAddress;
4121  }
4122  }
4123 
4124  return
4125  rename_constraint_internal(relid, typid,
4126  stmt->subname,
4127  stmt->newname,
4128  (stmt->relation &&
4129  stmt->relation->inh), /* recursive? */
4130  false, /* recursing? */
4131  0 /* expected inhcount */ );
4132 }
TypeName * makeTypeNameFromNameList(List *names)
Definition: makefuncs.c:458
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
@ OBJECT_DOMCONSTRAINT
Definition: parsenodes.h:2276
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:3980
void checkDomainOwner(HeapTuple tup)
Definition: typecmds.c:3490

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

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

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

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

◆ ResetRelRewrite()

void ResetRelRewrite ( Oid  myrelid)

Definition at line 4293 of file tablecmds.c.

4294 {
4295  Relation relrelation; /* for RELATION relation */
4296  HeapTuple reltup;
4297  Form_pg_class relform;
4298 
4299  /*
4300  * Find relation's pg_class tuple.
4301  */
4302  relrelation = table_open(RelationRelationId, RowExclusiveLock);
4303 
4304  reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
4305  if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
4306  elog(ERROR, "cache lookup failed for relation %u", myrelid);
4307  relform = (Form_pg_class) GETSTRUCT(reltup);
4308 
4309  /*
4310  * Update pg_class tuple.
4311  */
4312  relform->relrewrite = InvalidOid;
4313 
4314  CatalogTupleUpdate(relrelation, &reltup->t_self, reltup);
4315 
4316  heap_freetuple(reltup);
4317  table_close(relrelation, RowExclusiveLock);
4318 }

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

3589 {
3590  Relation relationRelation;
3591  HeapTuple tuple;
3592  Form_pg_class classtuple;
3593 
3594  /*
3595  * Fetch a modifiable copy of the tuple, modify it, update pg_class.
3596  */
3597  relationRelation = table_open(RelationRelationId, RowExclusiveLock);
3598  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
3599  if (!HeapTupleIsValid(tuple))
3600  elog(ERROR, "cache lookup failed for relation %u", relationId);
3601  classtuple = (Form_pg_class) GETSTRUCT(tuple);
3602 
3603  if (classtuple->relhassubclass != relhassubclass)
3604  {
3605  classtuple->relhassubclass = relhassubclass;
3606  CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
3607  }
3608  else
3609  {
3610  /* no need to change tuple, but force relcache rebuild anyway */
3612  }
3613 
3614  heap_freetuple(tuple);
3615  table_close(relationRelation, RowExclusiveLock);
3616 }
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 3686 of file tablecmds.c.

3689 {
3690  Relation pg_class;
3691  HeapTuple tuple;
3692  Form_pg_class rd_rel;
3693  Oid reloid = RelationGetRelid(rel);
3694 
3695  Assert(CheckRelationTableSpaceMove(rel, newTableSpaceId));
3696 
3697  /* Get a modifiable copy of the relation's pg_class row. */
3698  pg_class = table_open(RelationRelationId, RowExclusiveLock);
3699 
3700  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(reloid));
3701  if (!HeapTupleIsValid(tuple))
3702  elog(ERROR, "cache lookup failed for relation %u", reloid);
3703  rd_rel = (Form_pg_class) GETSTRUCT(tuple);
3704 
3705  /* Update the pg_class row. */
3706  rd_rel->reltablespace = (newTableSpaceId == MyDatabaseTableSpace) ?
3707  InvalidOid : newTableSpaceId;
3708  if (RelFileNumberIsValid(newRelFilenumber))
3709  rd_rel->relfilenode = newRelFilenumber;
3710  CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
3711 
3712  /*
3713  * Record dependency on tablespace. This is only required for relations
3714  * that have no physical storage.
3715  */
3716  if (!RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
3717  changeDependencyOnTablespace(RelationRelationId, reloid,
3718  rd_rel->reltablespace);
3719 
3720  heap_freetuple(tuple);
3721  table_close(pg_class, RowExclusiveLock);
3722 }
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:3629

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