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

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

4371 {
4372  Relation rel;
4373 
4374  /* Caller is required to provide an adequate lock. */
4375  rel = relation_open(context->relid, NoLock);
4376 
4377  CheckAlterTableIsSafe(rel);
4378 
4379  ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
4380 }
#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:4284
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:4722

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

Referenced by ProcessUtilitySlow().

◆ AlterTableGetLockLevel()

LOCKMODE AlterTableGetLockLevel ( List cmds)

Definition at line 4443 of file tablecmds.c.

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

4399 {
4400  Relation rel;
4401  LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
4402 
4403  rel = relation_open(relid, lockmode);
4404 
4406 
4407  ATController(NULL, rel, cmds, recurse, lockmode, NULL);
4408 }
void EventTriggerAlterTableRelid(Oid objectId)
LOCKMODE AlterTableGetLockLevel(List *cmds)
Definition: tablecmds.c:4443

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

Referenced by AlterTableMoveAll(), and DefineVirtualRelation().

◆ AlterTableLookupRelation()

Oid AlterTableLookupRelation ( AlterTableStmt stmt,
LOCKMODE  lockmode 
)

Definition at line 4310 of file tablecmds.c.

4311 {
4312  return RangeVarGetRelidExtended(stmt->relation, lockmode,
4313  stmt->missing_ok ? RVR_MISSING_OK : 0,
4315  (void *) stmt);
4316 }
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:17676

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

Referenced by ProcessUtilitySlow().

◆ AlterTableMoveAll()

Oid AlterTableMoveAll ( AlterTableMoveAllStmt stmt)

Definition at line 15221 of file tablecmds.c.

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

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

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

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

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

17551 {
17552  ListCell *cur_item;
17553 
17554  foreach(cur_item, on_commits)
17555  {
17556  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
17557 
17558  if (!isCommit && oc->creating_subid == mySubid)
17559  {
17560  /* cur_item must be removed */
17562  pfree(oc);
17563  }
17564  else
17565  {
17566  /* cur_item must be preserved */
17567  if (oc->creating_subid == mySubid)
17568  oc->creating_subid = parentSubid;
17569  if (oc->deleting_subid == mySubid)
17570  oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
17571  }
17572  }
17573 }
#define InvalidSubTransactionId
Definition: c.h:658
void pfree(void *pointer)
Definition: mcxt.c:1520
#define foreach_delete_current(lst, var_or_cell)
Definition: pg_list.h:391
SubTransactionId creating_subid
Definition: tablecmds.c: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 17517 of file tablecmds.c.

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

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

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

