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

17128 {
17129  HeapTuple classTup;
17130  Form_pg_class classForm;
17131  ObjectAddress thisobj;
17132  bool already_done = false;
17133 
17134  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
17135  if (!HeapTupleIsValid(classTup))
17136  elog(ERROR, "cache lookup failed for relation %u", relOid);
17137  classForm = (Form_pg_class) GETSTRUCT(classTup);
17138 
17139  Assert(classForm->relnamespace == oldNspOid);
17140 
17141  thisobj.classId = RelationRelationId;
17142  thisobj.objectId = relOid;
17143  thisobj.objectSubId = 0;
17144 
17145  /*
17146  * If the object has already been moved, don't move it again. If it's
17147  * already in the right place, don't move it, but still fire the object
17148  * access hook.
17149  */
17150  already_done = object_address_present(&thisobj, objsMoved);
17151  if (!already_done && oldNspOid != newNspOid)
17152  {
17153  /* check for duplicate name (more friendly than unique-index failure) */
17154  if (get_relname_relid(NameStr(classForm->relname),
17155  newNspOid) != InvalidOid)
17156  ereport(ERROR,
17157  (errcode(ERRCODE_DUPLICATE_TABLE),
17158  errmsg("relation \"%s\" already exists in schema \"%s\"",
17159  NameStr(classForm->relname),
17160  get_namespace_name(newNspOid))));
17161 
17162  /* classTup is a copy, so OK to scribble on */
17163  classForm->relnamespace = newNspOid;
17164 
17165  CatalogTupleUpdate(classRel, &classTup->t_self, classTup);
17166 
17167  /* Update dependency on schema if caller said so */
17168  if (hasDependEntry &&
17169  changeDependencyFor(RelationRelationId,
17170  relOid,
17171  NamespaceRelationId,
17172  oldNspOid,
17173  newNspOid) != 1)
17174  elog(ERROR, "could not change schema dependency for relation \"%s\"",
17175  NameStr(classForm->relname));
17176  }
17177  if (!already_done)
17178  {
17179  add_exact_object_address(&thisobj, objsMoved);
17180 
17181  InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
17182  }
17183 
17184  heap_freetuple(classTup);
17185 }
#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:2593
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2533
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
#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:458
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 4358 of file tablecmds.c.

4360 {
4361  Relation rel;
4362 
4363  /* Caller is required to provide an adequate lock. */
4364  rel = relation_open(context->relid, NoLock);
4365 
4366  CheckAlterTableIsSafe(rel);
4367 
4368  ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
4369 }
#define stmt
Definition: indent_codes.h:59
#define NoLock
Definition: lockdefs.h:34
tree context
Definition: radixtree.h:1835
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:47
static void CheckAlterTableIsSafe(Relation rel)
Definition: tablecmds.c:4273
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:4703

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

Referenced by ProcessUtilitySlow().

◆ AlterTableGetLockLevel()

LOCKMODE AlterTableGetLockLevel ( List cmds)

Definition at line 4432 of file tablecmds.c.

