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

17156 {
17157  HeapTuple classTup;
17158  Form_pg_class classForm;
17159  ObjectAddress thisobj;
17160  bool already_done = false;
17161 
17162  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
17163  if (!HeapTupleIsValid(classTup))
17164  elog(ERROR, "cache lookup failed for relation %u", relOid);
17165  classForm = (Form_pg_class) GETSTRUCT(classTup);
17166 
17167  Assert(classForm->relnamespace == oldNspOid);
17168 
17169  thisobj.classId = RelationRelationId;
17170  thisobj.objectId = relOid;
17171  thisobj.objectSubId = 0;
17172 
17173  /*
17174  * If the object has already been moved, don't move it again. If it's
17175  * already in the right place, don't move it, but still fire the object
17176  * access hook.
17177  */
17178  already_done = object_address_present(&thisobj, objsMoved);
17179  if (!already_done && oldNspOid != newNspOid)
17180  {
17181  /* check for duplicate name (more friendly than unique-index failure) */
17182  if (get_relname_relid(NameStr(classForm->relname),
17183  newNspOid) != InvalidOid)
17184  ereport(ERROR,
17185  (errcode(ERRCODE_DUPLICATE_TABLE),
17186  errmsg("relation \"%s\" already exists in schema \"%s\"",
17187  NameStr(classForm->relname),
17188  get_namespace_name(newNspOid))));
17189 
17190  /* classTup is a copy, so OK to scribble on */
17191  classForm->relnamespace = newNspOid;
17192 
17193  CatalogTupleUpdate(classRel, &classTup->t_self, classTup);
17194 
17195  /* Update dependency on schema if caller said so */
17196  if (hasDependEntry &&
17197  changeDependencyFor(RelationRelationId,
17198  relOid,
17199  NamespaceRelationId,
17200  oldNspOid,
17201  newNspOid) != 1)
17202  elog(ERROR, "could not change schema dependency for relation \"%s\"",
17203  NameStr(classForm->relname));
17204  }
17205  if (!already_done)
17206  {
17207  add_exact_object_address(&thisobj, objsMoved);
17208 
17209  InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
17210  }
17211 
17212  heap_freetuple(classTup);
17213 }
#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:224
#define ereport(elevel,...)
Definition: elog.h:149
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1434
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:313
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3366
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1885
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:197
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
long changeDependencyFor(Oid classId, Oid objectId, Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition: pg_depend.c: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 4362 of file tablecmds.c.

4364 {
4365  Relation rel;
4366 
4367  /* Caller is required to provide an adequate lock. */
4368  rel = relation_open(context->relid, NoLock);
4369 
4370  CheckAlterTableIsSafe(rel);
4371 
4372  ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
4373 }
#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:4277
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:4715

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

Referenced by ProcessUtilitySlow().

◆ AlterTableGetLockLevel()

LOCKMODE AlterTableGetLockLevel ( List cmds)

Definition at line 4436 of file tablecmds.c.

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

Referenced by AlterTableInternal(), and ProcessUtilitySlow().

◆ AlterTableInternal()

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

Definition at line 4391 of file tablecmds.c.

4392 {
4393  Relation rel;
4394  LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
4395 
4396  rel = relation_open(relid, lockmode);
4397 
4399 
4400  ATController(NULL, rel, cmds, recurse, lockmode, NULL);
4401 }
void EventTriggerAlterTableRelid(Oid objectId)
LOCKMODE AlterTableGetLockLevel(List *cmds)
Definition: tablecmds.c:4436

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

Referenced by AlterTableMoveAll(), and DefineVirtualRelation().

◆ AlterTableLookupRelation()

Oid AlterTableLookupRelation ( AlterTableStmt stmt,
LOCKMODE  lockmode 
)

Definition at line 4303 of file tablecmds.c.

4304 {
4305  return RangeVarGetRelidExtended(stmt->relation, lockmode,
4306  stmt->missing_ok ? RVR_MISSING_OK : 0,
4308  (void *) stmt);
4309 }
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:17677

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

Referenced by ProcessUtilitySlow().

◆ AlterTableMoveAll()

Oid AlterTableMoveAll ( AlterTableMoveAllStmt stmt)

Definition at line 15222 of file tablecmds.c.

15223 {
15224  List *relations = NIL;
15225  ListCell *l;
15226  ScanKeyData key[1];
15227  Relation rel;
15228  TableScanDesc scan;
15229  HeapTuple tuple;
15230  Oid orig_tablespaceoid;
15231  Oid new_tablespaceoid;
15232  List *role_oids = roleSpecsToIds(stmt->roles);
15233 
15234  /* Ensure we were not asked to move something we can't */
15235  if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
15236  stmt->objtype != OBJECT_MATVIEW)
15237  ereport(ERROR,
15238  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
15239  errmsg("only tables, indexes, and materialized views exist in tablespaces")));
15240 
15241  /* Get the orig and new tablespace OIDs */
15242  orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
15243  new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
15244 
15245  /* Can't move shared relations in to or out of pg_global */
15246  /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
15247  if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
15248  new_tablespaceoid == GLOBALTABLESPACE_OID)
15249  ereport(ERROR,
15250  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
15251  errmsg("cannot move relations in to or out of pg_global tablespace")));
15252 
15253  /*
15254  * Must have CREATE rights on the new tablespace, unless it is the
15255  * database default tablespace (which all users implicitly have CREATE
15256  * rights on).
15257  */
15258  if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
15259  {
15260  AclResult aclresult;
15261 
15262  aclresult = object_aclcheck(TableSpaceRelationId, new_tablespaceoid, GetUserId(),
15263  ACL_CREATE);
15264  if (aclresult != ACLCHECK_OK)
15265  aclcheck_error(aclresult, OBJECT_TABLESPACE,
15266  get_tablespace_name(new_tablespaceoid));
15267  }
15268 
15269  /*
15270  * Now that the checks are done, check if we should set either to
15271  * InvalidOid because it is our database's default tablespace.
15272  */
15273  if (orig_tablespaceoid == MyDatabaseTableSpace)
15274  orig_tablespaceoid = InvalidOid;
15275 
15276  if (new_tablespaceoid == MyDatabaseTableSpace)
15277  new_tablespaceoid = InvalidOid;
15278 
15279  /* no-op */
15280  if (orig_tablespaceoid == new_tablespaceoid)
15281  return new_tablespaceoid;
15282 
15283  /*
15284  * Walk the list of objects in the tablespace and move them. This will
15285  * only find objects in our database, of course.
15286  */
15287  ScanKeyInit(&key[0],
15288  Anum_pg_class_reltablespace,
15289  BTEqualStrategyNumber, F_OIDEQ,
15290  ObjectIdGetDatum(orig_tablespaceoid));
15291 
15292  rel = table_open(RelationRelationId, AccessShareLock);
15293  scan = table_beginscan_catalog(rel, 1, key);
15294  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
15295  {
15296  Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
15297  Oid relOid = relForm->oid;
15298 
15299  /*
15300  * Do not move objects in pg_catalog as part of this, if an admin
15301  * really wishes to do so, they can issue the individual ALTER
15302  * commands directly.
15303  *
15304  * Also, explicitly avoid any shared tables, temp tables, or TOAST
15305  * (TOAST will be moved with the main table).
15306  */
15307  if (IsCatalogNamespace(relForm->relnamespace) ||
15308  relForm->relisshared ||
15309  isAnyTempNamespace(relForm->relnamespace) ||
15310  IsToastNamespace(relForm->relnamespace))
15311  continue;
15312 
15313  /* Only move the object type requested */
15314  if ((stmt->objtype == OBJECT_TABLE &&
15315  relForm->relkind != RELKIND_RELATION &&
15316  relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
15317  (stmt->objtype == OBJECT_INDEX &&
15318  relForm->relkind != RELKIND_INDEX &&
15319  relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
15320  (stmt->objtype == OBJECT_MATVIEW &&
15321  relForm->relkind != RELKIND_MATVIEW))
15322  continue;
15323 
15324  /* Check if we are only moving objects owned by certain roles */
15325  if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
15326  continue;
15327 
15328  /*
15329  * Handle permissions-checking here since we are locking the tables
15330  * and also to avoid doing a bunch of work only to fail part-way. Note
15331  * that permissions will also be checked by AlterTableInternal().
15332  *
15333  * Caller must be considered an owner on the table to move it.
15334  */
15335  if (!object_ownercheck(RelationRelationId, relOid, GetUserId()))
15337  NameStr(relForm->relname));
15338 
15339  if (stmt->nowait &&
15341  ereport(ERROR,
15342  (errcode(ERRCODE_OBJECT_IN_USE),
15343  errmsg("aborting because lock on relation \"%s.%s\" is not available",
15344  get_namespace_name(relForm->relnamespace),
15345  NameStr(relForm->relname))));
15346  else
15348 
15349  /* Add to our list of objects to move */
15350  relations = lappend_oid(relations, relOid);
15351  }
15352 
15353  table_endscan(scan);
15355 
15356  if (relations == NIL)
15357  ereport(NOTICE,
15358  (errcode(ERRCODE_NO_DATA_FOUND),
15359  errmsg("no matching relations in tablespace \"%s\" found",
15360  orig_tablespaceoid == InvalidOid ? "(database default)" :
15361  get_tablespace_name(orig_tablespaceoid))));
15362 
15363  /* Everything is locked, loop through and move all of the relations. */
15364  foreach(l, relations)
15365  {
15366  List *cmds = NIL;
15368 
15369  cmd->subtype = AT_SetTableSpace;
15370  cmd->name = stmt->new_tablespacename;
15371 
15372  cmds = lappend(cmds, cmd);
15373 
15375  /* OID is set by AlterTableInternal */
15376  AlterTableInternal(lfirst_oid(l), cmds, false);
15378  }
15379 
15380  return new_tablespaceoid;
15381 }
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
List * roleSpecsToIds(List *memberNames)
Definition: user.c:1652
#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:94
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:2284
@ OBJECT_TABLESPACE
Definition: parsenodes.h:2303
@ OBJECT_INDEX
Definition: parsenodes.h:2281
@ OBJECT_TABLE
Definition: parsenodes.h:2302
#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:4391

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

17045 {
17046  Relation rel;
17047  Oid relid;
17048  Oid oldNspOid;
17049  Oid nspOid;
17050  RangeVar *newrv;
17051  ObjectAddresses *objsMoved;
17052  ObjectAddress myself;
17053 
17055  stmt->missing_ok ? RVR_MISSING_OK : 0,
17057  (void *) stmt);
17058 
17059  if (!OidIsValid(relid))
17060  {
17061  ereport(NOTICE,
17062  (errmsg("relation \"%s\" does not exist, skipping",
17063  stmt->relation->relname)));
17064  return InvalidObjectAddress;
17065  }
17066 
17067  rel = relation_open(relid, NoLock);
17068 
17069  oldNspOid = RelationGetNamespace(rel);
17070 
17071  /* If it's an owned sequence, disallow moving it by itself. */
17072  if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
17073  {
17074  Oid tableId;
17075  int32 colId;
17076 
17077  if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
17078  sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
17079  ereport(ERROR,
17080  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
17081  errmsg("cannot move an owned sequence into another schema"),
17082  errdetail("Sequence \"%s\" is linked to table \"%s\".",
17084  get_rel_name(tableId))));
17085  }
17086 
17087  /* Get and lock schema OID and check its permissions. */
17088  newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
17089  nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
17090 
17091  /* common checks on switching namespaces */
17092  CheckSetNamespace(oldNspOid, nspOid);
17093 
17094  objsMoved = new_object_addresses();
17095  AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
17096  free_object_addresses(objsMoved);
17097 
17098  ObjectAddressSet(myself, RelationRelationId, relid);
17099 
17100  if (oldschema)
17101  *oldschema = oldNspOid;
17102 
17103  /* close rel, but keep lock until commit */
17104  relation_close(rel, NoLock);
17105 
17106  return myself;
17107 }
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:17115

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