1280 {
1281  int natts;
1283  ListCell *l;
1284  TupleDesc desc;
1285  bool has_not_null;
1286  char *attname;
1287  Oid atttypid;
1288  int32 atttypmod;
1289  Oid attcollation;
1290  int attdim;
1291 
1292  /*
1293  * allocate a new tuple descriptor
1294  */
1295  natts = list_length(columns);
1296  desc = CreateTemplateTupleDesc(natts);
1297  has_not_null = false;
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  has_not_null |= entry->is_not_null;
1344  att->attislocal = entry->is_local;
1345  att->attinhcount = entry->inhcount;
1346  att->attidentity = entry->identity;
1347  att->attgenerated = entry->generated;
1348  att->attcompression = GetAttributeCompression(att->atttypid, entry->compression);
1349  if (entry->storage)
1350  att->attstorage = entry->storage;
1351  else if (entry->storage_name)
1352  att->attstorage = GetAttributeStorage(att->atttypid, entry->storage_name);
1353  }
1354 
1355  if (has_not_null)
1356  {
1357  TupleConstr *constr = (TupleConstr *) palloc0(sizeof(TupleConstr));
1358 
1359  constr->has_not_null = true;
1360  constr->has_generated_stored = false;
1361  constr->defval = NULL;
1362  constr->missing = NULL;
1363  constr->num_defval = 0;
1364  constr->check = NULL;
1365  constr->num_check = 0;
1366  desc->constr = constr;
1367  }
1368  else
1369  {
1370  desc->constr = NULL;
1371  }
1372 
1373  return desc;
1374 }
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 * palloc0(Size size)
Definition: mcxt.c:1346
void typenameTypeIdAndMod(ParseState *pstate, const TypeName *typeName, Oid *typeid_p, int32 *typmod_p)
Definition: parse_type.c:310
Oid GetColumnDefCollation(ParseState *pstate, const ColumnDef *coldef, Oid typeOid)
Definition: parse_type.c:540
#define ACL_USAGE
Definition: parsenodes.h:84
NameData attname
Definition: pg_attribute.h:41
int16 attnum
Definition: pg_attribute.h:74
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
static int list_length(const List *l)
Definition: pg_list.h:152
bool is_not_null
Definition: parsenodes.h:731
char identity
Definition: parsenodes.h:737
char * storage_name
Definition: parsenodes.h:734
int inhcount
Definition: parsenodes.h:729
char * colname
Definition: parsenodes.h:726
TypeName * typeName
Definition: parsenodes.h:727
char generated
Definition: parsenodes.h:740
char storage
Definition: parsenodes.h:733
bool is_local
Definition: parsenodes.h:730
char * compression
Definition: parsenodes.h:728
bool has_not_null
Definition: tupdesc.h:44
AttrDefault * defval
Definition: tupdesc.h:39
bool has_generated_stored
Definition: tupdesc.h:45
struct AttrMissing * missing
Definition: tupdesc.h:41
ConstrCheck * check
Definition: tupdesc.h:40
uint16 num_defval
Definition: tupdesc.h:42
uint16 num_check
Definition: tupdesc.h:43
TupleConstr * constr
Definition: tupdesc.h:85
bool setof
Definition: parsenodes.h:270
List * arrayBounds
Definition: parsenodes.h:274
static char GetAttributeCompression(Oid atttypid, const char *compression)
Definition: tablecmds.c:19980
static char GetAttributeStorage(Oid atttypid, const char *storagemode)
Definition: tablecmds.c:20018
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:67
void TupleDescInitEntryCollation(TupleDesc desc, AttrNumber attributeNumber, Oid collationid)
Definition: tupdesc.c:833
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:651
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

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

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

◆ check_of_type()

void check_of_type ( HeapTuple  typetuple)

Definition at line 6953 of file tablecmds.c.