4433 {
4434  /*
4435  * This only works if we read catalog tables using MVCC snapshots.
4436  */
4437  ListCell *lcmd;
4439 
4440  foreach(lcmd, cmds)
4441  {
4442  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
4443  LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
4444 
4445  switch (cmd->subtype)
4446  {
4447  /*
4448  * These subcommands rewrite the heap, so require full locks.
4449  */
4450  case AT_AddColumn: /* may rewrite heap, in some cases and visible
4451  * to SELECT */
4452  case AT_SetAccessMethod: /* must rewrite heap */
4453  case AT_SetTableSpace: /* must rewrite heap */
4454  case AT_AlterColumnType: /* must rewrite heap */
4455  cmd_lockmode = AccessExclusiveLock;
4456  break;
4457 
4458  /*
4459  * These subcommands may require addition of toast tables. If
4460  * we add a toast table to a table currently being scanned, we
4461  * might miss data added to the new toast table by concurrent
4462  * insert transactions.
4463  */
4464  case AT_SetStorage: /* may add toast tables, see
4465  * ATRewriteCatalogs() */
4466  cmd_lockmode = AccessExclusiveLock;
4467  break;
4468 
4469  /*
4470  * Removing constraints can affect SELECTs that have been
4471  * optimized assuming the constraint holds true. See also
4472  * CloneFkReferenced.
4473  */
4474  case AT_DropConstraint: /* as DROP INDEX */
4475  case AT_DropNotNull: /* may change some SQL plans */
4476  cmd_lockmode = AccessExclusiveLock;
4477  break;
4478 
4479  /*
4480  * Subcommands that may be visible to concurrent SELECTs
4481  */
4482  case AT_DropColumn: /* change visible to SELECT */
4483  case AT_AddColumnToView: /* CREATE VIEW */
4484  case AT_DropOids: /* used to equiv to DropColumn */
4485  case AT_EnableAlwaysRule: /* may change SELECT rules */
4486  case AT_EnableReplicaRule: /* may change SELECT rules */
4487  case AT_EnableRule: /* may change SELECT rules */
4488  case AT_DisableRule: /* may change SELECT rules */
4489  cmd_lockmode = AccessExclusiveLock;
4490  break;
4491 
4492  /*
4493  * Changing owner may remove implicit SELECT privileges
4494  */
4495  case AT_ChangeOwner: /* change visible to SELECT */
4496  cmd_lockmode = AccessExclusiveLock;
4497  break;
4498 
4499  /*
4500  * Changing foreign table options may affect optimization.
4501  */
4502  case AT_GenericOptions:
4504  cmd_lockmode = AccessExclusiveLock;
4505  break;
4506 
4507  /*
4508  * These subcommands affect write operations only.
4509  */
4510  case AT_EnableTrig:
4511  case AT_EnableAlwaysTrig:
4512  case AT_EnableReplicaTrig:
4513  case AT_EnableTrigAll:
4514  case AT_EnableTrigUser:
4515  case AT_DisableTrig:
4516  case AT_DisableTrigAll:
4517  case AT_DisableTrigUser:
4518  cmd_lockmode = ShareRowExclusiveLock;
4519  break;
4520 
4521  /*
4522  * These subcommands affect write operations only. XXX
4523  * Theoretically, these could be ShareRowExclusiveLock.
4524  */
4525  case AT_ColumnDefault:
4527  case AT_AlterConstraint:
4528  case AT_AddIndex: /* from ADD CONSTRAINT */
4529  case AT_AddIndexConstraint:
4530  case AT_ReplicaIdentity:
4531  case AT_SetNotNull:
4532  case AT_EnableRowSecurity:
4533  case AT_DisableRowSecurity:
4534  case AT_ForceRowSecurity:
4535  case AT_NoForceRowSecurity:
4536  case AT_AddIdentity:
4537  case AT_DropIdentity:
4538  case AT_SetIdentity:
4539  case AT_SetExpression:
4540  case AT_DropExpression:
4541  case AT_SetCompression:
4542  cmd_lockmode = AccessExclusiveLock;
4543  break;
4544 
4545  case AT_AddConstraint:
4546  case AT_ReAddConstraint: /* becomes AT_AddConstraint */
4547  case AT_ReAddDomainConstraint: /* becomes AT_AddConstraint */
4548  if (IsA(cmd->def, Constraint))
4549  {
4550  Constraint *con = (Constraint *) cmd->def;
4551 
4552  switch (con->contype)
4553  {
4554  case CONSTR_EXCLUSION:
4555  case CONSTR_PRIMARY:
4556  case CONSTR_UNIQUE:
4557 
4558  /*
4559  * Cases essentially the same as CREATE INDEX. We
4560  * could reduce the lock strength to ShareLock if
4561  * we can work out how to allow concurrent catalog
4562  * updates. XXX Might be set down to
4563  * ShareRowExclusiveLock but requires further
4564  * analysis.
4565  */
4566  cmd_lockmode = AccessExclusiveLock;
4567  break;
4568  case CONSTR_FOREIGN:
4569 
4570  /*
4571  * We add triggers to both tables when we add a
4572  * Foreign Key, so the lock level must be at least
4573  * as strong as CREATE TRIGGER.
4574  */
4575  cmd_lockmode = ShareRowExclusiveLock;
4576  break;
4577 
4578  default:
4579  cmd_lockmode = AccessExclusiveLock;
4580  }
4581  }
4582  break;
4583 
4584  /*
4585  * These subcommands affect inheritance behaviour. Queries
4586  * started before us will continue to see the old inheritance
4587  * behaviour, while queries started after we commit will see
4588  * new behaviour. No need to prevent reads or writes to the
4589  * subtable while we hook it up though. Changing the TupDesc
4590  * may be a problem, so keep highest lock.
4591  */
4592  case AT_AddInherit:
4593  case AT_DropInherit:
4594  cmd_lockmode = AccessExclusiveLock;
4595  break;
4596 
4597  /*
4598  * These subcommands affect implicit row type conversion. They
4599  * have affects similar to CREATE/DROP CAST on queries. don't
4600  * provide for invalidating parse trees as a result of such
4601  * changes, so we keep these at AccessExclusiveLock.
4602  */
4603  case AT_AddOf:
4604  case AT_DropOf:
4605  cmd_lockmode = AccessExclusiveLock;
4606  break;
4607 
4608  /*
4609  * Only used by CREATE OR REPLACE VIEW which must conflict
4610  * with an SELECTs currently using the view.
4611  */
4612  case AT_ReplaceRelOptions:
4613  cmd_lockmode = AccessExclusiveLock;
4614  break;
4615 
4616  /*
4617  * These subcommands affect general strategies for performance
4618  * and maintenance, though don't change the semantic results
4619  * from normal data reads and writes. Delaying an ALTER TABLE
4620  * behind currently active writes only delays the point where
4621  * the new strategy begins to take effect, so there is no
4622  * benefit in waiting. In this case the minimum restriction
4623  * applies: we don't currently allow concurrent catalog
4624  * updates.
4625  */
4626  case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
4627  case AT_ClusterOn: /* Uses MVCC in getIndexes() */
4628  case AT_DropCluster: /* Uses MVCC in getIndexes() */
4629  case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
4630  case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
4631  cmd_lockmode = ShareUpdateExclusiveLock;
4632  break;
4633 
4634  case AT_SetLogged:
4635  case AT_SetUnLogged:
4636  cmd_lockmode = AccessExclusiveLock;
4637  break;
4638 
4639  case AT_ValidateConstraint: /* Uses MVCC in getConstraints() */
4640  cmd_lockmode = ShareUpdateExclusiveLock;
4641  break;
4642 
4643  /*
4644  * Rel options are more complex than first appears. Options
4645  * are set here for tables, views and indexes; for historical
4646  * reasons these can all be used with ALTER TABLE, so we can't
4647  * decide between them using the basic grammar.
4648  */
4649  case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
4650  * getTables() */
4651  case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
4652  * getTables() */
4653  cmd_lockmode = AlterTableGetRelOptionsLockLevel((List *) cmd->def);
4654  break;
4655 
4656  case AT_AttachPartition:
4657  cmd_lockmode = ShareUpdateExclusiveLock;
4658  break;
4659 
4660  case AT_DetachPartition:
4661  if (((PartitionCmd *) cmd->def)->concurrent)
4662  cmd_lockmode = ShareUpdateExclusiveLock;
4663  else
4664  cmd_lockmode = AccessExclusiveLock;
4665  break;
4666 
4668  cmd_lockmode = ShareUpdateExclusiveLock;
4669  break;
4670 
4671  case AT_CheckNotNull:
4672 
4673  /*
4674  * This only examines the table's schema; but lock must be
4675  * strong enough to prevent concurrent DROP NOT NULL.
4676  */
4677  cmd_lockmode = AccessShareLock;
4678  break;
4679 
4680  default: /* oops */
4681  elog(ERROR, "unrecognized alter table type: %d",
4682  (int) cmd->subtype);
4683  break;
4684  }
4685 
4686  /*
4687  * Take the greatest lockmode from any subcommand
4688  */
4689  if (cmd_lockmode > lockmode)
4690  lockmode = cmd_lockmode;
4691  }
4692 
4693  return lockmode;
4694 }
int LOCKMODE
Definition: lockdefs.h:26
#define AccessExclusiveLock
Definition: lockdefs.h:43
#define ShareRowExclusiveLock
Definition: lockdefs.h:41
#define AccessShareLock
Definition: lockdefs.h:36
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
@ CONSTR_FOREIGN
Definition: parsenodes.h:2699
@ CONSTR_UNIQUE
Definition: parsenodes.h:2697
@ CONSTR_EXCLUSION
Definition: parsenodes.h:2698
@ CONSTR_PRIMARY
Definition: parsenodes.h:2696
@ AT_AddIndexConstraint
Definition: parsenodes.h:2362
@ AT_DropOf
Definition: parsenodes.h:2393
@ AT_CheckNotNull
Definition: parsenodes.h:2348
@ AT_SetOptions
Definition: parsenodes.h:2350
@ AT_DropIdentity
Definition: parsenodes.h:2405
@ AT_DisableTrigUser
Definition: parsenodes.h:2385
@ AT_DropNotNull
Definition: parsenodes.h:2344
@ AT_AddOf
Definition: parsenodes.h:2392
@ AT_ResetOptions
Definition: parsenodes.h:2351
@ AT_ReplicaIdentity
Definition: parsenodes.h:2394
@ AT_ReplaceRelOptions
Definition: parsenodes.h:2377
@ AT_EnableRowSecurity
Definition: parsenodes.h:2395
@ AT_AddColumnToView
Definition: parsenodes.h:2341
@ AT_ResetRelOptions
Definition: parsenodes.h:2376
@ AT_EnableReplicaTrig
Definition: parsenodes.h:2380
@ AT_DropOids
Definition: parsenodes.h:2372
@ AT_SetIdentity
Definition: parsenodes.h:2404
@ AT_SetUnLogged
Definition: parsenodes.h:2371
@ AT_DisableTrig
Definition: parsenodes.h:2381
@ AT_SetCompression
Definition: parsenodes.h:2353
@ AT_DropExpression
Definition: parsenodes.h:2347
@ AT_AddIndex
Definition: parsenodes.h:2355
@ AT_EnableReplicaRule
Definition: parsenodes.h:2388
@ AT_DropConstraint
Definition: parsenodes.h:2363
@ AT_SetNotNull
Definition: parsenodes.h:2345
@ AT_ClusterOn
Definition: parsenodes.h:2368
@ AT_AddIdentity
Definition: parsenodes.h:2403
@ AT_ForceRowSecurity
Definition: parsenodes.h:2397
@ AT_EnableAlwaysRule
Definition: parsenodes.h:2387
@ AT_SetAccessMethod
Definition: parsenodes.h:2373
@ AT_AlterColumnType
Definition: parsenodes.h:2365
@ AT_DetachPartitionFinalize
Definition: parsenodes.h:2402
@ AT_AddInherit
Definition: parsenodes.h:2390
@ AT_ReAddDomainConstraint
Definition: parsenodes.h:2359
@ AT_EnableTrig
Definition: parsenodes.h:2378
@ AT_DropColumn
Definition: parsenodes.h:2354
@ AT_AlterColumnGenericOptions
Definition: parsenodes.h:2366
@ AT_DisableTrigAll
Definition: parsenodes.h:2383
@ AT_EnableRule
Definition: parsenodes.h:2386
@ AT_NoForceRowSecurity
Definition: parsenodes.h:2398
@ AT_DetachPartition
Definition: parsenodes.h:2401
@ AT_SetStatistics
Definition: parsenodes.h:2349
@ AT_AttachPartition
Definition: parsenodes.h:2400
@ AT_AddConstraint
Definition: parsenodes.h:2357
@ AT_DropInherit
Definition: parsenodes.h:2391
@ AT_EnableAlwaysTrig
Definition: parsenodes.h:2379
@ AT_SetLogged
Definition: parsenodes.h:2370
@ AT_SetStorage
Definition: parsenodes.h:2352
@ AT_DisableRule
Definition: parsenodes.h:2389
@ AT_DisableRowSecurity
Definition: parsenodes.h:2396
@ AT_SetRelOptions
Definition: parsenodes.h:2375
@ AT_ChangeOwner
Definition: parsenodes.h:2367
@ AT_EnableTrigUser
Definition: parsenodes.h:2384
@ AT_SetExpression
Definition: parsenodes.h:2346
@ AT_ReAddConstraint
Definition: parsenodes.h:2358
@ AT_SetTableSpace
Definition: parsenodes.h:2374
@ AT_GenericOptions
Definition: parsenodes.h:2399
@ AT_ColumnDefault
Definition: parsenodes.h:2342
@ AT_CookedColumnDefault
Definition: parsenodes.h:2343
@ AT_AlterConstraint
Definition: parsenodes.h:2360
@ AT_EnableTrigAll
Definition: parsenodes.h:2382
@ AT_DropCluster
Definition: parsenodes.h:2369
@ AT_ValidateConstraint
Definition: parsenodes.h:2361
@ AT_AddColumn
Definition: parsenodes.h:2340
#define lfirst(lc)
Definition: pg_list.h:172
LOCKMODE AlterTableGetRelOptionsLockLevel(List *defList)
Definition: reloptions.c:2108
AlterTableType subtype
Definition: parsenodes.h:2419
ConstrType contype
Definition: parsenodes.h:2721
Definition: pg_list.h:54

References AccessExclusiveLock, AccessShareLock, 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_CheckNotNull, AT_ClusterOn, AT_ColumnDefault, AT_CookedColumnDefault, AT_DetachPartition, AT_DetachPartitionFinalize, AT_DisableRowSecurity, AT_DisableRule, AT_DisableTrig, AT_DisableTrigAll, AT_DisableTrigUser, AT_DropCluster, AT_DropColumn, AT_DropConstraint, AT_DropExpression, AT_DropIdentity, AT_DropInherit, AT_DropNotNull, AT_DropOf, AT_DropOids, AT_EnableAlwaysRule, AT_EnableAlwaysTrig, AT_EnableReplicaRule, AT_EnableReplicaTrig, AT_EnableRowSecurity, AT_EnableRule, AT_EnableTrig, AT_EnableTrigAll, AT_EnableTrigUser, AT_ForceRowSecurity, AT_GenericOptions, AT_NoForceRowSecurity, AT_ReAddConstraint, AT_ReAddDomainConstraint, AT_ReplaceRelOptions, AT_ReplicaIdentity, AT_ResetOptions, AT_ResetRelOptions, AT_SetAccessMethod, AT_SetCompression, AT_SetExpression, AT_SetIdentity, AT_SetLogged, AT_SetNotNull, AT_SetOptions, AT_SetRelOptions, AT_SetStatistics, AT_SetStorage, AT_SetTableSpace, AT_SetUnLogged, AT_ValidateConstraint, CONSTR_EXCLUSION, CONSTR_FOREIGN, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, AlterTableCmd::def, elog, ERROR, IsA, lfirst, ShareRowExclusiveLock, ShareUpdateExclusiveLock, and AlterTableCmd::subtype.

Referenced by AlterTableInternal(), and ProcessUtilitySlow().

◆ AlterTableInternal()

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

Definition at line 4387 of file tablecmds.c.

4388 {
4389  Relation rel;
4390  LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
4391 
4392  rel = relation_open(relid, lockmode);
4393 
4395 
4396  ATController(NULL, rel, cmds, recurse, lockmode, NULL);
4397 }
void EventTriggerAlterTableRelid(Oid objectId)
LOCKMODE AlterTableGetLockLevel(List *cmds)
Definition: tablecmds.c:4432

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