17117 {
17118  Relation classRel;
17119 
17120  Assert(objsMoved != NULL);
17121 
17122  /* OK, modify the pg_class row and pg_depend entry */
17123  classRel = table_open(RelationRelationId, RowExclusiveLock);
17124 
17125  AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
17126  nspOid, true, objsMoved);
17127 
17128  /* Fix the table's row type too, if it has one */
17129  if (OidIsValid(rel->rd_rel->reltype))
17130  AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid,
17131  false, /* isImplicitArray */
17132  false, /* ignoreDependent */
17133  false, /* errorOnTableType */
17134  objsMoved);
17135 
17136  /* Fix other dependent stuff */
17137  AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
17138  AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
17139  objsMoved, AccessExclusiveLock);
17140  AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
17141  false, objsMoved);
17142 
17143  table_close(classRel, RowExclusiveLock);
17144 }
#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:17152
static void AlterSeqNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved, LOCKMODE lockmode)
Definition: tablecmds.c:17267
static void AlterIndexNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:17222
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 17550 of file tablecmds.c.

17552 {
17553  ListCell *cur_item;
17554 
17555  foreach(cur_item, on_commits)
17556  {
17557  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
17558 
17559  if (!isCommit && oc->creating_subid == mySubid)
17560  {
17561  /* cur_item must be removed */
17563  pfree(oc);
17564  }
17565  else
17566  {
17567  /* cur_item must be preserved */
17568  if (oc->creating_subid == mySubid)
17569  oc->creating_subid = parentSubid;
17570  if (oc->deleting_subid == mySubid)
17571  oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
17572  }
17573  }
17574 }
#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 17518 of file tablecmds.c.