6954 {
6955  Form_pg_type typ = (Form_pg_type) GETSTRUCT(typetuple);
6956  bool typeOk = false;
6957 
6958  if (typ->typtype == TYPTYPE_COMPOSITE)
6959  {
6960  Relation typeRelation;
6961 
6962  Assert(OidIsValid(typ->typrelid));
6963  typeRelation = relation_open(typ->typrelid, AccessShareLock);
6964  typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
6965 
6966  /*
6967  * Close the parent rel, but keep our AccessShareLock on it until xact
6968  * commit. That will prevent someone else from deleting or ALTERing
6969  * the type before the typed table creation/conversion commits.
6970  */
6971  relation_close(typeRelation, NoLock);
6972  }
6973  if (!typeOk)
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(), 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 3537 of file tablecmds.c.

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

4252 {
4253  int expected_refcnt;
4254 
4255  expected_refcnt = rel->rd_isnailed ? 2 : 1;
4256  if (rel->rd_refcnt != expected_refcnt)
4257  ereport(ERROR,
4258  (errcode(ERRCODE_OBJECT_IN_USE),
4259  /* translator: first %s is a SQL command, eg ALTER TABLE */
4260  errmsg("cannot %s \"%s\" because it is being used by active queries in this session",
4261  stmt, RelationGetRelationName(rel))));
4262 
4263  if (rel->rd_rel->relkind != RELKIND_INDEX &&
4264  rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
4266  ereport(ERROR,
4267  (errcode(ERRCODE_OBJECT_IN_USE),
4268  /* translator: first %s is a SQL command, eg ALTER TABLE */
4269  errmsg("cannot %s \"%s\" because it has pending trigger events",
4270  stmt, RelationGetRelationName(rel))));
4271 }
int rd_refcnt
Definition: rel.h:59
bool rd_isnailed
Definition: rel.h:62
bool AfterTriggerPendingOnRel(Oid relid)
Definition: trigger.c:5975

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(), ExecRefreshMatView(), heap_drop_with_catalog(), index_drop(), MergeAttributes(), 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:127
void StorePartitionKey(Relation rel, char strategy, int16 partnatts, AttrNumber *partattrs, List *partexprs, Oid *partopclass, Oid *partcollation)
Definition: heap.c:3317
Oid heap_create_with_catalog(const char *relname, Oid relnamespace, Oid reltablespace, Oid relid, Oid reltypeid, Oid reloftypeid, Oid ownerid, Oid accessmtd, TupleDesc tupdesc, List *cooked_constraints, char relkind, char relpersistence, bool shared_relation, bool mapped_relation, OnCommitAction oncommit, Datum reloptions, bool use_user_acl, bool allow_system_table_mods, bool is_internal, Oid relrewrite, ObjectAddress *typaddress)
Definition: heap.c:1104
void StorePartitionBound(Relation rel, Relation parent, PartitionBoundSpec *bound)
Definition: heap.c:3473
List * AddRelationNewConstraints(Relation rel, List *newColDefaults, List *newConstraints, bool allow_merge, bool is_local, bool is_internal, const char *queryString)
Definition: heap.c:2250
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:1316
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:662
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:80
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:39
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:291
IndexStmt * generateClonedIndexStmt(RangeVar *heapRel, Relation source_idx, const AttrMap *attmap, Oid *constraintOid)
PartitionBoundSpec * transformPartitionBound(ParseState *pstate, Relation parent, PartitionBoundSpec *spec)
@ CONSTR_DEFAULT
Definition: parsenodes.h: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:2458
TupleDesc BuildDescForRelation(const List *columns)
Definition: tablecmds.c:1279
static void ComputePartitionAttrs(ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs, List **partexprs, Oid *partopclass, Oid *partcollation, PartitionStrategy strategy)
Definition: tablecmds.c:17875
static void CloneRowTriggersToPartition(Relation parent, Relation partition)
Definition: tablecmds.c:18829
static void StoreCatalogInheritance(Oid relationId, List *supers, bool child_is_partition)
Definition: tablecmds.c:3377
static void CloneForeignKeyConstraints(List **wqueue, Relation parentRel, Relation partitionRel)
Definition: tablecmds.c:10513
static PartitionSpec * transformPartitionSpec(Relation rel, PartitionSpec *partspec)
Definition: tablecmds.c:17817
void CommandCounterIncrement(void)
Definition: xact.c:1097

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

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

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

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

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

Referenced by apply_handle_truncate(), and ExecuteTruncate().

◆ find_composite_type_dependencies()

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

Definition at line 6746 of file tablecmds.c.

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

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

18135 {
18136  List *existConstraint = NIL;
18137  TupleConstr *constr = RelationGetDescr(scanrel)->constr;
18138  int i;
18139 
18140  if (constr && constr->has_not_null)
18141  {
18142  int natts = scanrel->rd_att->natts;
18143 
18144  for (i = 1; i <= natts; i++)
18145  {
18146  Form_pg_attribute att = TupleDescAttr(scanrel->rd_att, i - 1);
18147 
18148  if (att->attnotnull && !att->attisdropped)
18149  {
18150  NullTest *ntest = makeNode(NullTest);
18151 
18152  ntest->arg = (Expr *) makeVar(1,
18153  i,
18154  att->atttypid,
18155  att->atttypmod,
18156  att->attcollation,
18157  0);
18158  ntest->nulltesttype = IS_NOT_NULL;
18159 
18160  /*
18161  * argisrow=false is correct even for a composite column,
18162  * because attnotnull does not represent a SQL-spec IS NOT
18163  * NULL test in such a case, just IS DISTINCT FROM NULL.
18164  */
18165  ntest->argisrow = false;
18166  ntest->location = -1;
18167  existConstraint = lappend(existConstraint, ntest);
18168  }
18169  }
18170  }
18171 
18172  return ConstraintImpliedByRelConstraint(scanrel, partConstraint, existConstraint);
18173 }
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
@ IS_NOT_NULL
Definition: primnodes.h:1954
NullTestType nulltesttype
Definition: primnodes.h:1961
ParseLoc location
Definition: primnodes.h:1964
Expr * arg
Definition: primnodes.h:1960
TupleDesc rd_att
Definition: rel.h:112
static bool ConstraintImpliedByRelConstraint(Relation scanrel, List *testConstraint, List *provenConstraint)
Definition: tablecmds.c:18186

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

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

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

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

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

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

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

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

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

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

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

3995 {
3996  Oid relid = InvalidOid;
3997  Oid typid = InvalidOid;
3998 
3999  if (stmt->renameType == OBJECT_DOMCONSTRAINT)
4000  {
4001  Relation rel;
4002  HeapTuple tup;
4003 
4004  typid = typenameTypeId(NULL, makeTypeNameFromNameList(castNode(List, stmt->object)));
4005  rel = table_open(TypeRelationId, RowExclusiveLock);
4006  tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
4007  if (!HeapTupleIsValid(tup))
4008  elog(ERROR, "cache lookup failed for type %u", typid);
4009  checkDomainOwner(tup);
4010  ReleaseSysCache(tup);
4011  table_close(rel, NoLock);
4012  }
4013  else
4014  {
4015  /* lock level taken here should match rename_constraint_internal */
4017  stmt->missing_ok ? RVR_MISSING_OK : 0,
4019  NULL);
4020  if (!OidIsValid(relid))
4021  {
4022  ereport(NOTICE,
4023  (errmsg("relation \"%s\" does not exist, skipping",
4024  stmt->relation->relname)));
4025  return InvalidObjectAddress;
4026  }
4027  }
4028 
4029  return
4030  rename_constraint_internal(relid, typid,
4031  stmt->subname,
4032  stmt->newname,
4033  (stmt->relation &&
4034  stmt->relation->inh), /* recursive? */
4035  false, /* recursing? */
4036  0 /* expected inhcount */ );
4037 }
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:3888
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 4044 of file tablecmds.c.

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

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

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

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

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

3497 {
3498  Relation relationRelation;
3499  HeapTuple tuple;
3500  Form_pg_class classtuple;
3501 
3502  /*
3503  * Fetch a modifiable copy of the tuple, modify it, update pg_class.
3504  */
3505  relationRelation = table_open(RelationRelationId, RowExclusiveLock);
3506  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
3507  if (!HeapTupleIsValid(tuple))
3508  elog(ERROR, "cache lookup failed for relation %u", relationId);
3509  classtuple = (Form_pg_class) GETSTRUCT(tuple);
3510 
3511  if (classtuple->relhassubclass != relhassubclass)
3512  {
3513  classtuple->relhassubclass = relhassubclass;
3514  CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
3515  }
3516  else
3517  {
3518  /* no need to change tuple, but force relcache rebuild anyway */
3520  }
3521 
3522  heap_freetuple(tuple);
3523  table_close(relationRelation, RowExclusiveLock);
3524 }
void CacheInvalidateRelcacheByTuple(HeapTuple classTuple)
Definition: inval.c:1396

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

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

◆ SetRelationTableSpace()

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

Definition at line 3594 of file tablecmds.c.

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

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