Referenced by AlterTableMoveAll(), and DefineVirtualRelation().

◆ AlterTableLookupRelation()

Oid AlterTableLookupRelation ( AlterTableStmt stmt,
LOCKMODE  lockmode 
)

Definition at line 4299 of file tablecmds.c.

4300 {
4301  return RangeVarGetRelidExtended(stmt->relation, lockmode,
4302  stmt->missing_ok ? RVR_MISSING_OK : 0,
4304  (void *) stmt);
4305 }
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:17649

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

Referenced by ProcessUtilitySlow().

◆ AlterTableMoveAll()

Oid AlterTableMoveAll ( AlterTableMoveAllStmt stmt)

Definition at line 15191 of file tablecmds.c.

15192 {
15193  List *relations = NIL;
15194  ListCell *l;
15195  ScanKeyData key[1];
15196  Relation rel;
15197  TableScanDesc scan;
15198  HeapTuple tuple;
15199  Oid orig_tablespaceoid;
15200  Oid new_tablespaceoid;
15201  List *role_oids = roleSpecsToIds(stmt->roles);
15202 
15203  /* Ensure we were not asked to move something we can't */
15204  if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
15205  stmt->objtype != OBJECT_MATVIEW)
15206  ereport(ERROR,
15207  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
15208  errmsg("only tables, indexes, and materialized views exist in tablespaces")));
15209 
15210  /* Get the orig and new tablespace OIDs */
15211  orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
15212  new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
15213 
15214  /* Can't move shared relations in to or out of pg_global */
15215  /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
15216  if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
15217  new_tablespaceoid == GLOBALTABLESPACE_OID)
15218  ereport(ERROR,
15219  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
15220  errmsg("cannot move relations in to or out of pg_global tablespace")));
15221 
15222  /*
15223  * Must have CREATE rights on the new tablespace, unless it is the
15224  * database default tablespace (which all users implicitly have CREATE
15225  * rights on).
15226  */
15227  if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
15228  {
15229  AclResult aclresult;
15230 
15231  aclresult = object_aclcheck(TableSpaceRelationId, new_tablespaceoid, GetUserId(),
15232  ACL_CREATE);
15233  if (aclresult != ACLCHECK_OK)
15234  aclcheck_error(aclresult, OBJECT_TABLESPACE,
15235  get_tablespace_name(new_tablespaceoid));
15236  }
15237 
15238  /*
15239  * Now that the checks are done, check if we should set either to
15240  * InvalidOid because it is our database's default tablespace.
15241  */
15242  if (orig_tablespaceoid == MyDatabaseTableSpace)
15243  orig_tablespaceoid = InvalidOid;
15244 
15245  if (new_tablespaceoid == MyDatabaseTableSpace)
15246  new_tablespaceoid = InvalidOid;
15247 
15248  /* no-op */
15249  if (orig_tablespaceoid == new_tablespaceoid)
15250  return new_tablespaceoid;
15251 
15252  /*
15253  * Walk the list of objects in the tablespace and move them. This will
15254  * only find objects in our database, of course.
15255  */
15256  ScanKeyInit(&key[0],
15257  Anum_pg_class_reltablespace,
15258  BTEqualStrategyNumber, F_OIDEQ,
15259  ObjectIdGetDatum(orig_tablespaceoid));
15260 
15261  rel = table_open(RelationRelationId, AccessShareLock);
15262  scan = table_beginscan_catalog(rel, 1, key);
15263  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
15264  {
15265  Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
15266  Oid relOid = relForm->oid;
15267 
15268  /*
15269  * Do not move objects in pg_catalog as part of this, if an admin
15270  * really wishes to do so, they can issue the individual ALTER
15271  * commands directly.
15272  *
15273  * Also, explicitly avoid any shared tables, temp tables, or TOAST
15274  * (TOAST will be moved with the main table).
15275  */
15276  if (IsCatalogNamespace(relForm->relnamespace) ||
15277  relForm->relisshared ||
15278  isAnyTempNamespace(relForm->relnamespace) ||
15279  IsToastNamespace(relForm->relnamespace))
15280  continue;
15281 
15282  /* Only move the object type requested */
15283  if ((stmt->objtype == OBJECT_TABLE &&
15284  relForm->relkind != RELKIND_RELATION &&
15285  relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
15286  (stmt->objtype == OBJECT_INDEX &&
15287  relForm->relkind != RELKIND_INDEX &&
15288  relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
15289  (stmt->objtype == OBJECT_MATVIEW &&
15290  relForm->relkind != RELKIND_MATVIEW))
15291  continue;
15292 
15293  /* Check if we are only moving objects owned by certain roles */
15294  if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
15295  continue;
15296 
15297  /*
15298  * Handle permissions-checking here since we are locking the tables
15299  * and also to avoid doing a bunch of work only to fail part-way. Note
15300  * that permissions will also be checked by AlterTableInternal().
15301  *
15302  * Caller must be considered an owner on the table to move it.
15303  */
15304  if (!object_ownercheck(RelationRelationId, relOid, GetUserId()))
15306  NameStr(relForm->relname));
15307 
15308  if (stmt->nowait &&
15310  ereport(ERROR,
15311  (errcode(ERRCODE_OBJECT_IN_USE),
15312  errmsg("aborting because lock on relation \"%s.%s\" is not available",
15313  get_namespace_name(relForm->relnamespace),
15314  NameStr(relForm->relname))));
15315  else
15317 
15318  /* Add to our list of objects to move */
15319  relations = lappend_oid(relations, relOid);
15320  }
15321 
15322  table_endscan(scan);
15324 
15325  if (relations == NIL)
15326  ereport(NOTICE,
15327  (errcode(ERRCODE_NO_DATA_FOUND),
15328  errmsg("no matching relations in tablespace \"%s\" found",
15329  orig_tablespaceoid == InvalidOid ? "(database default)" :
15330  get_tablespace_name(orig_tablespaceoid))));
15331 
15332  /* Everything is locked, loop through and move all of the relations. */
15333  foreach(l, relations)
15334  {
15335  List *cmds = NIL;
15337 
15338  cmd->subtype = AT_SetTableSpace;
15339  cmd->name = stmt->new_tablespacename;
15340 
15341  cmds = lappend(cmds, cmd);
15342 
15344  /* OID is set by AlterTableInternal */
15345  AlterTableInternal(lfirst_oid(l), cmds, false);
15347  }
15348 
15349  return new_tablespaceoid;
15350 }
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:2700
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:3888
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4142
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
#define OidIsValid(objectId)
Definition: c.h:775
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:221
bool IsCatalogNamespace(Oid namespaceId)
Definition: catalog.c:203
#define NOTICE
Definition: elog.h:35
void EventTriggerAlterTableStart(Node *parsetree)
void EventTriggerAlterTableEnd(void)
Oid MyDatabaseTableSpace
Definition: globals.c:95
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1252
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
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:2271
@ OBJECT_TABLESPACE
Definition: parsenodes.h:2290
@ OBJECT_INDEX
Definition: parsenodes.h:2268
@ OBJECT_TABLE
Definition: parsenodes.h:2289
#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:1019
void AlterTableInternal(Oid relid, List *cmds, bool recurse)
Definition: tablecmds.c:4387
List * roleSpecsToIds(List *memberNames)
Definition: user.c:1652

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

17017 {
17018  Relation rel;
17019  Oid relid;
17020  Oid oldNspOid;
17021  Oid nspOid;
17022  RangeVar *newrv;
17023  ObjectAddresses *objsMoved;
17024  ObjectAddress myself;
17025 
17027  stmt->missing_ok ? RVR_MISSING_OK : 0,
17029  (void *) stmt);
17030 
17031  if (!OidIsValid(relid))
17032  {
17033  ereport(NOTICE,
17034  (errmsg("relation \"%s\" does not exist, skipping",
17035  stmt->relation->relname)));
17036  return InvalidObjectAddress;
17037  }
17038 
17039  rel = relation_open(relid, NoLock);
17040 
17041  oldNspOid = RelationGetNamespace(rel);
17042 
17043  /* If it's an owned sequence, disallow moving it by itself. */
17044  if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
17045  {
17046  Oid tableId;
17047  int32 colId;
17048 
17049  if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
17050  sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
17051  ereport(ERROR,
17052  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
17053  errmsg("cannot move an owned sequence into another schema"),
17054  errdetail("Sequence \"%s\" is linked to table \"%s\".",
17056  get_rel_name(tableId))));
17057  }
17058 
17059  /* Get and lock schema OID and check its permissions. */
17060  newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
17061  nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
17062 
17063  /* common checks on switching namespaces */
17064  CheckSetNamespace(oldNspOid, nspOid);
17065 
17066  objsMoved = new_object_addresses();
17067  AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
17068  free_object_addresses(objsMoved);
17069 
17070  ObjectAddressSet(myself, RelationRelationId, relid);
17071 
17072  if (oldschema)
17073  *oldschema = oldNspOid;
17074 
17075  /* close rel, but keep lock until commit */
17076  relation_close(rel, NoLock);
17077 
17078  return myself;
17079 }
signed int int32
Definition: c.h:494
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2487
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2773
@ DEPENDENCY_AUTO
Definition: dependency.h:34
@ DEPENDENCY_INTERNAL
Definition: dependency.h:35
int errdetail(const char *fmt,...)
Definition: elog.c:1203
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:829
#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:17087

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