17519 {
17520  ListCell *cur_item;
17521 
17522  foreach(cur_item, on_commits)
17523  {
17524  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
17525 
17526  if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
17528  {
17529  /* cur_item must be removed */
17531  pfree(oc);
17532  }
17533  else
17534  {
17535  /* cur_item must be preserved */
17538  }
17539  }
17540 }

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

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

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

6947 {
6948  Form_pg_type typ = (Form_pg_type) GETSTRUCT(typetuple);
6949  bool typeOk = false;
6950 
6951  if (typ->typtype == TYPTYPE_COMPOSITE)
6952  {
6953  Relation typeRelation;
6954 
6955  Assert(OidIsValid(typ->typrelid));
6956  typeRelation = relation_open(typ->typrelid, AccessShareLock);
6957  typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
6958 
6959  /*
6960  * Close the parent rel, but keep our AccessShareLock on it until xact
6961  * commit. That will prevent someone else from deleting or ALTERing
6962  * the type before the typed table creation/conversion commits.
6963  */
6964  relation_close(typeRelation, NoLock);
6965 
6966  if (!typeOk)
6967  ereport(ERROR,
6968  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6969  errmsg("type %s is the row type of another table",
6970  format_type_be(typ->oid)),
6971  errdetail("A typed table must use a stand-alone composite type created with CREATE TYPE.")));
6972  }
6973  else
6974  ereport(ERROR,
6975  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6976  errmsg("type %s is not a composite type",
6977  format_type_be(typ->oid))));
6978 }
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 3530 of file tablecmds.c.

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