17089 {
17090  Relation classRel;
17091 
17092  Assert(objsMoved != NULL);
17093 
17094  /* OK, modify the pg_class row and pg_depend entry */
17095  classRel = table_open(RelationRelationId, RowExclusiveLock);
17096 
17097  AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
17098  nspOid, true, objsMoved);
17099 
17100  /* Fix the table's row type too, if it has one */
17101  if (OidIsValid(rel->rd_rel->reltype))
17102  AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid,
17103  false, /* isImplicitArray */
17104  false, /* ignoreDependent */
17105  false, /* errorOnTableType */
17106  objsMoved);
17107 
17108  /* Fix other dependent stuff */
17109  AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
17110  AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
17111  objsMoved, AccessExclusiveLock);
17112  AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
17113  false, objsMoved);
17114 
17115  table_close(classRel, RowExclusiveLock);
17116 }
#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:17124
static void AlterSeqNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved, LOCKMODE lockmode)
Definition: tablecmds.c:17239
static void AlterIndexNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:17194
Oid AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid, bool isImplicitArray, bool ignoreDependent, bool errorOnTableType, ObjectAddresses *objsMoved)
Definition: typecmds.c:4156

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

17524 {
17525  ListCell *cur_item;
17526 
17527  foreach(cur_item, on_commits)
17528  {
17529  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
17530 
17531  if (!isCommit && oc->creating_subid == mySubid)
17532  {
17533  /* cur_item must be removed */
17535  pfree(oc);
17536  }
17537  else
17538  {
17539  /* cur_item must be preserved */
17540  if (oc->creating_subid == mySubid)
17541  oc->creating_subid = parentSubid;
17542  if (oc->deleting_subid == mySubid)
17543  oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
17544  }
17545  }
17546 }
#define InvalidSubTransactionId
Definition: c.h:658
void pfree(void *pointer)
Definition: mcxt.c:1521
#define foreach_delete_current(lst, var_or_cell)
Definition: pg_list.h:391
SubTransactionId creating_subid
Definition: tablecmds.c:125
SubTransactionId deleting_subid
Definition: tablecmds.c:126
static List * on_commits
Definition: tablecmds.c:129

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

17491 {
17492  ListCell *cur_item;
17493 
17494  foreach(cur_item, on_commits)
17495  {
17496  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
17497 
17498  if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
17500  {
17501  /* cur_item must be removed */
17503  pfree(oc);
17504  }
17505  else
17506  {
17507  /* cur_item must be preserved */
17510  }
17511  }
17512 }

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

14284 {
14285  Relation target_rel;
14286  Relation class_rel;
14287  HeapTuple tuple;
14288  Form_pg_class tuple_class;
14289 
14290  /*
14291  * Get exclusive lock till end of transaction on the target table. Use
14292  * relation_open so that we can work on indexes and sequences.
14293  */
14294  target_rel = relation_open(relationOid, lockmode);
14295 
14296  /* Get its pg_class tuple, too */
14297  class_rel = table_open(RelationRelationId, RowExclusiveLock);
14298 
14299  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
14300  if (!HeapTupleIsValid(tuple))
14301  elog(ERROR, "cache lookup failed for relation %u", relationOid);
14302  tuple_class = (Form_pg_class) GETSTRUCT(tuple);
14303 
14304  /* Can we change the ownership of this tuple? */
14305  switch (tuple_class->relkind)
14306  {
14307  case RELKIND_RELATION:
14308  case RELKIND_VIEW:
14309  case RELKIND_MATVIEW:
14310  case RELKIND_FOREIGN_TABLE:
14311  case RELKIND_PARTITIONED_TABLE:
14312  /* ok to change owner */
14313  break;
14314  case RELKIND_INDEX:
14315  if (!recursing)
14316  {
14317  /*
14318  * Because ALTER INDEX OWNER used to be allowed, and in fact
14319  * is generated by old versions of pg_dump, we give a warning
14320  * and do nothing rather than erroring out. Also, to avoid
14321  * unnecessary chatter while restoring those old dumps, say
14322  * nothing at all if the command would be a no-op anyway.
14323  */
14324  if (tuple_class->relowner != newOwnerId)
14325  ereport(WARNING,
14326  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
14327  errmsg("cannot change owner of index \"%s\"",
14328  NameStr(tuple_class->relname)),
14329  errhint("Change the ownership of the index's table instead.")));
14330  /* quick hack to exit via the no-op path */
14331  newOwnerId = tuple_class->relowner;
14332  }
14333  break;
14334  case RELKIND_PARTITIONED_INDEX:
14335  if (recursing)
14336  break;
14337  ereport(ERROR,
14338  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
14339  errmsg("cannot change owner of index \"%s\"",
14340  NameStr(tuple_class->relname)),
14341  errhint("Change the ownership of the index's table instead.")));
14342  break;
14343  case RELKIND_SEQUENCE:
14344  if (!recursing &&
14345  tuple_class->relowner != newOwnerId)
14346  {
14347  /* if it's an owned sequence, disallow changing it by itself */
14348  Oid tableId;
14349  int32 colId;
14350 
14351  if (sequenceIsOwned(relationOid, DEPENDENCY_AUTO, &tableId, &colId) ||
14352  sequenceIsOwned(relationOid, DEPENDENCY_INTERNAL, &tableId, &colId))
14353  ereport(ERROR,
14354  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
14355  errmsg("cannot change owner of sequence \"%s\"",
14356  NameStr(tuple_class->relname)),
14357  errdetail("Sequence \"%s\" is linked to table \"%s\".",
14358  NameStr(tuple_class->relname),
14359  get_rel_name(tableId))));
14360  }
14361  break;
14362  case RELKIND_COMPOSITE_TYPE:
14363  if (recursing)
14364  break;
14365  ereport(ERROR,
14366  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
14367  errmsg("\"%s\" is a composite type",
14368  NameStr(tuple_class->relname)),
14369  /* translator: %s is an SQL ALTER command */
14370  errhint("Use %s instead.",
14371  "ALTER TYPE")));
14372  break;
14373  case RELKIND_TOASTVALUE:
14374  if (recursing)
14375  break;
14376  /* FALL THRU */
14377  default:
14378  ereport(ERROR,
14379  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
14380  errmsg("cannot change owner of relation \"%s\"",
14381  NameStr(tuple_class->relname)),
14382  errdetail_relkind_not_supported(tuple_class->relkind)));
14383  }
14384 
14385  /*
14386  * If the new owner is the same as the existing owner, consider the
14387  * command to have succeeded. This is for dump restoration purposes.
14388  */
14389  if (tuple_class->relowner != newOwnerId)
14390  {
14391  Datum repl_val[Natts_pg_class];
14392  bool repl_null[Natts_pg_class];
14393  bool repl_repl[Natts_pg_class];
14394  Acl *newAcl;
14395  Datum aclDatum;
14396  bool isNull;
14397  HeapTuple newtuple;
14398 
14399  /* skip permission checks when recursing to index or toast table */
14400  if (!recursing)
14401  {
14402  /* Superusers can always do it */
14403  if (!superuser())
14404  {
14405  Oid namespaceOid = tuple_class->relnamespace;
14406  AclResult aclresult;
14407 
14408  /* Otherwise, must be owner of the existing object */
14409  if (!object_ownercheck(RelationRelationId, relationOid, GetUserId()))
14411  RelationGetRelationName(target_rel));
14412 
14413  /* Must be able to become new owner */
14414  check_can_set_role(GetUserId(), newOwnerId);
14415 
14416  /* New owner must have CREATE privilege on namespace */
14417  aclresult = object_aclcheck(NamespaceRelationId, namespaceOid, newOwnerId,
14418  ACL_CREATE);
14419  if (aclresult != ACLCHECK_OK)
14420  aclcheck_error(aclresult, OBJECT_SCHEMA,
14421  get_namespace_name(namespaceOid));
14422  }
14423  }
14424 
14425  memset(repl_null, false, sizeof(repl_null));
14426  memset(repl_repl, false, sizeof(repl_repl));
14427 
14428  repl_repl[Anum_pg_class_relowner - 1] = true;
14429  repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
14430 
14431  /*
14432  * Determine the modified ACL for the new owner. This is only
14433  * necessary when the ACL is non-null.
14434  */
14435  aclDatum = SysCacheGetAttr(RELOID, tuple,
14436  Anum_pg_class_relacl,
14437  &isNull);
14438  if (!isNull)
14439  {
14440  newAcl = aclnewowner(DatumGetAclP(aclDatum),
14441  tuple_class->relowner, newOwnerId);
14442  repl_repl[Anum_pg_class_relacl - 1] = true;
14443  repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
14444  }
14445 
14446  newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
14447 
14448  CatalogTupleUpdate(class_rel, &newtuple->t_self, newtuple);
14449 
14450  heap_freetuple(newtuple);
14451 
14452  /*
14453  * We must similarly update any per-column ACLs to reflect the new
14454  * owner; for neatness reasons that's split out as a subroutine.
14455  */
14456  change_owner_fix_column_acls(relationOid,
14457  tuple_class->relowner,
14458  newOwnerId);
14459 
14460  /*
14461  * Update owner dependency reference, if any. A composite type has
14462  * none, because it's tracked for the pg_type entry instead of here;
14463  * indexes and TOAST tables don't have their own entries either.
14464  */
14465  if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
14466  tuple_class->relkind != RELKIND_INDEX &&
14467  tuple_class->relkind != RELKIND_PARTITIONED_INDEX &&
14468  tuple_class->relkind != RELKIND_TOASTVALUE)
14469  changeDependencyOnOwner(RelationRelationId, relationOid,
14470  newOwnerId);
14471 
14472  /*
14473  * Also change the ownership of the table's row type, if it has one
14474  */
14475  if (OidIsValid(tuple_class->reltype))
14476  AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId);
14477 
14478  /*
14479  * If we are operating on a table or materialized view, also change
14480  * the ownership of any indexes and sequences that belong to the
14481  * relation, as well as its toast table (if it has one).
14482  */
14483  if (tuple_class->relkind == RELKIND_RELATION ||
14484  tuple_class->relkind == RELKIND_PARTITIONED_TABLE ||
14485  tuple_class->relkind == RELKIND_MATVIEW ||
14486  tuple_class->relkind == RELKIND_TOASTVALUE)
14487  {
14488  List *index_oid_list;
14489  ListCell *i;
14490 
14491  /* Find all the indexes belonging to this relation */
14492  index_oid_list = RelationGetIndexList(target_rel);
14493 
14494  /* For each index, recursively change its ownership */
14495  foreach(i, index_oid_list)
14496  ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
14497 
14498  list_free(index_oid_list);
14499  }
14500 
14501  /* If it has a toast table, recurse to change its ownership */
14502  if (tuple_class->reltoastrelid != InvalidOid)
14503  ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
14504  true, lockmode);
14505 
14506  /* If it has dependent sequences, recurse to change them too */
14507  change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
14508  }
14509 
14510  InvokeObjectPostAlterHook(RelationRelationId, relationOid, 0);
14511 
14512  ReleaseSysCache(tuple);
14513  table_close(class_rel, RowExclusiveLock);
14514  relation_close(target_rel, NoLock);
14515 }
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition: acl.c:1102
void check_can_set_role(Oid member, Oid role)
Definition: acl.c:5191
#define DatumGetAclP(X)
Definition: acl.h:120
int errhint(const char *fmt,...)
Definition: elog.c:1317
#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:2284
int errdetail_relkind_not_supported(char relkind)
Definition: pg_class.c:24
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
Definition: pg_shdepend.c:316
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:4801
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:14283
static void change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
Definition: tablecmds.c:14589
static void change_owner_fix_column_acls(Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
Definition: tablecmds.c:14524
void AlterTypeOwnerInternal(Oid typeOid, Oid newOwnerId)
Definition: typecmds.c:3987

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

◆ BuildDescForRelation()

TupleDesc BuildDescForRelation ( const List columns)

Definition at line 1277 of file tablecmds.c.

1278 {
1279  int natts;
1281  ListCell *l;
1282  TupleDesc desc;
1283  char *attname;
1284  Oid atttypid;
1285  int32 atttypmod;
1286  Oid attcollation;
1287  int attdim;
1288 
1289  /*
1290  * allocate a new tuple descriptor
1291  */
1292  natts = list_length(columns);
1293  desc = CreateTemplateTupleDesc(natts);
1294 
1295  attnum = 0;
1296 
1297  foreach(l, columns)
1298  {
1299  ColumnDef *entry = lfirst(l);
1300  AclResult aclresult;
1301  Form_pg_attribute att;
1302 
1303  /*
1304  * for each entry in the list, get the name and type information from
1305  * the list and have TupleDescInitEntry fill in the attribute
1306  * information we need.
1307  */
1308  attnum++;
1309 
1310  attname = entry->colname;
1311  typenameTypeIdAndMod(NULL, entry->typeName, &atttypid, &atttypmod);
1312 
1313  aclresult = object_aclcheck(TypeRelationId, atttypid, GetUserId(), ACL_USAGE);
1314  if (aclresult != ACLCHECK_OK)
1315  aclcheck_error_type(aclresult, atttypid);
1316 
1317  attcollation = GetColumnDefCollation(NULL, entry, atttypid);
1318  attdim = list_length(entry->typeName->arrayBounds);
1319  if (attdim > PG_INT16_MAX)
1320  ereport(ERROR,
1321  errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1322  errmsg("too many array dimensions"));
1323 
1324  if (entry->typeName->setof)
1325  ereport(ERROR,
1326  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1327  errmsg("column \"%s\" cannot be declared SETOF",
1328  attname)));
1329 
1331  atttypid, atttypmod, attdim);
1332  att = TupleDescAttr(desc, attnum - 1);
1333 
1334  /* Override TupleDescInitEntry's settings as requested */
1335  TupleDescInitEntryCollation(desc, attnum, attcollation);
1336 
1337  /* Fill in additional stuff not handled by TupleDescInitEntry */
1338  att->attnotnull = entry->is_not_null;
1339  att->attislocal = entry->is_local;
1340  att->attinhcount = entry->inhcount;
1341  att->attidentity = entry->identity;
1342  att->attgenerated = entry->generated;
1343  att->attcompression = GetAttributeCompression(att->atttypid, entry->compression);
1344  if (entry->storage)
1345  att->attstorage = entry->storage;
1346  else if (entry->storage_name)
1347  att->attstorage = GetAttributeStorage(att->atttypid, entry->storage_name);
1348  }
1349 
1350  return desc;
1351 }
void aclcheck_error_type(AclResult aclerr, Oid typeOid)
Definition: aclchk.c:3019
int16 AttrNumber
Definition: attnum.h:21
#define PG_INT16_MAX
Definition: c.h:586
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 setof
Definition: parsenodes.h:270
List * arrayBounds
Definition: parsenodes.h:274
static char GetAttributeCompression(Oid atttypid, const char *compression)
Definition: tablecmds.c:19946
static char GetAttributeStorage(Oid atttypid, const char *storagemode)
Definition: tablecmds.c:19984
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, ColumnDef::colname, ColumnDef::compression, CreateTemplateTupleDesc(), ereport, errcode(), errmsg(), ERROR, ColumnDef::generated, GetAttributeCompression(), GetAttributeStorage(), GetColumnDefCollation(), GetUserId(), ColumnDef::identity, ColumnDef::inhcount, ColumnDef::is_local, ColumnDef::is_not_null, lfirst, list_length(), object_aclcheck(), 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 6884 of file tablecmds.c.

6885 {
6886  Form_pg_type typ = (Form_pg_type) GETSTRUCT(typetuple);
6887  bool typeOk = false;
6888 
6889  if (typ->typtype == TYPTYPE_COMPOSITE)
6890  {
6891  Relation typeRelation;
6892 
6893  Assert(OidIsValid(typ->typrelid));
6894  typeRelation = relation_open(typ->typrelid, AccessShareLock);
6895  typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
6896 
6897  /*
6898  * Close the parent rel, but keep our AccessShareLock on it until xact
6899  * commit. That will prevent someone else from deleting or ALTERing
6900  * the type before the typed table creation/conversion commits.
6901  */
6902  relation_close(typeRelation, NoLock);
6903 
6904  if (!typeOk)
6905  ereport(ERROR,
6906  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6907  errmsg("type %s is the row type of another table",
6908  format_type_be(typ->oid)),
6909  errdetail("A typed table must use a stand-alone composite type created with CREATE TYPE.")));
6910  }
6911  else
6912  ereport(ERROR,
6913  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6914  errmsg("type %s is not a composite type",
6915  format_type_be(typ->oid))));
6916 }
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(), errdetail(), 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 3526 of file tablecmds.c.

3527 {
3528  Oid oldTableSpaceId;
3529 
3530  /*
3531  * No work if no change in tablespace. Note that MyDatabaseTableSpace is
3532  * stored as 0.
3533  */
3534  oldTableSpaceId = rel->rd_rel->reltablespace;
3535  if (newTableSpaceId == oldTableSpaceId ||
3536  (newTableSpaceId == MyDatabaseTableSpace && oldTableSpaceId == 0))
3537  return false;
3538 
3539  /*
3540  * We cannot support moving mapped relations into different tablespaces.
3541  * (In particular this eliminates all shared catalogs.)
3542  */
3543  if (RelationIsMapped(rel))
3544  ereport(ERROR,
3545  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3546  errmsg("cannot move system relation \"%s\"",
3547  RelationGetRelationName(rel))));
3548 
3549  /* Cannot move a non-shared relation into pg_global */
3550  if (newTableSpaceId == GLOBALTABLESPACE_OID)
3551  ereport(ERROR,
3552  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3553  errmsg("only shared relations can be placed in pg_global tablespace")));
3554 
3555  /*
3556  * Do not allow moving temp tables of other backends ... their local
3557  * buffer manager is not going to cope.
3558  */
3559  if (RELATION_IS_OTHER_TEMP(rel))
3560  ereport(ERROR,
3561  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3562  errmsg("cannot move temporary tables of other sessions")));
3563 
3564  return true;
3565 }
#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 4240 of file tablecmds.c.