4245 {
4246  int expected_refcnt;
4247 
4248  expected_refcnt = rel->rd_isnailed ? 2 : 1;
4249  if (rel->rd_refcnt != expected_refcnt)
4250  ereport(ERROR,
4251  (errcode(ERRCODE_OBJECT_IN_USE),
4252  /* translator: first %s is a SQL command, eg ALTER TABLE */
4253  errmsg("cannot %s \"%s\" because it is being used by active queries in this session",
4254  stmt, RelationGetRelationName(rel))));
4255 
4256  if (rel->rd_rel->relkind != RELKIND_INDEX &&
4257  rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
4259  ereport(ERROR,
4260  (errcode(ERRCODE_OBJECT_IN_USE),
4261  /* translator: first %s is a SQL command, eg ALTER TABLE */
4262  errmsg("cannot %s \"%s\" because it has pending trigger events",
4263  stmt, RelationGetRelationName(rel))));
4264 }
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 686 of file tablecmds.c.

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

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

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

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

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

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

Referenced by apply_handle_truncate(), and ExecuteTruncate().

◆ find_composite_type_dependencies()

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

Definition at line 6739 of file tablecmds.c.

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

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

18136 {
18137  List *existConstraint = NIL;
18138  TupleConstr *constr = RelationGetDescr(scanrel)->constr;
18139  int i;
18140 
18141  if (constr && constr->has_not_null)
18142  {
18143  int natts = scanrel->rd_att->natts;
18144 
18145  for (i = 1; i <= natts; i++)
18146  {
18147  Form_pg_attribute att = TupleDescAttr(scanrel->rd_att, i - 1);
18148 
18149  if (att->attnotnull && !att->attisdropped)
18150  {
18151  NullTest *ntest = makeNode(NullTest);
18152 
18153  ntest->arg = (Expr *) makeVar(1,
18154  i,
18155  att->atttypid,
18156  att->atttypmod,
18157  att->attcollation,
18158  0);
18159  ntest->nulltesttype = IS_NOT_NULL;
18160 
18161  /*
18162  * argisrow=false is correct even for a composite column,
18163  * because attnotnull does not represent a SQL-spec IS NOT
18164  * NULL test in such a case, just IS DISTINCT FROM NULL.
18165  */
18166  ntest->argisrow = false;
18167  ntest->location = -1;
18168  existConstraint = lappend(existConstraint, ntest);
18169  }
18170  }
18171  }
18172 
18173  return ConstraintImpliedByRelConstraint(scanrel, partConstraint, existConstraint);
18174 }
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:18187

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

17412 {
17413  ListCell *l;
17414  List *oids_to_truncate = NIL;
17415  List *oids_to_drop = NIL;
17416 
17417  foreach(l, on_commits)
17418  {
17419  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
17420 
17421  /* Ignore entry if already dropped in this xact */
17423  continue;
17424 
17425  switch (oc->oncommit)
17426  {
17427  case ONCOMMIT_NOOP:
17429  /* Do nothing (there shouldn't be such entries, actually) */
17430  break;
17431  case ONCOMMIT_DELETE_ROWS:
17432 
17433  /*
17434  * If this transaction hasn't accessed any temporary
17435  * relations, we can skip truncating ON COMMIT DELETE ROWS
17436  * tables, as they must still be empty.
17437  */
17439  oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
17440  break;
17441  case ONCOMMIT_DROP:
17442  oids_to_drop = lappend_oid(oids_to_drop, oc->relid);
17443  break;
17444  }
17445  }
17446 
17447  /*
17448  * Truncate relations before dropping so that all dependencies between
17449  * relations are removed after they are worked on. Doing it like this
17450  * might be a waste as it is possible that a relation being truncated will
17451  * be dropped anyway due to its parent being dropped, but this makes the
17452  * code more robust because of not having to re-check that the relation
17453  * exists at truncation time.
17454  */
17455  if (oids_to_truncate != NIL)
17456  heap_truncate(oids_to_truncate);
17457 
17458  if (oids_to_drop != NIL)
17459  {
17460  ObjectAddresses *targetObjects = new_object_addresses();
17461 
17462  foreach(l, oids_to_drop)
17463  {
17464  ObjectAddress object;
17465 
17466  object.classId = RelationRelationId;
17467  object.objectId = lfirst_oid(l);
17468  object.objectSubId = 0;
17469 
17470  Assert(!object_address_present(&object, targetObjects));
17471 
17472  add_exact_object_address(&object, targetObjects);
17473  }
17474 
17475  /*
17476  * Object deletion might involve toast table access (to clean up
17477  * toasted catalog entries), so ensure we have a valid snapshot.
17478  */
17480 
17481  /*
17482  * Since this is an automatic drop, rather than one directly initiated
17483  * by the user, we pass the PERFORM_DELETION_INTERNAL flag.
17484  */
17485  performMultipleDeletions(targetObjects, DROP_CASCADE,
17487 
17489 
17490 #ifdef USE_ASSERT_CHECKING
17491 
17492  /*
17493  * Note that table deletion will call remove_on_commit_action, so the
17494  * entry should get marked as deleted.
17495  */
17496  foreach(l, on_commits)
17497  {
17498  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
17499 
17500  if (oc->oncommit != ONCOMMIT_DROP)
17501  continue;
17502 
17504  }
17505 #endif
17506  }
17507 }
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:134
#define XACT_FLAGS_ACCESSEDTEMPNAMESPACE
Definition: xact.h:102

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

Referenced by CommitTransaction(), and PrepareTransaction().

◆ RangeVarCallbackMaintainsTable()

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

Definition at line 17585 of file tablecmds.c.

17587 {
17588  char relkind;
17589  AclResult aclresult;
17590 
17591  /* Nothing to do if the relation was not found. */
17592  if (!OidIsValid(relId))
17593  return;
17594 
17595  /*
17596  * If the relation does exist, check whether it's an index. But note that
17597  * the relation might have been dropped between the time we did the name
17598  * lookup and now. In that case, there's nothing to do.
17599  */
17600  relkind = get_rel_relkind(relId);
17601  if (!relkind)
17602  return;
17603  if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
17604  relkind != RELKIND_MATVIEW && relkind != RELKIND_PARTITIONED_TABLE)
17605  ereport(ERROR,
17606  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17607  errmsg("\"%s\" is not a table or materialized view", relation->relname)));
17608 
17609  /* Check permissions */
17610  aclresult = pg_class_aclcheck(relId, GetUserId(), ACL_MAINTAIN);
17611  if (aclresult != ACLCHECK_OK)
17612  aclcheck_error(aclresult,
17614  relation->relname);
17615 }
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 17645 of file tablecmds.c.