4241 {
4242  int expected_refcnt;
4243 
4244  expected_refcnt = rel->rd_isnailed ? 2 : 1;
4245  if (rel->rd_refcnt != expected_refcnt)
4246  ereport(ERROR,
4247  (errcode(ERRCODE_OBJECT_IN_USE),
4248  /* translator: first %s is a SQL command, eg ALTER TABLE */
4249  errmsg("cannot %s \"%s\" because it is being used by active queries in this session",
4250  stmt, RelationGetRelationName(rel))));
4251 
4252  if (rel->rd_rel->relkind != RELKIND_INDEX &&
4253  rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
4255  ereport(ERROR,
4256  (errcode(ERRCODE_OBJECT_IN_USE),
4257  /* translator: first %s is a SQL command, eg ALTER TABLE */
4258  errmsg("cannot %s \"%s\" because it has pending trigger events",
4259  stmt, RelationGetRelationName(rel))));
4260 }
int rd_refcnt
Definition: rel.h:59
bool rd_isnailed
Definition: rel.h:62
bool AfterTriggerPendingOnRel(Oid relid)
Definition: trigger.c:5976

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

Referenced by CheckAlterTableIsSafe(), cluster_rel(), DefineIndex(), DefineVirtualRelation(), heap_drop_with_catalog(), index_drop(), MergeAttributes(), RefreshMatViewByOid(), reindex_index(), and truncate_check_activity().

◆ DefineRelation()

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

Definition at line 682 of file tablecmds.c.

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

References AccessExclusiveLock, AccessShareLock, ACL_CREATE, ACL_USAGE, aclcheck_error(), aclcheck_error_type(), ACLCHECK_OK, addNSItemToQuery(), addRangeTableEntryForRelation(), AddRelationNewConstraints(), allowSystemTableMods, Assert, RawColumnDefault::attnum, CookedConstraint::attnum, attnum, build_attrmap_by_name(), BuildDescForRelation(), check_default_partition_contents(), check_new_partition_bound(), CloneForeignKeyConstraints(), CloneRowTriggersToPartition(), CommandCounterIncrement(), 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_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, 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 1756 of file tablecmds.c.

1757 {
1758  List *rels = NIL;
1759  List *relids = NIL;
1760  List *relids_logged = NIL;
1761  ListCell *cell;
1762 
1763  /*
1764  * Open, exclusive-lock, and check all the explicitly-specified relations
1765  */
1766  foreach(cell, stmt->relations)
1767  {
1768  RangeVar *rv = lfirst(cell);
1769  Relation rel;
1770  bool recurse = rv->inh;
1771  Oid myrelid;
1772  LOCKMODE lockmode = AccessExclusiveLock;
1773 
1774  myrelid = RangeVarGetRelidExtended(rv, lockmode,
1776  NULL);
1777 
1778  /* don't throw error for "TRUNCATE foo, foo" */
1779  if (list_member_oid(relids, myrelid))
1780  continue;
1781 
1782  /* open the relation, we already hold a lock on it */
1783  rel = table_open(myrelid, NoLock);
1784 
1785  /*
1786  * RangeVarGetRelidExtended() has done most checks with its callback,
1787  * but other checks with the now-opened Relation remain.
1788  */
1790 
1791  rels = lappend(rels, rel);
1792  relids = lappend_oid(relids, myrelid);
1793 
1794  /* Log this relation only if needed for logical decoding */
1795  if (RelationIsLogicallyLogged(rel))
1796  relids_logged = lappend_oid(relids_logged, myrelid);
1797 
1798  if (recurse)
1799  {
1800  ListCell *child;
1801  List *children;
1802 
1803  children = find_all_inheritors(myrelid, lockmode, NULL);
1804 
1805  foreach(child, children)
1806  {
1807  Oid childrelid = lfirst_oid(child);
1808 
1809  if (list_member_oid(relids, childrelid))
1810  continue;
1811 
1812  /* find_all_inheritors already got lock */
1813  rel = table_open(childrelid, NoLock);
1814 
1815  /*
1816  * It is possible that the parent table has children that are
1817  * temp tables of other backends. We cannot safely access
1818  * such tables (because of buffering issues), and the best
1819  * thing to do is to silently ignore them. Note that this
1820  * check is the same as one of the checks done in
1821  * truncate_check_activity() called below, still it is kept
1822  * here for simplicity.
1823  */
1824  if (RELATION_IS_OTHER_TEMP(rel))
1825  {
1826  table_close(rel, lockmode);
1827  continue;
1828  }
1829 
1830  /*
1831  * Inherited TRUNCATE commands perform access permission
1832  * checks on the parent table only. So we skip checking the
1833  * children's permissions and don't call
1834  * truncate_check_perms() here.
1835  */
1838 
1839  rels = lappend(rels, rel);
1840  relids = lappend_oid(relids, childrelid);
1841 
1842  /* Log this relation only if needed for logical decoding */
1843  if (RelationIsLogicallyLogged(rel))
1844  relids_logged = lappend_oid(relids_logged, childrelid);
1845  }
1846  }
1847  else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1848  ereport(ERROR,
1849  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1850  errmsg("cannot truncate only a partitioned table"),
1851  errhint("Do not specify the ONLY keyword, or use TRUNCATE ONLY on the partitions directly.")));
1852  }
1853 
1854  ExecuteTruncateGuts(rels, relids, relids_logged,
1855  stmt->behavior, stmt->restart_seqs, false);
1856 
1857  /* And close the rels */
1858  foreach(cell, rels)
1859  {
1860  Relation rel = (Relation) lfirst(cell);
1861 
1862  table_close(rel, NoLock);
1863  }
1864 }
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:2333
static void truncate_check_rel(Oid relid, Form_pg_class reltuple)
Definition: tablecmds.c:2267
static void RangeVarCallbackForTruncate(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:17593
void ExecuteTruncateGuts(List *explicit_rels, List *relids, List *relids_logged, DropBehavior behavior, bool restart_seqs, bool run_as_table_owner)
Definition: tablecmds.c:1880

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

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

6679 {
6680  Relation depRel;
6681  ScanKeyData key[2];
6682  SysScanDesc depScan;
6683  HeapTuple depTup;
6684 
6685  /* since this function recurses, it could be driven to stack overflow */
6687 
6688  /*
6689  * We scan pg_depend to find those things that depend on the given type.
6690  * (We assume we can ignore refobjsubid for a type.)
6691  */
6692  depRel = table_open(DependRelationId, AccessShareLock);
6693 
6694  ScanKeyInit(&key[0],
6695  Anum_pg_depend_refclassid,
6696  BTEqualStrategyNumber, F_OIDEQ,
6697  ObjectIdGetDatum(TypeRelationId));
6698  ScanKeyInit(&key[1],
6699  Anum_pg_depend_refobjid,
6700  BTEqualStrategyNumber, F_OIDEQ,
6701  ObjectIdGetDatum(typeOid));
6702 
6703  depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
6704  NULL, 2, key);
6705 
6706  while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
6707  {
6708  Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
6709  Relation rel;
6710  TupleDesc tupleDesc;
6711  Form_pg_attribute att;
6712 
6713  /* Check for directly dependent types */
6714  if (pg_depend->classid == TypeRelationId)
6715  {
6716  /*
6717  * This must be an array, domain, or range containing the given
6718  * type, so recursively check for uses of this type. Note that
6719  * any error message will mention the original type not the
6720  * container; this is intentional.
6721  */
6722  find_composite_type_dependencies(pg_depend->objid,
6723  origRelation, origTypeName);
6724  continue;
6725  }
6726 
6727  /* Else, ignore dependees that aren't relations */
6728  if (pg_depend->classid != RelationRelationId)
6729  continue;
6730 
6731  rel = relation_open(pg_depend->objid, AccessShareLock);
6732  tupleDesc = RelationGetDescr(rel);
6733 
6734  /*
6735  * If objsubid identifies a specific column, refer to that in error
6736  * messages. Otherwise, search to see if there's a user column of the
6737  * type. (We assume system columns are never of interesting types.)
6738  * The search is needed because an index containing an expression
6739  * column of the target type will just be recorded as a whole-relation
6740  * dependency. If we do not find a column of the type, the dependency
6741  * must indicate that the type is transiently referenced in an index
6742  * expression but not stored on disk, which we assume is OK, just as
6743  * we do for references in views. (It could also be that the target
6744  * type is embedded in some container type that is stored in an index
6745  * column, but the previous recursion should catch such cases.)
6746  */
6747  if (pg_depend->objsubid > 0 && pg_depend->objsubid <= tupleDesc->natts)
6748  att = TupleDescAttr(tupleDesc, pg_depend->objsubid - 1);
6749  else
6750  {
6751  att = NULL;
6752  for (int attno = 1; attno <= tupleDesc->natts; attno++)
6753  {
6754  att = TupleDescAttr(tupleDesc, attno - 1);
6755  if (att->atttypid == typeOid && !att->attisdropped)
6756  break;
6757  att = NULL;
6758  }
6759  if (att == NULL)
6760  {
6761  /* No such column, so assume OK */
6763  continue;
6764  }
6765  }
6766 
6767  /*
6768  * We definitely should reject if the relation has storage. If it's
6769  * partitioned, then perhaps we don't have to reject: if there are
6770  * partitions then we'll fail when we find one, else there is no
6771  * stored data to worry about. However, it's possible that the type
6772  * change would affect conclusions about whether the type is sortable
6773  * or hashable and thus (if it's a partitioning column) break the
6774  * partitioning rule. For now, reject for partitioned rels too.
6775  */
6776  if (RELKIND_HAS_STORAGE(rel->rd_rel->relkind) ||
6777  RELKIND_HAS_PARTITIONS(rel->rd_rel->relkind))
6778  {
6779  if (origTypeName)
6780  ereport(ERROR,
6781  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6782  errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
6783  origTypeName,
6785  NameStr(att->attname))));
6786  else if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
6787  ereport(ERROR,
6788  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6789  errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
6790  RelationGetRelationName(origRelation),
6792  NameStr(att->attname))));
6793  else if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
6794  ereport(ERROR,
6795  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6796  errmsg("cannot alter foreign table \"%s\" because column \"%s.%s\" uses its row type",
6797  RelationGetRelationName(origRelation),
6799  NameStr(att->attname))));
6800  else
6801  ereport(ERROR,
6802  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6803  errmsg("cannot alter table \"%s\" because column \"%s.%s\" uses its row type",
6804  RelationGetRelationName(origRelation),
6806  NameStr(att->attname))));
6807  }
6808  else if (OidIsValid(rel->rd_rel->reltype))
6809  {
6810  /*
6811  * A view or composite type itself isn't a problem, but we must
6812  * recursively check for indirect dependencies via its rowtype.
6813  */
6815  origRelation, origTypeName);
6816  }
6817 
6819  }
6820 
6821  systable_endscan(depScan);
6822 
6824 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:597
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:504
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:385
FormData_pg_depend * Form_pg_depend
Definition: pg_depend.h:72
void check_stack_depth(void)
Definition: postgres.c:3540
void find_composite_type_dependencies(Oid typeOid, Relation origRelation, const char *origTypeName)
Definition: tablecmds.c:6677

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

18108 {
18109  List *existConstraint = NIL;
18110  TupleConstr *constr = RelationGetDescr(scanrel)->constr;
18111  int i;
18112 
18113  if (constr && constr->has_not_null)
18114  {
18115  int natts = scanrel->rd_att->natts;
18116 
18117  for (i = 1; i <= natts; i++)
18118  {
18119  Form_pg_attribute att = TupleDescAttr(scanrel->rd_att, i - 1);
18120 
18121  if (att->attnotnull && !att->attisdropped)
18122  {
18123  NullTest *ntest = makeNode(NullTest);
18124 
18125  ntest->arg = (Expr *) makeVar(1,
18126  i,
18127  att->atttypid,
18128  att->atttypmod,
18129  att->attcollation,
18130  0);
18131  ntest->nulltesttype = IS_NOT_NULL;
18132 
18133  /*
18134  * argisrow=false is correct even for a composite column,
18135  * because attnotnull does not represent a SQL-spec IS NOT
18136  * NULL test in such a case, just IS DISTINCT FROM NULL.
18137  */
18138  ntest->argisrow = false;
18139  ntest->location = -1;
18140  existConstraint = lappend(existConstraint, ntest);
18141  }
18142  }
18143  }
18144 
18145  return ConstraintImpliedByRelConstraint(scanrel, partConstraint, existConstraint);
18146 }
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
@ IS_NOT_NULL
Definition: primnodes.h:1948
NullTestType nulltesttype
Definition: primnodes.h:1955
ParseLoc location
Definition: primnodes.h:1958
Expr * arg
Definition: primnodes.h:1954
TupleDesc rd_att
Definition: rel.h:112
bool has_not_null
Definition: tupdesc.h:44
static bool ConstraintImpliedByRelConstraint(Relation scanrel, List *testConstraint, List *provenConstraint)
Definition: tablecmds.c:18159

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

17384 {
17385  ListCell *l;
17386  List *oids_to_truncate = NIL;
17387  List *oids_to_drop = NIL;
17388 
17389  foreach(l, on_commits)
17390  {
17391  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
17392 
17393  /* Ignore entry if already dropped in this xact */
17395  continue;
17396 
17397  switch (oc->oncommit)
17398  {
17399  case ONCOMMIT_NOOP:
17401  /* Do nothing (there shouldn't be such entries, actually) */
17402  break;
17403  case ONCOMMIT_DELETE_ROWS:
17404 
17405  /*
17406  * If this transaction hasn't accessed any temporary
17407  * relations, we can skip truncating ON COMMIT DELETE ROWS
17408  * tables, as they must still be empty.
17409  */
17411  oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
17412  break;
17413  case ONCOMMIT_DROP:
17414  oids_to_drop = lappend_oid(oids_to_drop, oc->relid);
17415  break;
17416  }
17417  }
17418 
17419  /*
17420  * Truncate relations before dropping so that all dependencies between
17421  * relations are removed after they are worked on. Doing it like this
17422  * might be a waste as it is possible that a relation being truncated will
17423  * be dropped anyway due to its parent being dropped, but this makes the
17424  * code more robust because of not having to re-check that the relation
17425  * exists at truncation time.
17426  */
17427  if (oids_to_truncate != NIL)
17428  heap_truncate(oids_to_truncate);
17429 
17430  if (oids_to_drop != NIL)
17431  {
17432  ObjectAddresses *targetObjects = new_object_addresses();
17433 
17434  foreach(l, oids_to_drop)
17435  {
17436  ObjectAddress object;
17437 
17438  object.classId = RelationRelationId;
17439  object.objectId = lfirst_oid(l);
17440  object.objectSubId = 0;
17441 
17442  Assert(!object_address_present(&object, targetObjects));
17443 
17444  add_exact_object_address(&object, targetObjects);
17445  }
17446 
17447  /*
17448  * Object deletion might involve toast table access (to clean up
17449  * toasted catalog entries), so ensure we have a valid snapshot.
17450  */
17452 
17453  /*
17454  * Since this is an automatic drop, rather than one directly initiated
17455  * by the user, we pass the PERFORM_DELETION_INTERNAL flag.
17456  */
17457  performMultipleDeletions(targetObjects, DROP_CASCADE,
17459 
17461 
17462 #ifdef USE_ASSERT_CHECKING
17463 
17464  /*
17465  * Note that table deletion will call remove_on_commit_action, so the
17466  * entry should get marked as deleted.
17467  */
17468  foreach(l, on_commits)
17469  {
17470  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
17471 
17472  if (oc->oncommit != ONCOMMIT_DROP)
17473  continue;
17474 
17476  }
17477 #endif
17478  }
17479 }
void performMultipleDeletions(const ObjectAddresses *objects, DropBehavior behavior, int flags)
Definition: dependency.c:332
#define PERFORM_DELETION_QUIETLY
Definition: dependency.h:94
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:92
void heap_truncate(List *relids)
Definition: heap.c:3018
@ 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:116
int MyXactFlags
Definition: xact.c:135
#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 17557 of file tablecmds.c.

17559 {
17560  char relkind;
17561  AclResult aclresult;
17562 
17563  /* Nothing to do if the relation was not found. */
17564  if (!OidIsValid(relId))
17565  return;
17566 
17567  /*
17568  * If the relation does exist, check whether it's an index. But note that
17569  * the relation might have been dropped between the time we did the name
17570  * lookup and now. In that case, there's nothing to do.
17571  */
17572  relkind = get_rel_relkind(relId);
17573  if (!relkind)
17574  return;
17575  if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
17576  relkind != RELKIND_MATVIEW && relkind != RELKIND_PARTITIONED_TABLE)
17577  ereport(ERROR,
17578  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17579  errmsg("\"%s\" is not a table or materialized view", relation->relname)));
17580 
17581  /* Check permissions */
17582  aclresult = pg_class_aclcheck(relId, GetUserId(), ACL_MAINTAIN);
17583  if (aclresult != ACLCHECK_OK)
17584  aclcheck_error(aclresult,
17586  relation->relname);
17587 }
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4091
#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 17617 of file tablecmds.c.

17619 {
17620  HeapTuple tuple;
17621 
17622  /* Nothing to do if the relation was not found. */
17623  if (!OidIsValid(relId))
17624  return;
17625 
17626  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
17627  if (!HeapTupleIsValid(tuple)) /* should not happen */
17628  elog(ERROR, "cache lookup failed for relation %u", relId);
17629 
17630  if (!object_ownercheck(RelationRelationId, relId, GetUserId()))
17632  relation->relname);
17633 
17634  if (!allowSystemTableMods &&
17635  IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
17636  ereport(ERROR,
17637  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
17638  errmsg("permission denied: \"%s\" is a system catalog",
17639  relation->relname)));
17640 
17641  ReleaseSysCache(tuple);
17642 }
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 17324 of file tablecmds.c.

17325 {
17326  OnCommitItem *oc;
17327  MemoryContext oldcxt;
17328 
17329  /*
17330  * We needn't bother registering the relation unless there is an ON COMMIT
17331  * action we need to take.
17332  */
17334  return;
17335 
17337 
17338  oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
17339  oc->relid = relid;
17340  oc->oncommit = action;
17343 
17344  /*
17345  * We use lcons() here so that ON COMMIT actions are processed in reverse
17346  * order of registration. That might not be essential but it seems
17347  * reasonable.
17348  */
17349  on_commits = lcons(oc, on_commits);
17350 
17351  MemoryContextSwitchTo(oldcxt);
17352 }
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 17360 of file tablecmds.c.

17361 {
17362  ListCell *l;
17363 
17364  foreach(l, on_commits)
17365  {
17366  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
17367 
17368  if (oc->relid == relid)
17369  {
17371  break;
17372  }
17373  }
17374 }

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

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

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

3840 {
3841  Oid relid;
3843  ObjectAddress address;
3844 
3845  /* lock level taken here should match renameatt_internal */
3847  stmt->missing_ok ? RVR_MISSING_OK : 0,
3849  NULL);
3850 
3851  if (!OidIsValid(relid))
3852  {
3853  ereport(NOTICE,
3854  (errmsg("relation \"%s\" does not exist, skipping",
3855  stmt->relation->relname)));
3856  return InvalidObjectAddress;
3857  }
3858 
3859  attnum =
3860  renameatt_internal(relid,
3861  stmt->subname, /* old att name */
3862  stmt->newname, /* new att name */
3863  stmt->relation->inh, /* recursive? */
3864  false, /* recursing? */
3865  0, /* expected inhcount */
3866  stmt->behavior);
3867 
3868  ObjectAddressSubSet(address, RelationRelationId, relid, attnum);
3869 
3870  return address;
3871 }
#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:3674
static void RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:3819

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

3984 {
3985  Oid relid = InvalidOid;
3986  Oid typid = InvalidOid;
3987 
3988  if (stmt->renameType == OBJECT_DOMCONSTRAINT)
3989  {
3990  Relation rel;
3991  HeapTuple tup;
3992 
3993  typid = typenameTypeId(NULL, makeTypeNameFromNameList(castNode(List, stmt->object)));
3994  rel = table_open(TypeRelationId, RowExclusiveLock);
3995  tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
3996  if (!HeapTupleIsValid(tup))
3997  elog(ERROR, "cache lookup failed for type %u", typid);
3998  checkDomainOwner(tup);
3999  ReleaseSysCache(tup);
4000  table_close(rel, NoLock);
4001  }
4002  else
4003  {
4004  /* lock level taken here should match rename_constraint_internal */
4006  stmt->missing_ok ? RVR_MISSING_OK : 0,
4008  NULL);
4009  if (!OidIsValid(relid))
4010  {
4011  ereport(NOTICE,
4012  (errmsg("relation \"%s\" does not exist, skipping",
4013  stmt->relation->relname)));
4014  return InvalidObjectAddress;
4015  }
4016  }
4017 
4018  return
4019  rename_constraint_internal(relid, typid,
4020  stmt->subname,
4021  stmt->newname,
4022  (stmt->relation &&
4023  stmt->relation->inh), /* recursive? */
4024  false, /* recursing? */
4025  0 /* expected inhcount */ );
4026 }
TypeName * makeTypeNameFromNameList(List *names)
Definition: makefuncs.c:458
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
@ OBJECT_DOMCONSTRAINT
Definition: parsenodes.h:2261
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:3877
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 4033 of file tablecmds.c.