17647 {
17648  HeapTuple tuple;
17649 
17650  /* Nothing to do if the relation was not found. */
17651  if (!OidIsValid(relId))
17652  return;
17653 
17654  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
17655  if (!HeapTupleIsValid(tuple)) /* should not happen */
17656  elog(ERROR, "cache lookup failed for relation %u", relId);
17657 
17658  if (!object_ownercheck(RelationRelationId, relId, GetUserId()))
17660  relation->relname);
17661 
17662  if (!allowSystemTableMods &&
17663  IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
17664  ereport(ERROR,
17665  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
17666  errmsg("permission denied: \"%s\" is a system catalog",
17667  relation->relname)));
17668 
17669  ReleaseSysCache(tuple);
17670 }
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 17352 of file tablecmds.c.

17353 {
17354  OnCommitItem *oc;
17355  MemoryContext oldcxt;
17356 
17357  /*
17358  * We needn't bother registering the relation unless there is an ON COMMIT
17359  * action we need to take.
17360  */
17362  return;
17363 
17365 
17366  oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
17367  oc->relid = relid;
17368  oc->oncommit = action;
17371 
17372  /*
17373  * We use lcons() here so that ON COMMIT actions are processed in reverse
17374  * order of registration. That might not be essential but it seems
17375  * reasonable.
17376  */
17377  on_commits = lcons(oc, on_commits);
17378 
17379  MemoryContextSwitchTo(oldcxt);
17380 }
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 17388 of file tablecmds.c.