4034 {
4035  bool is_index_stmt = stmt->renameType == OBJECT_INDEX;
4036  Oid relid;
4037  ObjectAddress address;
4038 
4039  /*
4040  * Grab an exclusive lock on the target table, index, sequence, view,
4041  * materialized view, or foreign table, which we will NOT release until
4042  * end of transaction.
4043  *
4044  * Lock level used here should match RenameRelationInternal, to avoid lock
4045  * escalation. However, because ALTER INDEX can be used with any relation
4046  * type, we mustn't believe without verification.
4047  */
4048  for (;;)
4049  {
4050  LOCKMODE lockmode;
4051  char relkind;
4052  bool obj_is_index;
4053 
4054  lockmode = is_index_stmt ? ShareUpdateExclusiveLock : AccessExclusiveLock;
4055 
4056  relid = RangeVarGetRelidExtended(stmt->relation, lockmode,
4057  stmt->missing_ok ? RVR_MISSING_OK : 0,
4059  (void *) stmt);
4060 
4061  if (!OidIsValid(relid))
4062  {
4063  ereport(NOTICE,
4064  (errmsg("relation \"%s\" does not exist, skipping",
4065  stmt->relation->relname)));
4066  return InvalidObjectAddress;
4067  }
4068 
4069  /*
4070  * We allow mismatched statement and object types (e.g., ALTER INDEX
4071  * to rename a table), but we might've used the wrong lock level. If
4072  * that happens, retry with the correct lock level. We don't bother
4073  * if we already acquired AccessExclusiveLock with an index, however.
4074  */
4075  relkind = get_rel_relkind(relid);
4076  obj_is_index = (relkind == RELKIND_INDEX ||
4077  relkind == RELKIND_PARTITIONED_INDEX);
4078  if (obj_is_index || is_index_stmt == obj_is_index)
4079  break;
4080 
4081  UnlockRelationOid(relid, lockmode);
4082  is_index_stmt = obj_is_index;
4083  }
4084 
4085  /* Do the work */
4086  RenameRelationInternal(relid, stmt->newname, false, is_index_stmt);
4087 
4088  ObjectAddressSet(address, RelationRelationId, relid);
4089 
4090  return address;
4091 }
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:4097

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

4098 {
4099  Relation targetrelation;
4100  Relation relrelation; /* for RELATION relation */
4101  HeapTuple reltup;
4102  Form_pg_class relform;
4103  Oid namespaceId;
4104 
4105  /*
4106  * Grab a lock on the target relation, which we will NOT release until end
4107  * of transaction. We need at least a self-exclusive lock so that
4108  * concurrent DDL doesn't overwrite the rename if they start updating
4109  * while still seeing the old version. The lock also guards against
4110  * triggering relcache reloads in concurrent sessions, which might not
4111  * handle this information changing under them. For indexes, we can use a
4112  * reduced lock level because RelationReloadIndexInfo() handles indexes
4113  * specially.
4114  */
4115  targetrelation = relation_open(myrelid, is_index ? ShareUpdateExclusiveLock : AccessExclusiveLock);
4116  namespaceId = RelationGetNamespace(targetrelation);
4117 
4118  /*
4119  * Find relation's pg_class tuple, and make sure newrelname isn't in use.
4120  */
4121  relrelation = table_open(RelationRelationId, RowExclusiveLock);
4122 
4123  reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
4124  if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
4125  elog(ERROR, "cache lookup failed for relation %u", myrelid);
4126  relform = (Form_pg_class) GETSTRUCT(reltup);
4127 
4128  if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
4129  ereport(ERROR,
4130  (errcode(ERRCODE_DUPLICATE_TABLE),
4131  errmsg("relation \"%s\" already exists",
4132  newrelname)));
4133 
4134  /*
4135  * RenameRelation is careful not to believe the caller's idea of the
4136  * relation kind being handled. We don't have to worry about this, but
4137  * let's not be totally oblivious to it. We can process an index as
4138  * not-an-index, but not the other way around.
4139  */
4140  Assert(!is_index ||
4141  is_index == (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
4142  targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX));
4143 
4144  /*
4145  * Update pg_class tuple with new relname. (Scribbling on reltup is OK
4146  * because it's a copy...)
4147  */
4148  namestrcpy(&(relform->relname), newrelname);
4149 
4150  CatalogTupleUpdate(relrelation, &reltup->t_self, reltup);
4151 
4152  InvokeObjectPostAlterHookArg(RelationRelationId, myrelid, 0,
4153  InvalidOid, is_internal);
4154 
4155  heap_freetuple(reltup);
4156  table_close(relrelation, RowExclusiveLock);
4157 
4158  /*
4159  * Also rename the associated type, if any.
4160  */
4161  if (OidIsValid(targetrelation->rd_rel->reltype))
4162  RenameTypeInternal(targetrelation->rd_rel->reltype,
4163  newrelname, namespaceId);
4164 
4165  /*
4166  * Also rename the associated constraint, if any.
4167  */
4168  if (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
4169  targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
4170  {
4171  Oid constraintId = get_index_constraint(myrelid);
4172 
4173  if (OidIsValid(constraintId))
4174  RenameConstraintById(constraintId, newrelname);
4175  }
4176 
4177  /*
4178  * Close rel, but keep lock!
4179  */
4180  relation_close(targetrelation, NoLock);
4181 }
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:989
void RenameTypeInternal(Oid typeOid, const char *newTypeName, Oid typeNamespace)
Definition: pg_type.c:765

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

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

◆ ResetRelRewrite()

void ResetRelRewrite ( Oid  myrelid)

Definition at line 4187 of file tablecmds.c.

4188 {
4189  Relation relrelation; /* for RELATION relation */
4190  HeapTuple reltup;
4191  Form_pg_class relform;
4192 
4193  /*
4194  * Find relation's pg_class tuple.
4195  */
4196  relrelation = table_open(RelationRelationId, RowExclusiveLock);
4197 
4198  reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
4199  if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
4200  elog(ERROR, "cache lookup failed for relation %u", myrelid);
4201  relform = (Form_pg_class) GETSTRUCT(reltup);
4202 
4203  /*
4204  * Update pg_class tuple.
4205  */
4206  relform->relrewrite = InvalidOid;
4207 
4208  CatalogTupleUpdate(relrelation, &reltup->t_self, reltup);
4209 
4210  heap_freetuple(reltup);
4211  table_close(relrelation, RowExclusiveLock);
4212 }

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

3481 {
3482  Relation relationRelation;
3483  HeapTuple tuple;
3484  Form_pg_class classtuple;
3485 
3487  ShareUpdateExclusiveLock, false) ||
3488  CheckRelationOidLockedByMe(relationId,
3489  ShareRowExclusiveLock, true));
3490 
3491  /*
3492  * Fetch a modifiable copy of the tuple, modify it, update pg_class.
3493  */
3494  relationRelation = table_open(RelationRelationId, RowExclusiveLock);
3495  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
3496  if (!HeapTupleIsValid(tuple))
3497  elog(ERROR, "cache lookup failed for relation %u", relationId);
3498  classtuple = (Form_pg_class) GETSTRUCT(tuple);
3499 
3500  if (classtuple->relhassubclass != relhassubclass)
3501  {
3502  classtuple->relhassubclass = relhassubclass;
3503  CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
3504  }
3505  else
3506  {
3507  /* no need to change tuple, but force relcache rebuild anyway */
3509  }
3510 
3511  heap_freetuple(tuple);
3512  table_close(relationRelation, RowExclusiveLock);
3513 }
void CacheInvalidateRelcacheByTuple(HeapTuple classTuple)
Definition: inval.c:1396
bool CheckRelationOidLockedByMe(Oid relid, LOCKMODE lockmode, bool orstronger)
Definition: lmgr.c:347

References Assert, CacheInvalidateRelcacheByTuple(), CatalogTupleUpdate(), CheckRelationOidLockedByMe(), elog, ERROR, GETSTRUCT, heap_freetuple(), HeapTupleIsValid, ObjectIdGetDatum(), RowExclusiveLock, SearchSysCacheCopy1, ShareRowExclusiveLock, ShareUpdateExclusiveLock, 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 3583 of file tablecmds.c.

3586 {
3587  Relation pg_class;
3588  HeapTuple tuple;
3589  Form_pg_class rd_rel;
3590  Oid reloid = RelationGetRelid(rel);
3591 
3592  Assert(CheckRelationTableSpaceMove(rel, newTableSpaceId));
3593 
3594  /* Get a modifiable copy of the relation's pg_class row. */
3595  pg_class = table_open(RelationRelationId, RowExclusiveLock);
3596 
3597  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(reloid));
3598  if (!HeapTupleIsValid(tuple))
3599  elog(ERROR, "cache lookup failed for relation %u", reloid);
3600  rd_rel = (Form_pg_class) GETSTRUCT(tuple);
3601 
3602  /* Update the pg_class row. */
3603  rd_rel->reltablespace = (newTableSpaceId == MyDatabaseTableSpace) ?
3604  InvalidOid : newTableSpaceId;
3605  if (RelFileNumberIsValid(newRelFilenumber))
3606  rd_rel->relfilenode = newRelFilenumber;
3607  CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
3608 
3609  /*
3610  * Record dependency on tablespace. This is only required for relations
3611  * that have no physical storage.
3612  */
3613  if (!RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
3614  changeDependencyOnTablespace(RelationRelationId, reloid,
3615  rd_rel->reltablespace);
3616 
3617  heap_freetuple(tuple);
3618  table_close(pg_class, RowExclusiveLock);
3619 }
void changeDependencyOnTablespace(Oid classId, Oid objectId, Oid newTablespaceId)
Definition: pg_shdepend.c:391
#define RelFileNumberIsValid(relnumber)
Definition: relpath.h:27
bool CheckRelationTableSpaceMove(Relation rel, Oid newTableSpaceId)
Definition: tablecmds.c:3526

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