17389 {
17390  ListCell *l;
17391 
17392  foreach(l, on_commits)
17393  {
17394  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
17395 
17396  if (oc->relid == relid)
17397  {
17399  break;
17400  }
17401  }
17402 }

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

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

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

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

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

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

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

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

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

◆ ResetRelRewrite()

void ResetRelRewrite ( Oid  myrelid)

Definition at line 4191 of file tablecmds.c.

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

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

3485 {
3486  Relation relationRelation;
3487  HeapTuple tuple;
3488  Form_pg_class classtuple;
3489 
3491  ShareUpdateExclusiveLock, false) ||
3492  CheckRelationOidLockedByMe(relationId,
3493  ShareRowExclusiveLock, true));
3494 
3495  /*
3496  * Fetch a modifiable copy of the tuple, modify it, update pg_class.
3497  */
3498  relationRelation = table_open(RelationRelationId, RowExclusiveLock);
3499  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
3500  if (!HeapTupleIsValid(tuple))
3501  elog(ERROR, "cache lookup failed for relation %u", relationId);
3502  classtuple = (Form_pg_class) GETSTRUCT(tuple);
3503 
3504  if (classtuple->relhassubclass != relhassubclass)
3505  {
3506  classtuple->relhassubclass = relhassubclass;
3507  CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
3508  }
3509  else
3510  {
3511  /* no need to change tuple, but force relcache rebuild anyway */
3513  }
3514 
3515  heap_freetuple(tuple);
3516  table_close(relationRelation, RowExclusiveLock);
3517 }
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 3587 of file tablecmds.c.

3590 {
3591  Relation pg_class;
3592  HeapTuple tuple;
3593  Form_pg_class rd_rel;
3594  Oid reloid = RelationGetRelid(rel);
3595 
3596  Assert(CheckRelationTableSpaceMove(rel, newTableSpaceId));
3597 
3598  /* Get a modifiable copy of the relation's pg_class row. */
3599  pg_class = table_open(RelationRelationId, RowExclusiveLock);
3600 
3601  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(reloid));
3602  if (!HeapTupleIsValid(tuple))
3603  elog(ERROR, "cache lookup failed for relation %u", reloid);
3604  rd_rel = (Form_pg_class) GETSTRUCT(tuple);
3605 
3606  /* Update the pg_class row. */
3607  rd_rel->reltablespace = (newTableSpaceId == MyDatabaseTableSpace) ?
3608  InvalidOid : newTableSpaceId;
3609  if (RelFileNumberIsValid(newRelFilenumber))
3610  rd_rel->relfilenode = newRelFilenumber;
3611  CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
3612 
3613  /*
3614  * Record dependency on tablespace. This is only required for relations
3615  * that have no physical storage.
3616  */
3617  if (!RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
3618  changeDependencyOnTablespace(RelationRelationId, reloid,
3619  rd_rel->reltablespace);
3620 
3621  heap_freetuple(tuple);
3622  table_close(pg_class, RowExclusiveLock);
3623 }
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:3530

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