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)
 
void RemoveRelations (DropStmt *drop)
 
Oid AlterTableLookupRelation (AlterTableStmt *stmt, LOCKMODE lockmode)
 
void AlterTable (Oid relid, LOCKMODE lockmode, AlterTableStmt *stmt)
 
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)
 
void SetRelationHasSubclass (Oid relationId, bool relhassubclass)
 
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 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 RangeVarCallbackOwnsTable (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 14319 of file tablecmds.c.

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

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

14323 {
14324  HeapTuple classTup;
14325  Form_pg_class classForm;
14326  ObjectAddress thisobj;
14327  bool already_done = false;
14328 
14329  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
14330  if (!HeapTupleIsValid(classTup))
14331  elog(ERROR, "cache lookup failed for relation %u", relOid);
14332  classForm = (Form_pg_class) GETSTRUCT(classTup);
14333 
14334  Assert(classForm->relnamespace == oldNspOid);
14335 
14336  thisobj.classId = RelationRelationId;
14337  thisobj.objectId = relOid;
14338  thisobj.objectSubId = 0;
14339 
14340  /*
14341  * If the object has already been moved, don't move it again. If it's
14342  * already in the right place, don't move it, but still fire the object
14343  * access hook.
14344  */
14345  already_done = object_address_present(&thisobj, objsMoved);
14346  if (!already_done && oldNspOid != newNspOid)
14347  {
14348  /* check for duplicate name (more friendly than unique-index failure) */
14349  if (get_relname_relid(NameStr(classForm->relname),
14350  newNspOid) != InvalidOid)
14351  ereport(ERROR,
14352  (errcode(ERRCODE_DUPLICATE_TABLE),
14353  errmsg("relation \"%s\" already exists in schema \"%s\"",
14354  NameStr(classForm->relname),
14355  get_namespace_name(newNspOid))));
14356 
14357  /* classTup is a copy, so OK to scribble on */
14358  classForm->relnamespace = newNspOid;
14359 
14360  CatalogTupleUpdate(classRel, &classTup->t_self, classTup);
14361 
14362  /* Update dependency on schema if caller said so */
14363  if (hasDependEntry &&
14364  changeDependencyFor(RelationRelationId,
14365  relOid,
14366  NamespaceRelationId,
14367  oldNspOid,
14368  newNspOid) != 1)
14369  elog(ERROR, "failed to change schema dependency for relation \"%s\"",
14370  NameStr(classForm->relname));
14371  }
14372  if (!already_done)
14373  {
14374  add_exact_object_address(&thisobj, objsMoved);
14375 
14376  InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
14377  }
14378 
14379  heap_freetuple(classTup);
14380 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2500
int errcode(int sqlerrcode)
Definition: elog.c:570
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2440
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1687
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:732
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:224
FormData_pg_class * Form_pg_class
Definition: pg_class.h:150
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
int errmsg(const char *fmt,...)
Definition: elog.c:784
long changeDependencyFor(Oid classId, Oid objectId, Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition: pg_depend.c:297
#define elog(elevel,...)
Definition: elog.h:226
#define NameStr(name)
Definition: c.h:609

◆ AlterTable()

void AlterTable ( Oid  relid,
LOCKMODE  lockmode,
AlterTableStmt stmt 
)

Definition at line 3494 of file tablecmds.c.

References ATController(), CheckTableNotInUse(), AlterTableStmt::cmds, RangeVar::inh, NoLock, AlterTableStmt::relation, and relation_open().

Referenced by ProcessUtilitySlow().

3495 {
3496  Relation rel;
3497 
3498  /* Caller is required to provide an adequate lock. */
3499  rel = relation_open(relid, NoLock);
3500 
3501  CheckTableNotInUse(rel, "ALTER TABLE");
3502 
3503  ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode);
3504 }
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
Definition: tablecmds.c:3824
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define NoLock
Definition: lockdefs.h:34
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3415
bool inh
Definition: primnodes.h:69
RangeVar * relation
Definition: parsenodes.h:1753

◆ AlterTableGetLockLevel()

LOCKMODE AlterTableGetLockLevel ( List cmds)

Definition at line 3563 of file tablecmds.c.

References AccessExclusiveLock, AccessShareLock, AlterTableGetRelOptionsLockLevel(), AT_AddColumn, AT_AddColumnToView, AT_AddConstraint, AT_AddConstraintRecurse, 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_DetachPartition, AT_DisableRowSecurity, AT_DisableRule, AT_DisableTrig, AT_DisableTrigAll, AT_DisableTrigUser, AT_DropCluster, AT_DropColumn, AT_DropConstraint, AT_DropIdentity, AT_DropInherit, AT_DropNotNull, AT_DropOf, AT_DropOids, AT_EnableAlwaysRule, AT_EnableAlwaysTrig, AT_EnableReplicaRule, AT_EnableReplicaTrig, AT_EnableRowSecurity, AT_EnableRule, AT_EnableTrig, AT_EnableTrigAll, AT_EnableTrigUser, AT_ForceRowSecurity, AT_GenericOptions, AT_NoForceRowSecurity, AT_ProcessedConstraint, AT_ReAddConstraint, AT_ReAddDomainConstraint, AT_ReplaceRelOptions, AT_ReplicaIdentity, AT_ResetOptions, AT_ResetRelOptions, AT_SetIdentity, AT_SetLogged, AT_SetNotNull, AT_SetOptions, AT_SetRelOptions, AT_SetStatistics, AT_SetStorage, AT_SetTableSpace, AT_SetUnLogged, AT_ValidateConstraint, CONSTR_EXCLUSION, CONSTR_FOREIGN, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, AlterTableCmd::def, elog, ERROR, IsA, lfirst, ShareRowExclusiveLock, ShareUpdateExclusiveLock, and AlterTableCmd::subtype.

Referenced by AlterTableInternal(), and ProcessUtilitySlow().

3564 {
3565  /*
3566  * This only works if we read catalog tables using MVCC snapshots.
3567  */
3568  ListCell *lcmd;
3570 
3571  foreach(lcmd, cmds)
3572  {
3573  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3574  LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
3575 
3576  switch (cmd->subtype)
3577  {
3578  /*
3579  * These subcommands rewrite the heap, so require full locks.
3580  */
3581  case AT_AddColumn: /* may rewrite heap, in some cases and visible
3582  * to SELECT */
3583  case AT_SetTableSpace: /* must rewrite heap */
3584  case AT_AlterColumnType: /* must rewrite heap */
3585  cmd_lockmode = AccessExclusiveLock;
3586  break;
3587 
3588  /*
3589  * These subcommands may require addition of toast tables. If
3590  * we add a toast table to a table currently being scanned, we
3591  * might miss data added to the new toast table by concurrent
3592  * insert transactions.
3593  */
3594  case AT_SetStorage: /* may add toast tables, see
3595  * ATRewriteCatalogs() */
3596  cmd_lockmode = AccessExclusiveLock;
3597  break;
3598 
3599  /*
3600  * Removing constraints can affect SELECTs that have been
3601  * optimized assuming the constraint holds true. See also
3602  * CloneFkReferenced.
3603  */
3604  case AT_DropConstraint: /* as DROP INDEX */
3605  case AT_DropNotNull: /* may change some SQL plans */
3606  cmd_lockmode = AccessExclusiveLock;
3607  break;
3608 
3609  /*
3610  * Subcommands that may be visible to concurrent SELECTs
3611  */
3612  case AT_DropColumn: /* change visible to SELECT */
3613  case AT_AddColumnToView: /* CREATE VIEW */
3614  case AT_DropOids: /* used to equiv to DropColumn */
3615  case AT_EnableAlwaysRule: /* may change SELECT rules */
3616  case AT_EnableReplicaRule: /* may change SELECT rules */
3617  case AT_EnableRule: /* may change SELECT rules */
3618  case AT_DisableRule: /* may change SELECT rules */
3619  cmd_lockmode = AccessExclusiveLock;
3620  break;
3621 
3622  /*
3623  * Changing owner may remove implicit SELECT privileges
3624  */
3625  case AT_ChangeOwner: /* change visible to SELECT */
3626  cmd_lockmode = AccessExclusiveLock;
3627  break;
3628 
3629  /*
3630  * Changing foreign table options may affect optimization.
3631  */
3632  case AT_GenericOptions:
3634  cmd_lockmode = AccessExclusiveLock;
3635  break;
3636 
3637  /*
3638  * These subcommands affect write operations only.
3639  */
3640  case AT_EnableTrig:
3641  case AT_EnableAlwaysTrig:
3642  case AT_EnableReplicaTrig:
3643  case AT_EnableTrigAll:
3644  case AT_EnableTrigUser:
3645  case AT_DisableTrig:
3646  case AT_DisableTrigAll:
3647  case AT_DisableTrigUser:
3648  cmd_lockmode = ShareRowExclusiveLock;
3649  break;
3650 
3651  /*
3652  * These subcommands affect write operations only. XXX
3653  * Theoretically, these could be ShareRowExclusiveLock.
3654  */
3655  case AT_ColumnDefault:
3656  case AT_AlterConstraint:
3657  case AT_AddIndex: /* from ADD CONSTRAINT */
3658  case AT_AddIndexConstraint:
3659  case AT_ReplicaIdentity:
3660  case AT_SetNotNull:
3661  case AT_EnableRowSecurity:
3662  case AT_DisableRowSecurity:
3663  case AT_ForceRowSecurity:
3664  case AT_NoForceRowSecurity:
3665  case AT_AddIdentity:
3666  case AT_DropIdentity:
3667  case AT_SetIdentity:
3668  cmd_lockmode = AccessExclusiveLock;
3669  break;
3670 
3671  case AT_AddConstraint:
3672  case AT_ProcessedConstraint: /* becomes AT_AddConstraint */
3673  case AT_AddConstraintRecurse: /* becomes AT_AddConstraint */
3674  case AT_ReAddConstraint: /* becomes AT_AddConstraint */
3675  case AT_ReAddDomainConstraint: /* becomes AT_AddConstraint */
3676  if (IsA(cmd->def, Constraint))
3677  {
3678  Constraint *con = (Constraint *) cmd->def;
3679 
3680  switch (con->contype)
3681  {
3682  case CONSTR_EXCLUSION:
3683  case CONSTR_PRIMARY:
3684  case CONSTR_UNIQUE:
3685 
3686  /*
3687  * Cases essentially the same as CREATE INDEX. We
3688  * could reduce the lock strength to ShareLock if
3689  * we can work out how to allow concurrent catalog
3690  * updates. XXX Might be set down to
3691  * ShareRowExclusiveLock but requires further
3692  * analysis.
3693  */
3694  cmd_lockmode = AccessExclusiveLock;
3695  break;
3696  case CONSTR_FOREIGN:
3697 
3698  /*
3699  * We add triggers to both tables when we add a
3700  * Foreign Key, so the lock level must be at least
3701  * as strong as CREATE TRIGGER.
3702  */
3703  cmd_lockmode = ShareRowExclusiveLock;
3704  break;
3705 
3706  default:
3707  cmd_lockmode = AccessExclusiveLock;
3708  }
3709  }
3710  break;
3711 
3712  /*
3713  * These subcommands affect inheritance behaviour. Queries
3714  * started before us will continue to see the old inheritance
3715  * behaviour, while queries started after we commit will see
3716  * new behaviour. No need to prevent reads or writes to the
3717  * subtable while we hook it up though. Changing the TupDesc
3718  * may be a problem, so keep highest lock.
3719  */
3720  case AT_AddInherit:
3721  case AT_DropInherit:
3722  cmd_lockmode = AccessExclusiveLock;
3723  break;
3724 
3725  /*
3726  * These subcommands affect implicit row type conversion. They
3727  * have affects similar to CREATE/DROP CAST on queries. don't
3728  * provide for invalidating parse trees as a result of such
3729  * changes, so we keep these at AccessExclusiveLock.
3730  */
3731  case AT_AddOf:
3732  case AT_DropOf:
3733  cmd_lockmode = AccessExclusiveLock;
3734  break;
3735 
3736  /*
3737  * Only used by CREATE OR REPLACE VIEW which must conflict
3738  * with an SELECTs currently using the view.
3739  */
3740  case AT_ReplaceRelOptions:
3741  cmd_lockmode = AccessExclusiveLock;
3742  break;
3743 
3744  /*
3745  * These subcommands affect general strategies for performance
3746  * and maintenance, though don't change the semantic results
3747  * from normal data reads and writes. Delaying an ALTER TABLE
3748  * behind currently active writes only delays the point where
3749  * the new strategy begins to take effect, so there is no
3750  * benefit in waiting. In this case the minimum restriction
3751  * applies: we don't currently allow concurrent catalog
3752  * updates.
3753  */
3754  case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
3755  case AT_ClusterOn: /* Uses MVCC in getIndexes() */
3756  case AT_DropCluster: /* Uses MVCC in getIndexes() */
3757  case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
3758  case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
3759  cmd_lockmode = ShareUpdateExclusiveLock;
3760  break;
3761 
3762  case AT_SetLogged:
3763  case AT_SetUnLogged:
3764  cmd_lockmode = AccessExclusiveLock;
3765  break;
3766 
3767  case AT_ValidateConstraint: /* Uses MVCC in getConstraints() */
3768  cmd_lockmode = ShareUpdateExclusiveLock;
3769  break;
3770 
3771  /*
3772  * Rel options are more complex than first appears. Options
3773  * are set here for tables, views and indexes; for historical
3774  * reasons these can all be used with ALTER TABLE, so we can't
3775  * decide between them using the basic grammar.
3776  */
3777  case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
3778  * getTables() */
3779  case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
3780  * getTables() */
3781  cmd_lockmode = AlterTableGetRelOptionsLockLevel((List *) cmd->def);
3782  break;
3783 
3784  case AT_AttachPartition:
3785  cmd_lockmode = ShareUpdateExclusiveLock;
3786  break;
3787 
3788  case AT_DetachPartition:
3789  cmd_lockmode = AccessExclusiveLock;
3790  break;
3791 
3792  case AT_CheckNotNull:
3793 
3794  /*
3795  * This only examines the table's schema; but lock must be
3796  * strong enough to prevent concurrent DROP NOT NULL.
3797  */
3798  cmd_lockmode = AccessShareLock;
3799  break;
3800 
3801  default: /* oops */
3802  elog(ERROR, "unrecognized alter table type: %d",
3803  (int) cmd->subtype);
3804  break;
3805  }
3806 
3807  /*
3808  * Take the greatest lockmode from any subcommand
3809  */
3810  if (cmd_lockmode > lockmode)
3811  lockmode = cmd_lockmode;
3812  }
3813 
3814  return lockmode;
3815 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
int LOCKMODE
Definition: lockdefs.h:26
#define AccessShareLock
Definition: lockdefs.h:36
AlterTableType subtype
Definition: parsenodes.h:1840
#define ERROR
Definition: elog.h:43
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define lfirst(lc)
Definition: pg_list.h:190
#define ShareRowExclusiveLock
Definition: lockdefs.h:42
LOCKMODE AlterTableGetRelOptionsLockLevel(List *defList)
Definition: reloptions.c:1589
#define AccessExclusiveLock
Definition: lockdefs.h:45
#define elog(elevel,...)
Definition: elog.h:226
ConstrType contype
Definition: parsenodes.h:2129
Definition: pg_list.h:50

◆ AlterTableInternal()

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

Definition at line 3518 of file tablecmds.c.

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

Referenced by AlterTableMoveAll(), and DefineVirtualRelation().

3519 {
3520  Relation rel;
3521  LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
3522 
3523  rel = relation_open(relid, lockmode);
3524 
3526 
3527  ATController(NULL, rel, cmds, recurse, lockmode);
3528 }
int LOCKMODE
Definition: lockdefs.h:26
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
Definition: tablecmds.c:3824
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
LOCKMODE AlterTableGetLockLevel(List *cmds)
Definition: tablecmds.c:3563
void EventTriggerAlterTableRelid(Oid objectId)

◆ AlterTableLookupRelation()

Oid AlterTableLookupRelation ( AlterTableStmt stmt,
LOCKMODE  lockmode 
)

Definition at line 3443 of file tablecmds.c.

References AlterTableStmt::missing_ok, RangeVarCallbackForAlterRelation(), RangeVarGetRelidExtended(), AlterTableStmt::relation, and RVR_MISSING_OK.

Referenced by ProcessUtilitySlow().

3444 {
3445  return RangeVarGetRelidExtended(stmt->relation, lockmode,
3446  stmt->missing_ok ? RVR_MISSING_OK : 0,
3448  (void *) stmt);
3449 }
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:14832
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:228
RangeVar * relation
Definition: parsenodes.h:1753

◆ AlterTableMoveAll()

Oid AlterTableMoveAll ( AlterTableMoveAllStmt stmt)

Definition at line 12514 of file tablecmds.c.

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, AlterTableMoveAllStmt::new_tablespacename, NIL, NOTICE, AlterTableMoveAllStmt::nowait, OBJECT_INDEX, OBJECT_MATVIEW, OBJECT_TABLE, OBJECT_TABLESPACE, ObjectIdGetDatum, AlterTableMoveAllStmt::objtype, OidIsValid, AlterTableMoveAllStmt::orig_tablespacename, pg_class_ownercheck(), pg_tablespace_aclcheck(), AlterTableMoveAllStmt::roles, roleSpecsToIds(), ScanKeyInit(), AlterTableCmd::subtype, table_beginscan_catalog(), table_close(), table_endscan(), and table_open().

Referenced by ProcessUtilitySlow().

12515 {
12516  List *relations = NIL;
12517  ListCell *l;
12518  ScanKeyData key[1];
12519  Relation rel;
12520  TableScanDesc scan;
12521  HeapTuple tuple;
12522  Oid orig_tablespaceoid;
12523  Oid new_tablespaceoid;
12524  List *role_oids = roleSpecsToIds(stmt->roles);
12525 
12526  /* Ensure we were not asked to move something we can't */
12527  if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
12528  stmt->objtype != OBJECT_MATVIEW)
12529  ereport(ERROR,
12530  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
12531  errmsg("only tables, indexes, and materialized views exist in tablespaces")));
12532 
12533  /* Get the orig and new tablespace OIDs */
12534  orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
12535  new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
12536 
12537  /* Can't move shared relations in to or out of pg_global */
12538  /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
12539  if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
12540  new_tablespaceoid == GLOBALTABLESPACE_OID)
12541  ereport(ERROR,
12542  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
12543  errmsg("cannot move relations in to or out of pg_global tablespace")));
12544 
12545  /*
12546  * Must have CREATE rights on the new tablespace, unless it is the
12547  * database default tablespace (which all users implicitly have CREATE
12548  * rights on).
12549  */
12550  if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
12551  {
12552  AclResult aclresult;
12553 
12554  aclresult = pg_tablespace_aclcheck(new_tablespaceoid, GetUserId(),
12555  ACL_CREATE);
12556  if (aclresult != ACLCHECK_OK)
12557  aclcheck_error(aclresult, OBJECT_TABLESPACE,
12558  get_tablespace_name(new_tablespaceoid));
12559  }
12560 
12561  /*
12562  * Now that the checks are done, check if we should set either to
12563  * InvalidOid because it is our database's default tablespace.
12564  */
12565  if (orig_tablespaceoid == MyDatabaseTableSpace)
12566  orig_tablespaceoid = InvalidOid;
12567 
12568  if (new_tablespaceoid == MyDatabaseTableSpace)
12569  new_tablespaceoid = InvalidOid;
12570 
12571  /* no-op */
12572  if (orig_tablespaceoid == new_tablespaceoid)
12573  return new_tablespaceoid;
12574 
12575  /*
12576  * Walk the list of objects in the tablespace and move them. This will
12577  * only find objects in our database, of course.
12578  */
12579  ScanKeyInit(&key[0],
12580  Anum_pg_class_reltablespace,
12581  BTEqualStrategyNumber, F_OIDEQ,
12582  ObjectIdGetDatum(orig_tablespaceoid));
12583 
12584  rel = table_open(RelationRelationId, AccessShareLock);
12585  scan = table_beginscan_catalog(rel, 1, key);
12586  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
12587  {
12588  Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
12589  Oid relOid = relForm->oid;
12590 
12591  /*
12592  * Do not move objects in pg_catalog as part of this, if an admin
12593  * really wishes to do so, they can issue the individual ALTER
12594  * commands directly.
12595  *
12596  * Also, explicitly avoid any shared tables, temp tables, or TOAST
12597  * (TOAST will be moved with the main table).
12598  */
12599  if (IsCatalogNamespace(relForm->relnamespace) ||
12600  relForm->relisshared ||
12601  isAnyTempNamespace(relForm->relnamespace) ||
12602  IsToastNamespace(relForm->relnamespace))
12603  continue;
12604 
12605  /* Only move the object type requested */
12606  if ((stmt->objtype == OBJECT_TABLE &&
12607  relForm->relkind != RELKIND_RELATION &&
12608  relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
12609  (stmt->objtype == OBJECT_INDEX &&
12610  relForm->relkind != RELKIND_INDEX &&
12611  relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
12612  (stmt->objtype == OBJECT_MATVIEW &&
12613  relForm->relkind != RELKIND_MATVIEW))
12614  continue;
12615 
12616  /* Check if we are only moving objects owned by certain roles */
12617  if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
12618  continue;
12619 
12620  /*
12621  * Handle permissions-checking here since we are locking the tables
12622  * and also to avoid doing a bunch of work only to fail part-way. Note
12623  * that permissions will also be checked by AlterTableInternal().
12624  *
12625  * Caller must be considered an owner on the table to move it.
12626  */
12627  if (!pg_class_ownercheck(relOid, GetUserId()))
12629  NameStr(relForm->relname));
12630 
12631  if (stmt->nowait &&
12633  ereport(ERROR,
12634  (errcode(ERRCODE_OBJECT_IN_USE),
12635  errmsg("aborting because lock on relation \"%s.%s\" is not available",
12636  get_namespace_name(relForm->relnamespace),
12637  NameStr(relForm->relname))));
12638  else
12640 
12641  /* Add to our list of objects to move */
12642  relations = lappend_oid(relations, relOid);
12643  }
12644 
12645  table_endscan(scan);
12647 
12648  if (relations == NIL)
12649  ereport(NOTICE,
12650  (errcode(ERRCODE_NO_DATA_FOUND),
12651  errmsg("no matching relations in tablespace \"%s\" found",
12652  orig_tablespaceoid == InvalidOid ? "(database default)" :
12653  get_tablespace_name(orig_tablespaceoid))));
12654 
12655  /* Everything is locked, loop through and move all of the relations. */
12656  foreach(l, relations)
12657  {
12658  List *cmds = NIL;
12660 
12661  cmd->subtype = AT_SetTableSpace;
12662  cmd->name = stmt->new_tablespacename;
12663 
12664  cmds = lappend(cmds, cmd);
12665 
12667  /* OID is set by AlterTableInternal */
12668  AlterTableInternal(lfirst_oid(l), cmds, false);
12670  }
12671 
12672  return new_tablespaceoid;
12673 }
#define NIL
Definition: pg_list.h:65
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:151
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1417
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4705
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:98
Oid GetUserId(void)
Definition: miscinit.c:380
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1805
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:570
AlterTableType subtype
Definition: parsenodes.h:1840
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:197
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
#define OidIsValid(objectId)
Definition: c.h:638
Oid MyDatabaseTableSpace
Definition: globals.c:87
void EventTriggerAlterTableStart(Node *parsetree)
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3353
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define ACL_CREATE
Definition: parsenodes.h:84
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1290
#define ereport(elevel, rest)
Definition: elog.h:141
List * lappend(List *list, void *datum)
Definition: list.c:321
AclResult
Definition: acl.h:177
#define InvalidOid
Definition: postgres_ext.h:36
#define NOTICE
Definition: elog.h:37
#define makeNode(_type_)
Definition: nodes.h:573
List * roleSpecsToIds(List *memberNames)
Definition: user.c:1423
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:674
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4755
bool IsCatalogNamespace(Oid namespaceId)
Definition: catalog.c:179
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:831
FormData_pg_class * Form_pg_class
Definition: pg_class.h:150
void AlterTableInternal(Oid relid, List *cmds, bool recurse)
Definition: tablecmds.c:3518
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:784
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1463
ObjectType get_relkind_objtype(char relkind)
#define NameStr(name)
Definition: c.h:609
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
bool isAnyTempNamespace(Oid namespaceId)
Definition: namespace.c:3187
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:108
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define lfirst_oid(lc)
Definition: pg_list.h:192
void EventTriggerAlterTableEnd(void)

◆ AlterTableNamespace()

ObjectAddress AlterTableNamespace ( AlterObjectSchemaStmt stmt,
Oid oldschema 
)

Definition at line 14210 of file tablecmds.c.

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

Referenced by ExecAlterObjectSchemaStmt().

14211 {
14212  Relation rel;
14213  Oid relid;
14214  Oid oldNspOid;
14215  Oid nspOid;
14216  RangeVar *newrv;
14217  ObjectAddresses *objsMoved;
14218  ObjectAddress myself;
14219 
14221  stmt->missing_ok ? RVR_MISSING_OK : 0,
14223  (void *) stmt);
14224 
14225  if (!OidIsValid(relid))
14226  {
14227  ereport(NOTICE,
14228  (errmsg("relation \"%s\" does not exist, skipping",
14229  stmt->relation->relname)));
14230  return InvalidObjectAddress;
14231  }
14232 
14233  rel = relation_open(relid, NoLock);
14234 
14235  oldNspOid = RelationGetNamespace(rel);
14236 
14237  /* If it's an owned sequence, disallow moving it by itself. */
14238  if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
14239  {
14240  Oid tableId;
14241  int32 colId;
14242 
14243  if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
14244  sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
14245  ereport(ERROR,
14246  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
14247  errmsg("cannot move an owned sequence into another schema"),
14248  errdetail("Sequence \"%s\" is linked to table \"%s\".",
14250  get_rel_name(tableId))));
14251  }
14252 
14253  /* Get and lock schema OID and check its permissions. */
14254  newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
14255  nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
14256 
14257  /* common checks on switching namespaces */
14258  CheckSetNamespace(oldNspOid, nspOid);
14259 
14260  objsMoved = new_object_addresses();
14261  AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
14262  free_object_addresses(objsMoved);
14263 
14264  ObjectAddressSet(myself, RelationRelationId, relid);
14265 
14266  if (oldschema)
14267  *oldschema = oldNspOid;
14268 
14269  /* close rel, but keep lock until commit */
14270  relation_close(rel, NoLock);
14271 
14272  return myself;
14273 }
bool sequenceIsOwned(Oid seqId, char deptype, Oid *tableId, int32 *colId)
Definition: pg_depend.c:663
int errcode(int sqlerrcode)
Definition: elog.c:570
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2385
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2680
Form_pg_class rd_rel
Definition: rel.h:83
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:638
signed int int32
Definition: c.h:346
char * relname
Definition: primnodes.h:68
#define ERROR
Definition: elog.h:43
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
void AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:14281
#define NoLock
Definition: lockdefs.h:34
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:14832
int errdetail(const char *fmt,...)
Definition: elog.c:860
#define RelationGetRelationName(relation)
Definition: rel.h:450
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:228
#define ereport(elevel, rest)
Definition: elog.h:141
void CheckSetNamespace(Oid oldNspOid, Oid nspOid)
Definition: namespace.c:2959
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:526
#define NOTICE
Definition: elog.h:37
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define AccessExclusiveLock
Definition: lockdefs.h:45
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:784
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1730
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:420
#define RelationGetNamespace(relation)
Definition: rel.h:457

◆ AlterTableNamespaceInternal()

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

Definition at line 14281 of file tablecmds.c.

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

Referenced by AlterObjectNamespace_oid(), and AlterTableNamespace().

14283 {
14284  Relation classRel;
14285 
14286  Assert(objsMoved != NULL);
14287 
14288  /* OK, modify the pg_class row and pg_depend entry */
14289  classRel = table_open(RelationRelationId, RowExclusiveLock);
14290 
14291  AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
14292  nspOid, true, objsMoved);
14293 
14294  /* Fix the table's row type too */
14295  AlterTypeNamespaceInternal(rel->rd_rel->reltype,
14296  nspOid, false, false, objsMoved);
14297 
14298  /* Fix other dependent stuff */
14299  if (rel->rd_rel->relkind == RELKIND_RELATION ||
14300  rel->rd_rel->relkind == RELKIND_MATVIEW ||
14301  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
14302  {
14303  AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
14304  AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
14305  objsMoved, AccessExclusiveLock);
14306  AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
14307  false, objsMoved);
14308  }
14309 
14310  table_close(classRel, RowExclusiveLock);
14311 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
Oid AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid, bool isImplicitArray, bool errorOnTableType, ObjectAddresses *objsMoved)
Definition: typecmds.c:3579
Form_pg_class rd_rel
Definition: rel.h:83
static void AlterIndexNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:14389
void AlterConstraintNamespaces(Oid ownerId, Oid oldNspId, Oid newNspId, bool isType, ObjectAddresses *objsMoved)
static void AlterSeqNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved, LOCKMODE lockmode)
Definition: tablecmds.c:14434
#define RowExclusiveLock
Definition: lockdefs.h:38
#define Assert(condition)
Definition: c.h:732
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
Definition: tablecmds.c:14319
#define AccessExclusiveLock
Definition: lockdefs.h:45
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define RelationGetRelid(relation)
Definition: rel.h:416

◆ AtEOSubXact_on_commit_actions()

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

Definition at line 14710 of file tablecmds.c.

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

Referenced by AbortSubTransaction(), and CommitSubTransaction().

14712 {
14713  ListCell *cur_item;
14714 
14715  foreach(cur_item, on_commits)
14716  {
14717  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
14718 
14719  if (!isCommit && oc->creating_subid == mySubid)
14720  {
14721  /* cur_item must be removed */
14723  pfree(oc);
14724  }
14725  else
14726  {
14727  /* cur_item must be preserved */
14728  if (oc->creating_subid == mySubid)
14729  oc->creating_subid = parentSubid;
14730  if (oc->deleting_subid == mySubid)
14731  oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
14732  }
14733  }
14734 }
SubTransactionId creating_subid
Definition: tablecmds.c:119
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:368
void pfree(void *pointer)
Definition: mcxt.c:1031
static List * on_commits
Definition: tablecmds.c:123
SubTransactionId deleting_subid
Definition: tablecmds.c:120
#define lfirst(lc)
Definition: pg_list.h:190
#define InvalidSubTransactionId
Definition: c.h:513

◆ AtEOXact_on_commit_actions()

void AtEOXact_on_commit_actions ( bool  isCommit)

Definition at line 14678 of file tablecmds.c.

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

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

14679 {
14680  ListCell *cur_item;
14681 
14682  foreach(cur_item, on_commits)
14683  {
14684  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
14685 
14686  if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
14688  {
14689  /* cur_item must be removed */
14691  pfree(oc);
14692  }
14693  else
14694  {
14695  /* cur_item must be preserved */
14698  }
14699  }
14700 }
SubTransactionId creating_subid
Definition: tablecmds.c:119
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:368
void pfree(void *pointer)
Definition: mcxt.c:1031
static List * on_commits
Definition: tablecmds.c:123
SubTransactionId deleting_subid
Definition: tablecmds.c:120
#define lfirst(lc)
Definition: pg_list.h:190
#define InvalidSubTransactionId
Definition: c.h:513

◆ ATExecChangeOwner()

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

Definition at line 11664 of file tablecmds.c.

References ACL_CREATE, aclcheck_error(), ACLCHECK_NOT_OWNER, ACLCHECK_OK, aclnewowner(), AlterTypeOwnerInternal(), ATExecChangeOwner(), CatalogTupleUpdate(), change_owner_fix_column_acls(), change_owner_recurse_to_sequences(), changeDependencyOnOwner(), check_is_member_of_role(), DatumGetAclP, DEPENDENCY_AUTO, DEPENDENCY_INTERNAL, elog, ereport, errcode(), errdetail(), 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_SCHEMA, ObjectIdGetDatum, pg_class_ownercheck(), pg_namespace_aclcheck(), PointerGetDatum, relation_close(), relation_open(), RelationGetDescr, RelationGetIndexList(), RelationGetRelationName, ReleaseSysCache(), RELOID, RowExclusiveLock, SearchSysCache1(), sequenceIsOwned(), superuser(), SysCacheGetAttr(), HeapTupleData::t_self, table_close(), table_open(), and WARNING.

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

11665 {
11666  Relation target_rel;
11667  Relation class_rel;
11668  HeapTuple tuple;
11669  Form_pg_class tuple_class;
11670 
11671  /*
11672  * Get exclusive lock till end of transaction on the target table. Use
11673  * relation_open so that we can work on indexes and sequences.
11674  */
11675  target_rel = relation_open(relationOid, lockmode);
11676 
11677  /* Get its pg_class tuple, too */
11678  class_rel = table_open(RelationRelationId, RowExclusiveLock);
11679 
11680  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
11681  if (!HeapTupleIsValid(tuple))
11682  elog(ERROR, "cache lookup failed for relation %u", relationOid);
11683  tuple_class = (Form_pg_class) GETSTRUCT(tuple);
11684 
11685  /* Can we change the ownership of this tuple? */
11686  switch (tuple_class->relkind)
11687  {
11688  case RELKIND_RELATION:
11689  case RELKIND_VIEW:
11690  case RELKIND_MATVIEW:
11691  case RELKIND_FOREIGN_TABLE:
11692  case RELKIND_PARTITIONED_TABLE:
11693  /* ok to change owner */
11694  break;
11695  case RELKIND_INDEX:
11696  if (!recursing)
11697  {
11698  /*
11699  * Because ALTER INDEX OWNER used to be allowed, and in fact
11700  * is generated by old versions of pg_dump, we give a warning
11701  * and do nothing rather than erroring out. Also, to avoid
11702  * unnecessary chatter while restoring those old dumps, say
11703  * nothing at all if the command would be a no-op anyway.
11704  */
11705  if (tuple_class->relowner != newOwnerId)
11706  ereport(WARNING,
11707  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11708  errmsg("cannot change owner of index \"%s\"",
11709  NameStr(tuple_class->relname)),
11710  errhint("Change the ownership of the index's table, instead.")));
11711  /* quick hack to exit via the no-op path */
11712  newOwnerId = tuple_class->relowner;
11713  }
11714  break;
11715  case RELKIND_PARTITIONED_INDEX:
11716  if (recursing)
11717  break;
11718  ereport(ERROR,
11719  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11720  errmsg("cannot change owner of index \"%s\"",
11721  NameStr(tuple_class->relname)),
11722  errhint("Change the ownership of the index's table, instead.")));
11723  break;
11724  case RELKIND_SEQUENCE:
11725  if (!recursing &&
11726  tuple_class->relowner != newOwnerId)
11727  {
11728  /* if it's an owned sequence, disallow changing it by itself */
11729  Oid tableId;
11730  int32 colId;
11731 
11732  if (sequenceIsOwned(relationOid, DEPENDENCY_AUTO, &tableId, &colId) ||
11733  sequenceIsOwned(relationOid, DEPENDENCY_INTERNAL, &tableId, &colId))
11734  ereport(ERROR,
11735  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
11736  errmsg("cannot change owner of sequence \"%s\"",
11737  NameStr(tuple_class->relname)),
11738  errdetail("Sequence \"%s\" is linked to table \"%s\".",
11739  NameStr(tuple_class->relname),
11740  get_rel_name(tableId))));
11741  }
11742  break;
11743  case RELKIND_COMPOSITE_TYPE:
11744  if (recursing)
11745  break;
11746  ereport(ERROR,
11747  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11748  errmsg("\"%s\" is a composite type",
11749  NameStr(tuple_class->relname)),
11750  errhint("Use ALTER TYPE instead.")));
11751  break;
11752  case RELKIND_TOASTVALUE:
11753  if (recursing)
11754  break;
11755  /* FALL THRU */
11756  default:
11757  ereport(ERROR,
11758  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11759  errmsg("\"%s\" is not a table, view, sequence, or foreign table",
11760  NameStr(tuple_class->relname))));
11761  }
11762 
11763  /*
11764  * If the new owner is the same as the existing owner, consider the
11765  * command to have succeeded. This is for dump restoration purposes.
11766  */
11767  if (tuple_class->relowner != newOwnerId)
11768  {
11769  Datum repl_val[Natts_pg_class];
11770  bool repl_null[Natts_pg_class];
11771  bool repl_repl[Natts_pg_class];
11772  Acl *newAcl;
11773  Datum aclDatum;
11774  bool isNull;
11775  HeapTuple newtuple;
11776 
11777  /* skip permission checks when recursing to index or toast table */
11778  if (!recursing)
11779  {
11780  /* Superusers can always do it */
11781  if (!superuser())
11782  {
11783  Oid namespaceOid = tuple_class->relnamespace;
11784  AclResult aclresult;
11785 
11786  /* Otherwise, must be owner of the existing object */
11787  if (!pg_class_ownercheck(relationOid, GetUserId()))
11789  RelationGetRelationName(target_rel));
11790 
11791  /* Must be able to become new owner */
11792  check_is_member_of_role(GetUserId(), newOwnerId);
11793 
11794  /* New owner must have CREATE privilege on namespace */
11795  aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
11796  ACL_CREATE);
11797  if (aclresult != ACLCHECK_OK)
11798  aclcheck_error(aclresult, OBJECT_SCHEMA,
11799  get_namespace_name(namespaceOid));
11800  }
11801  }
11802 
11803  memset(repl_null, false, sizeof(repl_null));
11804  memset(repl_repl, false, sizeof(repl_repl));
11805 
11806  repl_repl[Anum_pg_class_relowner - 1] = true;
11807  repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
11808 
11809  /*
11810  * Determine the modified ACL for the new owner. This is only
11811  * necessary when the ACL is non-null.
11812  */
11813  aclDatum = SysCacheGetAttr(RELOID, tuple,
11814  Anum_pg_class_relacl,
11815  &isNull);
11816  if (!isNull)
11817  {
11818  newAcl = aclnewowner(DatumGetAclP(aclDatum),
11819  tuple_class->relowner, newOwnerId);
11820  repl_repl[Anum_pg_class_relacl - 1] = true;
11821  repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
11822  }
11823 
11824  newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
11825 
11826  CatalogTupleUpdate(class_rel, &newtuple->t_self, newtuple);
11827 
11828  heap_freetuple(newtuple);
11829 
11830  /*
11831  * We must similarly update any per-column ACLs to reflect the new
11832  * owner; for neatness reasons that's split out as a subroutine.
11833  */
11834  change_owner_fix_column_acls(relationOid,
11835  tuple_class->relowner,
11836  newOwnerId);
11837 
11838  /*
11839  * Update owner dependency reference, if any. A composite type has
11840  * none, because it's tracked for the pg_type entry instead of here;
11841  * indexes and TOAST tables don't have their own entries either.
11842  */
11843  if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
11844  tuple_class->relkind != RELKIND_INDEX &&
11845  tuple_class->relkind != RELKIND_PARTITIONED_INDEX &&
11846  tuple_class->relkind != RELKIND_TOASTVALUE)
11847  changeDependencyOnOwner(RelationRelationId, relationOid,
11848  newOwnerId);
11849 
11850  /*
11851  * Also change the ownership of the table's row type, if it has one
11852  */
11853  if (tuple_class->relkind != RELKIND_INDEX &&
11854  tuple_class->relkind != RELKIND_PARTITIONED_INDEX)
11855  AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId);
11856 
11857  /*
11858  * If we are operating on a table or materialized view, also change
11859  * the ownership of any indexes and sequences that belong to the
11860  * relation, as well as its toast table (if it has one).
11861  */
11862  if (tuple_class->relkind == RELKIND_RELATION ||
11863  tuple_class->relkind == RELKIND_PARTITIONED_TABLE ||
11864  tuple_class->relkind == RELKIND_MATVIEW ||
11865  tuple_class->relkind == RELKIND_TOASTVALUE)
11866  {
11867  List *index_oid_list;
11868  ListCell *i;
11869 
11870  /* Find all the indexes belonging to this relation */
11871  index_oid_list = RelationGetIndexList(target_rel);
11872 
11873  /* For each index, recursively change its ownership */
11874  foreach(i, index_oid_list)
11875  ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
11876 
11877  list_free(index_oid_list);
11878  }
11879 
11880  /* If it has a toast table, recurse to change its ownership */
11881  if (tuple_class->reltoastrelid != InvalidOid)
11882  ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
11883  true, lockmode);
11884 
11885  /* If it has dependent sequences, recurse to change them too */
11886  change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
11887  }
11888 
11889  InvokeObjectPostAlterHook(RelationRelationId, relationOid, 0);
11890 
11891  ReleaseSysCache(tuple);
11892  table_close(class_rel, RowExclusiveLock);
11893  relation_close(target_rel, NoLock);
11894 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
int errhint(const char *fmt,...)
Definition: elog.c:974
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
bool sequenceIsOwned(Oid seqId, char deptype, Oid *tableId, int32 *colId)
Definition: pg_depend.c:663
#define RelationGetDescr(relation)
Definition: rel.h:442
Oid GetUserId(void)
Definition: miscinit.c:380
#define DatumGetAclP(X)
Definition: acl.h:120
#define PointerGetDatum(X)
Definition: postgres.h:556
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1805
int errcode(int sqlerrcode)
Definition: elog.c:570
bool superuser(void)
Definition: superuser.c:47
void AlterTypeOwnerInternal(Oid typeOid, Oid newOwnerId)
Definition: typecmds.c:3449
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
AclResult pg_namespace_aclcheck(Oid nsp_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4693
signed int int32
Definition: c.h:346
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
Definition: pg_shdepend.c:310
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3353
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define ACL_CREATE
Definition: parsenodes.h:84
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
ItemPointerData t_self
Definition: htup.h:65
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:860
#define RelationGetRelationName(relation)
Definition: rel.h:450
void check_is_member_of_role(Oid member, Oid role)
Definition: acl.c:4954
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
void ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
Definition: tablecmds.c:11664
#define WARNING
Definition: elog.h:40
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1124
AclResult
Definition: acl.h:177
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1172
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1385
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4755
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:224
static void change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
Definition: tablecmds.c:11968
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4348
FormData_pg_class * Form_pg_class
Definition: pg_class.h:150
static void change_owner_fix_column_acls(Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
Definition: tablecmds.c:11903
int errmsg(const char *fmt,...)
Definition: elog.c:784
void list_free(List *list)
Definition: list.c:1373
#define elog(elevel,...)
Definition: elog.h:226
int i
ObjectType get_relkind_objtype(char relkind)
#define NameStr(name)
Definition: c.h:609
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
Definition: pg_list.h:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1730
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition: acl.c:1052
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ check_of_type()

void check_of_type ( HeapTuple  typetuple)

Definition at line 5515 of file tablecmds.c.

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

5516 {
5517  Form_pg_type typ = (Form_pg_type) GETSTRUCT(typetuple);
5518  bool typeOk = false;
5519 
5520  if (typ->typtype == TYPTYPE_COMPOSITE)
5521  {
5522  Relation typeRelation;
5523 
5524  Assert(OidIsValid(typ->typrelid));
5525  typeRelation = relation_open(typ->typrelid, AccessShareLock);
5526  typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
5527 
5528  /*
5529  * Close the parent rel, but keep our AccessShareLock on it until xact
5530  * commit. That will prevent someone else from deleting or ALTERing
5531  * the type before the typed table creation/conversion commits.
5532  */
5533  relation_close(typeRelation, NoLock);
5534  }
5535  if (!typeOk)
5536  ereport(ERROR,
5537  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5538  errmsg("type %s is not a composite type",
5539  format_type_be(typ->oid))));
5540 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:570
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
Form_pg_class rd_rel
Definition: rel.h:83
#define OidIsValid(objectId)
Definition: c.h:638
#define ERROR
Definition: elog.h:43
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define NoLock
Definition: lockdefs.h:34
#define ereport(elevel, rest)
Definition: elog.h:141
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define Assert(condition)
Definition: c.h:732
FormData_pg_type * Form_pg_type
Definition: pg_type.h:251
int errmsg(const char *fmt,...)
Definition: elog.c:784

◆ CheckTableNotInUse()

void CheckTableNotInUse ( Relation  rel,
const char *  stmt 
)

Definition at line 3415 of file tablecmds.c.

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

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

3416 {
3417  int expected_refcnt;
3418 
3419  expected_refcnt = rel->rd_isnailed ? 2 : 1;
3420  if (rel->rd_refcnt != expected_refcnt)
3421  ereport(ERROR,
3422  (errcode(ERRCODE_OBJECT_IN_USE),
3423  /* translator: first %s is a SQL command, eg ALTER TABLE */
3424  errmsg("cannot %s \"%s\" because it is being used by active queries in this session",
3425  stmt, RelationGetRelationName(rel))));
3426 
3427  if (rel->rd_rel->relkind != RELKIND_INDEX &&
3428  rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
3430  ereport(ERROR,
3431  (errcode(ERRCODE_OBJECT_IN_USE),
3432  /* translator: first %s is a SQL command, eg ALTER TABLE */
3433  errmsg("cannot %s \"%s\" because it has pending trigger events",
3434  stmt, RelationGetRelationName(rel))));
3435 }
bool rd_isnailed
Definition: rel.h:60
int errcode(int sqlerrcode)
Definition: elog.c:570
Form_pg_class rd_rel
Definition: rel.h:83
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:450
#define ereport(elevel, rest)
Definition: elog.h:141
bool AfterTriggerPendingOnRel(Oid relid)
Definition: trigger.c:5648
int errmsg(const char *fmt,...)
Definition: elog.c:784
int rd_refcnt
Definition: rel.h:57
#define RelationGetRelid(relation)
Definition: rel.h:416

◆ DefineRelation()

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

Definition at line 555 of file tablecmds.c.

References AccessExclusiveLock, CreateStmt::accessMethod, AccessShareLock, ACL_CREATE, ACL_USAGE, aclcheck_error(), aclcheck_error_type(), ACLCHECK_OK, addRangeTableEntryForRelation(), AddRelationNewConstraints(), addRTEtoQuery(), allowSystemTableMods, Assert, RawColumnDefault::attnum, CookedConstraint::attnum, attnum, BuildDescForRelation(), check_default_partition_contents(), check_new_partition_bound(), CloneForeignKeyConstraints(), CloneRowTriggersToPartition(), CommandCounterIncrement(), ComputePartitionAttrs(), CookedConstraint::conoid, CONSTR_DEFAULT, CreateStmt::constraints, CookedConstraint::contype, convert_tuples_by_name_map(), ColumnDef::cooked_default, default_table_access_method, DefineIndex(), elog, ereport, errcode(), errdetail(), errmsg(), ERROR, CookedConstraint::expr, generateClonedIndexStmt(), RawColumnDefault::generated, ColumnDef::generated, get_default_oid_from_partdesc(), get_rel_name(), get_rel_tablespace(), get_table_am_oid(), get_tablespace_name(), get_tablespace_oid(), GetDefaultTablespace(), GetUserId(), heap_create_with_catalog(), HEAP_RELOPT_NAMESPACES, heap_reloptions(), ColumnDef::identity, index_close(), index_open(), CookedConstraint::inhcount, CreateStmt::inhRelations, 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_TABLESPACE, ObjectAddressSet, CreateStmt::ofTypename, OidIsValid, CreateStmt::oncommit, ONCOMMIT_NOOP, CreateStmt::options, ParseState::p_sourcetext, palloc(), CreateStmt::partbound, PARTITION_MAX_KEYS, PartitionSpec::partParams, CreateStmt::partspec, pg_tablespace_aclcheck(), pg_type_aclcheck(), RangeVarGetAndCheckCreationNamespace(), RangeVarGetRelid, RawColumnDefault::raw_default, ColumnDef::raw_default, RelationData::rd_index, RelationData::rd_rel, CreateStmt::relation, relation_close(), relation_open(), RelationGetDescr, RelationGetIndexList(), RelationGetPartitionDesc, RelationGetRelationName, RelationGetRelid, relname, RangeVar::relname, RangeVar::relpersistence, ShareUpdateExclusiveLock, CookedConstraint::skip_validation, StoreCatalogInheritance(), StorePartitionBound(), StorePartitionKey(), StrNCpy, table_close(), table_open(), CreateStmt::tableElts, CreateStmt::tablespacename, transformPartitionBound(), transformPartitionSpec(), transformRelOptions(), RelationData::trigdesc, TupleDescAttr, typenameTypeId(), and view_reloptions().

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

557 {
558  char relname[NAMEDATALEN];
559  Oid namespaceId;
560  Oid relationId;
561  Oid tablespaceId;
562  Relation rel;
564  List *inheritOids;
565  List *old_constraints;
566  List *rawDefaults;
567  List *cookedDefaults;
568  Datum reloptions;
569  ListCell *listptr;
571  bool partitioned;
572  static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
573  Oid ofTypeId;
574  ObjectAddress address;
575  LOCKMODE parentLockmode;
576  const char *accessMethod = NULL;
577  Oid accessMethodId = InvalidOid;
578 
579  /*
580  * Truncate relname to appropriate length (probably a waste of time, as
581  * parser should have done this already).
582  */
583  StrNCpy(relname, stmt->relation->relname, NAMEDATALEN);
584 
585  /*
586  * Check consistency of arguments
587  */
588  if (stmt->oncommit != ONCOMMIT_NOOP
589  && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
590  ereport(ERROR,
591  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
592  errmsg("ON COMMIT can only be used on temporary tables")));
593 
594  if (stmt->partspec != NULL)
595  {
596  if (relkind != RELKIND_RELATION)
597  elog(ERROR, "unexpected relkind: %d", (int) relkind);
598 
599  relkind = RELKIND_PARTITIONED_TABLE;
600  partitioned = true;
601  }
602  else
603  partitioned = false;
604 
605  /*
606  * Look up the namespace in which we are supposed to create the relation,
607  * check we have permission to create there, lock it against concurrent
608  * drop, and mark stmt->relation as RELPERSISTENCE_TEMP if a temporary
609  * namespace is selected.
610  */
611  namespaceId =
613 
614  /*
615  * Security check: disallow creating temp tables from security-restricted
616  * code. This is needed because calling code might not expect untrusted
617  * tables to appear in pg_temp at the front of its search path.
618  */
619  if (stmt->relation->relpersistence == RELPERSISTENCE_TEMP
621  ereport(ERROR,
622  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
623  errmsg("cannot create temporary table within security-restricted operation")));
624 
625  /*
626  * Determine the lockmode to use when scanning parents. A self-exclusive
627  * lock is needed here.
628  *
629  * For regular inheritance, if two backends attempt to add children to the
630  * same parent simultaneously, and that parent has no pre-existing
631  * children, then both will attempt to update the parent's relhassubclass
632  * field, leading to a "tuple concurrently updated" error. Also, this
633  * interlocks against a concurrent ANALYZE on the parent table, which
634  * might otherwise be attempting to clear the parent's relhassubclass
635  * field, if its previous children were recently dropped.
636  *
637  * If the child table is a partition, then we instead grab an exclusive
638  * lock on the parent because its partition descriptor will be changed by
639  * addition of the new partition.
640  */
641  parentLockmode = (stmt->partbound != NULL ? AccessExclusiveLock :
643 
644  /* Determine the list of OIDs of the parents. */
645  inheritOids = NIL;
646  foreach(listptr, stmt->inhRelations)
647  {
648  RangeVar *rv = (RangeVar *) lfirst(listptr);
649  Oid parentOid;
650 
651  parentOid = RangeVarGetRelid(rv, parentLockmode, false);
652 
653  /*
654  * Reject duplications in the list of parents.
655  */
656  if (list_member_oid(inheritOids, parentOid))
657  ereport(ERROR,
658  (errcode(ERRCODE_DUPLICATE_TABLE),
659  errmsg("relation \"%s\" would be inherited from more than once",
660  get_rel_name(parentOid))));
661 
662  inheritOids = lappend_oid(inheritOids, parentOid);
663  }
664 
665  /*
666  * Select tablespace to use: an explicitly indicated one, or (in the case
667  * of a partitioned table) the parent's, if it has one.
668  */
669  if (stmt->tablespacename)
670  {
671  tablespaceId = get_tablespace_oid(stmt->tablespacename, false);
672 
673  if (partitioned && tablespaceId == MyDatabaseTableSpace)
674  ereport(ERROR,
675  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
676  errmsg("cannot specify default tablespace for partitioned relations")));
677  }
678  else if (stmt->partbound)
679  {
680  /*
681  * For partitions, when no other tablespace is specified, we default
682  * the tablespace to the parent partitioned table's.
683  */
684  Assert(list_length(inheritOids) == 1);
685  tablespaceId = get_rel_tablespace(linitial_oid(inheritOids));
686  }
687  else
688  tablespaceId = InvalidOid;
689 
690  /* still nothing? use the default */
691  if (!OidIsValid(tablespaceId))
692  tablespaceId = GetDefaultTablespace(stmt->relation->relpersistence,
693  partitioned);
694 
695  /* Check permissions except when using database's default */
696  if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
697  {
698  AclResult aclresult;
699 
700  aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
701  ACL_CREATE);
702  if (aclresult != ACLCHECK_OK)
704  get_tablespace_name(tablespaceId));
705  }
706 
707  /* In all cases disallow placing user relations in pg_global */
708  if (tablespaceId == GLOBALTABLESPACE_OID)
709  ereport(ERROR,
710  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
711  errmsg("only shared relations can be placed in pg_global tablespace")));
712 
713  /* Identify user ID that will own the table */
714  if (!OidIsValid(ownerId))
715  ownerId = GetUserId();
716 
717  /*
718  * Parse and validate reloptions, if any.
719  */
720  reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, validnsps,
721  true, false);
722 
723  if (relkind == RELKIND_VIEW)
724  (void) view_reloptions(reloptions, true);
725  else
726  (void) heap_reloptions(relkind, reloptions, true);
727 
728  if (stmt->ofTypename)
729  {
730  AclResult aclresult;
731 
732  ofTypeId = typenameTypeId(NULL, stmt->ofTypename);
733 
734  aclresult = pg_type_aclcheck(ofTypeId, GetUserId(), ACL_USAGE);
735  if (aclresult != ACLCHECK_OK)
736  aclcheck_error_type(aclresult, ofTypeId);
737  }
738  else
739  ofTypeId = InvalidOid;
740 
741  /*
742  * Look up inheritance ancestors and generate relation schema, including
743  * inherited attributes. (Note that stmt->tableElts is destructively
744  * modified by MergeAttributes.)
745  */
746  stmt->tableElts =
747  MergeAttributes(stmt->tableElts, inheritOids,
748  stmt->relation->relpersistence,
749  stmt->partbound != NULL,
750  &old_constraints);
751 
752  /*
753  * Create a tuple descriptor from the relation schema. Note that this
754  * deals with column names, types, and NOT NULL constraints, but not
755  * default values or CHECK constraints; we handle those below.
756  */
757  descriptor = BuildDescForRelation(stmt->tableElts);
758 
759  /*
760  * Find columns with default values and prepare for insertion of the
761  * defaults. Pre-cooked (that is, inherited) defaults go into a list of
762  * CookedConstraint structs that we'll pass to heap_create_with_catalog,
763  * while raw defaults go into a list of RawColumnDefault structs that will
764  * be processed by AddRelationNewConstraints. (We can't deal with raw
765  * expressions until we can do transformExpr.)
766  *
767  * We can set the atthasdef flags now in the tuple descriptor; this just
768  * saves StoreAttrDefault from having to do an immediate update of the
769  * pg_attribute rows.
770  */
771  rawDefaults = NIL;
772  cookedDefaults = NIL;
773  attnum = 0;
774 
775  foreach(listptr, stmt->tableElts)
776  {
777  ColumnDef *colDef = lfirst(listptr);
778  Form_pg_attribute attr;
779 
780  attnum++;
781  attr = TupleDescAttr(descriptor, attnum - 1);
782 
783  if (colDef->raw_default != NULL)
784  {
785  RawColumnDefault *rawEnt;
786 
787  Assert(colDef->cooked_default == NULL);
788 
789  rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
790  rawEnt->attnum = attnum;
791  rawEnt->raw_default = colDef->raw_default;
792  rawEnt->missingMode = false;
793  rawEnt->generated = colDef->generated;
794  rawDefaults = lappend(rawDefaults, rawEnt);
795  attr->atthasdef = true;
796  }
797  else if (colDef->cooked_default != NULL)
798  {
799  CookedConstraint *cooked;
800 
801  cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
802  cooked->contype = CONSTR_DEFAULT;
803  cooked->conoid = InvalidOid; /* until created */
804  cooked->name = NULL;
805  cooked->attnum = attnum;
806  cooked->expr = colDef->cooked_default;
807  cooked->skip_validation = false;
808  cooked->is_local = true; /* not used for defaults */
809  cooked->inhcount = 0; /* ditto */
810  cooked->is_no_inherit = false;
811  cookedDefaults = lappend(cookedDefaults, cooked);
812  attr->atthasdef = true;
813  }
814 
815  if (colDef->identity)
816  attr->attidentity = colDef->identity;
817 
818  if (colDef->generated)
819  attr->attgenerated = colDef->generated;
820  }
821 
822  /*
823  * If the statement hasn't specified an access method, but we're defining
824  * a type of relation that needs one, use the default.
825  */
826  if (stmt->accessMethod != NULL)
827  {
828  accessMethod = stmt->accessMethod;
829 
830  if (partitioned)
831  ereport(ERROR,
832  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
833  errmsg("specifying a table access method is not supported on a partitioned table")));
834 
835  }
836  else if (relkind == RELKIND_RELATION ||
837  relkind == RELKIND_TOASTVALUE ||
838  relkind == RELKIND_MATVIEW)
839  accessMethod = default_table_access_method;
840 
841  /* look up the access method, verify it is for a table */
842  if (accessMethod != NULL)
843  accessMethodId = get_table_am_oid(accessMethod, false);
844 
845  /*
846  * Create the relation. Inherited defaults and constraints are passed in
847  * for immediate handling --- since they don't need parsing, they can be
848  * stored immediately.
849  */
850  relationId = heap_create_with_catalog(relname,
851  namespaceId,
852  tablespaceId,
853  InvalidOid,
854  InvalidOid,
855  ofTypeId,
856  ownerId,
857  accessMethodId,
858  descriptor,
859  list_concat(cookedDefaults,
860  old_constraints),
861  relkind,
862  stmt->relation->relpersistence,
863  false,
864  false,
865  stmt->oncommit,
866  reloptions,
867  true,
869  false,
870  InvalidOid,
871  typaddress);
872 
873  /*
874  * We must bump the command counter to make the newly-created relation
875  * tuple visible for opening.
876  */
878 
879  /*
880  * Open the new relation and acquire exclusive lock on it. This isn't
881  * really necessary for locking out other backends (since they can't see
882  * the new rel anyway until we commit), but it keeps the lock manager from
883  * complaining about deadlock risks.
884  */
885  rel = relation_open(relationId, AccessExclusiveLock);
886 
887  /*
888  * Now add any newly specified column default and generation expressions
889  * to the new relation. These are passed to us in the form of raw
890  * parsetrees; we need to transform them to executable expression trees
891  * before they can be added. The most convenient way to do that is to
892  * apply the parser's transformExpr routine, but transformExpr doesn't
893  * work unless we have a pre-existing relation. So, the transformation has
894  * to be postponed to this final step of CREATE TABLE.
895  *
896  * This needs to be before processing the partitioning clauses because
897  * those could refer to generated columns.
898  */
899  if (rawDefaults)
900  AddRelationNewConstraints(rel, rawDefaults, NIL,
901  true, true, false, queryString);
902 
903  /*
904  * Make column generation expressions visible for use by partitioning.
905  */
907 
908  /* Process and store partition bound, if any. */
909  if (stmt->partbound)
910  {
911  PartitionBoundSpec *bound;
912  ParseState *pstate;
913  Oid parentId = linitial_oid(inheritOids),
914  defaultPartOid;
915  Relation parent,
916  defaultRel = NULL;
917  RangeTblEntry *rte;
918 
919  /* Already have strong enough lock on the parent */
920  parent = table_open(parentId, NoLock);
921 
922  /*
923  * We are going to try to validate the partition bound specification
924  * against the partition key of parentRel, so it better have one.
925  */
926  if (parent->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
927  ereport(ERROR,
928  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
929  errmsg("\"%s\" is not partitioned",
930  RelationGetRelationName(parent))));
931 
932  /*
933  * The partition constraint of the default partition depends on the
934  * partition bounds of every other partition. It is possible that
935  * another backend might be about to execute a query on the default
936  * partition table, and that the query relies on previously cached
937  * default partition constraints. We must therefore take a table lock
938  * strong enough to prevent all queries on the default partition from
939  * proceeding until we commit and send out a shared-cache-inval notice
940  * that will make them update their index lists.
941  *
942  * Order of locking: The relation being added won't be visible to
943  * other backends until it is committed, hence here in
944  * DefineRelation() the order of locking the default partition and the
945  * relation being added does not matter. But at all other places we
946  * need to lock the default relation before we lock the relation being
947  * added or removed i.e. we should take the lock in same order at all
948  * the places such that lock parent, lock default partition and then
949  * lock the partition so as to avoid a deadlock.
950  */
951  defaultPartOid =
953  if (OidIsValid(defaultPartOid))
954  defaultRel = table_open(defaultPartOid, AccessExclusiveLock);
955 
956  /* Transform the bound values */
957  pstate = make_parsestate(NULL);
958  pstate->p_sourcetext = queryString;
959 
960  /*
961  * Add an RTE containing this relation, so that transformExpr called
962  * on partition bound expressions is able to report errors using a
963  * proper context.
964  */
966  NULL, false, false);
967  addRTEtoQuery(pstate, rte, false, true, true);
968  bound = transformPartitionBound(pstate, parent, stmt->partbound);
969 
970  /*
971  * Check first that the new partition's bound is valid and does not
972  * overlap with any of existing partitions of the parent.
973  */
974  check_new_partition_bound(relname, parent, bound);
975 
976  /*
977  * If the default partition exists, its partition constraints will
978  * change after the addition of this new partition such that it won't
979  * allow any row that qualifies for this new partition. So, check that
980  * the existing data in the default partition satisfies the constraint
981  * as it will exist after adding this partition.
982  */
983  if (OidIsValid(defaultPartOid))
984  {
985  check_default_partition_contents(parent, defaultRel, bound);
986  /* Keep the lock until commit. */
987  table_close(defaultRel, NoLock);
988  }
989 
990  /* Update the pg_class entry. */
991  StorePartitionBound(rel, parent, bound);
992 
993  table_close(parent, NoLock);
994  }
995 
996  /* Store inheritance information for new rel. */
997  StoreCatalogInheritance(relationId, inheritOids, stmt->partbound != NULL);
998 
999  /*
1000  * Process the partitioning specification (if any) and store the partition
1001  * key information into the catalog.
1002  */
1003  if (partitioned)
1004  {
1005  ParseState *pstate;
1006  char strategy;
1007  int partnatts;
1008  AttrNumber partattrs[PARTITION_MAX_KEYS];
1009  Oid partopclass[PARTITION_MAX_KEYS];
1010  Oid partcollation[PARTITION_MAX_KEYS];
1011  List *partexprs = NIL;
1012 
1013  pstate = make_parsestate(NULL);
1014  pstate->p_sourcetext = queryString;
1015 
1016  partnatts = list_length(stmt->partspec->partParams);
1017 
1018  /* Protect fixed-size arrays here and in executor */
1019  if (partnatts > PARTITION_MAX_KEYS)
1020  ereport(ERROR,
1021  (errcode(ERRCODE_TOO_MANY_COLUMNS),
1022  errmsg("cannot partition using more than %d columns",
1023  PARTITION_MAX_KEYS)));
1024 
1025  /*
1026  * We need to transform the raw parsetrees corresponding to partition
1027  * expressions into executable expression trees. Like column defaults
1028  * and CHECK constraints, we could not have done the transformation
1029  * earlier.
1030  */
1031  stmt->partspec = transformPartitionSpec(rel, stmt->partspec,
1032  &strategy);
1033 
1034  ComputePartitionAttrs(pstate, rel, stmt->partspec->partParams,
1035  partattrs, &partexprs, partopclass,
1036  partcollation, strategy);
1037 
1038  StorePartitionKey(rel, strategy, partnatts, partattrs, partexprs,
1039  partopclass, partcollation);
1040 
1041  /* make it all visible */
1043  }
1044 
1045  /*
1046  * If we're creating a partition, create now all the indexes, triggers,
1047  * FKs defined in the parent.
1048  *
1049  * We can't do it earlier, because DefineIndex wants to know the partition
1050  * key which we just stored.
1051  */
1052  if (stmt->partbound)
1053  {
1054  Oid parentId = linitial_oid(inheritOids);
1055  Relation parent;
1056  List *idxlist;
1057  ListCell *cell;
1058 
1059  /* Already have strong enough lock on the parent */
1060  parent = table_open(parentId, NoLock);
1061  idxlist = RelationGetIndexList(parent);
1062 
1063  /*
1064  * For each index in the parent table, create one in the partition
1065  */
1066  foreach(cell, idxlist)
1067  {
1068  Relation idxRel = index_open(lfirst_oid(cell), AccessShareLock);
1069  AttrNumber *attmap;
1070  IndexStmt *idxstmt;
1071  Oid constraintOid;
1072 
1073  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1074  {
1075  if (idxRel->rd_index->indisunique)
1076  ereport(ERROR,
1077  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1078  errmsg("cannot create foreign partition of partitioned table \"%s\"",
1079  RelationGetRelationName(parent)),
1080  errdetail("Table \"%s\" contains indexes that are unique.",
1081  RelationGetRelationName(parent))));
1082  else
1083  {
1084  index_close(idxRel, AccessShareLock);
1085  continue;
1086  }
1087  }
1088 
1090  RelationGetDescr(parent));
1091  idxstmt =
1092  generateClonedIndexStmt(NULL, idxRel,
1093  attmap, RelationGetDescr(rel)->natts,
1094  &constraintOid);
1096  idxstmt,
1097  InvalidOid,
1098  RelationGetRelid(idxRel),
1099  constraintOid,
1100  false, false, false, false, false);
1101 
1102  index_close(idxRel, AccessShareLock);
1103  }
1104 
1105  list_free(idxlist);
1106 
1107  /*
1108  * If there are any row-level triggers, clone them to the new
1109  * partition.
1110  */
1111  if (parent->trigdesc != NULL)
1112  CloneRowTriggersToPartition(parent, rel);
1113 
1114  /*
1115  * And foreign keys too. Note that because we're freshly creating the
1116  * table, there is no need to verify these new constraints.
1117  */
1118  CloneForeignKeyConstraints(NULL, parent, rel);
1119 
1120  table_close(parent, NoLock);
1121  }
1122 
1123  /*
1124  * Now add any newly specified CHECK constraints to the new relation. Same
1125  * as for defaults above, but these need to come after partitioning is set
1126  * up.
1127  */
1128  if (stmt->constraints)
1130  true, true, false, queryString);
1131 
1132  ObjectAddressSet(address, RelationRelationId, relationId);
1133 
1134  /*
1135  * Clean up. We keep lock on new relation (although it shouldn't be
1136  * visible to anyone else anyway, until commit).
1137  */
1138  relation_close(rel, NoLock);
1139 
1140  return address;
1141 }
RangeVar * relation
Definition: parsenodes.h:2049
bytea * heap_reloptions(char relkind, Datum reloptions, bool validate)
Definition: reloptions.c:1470
#define NIL
Definition: pg_list.h:65
List * AddRelationNewConstraints(Relation rel, List *newColDefaults, List *newConstraints, bool allow_merge, bool is_local, bool is_internal, const char *queryString)
Definition: heap.c:2490
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1417
OnCommitAction oncommit
Definition: parsenodes.h:2058
static void ComputePartitionAttrs(ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs, List **partexprs, Oid *partopclass, Oid *partcollation, char strategy)
Definition: tablecmds.c:15030
List * inhRelations
Definition: parsenodes.h:2051
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4705
ObjectAddress DefineIndex(Oid relationId, IndexStmt *stmt, Oid indexRelationId, Oid parentIndexId, Oid parentConstraintId, bool is_alter_table, bool check_rights, bool check_not_in_use, bool skip_build, bool quiet)
Definition: indexcmds.c:428
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
bool is_no_inherit
Definition: heap.h:44
Datum transformRelOptions(Datum oldOptions, List *defList, const char *namspace, char *validnsps[], bool acceptOidsOff, bool isReset)
Definition: reloptions.c:784
void StorePartitionKey(Relation rel, char strategy, int16 partnatts, AttrNumber *partattrs, List *partexprs, Oid *partopclass, Oid *partcollation)
Definition: heap.c:3406
AttrNumber attnum
Definition: heap.h:28
List * partParams
Definition: parsenodes.h:793
void check_new_partition_bound(char *relname, Relation parent, PartitionBoundSpec *spec)
Definition: partbounds.c:935
#define RelationGetDescr(relation)
Definition: rel.h:442
int LOCKMODE
Definition: lockdefs.h:26
Oid GetUserId(void)
Definition: miscinit.c:380
char identity
Definition: parsenodes.h:655
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:63
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define AccessShareLock
Definition: lockdefs.h:36
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
int errcode(int sqlerrcode)
Definition: elog.c:570
#define PARTITION_MAX_KEYS
char generated
Definition: parsenodes.h:658
Form_pg_class rd_rel
Definition: rel.h:83
NameData relname
Definition: pg_class.h:35
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
#define OidIsValid(objectId)
Definition: c.h:638
static void StoreCatalogInheritance(Oid relationId, List *supers, bool child_is_partition)
Definition: tablecmds.c:2710
static PartitionSpec * transformPartitionSpec(Relation rel, PartitionSpec *partspec, char *strategy)
Definition: tablecmds.c:14959
void aclcheck_error_type(AclResult aclerr, Oid typeOid)
Definition: aclchk.c:3666
char relkind
Definition: pg_class.h:81
Oid MyDatabaseTableSpace
Definition: globals.c:87
Oid get_rel_tablespace(Oid relid)
Definition: lsyscache.c:1856
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
bytea * view_reloptions(Datum reloptions, bool validate)
Definition: reloptions.c:1438
List * constraints
Definition: parsenodes.h:2056
PartitionBoundSpec * transformPartitionBound(ParseState *pstate, Relation parent, PartitionBoundSpec *spec)
#define NAMEDATALEN
char * accessMethod
Definition: parsenodes.h:2060
PartitionBoundSpec * partbound
Definition: parsenodes.h:2053
Node * cooked_default
Definition: parsenodes.h:654
char * relname
Definition: primnodes.h:68
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3353
Form_pg_index rd_index
Definition: rel.h:143
IndexStmt * generateClonedIndexStmt(RangeVar *heapRel, Relation source_idx, const AttrNumber *attmap, int attmap_length, Oid *constraintOid)
AttrNumber attnum
Definition: heap.h:39
#define ERROR
Definition: elog.h:43
#define ACL_CREATE
Definition: parsenodes.h:84
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
TriggerDesc * trigdesc
Definition: rel.h:89
void check_default_partition_contents(Relation parent, Relation default_rel, PartitionBoundSpec *new_spec)
Definition: partbounds.c:1227
bool missingMode
Definition: heap.h:30
int inhcount
Definition: heap.h:43
Oid GetDefaultTablespace(char relpersistence, bool partitioned)
Definition: tablespace.c:1139
#define NoLock
Definition: lockdefs.h:34
int errdetail(const char *fmt,...)
Definition: elog.c:860
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
char generated
Definition: heap.h:31
#define RelationGetRelationName(relation)
Definition: rel.h:450
List * options
Definition: parsenodes.h:2057
Node * raw_default
Definition: heap.h:29
static void CloneForeignKeyConstraints(List **wqueue, Relation parentRel, Relation partitionRel)
Definition: tablecmds.c:8433
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
#define ACL_USAGE
Definition: parsenodes.h:82
bool skip_validation
Definition: heap.h:41
#define HEAP_RELOPT_NAMESPACES
Definition: reloptions.h:59
const char * p_sourcetext
Definition: parse_node.h:176
ConstrType contype
Definition: heap.h:36
#define ereport(elevel, rest)
Definition: elog.h:141
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Node * raw_default
Definition: parsenodes.h:653
List * lappend(List *list, void *datum)
Definition: list.c:321
char * tablespacename
Definition: parsenodes.h:2059
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:526
AclResult
Definition: acl.h:177
uintptr_t Datum
Definition: postgres.h:367
void CommandCounterIncrement(void)
Definition: xact.c:1003
static List * MergeAttributes(List *schema, List *supers, char relpersistence, bool is_partition, List **supconstr)
Definition: tablecmds.c:2040
bool allowSystemTableMods
Definition: globals.c:120
#define InvalidOid
Definition: postgres_ext.h:36
void StorePartitionBound(Relation rel, Relation parent, PartitionBoundSpec *bound)
Definition: heap.c:3569
int16 attnum
Definition: pg_attribute.h:79
List * tableElts
Definition: parsenodes.h:2050
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:674
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define Assert(condition)
Definition: c.h:732
#define lfirst(lc)
Definition: pg_list.h:190
#define StrNCpy(dst, src, len)
Definition: c.h:928
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:1065
Oid get_table_am_oid(const char *amname, bool missing_ok)
Definition: amcmds.c:197
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:512
#define linitial_oid(l)
Definition: pg_list.h:197
static int list_length(const List *l)
Definition: pg_list.h:169
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4348
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:152
char relpersistence
Definition: primnodes.h:71
#define AccessExclusiveLock
Definition: lockdefs.h:45
void * palloc(Size size)
Definition: mcxt.c:924
int errmsg(const char *fmt,...)
Definition: elog.c:784
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1463
void list_free(List *list)
Definition: list.c:1373
static void CloneRowTriggersToPartition(Relation parent, Relation partition)
Definition: tablecmds.c:15931
#define elog(elevel,...)
Definition: elog.h:226
Oid conoid
Definition: heap.h:37
Node * expr
Definition: heap.h:40
char * default_table_access_method
Definition: tableam.c:34
TupleDesc BuildDescForRelation(List *schema)
Definition: tupdesc.c:794
AclResult pg_type_aclcheck(Oid type_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4743
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
PartitionSpec * partspec
Definition: parsenodes.h:2054
AttrNumber * convert_tuples_by_name_map(TupleDesc indesc, TupleDesc outdesc)
Definition: tupconvert.c:245
Definition: pg_list.h:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1730
int16 AttrNumber
Definition: attnum.h:21
char * name
Definition: heap.h:38
#define RelationGetRelid(relation)
Definition: rel.h:416
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:126
TypeName * ofTypename
Definition: parsenodes.h:2055
#define lfirst_oid(lc)
Definition: pg_list.h:192
#define RelationGetPartitionDesc(relation)
Definition: rel.h:603
bool is_local
Definition: heap.h:42
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:292
Oid get_default_oid_from_partdesc(PartitionDesc partdesc)
Definition: partdesc.c:373

◆ ExecuteTruncate()

void ExecuteTruncate ( TruncateStmt stmt)

Definition at line 1497 of file tablecmds.c.

References AccessExclusiveLock, TruncateStmt::behavior, 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, TruncateStmt::relations, TruncateStmt::restart_seqs, table_close(), table_open(), truncate_check_activity(), and truncate_check_rel().

Referenced by standard_ProcessUtility().

1498 {
1499  List *rels = NIL;
1500  List *relids = NIL;
1501  List *relids_logged = NIL;
1502  ListCell *cell;
1503 
1504  /*
1505  * Open, exclusive-lock, and check all the explicitly-specified relations
1506  */
1507  foreach(cell, stmt->relations)
1508  {
1509  RangeVar *rv = lfirst(cell);
1510  Relation rel;
1511  bool recurse = rv->inh;
1512  Oid myrelid;
1513  LOCKMODE lockmode = AccessExclusiveLock;
1514 
1515  myrelid = RangeVarGetRelidExtended(rv, lockmode,
1517  NULL);
1518 
1519  /* open the relation, we already hold a lock on it */
1520  rel = table_open(myrelid, NoLock);
1521 
1522  /* don't throw error for "TRUNCATE foo, foo" */
1523  if (list_member_oid(relids, myrelid))
1524  {
1525  table_close(rel, lockmode);
1526  continue;
1527  }
1528 
1529  /*
1530  * RangeVarGetRelidExtended() has done most checks with its callback,
1531  * but other checks with the now-opened Relation remain.
1532  */
1534 
1535  rels = lappend(rels, rel);
1536  relids = lappend_oid(relids, myrelid);
1537  /* Log this relation only if needed for logical decoding */
1538  if (RelationIsLogicallyLogged(rel))
1539  relids_logged = lappend_oid(relids_logged, myrelid);
1540 
1541  if (recurse)
1542  {
1543  ListCell *child;
1544  List *children;
1545 
1546  children = find_all_inheritors(myrelid, lockmode, NULL);
1547 
1548  foreach(child, children)
1549  {
1550  Oid childrelid = lfirst_oid(child);
1551 
1552  if (list_member_oid(relids, childrelid))
1553  continue;
1554 
1555  /* find_all_inheritors already got lock */
1556  rel = table_open(childrelid, NoLock);
1557 
1558  /*
1559  * It is possible that the parent table has children that are
1560  * temp tables of other backends. We cannot safely access
1561  * such tables (because of buffering issues), and the best
1562  * thing to do is to silently ignore them. Note that this
1563  * check is the same as one of the checks done in
1564  * truncate_check_activity() called below, still it is kept
1565  * here for simplicity.
1566  */
1567  if (RELATION_IS_OTHER_TEMP(rel))
1568  {
1569  table_close(rel, lockmode);
1570  continue;
1571  }
1572 
1575 
1576  rels = lappend(rels, rel);
1577  relids = lappend_oid(relids, childrelid);
1578  /* Log this relation only if needed for logical decoding */
1579  if (RelationIsLogicallyLogged(rel))
1580  relids_logged = lappend_oid(relids_logged, childrelid);
1581  }
1582  }
1583  else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1584  ereport(ERROR,
1585  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1586  errmsg("cannot truncate only a partitioned table"),
1587  errhint("Do not specify the ONLY keyword, or use TRUNCATE ONLY on the partitions directly.")));
1588  }
1589 
1590  ExecuteTruncateGuts(rels, relids, relids_logged,
1591  stmt->behavior, stmt->restart_seqs);
1592 
1593  /* And close the rels */
1594  foreach(cell, rels)
1595  {
1596  Relation rel = (Relation) lfirst(cell);
1597 
1598  table_close(rel, NoLock);
1599  }
1600 }
#define NIL
Definition: pg_list.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
int errhint(const char *fmt,...)
Definition: elog.c:974
int LOCKMODE
Definition: lockdefs.h:26
static void RangeVarCallbackForTruncate(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:14777
int errcode(int sqlerrcode)
Definition: elog.c:570
#define RelationIsLogicallyLogged(relation)
Definition: rel.h:588
Form_pg_class rd_rel
Definition: rel.h:83
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
DropBehavior behavior
Definition: parsenodes.h:2647
struct RelationData * Relation
Definition: relcache.h:26
#define ERROR
Definition: elog.h:43
void ExecuteTruncateGuts(List *explicit_rels, List *relids, List *relids_logged, DropBehavior behavior, bool restart_seqs)
Definition: tablecmds.c:1616
List * relations
Definition: parsenodes.h:2645
#define NoLock
Definition: lockdefs.h:34
bool restart_seqs
Definition: parsenodes.h:2646
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:228
#define ereport(elevel, rest)
Definition: elog.h:141
bool inh
Definition: primnodes.h:69
List * lappend(List *list, void *datum)
Definition: list.c:321
static void truncate_check_activity(Relation rel)
Definition: tablecmds.c:1942
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:674
#define lfirst(lc)
Definition: pg_list.h:190
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:546
static void truncate_check_rel(Oid relid, Form_pg_class reltuple)
Definition: tablecmds.c:1907
#define AccessExclusiveLock
Definition: lockdefs.h:45
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:165
int errmsg(const char *fmt,...)
Definition: elog.c:784
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:416
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ ExecuteTruncateGuts()

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

Definition at line 1616 of file tablecmds.c.

References AccessExclusiveLock, aclcheck_error(), ACLCHECK_NOT_OWNER, AfterTriggerBeginQuery(), AfterTriggerEndQuery(), Assert, CheckTableForSerializableConflictIn(), CreateExecutorState(), xl_heap_truncate::dbId, DROP_CASCADE, DROP_RESTRICT, ereport, errmsg(), EState::es_num_result_relations, EState::es_result_relation_info, EState::es_result_relations, ExecASTruncateTriggers(), ExecBSTruncateTriggers(), xl_heap_truncate::flags, FreeExecutorState(), GetCurrentSubTransactionId(), getOwnedSequences(), GetUserId(), heap_truncate_check_FKs(), heap_truncate_find_FKs(), heap_truncate_one_rel(), i, InitResultRelInfo(), lappend(), lappend_oid(), lfirst, lfirst_oid, list_copy(), list_difference_ptr(), list_length(), MyDatabaseId, NIL, NoLock, NOTICE, xl_heap_truncate::nrelids, OBJECT_SEQUENCE, OidIsValid, palloc(), pg_class_ownercheck(), pgstat_count_truncate(), RelationData::rd_createSubid, RelationData::rd_newRelfilenodeSubid, RelationData::rd_rel, REINDEX_REL_PROCESS_TOAST, reindex_relation(), relation_close(), relation_open(), RelationGetRelationName, RelationGetRelid, RelationIsLogicallyLogged, RelationSetNewRelfilenode(), OnCommitItem::relid, ResetSequence(), SizeOfHeapTruncate, table_close(), table_open(), truncate_check_activity(), 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().

1618 {
1619  List *rels;
1620  List *seq_relids = NIL;
1621  EState *estate;
1622  ResultRelInfo *resultRelInfos;
1623  ResultRelInfo *resultRelInfo;
1624  SubTransactionId mySubid;
1625  ListCell *cell;
1626  Oid *logrelids;
1627 
1628  /*
1629  * Check the explicitly-specified relations.
1630  *
1631  * In CASCADE mode, suck in all referencing relations as well. This
1632  * requires multiple iterations to find indirectly-dependent relations. At
1633  * each phase, we need to exclusive-lock new rels before looking for their
1634  * dependencies, else we might miss something. Also, we check each rel as
1635  * soon as we open it, to avoid a faux pas such as holding lock for a long
1636  * time on a rel we have no permissions for.
1637  */
1638  rels = list_copy(explicit_rels);
1639  if (behavior == DROP_CASCADE)
1640  {
1641  for (;;)
1642  {
1643  List *newrelids;
1644 
1645  newrelids = heap_truncate_find_FKs(relids);
1646  if (newrelids == NIL)
1647  break; /* nothing else to add */
1648 
1649  foreach(cell, newrelids)
1650  {
1651  Oid relid = lfirst_oid(cell);
1652  Relation rel;
1653 
1654  rel = table_open(relid, AccessExclusiveLock);
1655  ereport(NOTICE,
1656  (errmsg("truncate cascades to table \"%s\"",
1657  RelationGetRelationName(rel))));
1658  truncate_check_rel(relid, rel->rd_rel);
1660  rels = lappend(rels, rel);
1661  relids = lappend_oid(relids, relid);
1662  /* Log this relation only if needed for logical decoding */
1663  if (RelationIsLogicallyLogged(rel))
1664  relids_logged = lappend_oid(relids_logged, relid);
1665  }
1666  }
1667  }
1668 
1669  /*
1670  * Check foreign key references. In CASCADE mode, this should be
1671  * unnecessary since we just pulled in all the references; but as a
1672  * cross-check, do it anyway if in an Assert-enabled build.
1673  */
1674 #ifdef USE_ASSERT_CHECKING
1675  heap_truncate_check_FKs(rels, false);
1676 #else
1677  if (behavior == DROP_RESTRICT)
1678  heap_truncate_check_FKs(rels, false);
1679 #endif
1680 
1681  /*
1682  * If we are asked to restart sequences, find all the sequences, lock them
1683  * (we need AccessExclusiveLock for ResetSequence), and check permissions.
1684  * We want to do this early since it's pointless to do all the truncation
1685  * work only to fail on sequence permissions.
1686  */
1687  if (restart_seqs)
1688  {
1689  foreach(cell, rels)
1690  {
1691  Relation rel = (Relation) lfirst(cell);
1692  List *seqlist = getOwnedSequences(RelationGetRelid(rel));
1693  ListCell *seqcell;
1694 
1695  foreach(seqcell, seqlist)
1696  {
1697  Oid seq_relid = lfirst_oid(seqcell);
1698  Relation seq_rel;
1699 
1700  seq_rel = relation_open(seq_relid, AccessExclusiveLock);
1701 
1702  /* This check must match AlterSequence! */
1703  if (!pg_class_ownercheck(seq_relid, GetUserId()))
1705  RelationGetRelationName(seq_rel));
1706 
1707  seq_relids = lappend_oid(seq_relids, seq_relid);
1708 
1709  relation_close(seq_rel, NoLock);
1710  }
1711  }
1712  }
1713 
1714  /* Prepare to catch AFTER triggers. */
1716 
1717  /*
1718  * To fire triggers, we'll need an EState as well as a ResultRelInfo for
1719  * each relation. We don't need to call ExecOpenIndices, though.
1720  */
1721  estate = CreateExecutorState();
1722  resultRelInfos = (ResultRelInfo *)
1723  palloc(list_length(rels) * sizeof(ResultRelInfo));
1724  resultRelInfo = resultRelInfos;
1725  foreach(cell, rels)
1726  {
1727  Relation rel = (Relation) lfirst(cell);
1728 
1729  InitResultRelInfo(resultRelInfo,
1730  rel,
1731  0, /* dummy rangetable index */
1732  NULL,
1733  0);
1734  resultRelInfo++;
1735  }
1736  estate->es_result_relations = resultRelInfos;
1737  estate->es_num_result_relations = list_length(rels);
1738 
1739  /*
1740  * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
1741  * truncating (this is because one of them might throw an error). Also, if
1742  * we were to allow them to prevent statement execution, that would need
1743  * to be handled here.
1744  */
1745  resultRelInfo = resultRelInfos;
1746  foreach(cell, rels)
1747  {
1748  estate->es_result_relation_info = resultRelInfo;
1749  ExecBSTruncateTriggers(estate, resultRelInfo);
1750  resultRelInfo++;
1751  }
1752 
1753  /*
1754  * OK, truncate each table.
1755  */
1756  mySubid = GetCurrentSubTransactionId();
1757 
1758  foreach(cell, rels)
1759  {
1760  Relation rel = (Relation) lfirst(cell);
1761 
1762  /* Skip partitioned tables as there is nothing to do */
1763  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1764  continue;
1765 
1766  /*
1767  * Normally, we need a transaction-safe truncation here. However, if
1768  * the table was either created in the current (sub)transaction or has
1769  * a new relfilenode in the current (sub)transaction, then we can just
1770  * truncate it in-place, because a rollback would cause the whole
1771  * table or the current physical file to be thrown away anyway.
1772  */
1773  if (rel->rd_createSubid == mySubid ||
1774  rel->rd_newRelfilenodeSubid == mySubid)
1775  {
1776  /* Immediate, non-rollbackable truncation is OK */
1777  heap_truncate_one_rel(rel);
1778  }
1779  else
1780  {
1781  Oid heap_relid;
1782  Oid toast_relid;
1783 
1784  /*
1785  * This effectively deletes all rows in the table, and may be done
1786  * in a serializable transaction. In that case we must record a
1787  * rw-conflict in to this transaction from each transaction
1788  * holding a predicate lock on the table.
1789  */
1791 
1792  /*
1793  * Need the full transaction-safe pushups.
1794  *
1795  * Create a new empty storage file for the relation, and assign it
1796  * as the relfilenode value. The old storage file is scheduled for
1797  * deletion at commit.
1798  */
1799  RelationSetNewRelfilenode(rel, rel->rd_rel->relpersistence);
1800 
1801  heap_relid = RelationGetRelid(rel);
1802 
1803  /*
1804  * The same for the toast table, if any.
1805  */
1806  toast_relid = rel->rd_rel->reltoastrelid;
1807  if (OidIsValid(toast_relid))
1808  {
1809  Relation toastrel = relation_open(toast_relid,
1811 
1812  RelationSetNewRelfilenode(toastrel,
1813  toastrel->rd_rel->relpersistence);
1814  table_close(toastrel, NoLock);
1815  }
1816 
1817  /*
1818  * Reconstruct the indexes to match, and we're done.
1819  */
1821  }
1822 
1823  pgstat_count_truncate(rel);
1824  }
1825 
1826  /*
1827  * Restart owned sequences if we were asked to.
1828  */
1829  foreach(cell, seq_relids)
1830  {
1831  Oid seq_relid = lfirst_oid(cell);
1832 
1833  ResetSequence(seq_relid);
1834  }
1835 
1836  /*
1837  * Write a WAL record to allow this set of actions to be logically
1838  * decoded.
1839  *
1840  * Assemble an array of relids so we can write a single WAL record for the
1841  * whole action.
1842  */
1843  if (list_length(relids_logged) > 0)
1844  {
1845  xl_heap_truncate xlrec;
1846  int i = 0;
1847 
1848  /* should only get here if wal_level >= logical */
1850 
1851  logrelids = palloc(list_length(relids_logged) * sizeof(Oid));
1852  foreach(cell, relids_logged)
1853  logrelids[i++] = lfirst_oid(cell);
1854 
1855  xlrec.dbId = MyDatabaseId;
1856  xlrec.nrelids = list_length(relids_logged);
1857  xlrec.flags = 0;
1858  if (behavior == DROP_CASCADE)
1859  xlrec.flags |= XLH_TRUNCATE_CASCADE;
1860  if (restart_seqs)
1862 
1863  XLogBeginInsert();
1864  XLogRegisterData((char *) &xlrec, SizeOfHeapTruncate);
1865  XLogRegisterData((char *) logrelids, list_length(relids_logged) * sizeof(Oid));
1866 
1868 
1869  (void) XLogInsert(RM_HEAP_ID, XLOG_HEAP_TRUNCATE);
1870  }
1871 
1872  /*
1873  * Process all AFTER STATEMENT TRUNCATE triggers.
1874  */
1875  resultRelInfo = resultRelInfos;
1876  foreach(cell, rels)
1877  {
1878  estate->es_result_relation_info = resultRelInfo;
1879  ExecASTruncateTriggers(estate, resultRelInfo);
1880  resultRelInfo++;
1881  }
1882 
1883  /* Handle queued AFTER triggers */
1884  AfterTriggerEndQuery(estate);
1885 
1886  /* We can clean up the EState now */
1887  FreeExecutorState(estate);
1888 
1889  /*
1890  * Close any rels opened by CASCADE (can't do this while EState still
1891  * holds refs)
1892  */
1893  rels = list_difference_ptr(rels, explicit_rels);
1894  foreach(cell, rels)
1895  {
1896  Relation rel = (Relation) lfirst(cell);
1897 
1898  table_close(rel, NoLock);
1899  }
1900 }
#define NIL
Definition: pg_list.h:65
#define XLH_TRUNCATE_CASCADE
Definition: heapam_xlog.h:116
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, Relation partition_root, int instrument_options)
Definition: execMain.c:1277
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
Oid GetUserId(void)
Definition: miscinit.c:380
void heap_truncate_one_rel(Relation rel)
Definition: heap.c:3219
List * list_difference_ptr(const List *list1, const List *list2)
Definition: list.c:1099
List * list_copy(const List *oldlist)
Definition: list.c:1400
void heap_truncate_check_FKs(List *relations, bool tempTables)
Definition: heap.c:3263
SubTransactionId rd_newRelfilenodeSubid
Definition: rel.h:80
#define XLOG_INCLUDE_ORIGIN
Definition: xlog.h:228
uint32 SubTransactionId
Definition: c.h:511
#define RelationIsLogicallyLogged(relation)
Definition: rel.h:588
Form_pg_class rd_rel
Definition: rel.h:83
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
#define OidIsValid(objectId)
Definition: c.h:638
void RelationSetNewRelfilenode(Relation relation, char persistence)
Definition: relcache.c:3418
void FreeExecutorState(EState *estate)
Definition: execUtils.c:190
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3353
struct RelationData * Relation
Definition: relcache.h:26
void ExecBSTruncateTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:3244
#define XLogLogicalInfoActive()
Definition: xlog.h:198
struct ResultRelInfo ResultRelInfo
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define NoLock
Definition: lockdefs.h:34
ResultRelInfo * es_result_relations
Definition: execnodes.h:520
void ExecASTruncateTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:3297
#define RelationGetRelationName(relation)
Definition: rel.h:450
void pgstat_count_truncate(Relation rel)
Definition: pgstat.c:2049
void XLogSetRecordFlags(uint8 flags)
Definition: xloginsert.c:397
#define ereport(elevel, rest)
Definition: elog.h:141
EState * CreateExecutorState(void)
Definition: execUtils.c:88
List * lappend(List *list, void *datum)
Definition: list.c:321
SubTransactionId rd_createSubid
Definition: rel.h:79
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:323
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:415
List * getOwnedSequences(Oid relid)
Definition: pg_depend.c:771
Oid MyDatabaseId
Definition: globals.c:85
int es_num_result_relations
Definition: execnodes.h:521
#define XLH_TRUNCATE_RESTART_SEQS
Definition: heapam_xlog.h:117
#define XLOG_HEAP_TRUNCATE
Definition: heapam_xlog.h:35
static void truncate_check_activity(Relation rel)
Definition: tablecmds.c:1942
#define NOTICE
Definition: elog.h:37
void AfterTriggerBeginQuery(void)
Definition: trigger.c:4783
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define Assert(condition)
Definition: c.h:732
#define lfirst(lc)
Definition: pg_list.h:190
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:708
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4755
#define SizeOfHeapTruncate
Definition: heapam_xlog.h:132
static int list_length(const List *l)
Definition: pg_list.h:169
void CheckTableForSerializableConflictIn(Relation relation)
Definition: predicate.c:4526
static void truncate_check_rel(Oid relid, Form_pg_class reltuple)
Definition: tablecmds.c:1907
#define AccessExclusiveLock
Definition: lockdefs.h:45
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:4803
void * palloc(Size size)
Definition: mcxt.c:924
int errmsg(const char *fmt,...)
Definition: elog.c:784
int i
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:136
void ResetSequence(Oid seq_relid)
Definition: sequence.c:270
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void XLogBeginInsert(void)
Definition: xloginsert.c:120
bool reindex_relation(Oid relid, int flags, int options)
Definition: index.c:3535
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:416
List * heap_truncate_find_FKs(List *relationIds)
Definition: heap.c:3358
#define lfirst_oid(lc)
Definition: pg_list.h:192
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:522

◆ find_composite_type_dependencies()

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

Definition at line 5348 of file tablecmds.c.

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

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

5350 {
5351  Relation depRel;
5352  ScanKeyData key[2];
5353  SysScanDesc depScan;
5354  HeapTuple depTup;
5355 
5356  /* since this function recurses, it could be driven to stack overflow */
5358 
5359  /*
5360  * We scan pg_depend to find those things that depend on the given type.
5361  * (We assume we can ignore refobjsubid for a type.)
5362  */
5363  depRel = table_open(DependRelationId, AccessShareLock);
5364 
5365  ScanKeyInit(&key[0],
5366  Anum_pg_depend_refclassid,
5367  BTEqualStrategyNumber, F_OIDEQ,
5368  ObjectIdGetDatum(TypeRelationId));
5369  ScanKeyInit(&key[1],
5370  Anum_pg_depend_refobjid,
5371  BTEqualStrategyNumber, F_OIDEQ,
5372  ObjectIdGetDatum(typeOid));
5373 
5374  depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
5375  NULL, 2, key);
5376 
5377  while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
5378  {
5379  Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
5380  Relation rel;
5381  Form_pg_attribute att;
5382 
5383  /* Check for directly dependent types */
5384  if (pg_depend->classid == TypeRelationId)
5385  {
5386  /*
5387  * This must be an array, domain, or range containing the given
5388  * type, so recursively check for uses of this type. Note that
5389  * any error message will mention the original type not the
5390  * container; this is intentional.
5391  */
5392  find_composite_type_dependencies(pg_depend->objid,
5393  origRelation, origTypeName);
5394  continue;
5395  }
5396 
5397  /* Else, ignore dependees that aren't user columns of relations */
5398  /* (we assume system columns are never of interesting types) */
5399  if (pg_depend->classid != RelationRelationId ||
5400  pg_depend->objsubid <= 0)
5401  continue;
5402 
5403  rel = relation_open(pg_depend->objid, AccessShareLock);
5404  att = TupleDescAttr(rel->rd_att, pg_depend->objsubid - 1);
5405 
5406  if (rel->rd_rel->relkind == RELKIND_RELATION ||
5407  rel->rd_rel->relkind == RELKIND_MATVIEW ||
5408  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
5409  {
5410  if (origTypeName)
5411  ereport(ERROR,
5412  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5413  errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
5414  origTypeName,
5416  NameStr(att->attname))));
5417  else if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
5418  ereport(ERROR,
5419  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5420  errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
5421  RelationGetRelationName(origRelation),
5423  NameStr(att->attname))));
5424  else if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
5425  ereport(ERROR,
5426  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5427  errmsg("cannot alter foreign table \"%s\" because column \"%s.%s\" uses its row type",
5428  RelationGetRelationName(origRelation),
5430  NameStr(att->attname))));
5431  else
5432  ereport(ERROR,
5433  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5434  errmsg("cannot alter table \"%s\" because column \"%s.%s\" uses its row type",
5435  RelationGetRelationName(origRelation),
5437  NameStr(att->attname))));
5438  }
5439  else if (OidIsValid(rel->rd_rel->reltype))
5440  {
5441  /*
5442  * A view or composite type itself isn't a problem, but we must
5443  * recursively check for indirect dependencies via its rowtype.
5444  */
5446  origRelation, origTypeName);
5447  }
5448 
5450  }
5451 
5452  systable_endscan(depScan);
5453 
5455 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:525
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define DependReferenceIndexId
Definition: indexing.h:151
void find_composite_type_dependencies(Oid typeOid, Relation origRelation, const char *origTypeName)
Definition: tablecmds.c:5348
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:570
Form_pg_class rd_rel
Definition: rel.h:83
#define OidIsValid(objectId)
Definition: c.h:638
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:352
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:444
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
void check_stack_depth(void)
Definition: postgres.c:3262
#define RelationGetRelationName(relation)
Definition: rel.h:450
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
FormData_pg_depend * Form_pg_depend
Definition: pg_depend.h:71
#define ereport(elevel, rest)
Definition: elog.h:141
TupleDesc rd_att
Definition: rel.h:84
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define NameStr(name)
Definition: c.h:609
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ PartConstraintImpliedByRelConstraint()

bool PartConstraintImpliedByRelConstraint ( Relation  scanrel,
List partConstraint 
)

Definition at line 15278 of file tablecmds.c.

References NullTest::arg, NullTest::argisrow, 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(), and QueuePartitionConstraintValidation().

15280 {
15281  List *existConstraint = NIL;
15282  TupleConstr *constr = RelationGetDescr(scanrel)->constr;
15283  int i;
15284 
15285  if (constr && constr->has_not_null)
15286  {
15287  int natts = scanrel->rd_att->natts;
15288 
15289  for (i = 1; i <= natts; i++)
15290  {
15291  Form_pg_attribute att = TupleDescAttr(scanrel->rd_att, i - 1);
15292 
15293  if (att->attnotnull && !att->attisdropped)
15294  {
15295  NullTest *ntest = makeNode(NullTest);
15296 
15297  ntest->arg = (Expr *) makeVar(1,
15298  i,
15299  att->atttypid,
15300  att->atttypmod,
15301  att->attcollation,
15302  0);
15303  ntest->nulltesttype = IS_NOT_NULL;
15304 
15305  /*
15306  * argisrow=false is correct even for a composite column,
15307  * because attnotnull does not represent a SQL-spec IS NOT
15308  * NULL test in such a case, just IS DISTINCT FROM NULL.
15309  */
15310  ntest->argisrow = false;
15311  ntest->location = -1;
15312  existConstraint = lappend(existConstraint, ntest);
15313  }
15314  }
15315  }
15316 
15317  return ConstraintImpliedByRelConstraint(scanrel, partConstraint, existConstraint);
15318 }
#define NIL
Definition: pg_list.h:65
#define RelationGetDescr(relation)
Definition: rel.h:442
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
Expr * arg
Definition: primnodes.h:1205
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
List * lappend(List *list, void *datum)
Definition: list.c:321
TupleDesc rd_att
Definition: rel.h:84
NullTestType nulltesttype
Definition: primnodes.h:1206
#define makeNode(_type_)
Definition: nodes.h:573
static bool ConstraintImpliedByRelConstraint(Relation scanrel, List *testConstraint, List *provenConstraint)
Definition: tablecmds.c:15331
int location
Definition: primnodes.h:1208
int i
bool argisrow
Definition: primnodes.h:1207
bool has_not_null
Definition: tupdesc.h:44
Definition: pg_list.h:50

◆ PreCommit_on_commit_actions()

void PreCommit_on_commit_actions ( void  )

Definition at line 14578 of file tablecmds.c.

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

Referenced by CommitTransaction(), and PrepareTransaction().

14579 {
14580  ListCell *l;
14581  List *oids_to_truncate = NIL;
14582  List *oids_to_drop = NIL;
14583 
14584  foreach(l, on_commits)
14585  {
14586  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
14587 
14588  /* Ignore entry if already dropped in this xact */
14590  continue;
14591 
14592  switch (oc->oncommit)
14593  {
14594  case ONCOMMIT_NOOP:
14596  /* Do nothing (there shouldn't be such entries, actually) */
14597  break;
14598  case ONCOMMIT_DELETE_ROWS:
14599 
14600  /*
14601  * If this transaction hasn't accessed any temporary
14602  * relations, we can skip truncating ON COMMIT DELETE ROWS
14603  * tables, as they must still be empty.
14604  */
14606  oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
14607  break;
14608  case ONCOMMIT_DROP:
14609  oids_to_drop = lappend_oid(oids_to_drop, oc->relid);
14610  break;
14611  }
14612  }
14613 
14614  /*
14615  * Truncate relations before dropping so that all dependencies between
14616  * relations are removed after they are worked on. Doing it like this
14617  * might be a waste as it is possible that a relation being truncated will
14618  * be dropped anyway due to its parent being dropped, but this makes the
14619  * code more robust because of not having to re-check that the relation
14620  * exists at truncation time.
14621  */
14622  if (oids_to_truncate != NIL)
14623  heap_truncate(oids_to_truncate);
14624 
14625  if (oids_to_drop != NIL)
14626  {
14627  ObjectAddresses *targetObjects = new_object_addresses();
14628  ListCell *l;
14629 
14630  foreach(l, oids_to_drop)
14631  {
14632  ObjectAddress object;
14633 
14634  object.classId = RelationRelationId;
14635  object.objectId = lfirst_oid(l);
14636  object.objectSubId = 0;
14637 
14638  Assert(!object_address_present(&object, targetObjects));
14639 
14640  add_exact_object_address(&object, targetObjects);
14641  }
14642 
14643  /*
14644  * Since this is an automatic drop, rather than one directly initiated
14645  * by the user, we pass the PERFORM_DELETION_INTERNAL flag.
14646  */
14647  performMultipleDeletions(targetObjects, DROP_CASCADE,
14649 
14650 #ifdef USE_ASSERT_CHECKING
14651 
14652  /*
14653  * Note that table deletion will call remove_on_commit_action, so the
14654  * entry should get marked as deleted.
14655  */
14656  foreach(l, on_commits)
14657  {
14658  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
14659 
14660  if (oc->oncommit != ONCOMMIT_DROP)
14661  continue;
14662 
14664  }
14665 #endif
14666  }
14667 }
#define NIL
Definition: pg_list.h:65
OnCommitAction oncommit
Definition: tablecmds.c:110
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2500
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2440
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2385
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
static List * on_commits
Definition: tablecmds.c:123
int MyXactFlags
Definition: xact.c:119
#define XACT_FLAGS_ACCESSEDTEMPNAMESPACE
Definition: xact.h:97
SubTransactionId deleting_subid
Definition: tablecmds.c:120
#define Assert(condition)
Definition: c.h:732
#define lfirst(lc)
Definition: pg_list.h:190
#define PERFORM_DELETION_QUIETLY
Definition: dependency.h:136
void heap_truncate(List *relids)
Definition: heap.c:3178
#define InvalidSubTransactionId
Definition: c.h:513
void performMultipleDeletions(const ObjectAddresses *objects, DropBehavior behavior, int flags)
Definition: dependency.c:374
Definition: pg_list.h:50
#define lfirst_oid(lc)
Definition: pg_list.h:192
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:134

◆ RangeVarCallbackOwnsRelation()

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

Definition at line 14800 of file tablecmds.c.

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

Referenced by AlterSequence(), and ProcessUtilitySlow().

14802 {
14803  HeapTuple tuple;
14804 
14805  /* Nothing to do if the relation was not found. */
14806  if (!OidIsValid(relId))
14807  return;
14808 
14809  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
14810  if (!HeapTupleIsValid(tuple)) /* should not happen */
14811  elog(ERROR, "cache lookup failed for relation %u", relId);
14812 
14813  if (!pg_class_ownercheck(relId, GetUserId()))
14815  relation->relname);
14816 
14817  if (!allowSystemTableMods &&
14818  IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
14819  ereport(ERROR,
14820  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
14821  errmsg("permission denied: \"%s\" is a system catalog",
14822  relation->relname)));
14823 
14824  ReleaseSysCache(tuple);
14825 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Oid GetUserId(void)
Definition: miscinit.c:380
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1805
int errcode(int sqlerrcode)
Definition: elog.c:570
#define OidIsValid(objectId)
Definition: c.h:638
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
Definition: catalog.c:82
char * relname
Definition: primnodes.h:68
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3353
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1124
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1172
bool allowSystemTableMods
Definition: globals.c:120
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4755
FormData_pg_class * Form_pg_class
Definition: pg_class.h:150
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
ObjectType get_relkind_objtype(char relkind)

◆ RangeVarCallbackOwnsTable()

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

Definition at line 14745 of file tablecmds.c.

References aclcheck_error(), ACLCHECK_NOT_OWNER, ereport, errcode(), errmsg(), ERROR, get_rel_relkind(), get_relkind_objtype(), GetUserId(), OidIsValid, pg_class_ownercheck(), relkind, and RangeVar::relname.

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

14747 {
14748  char relkind;
14749 
14750  /* Nothing to do if the relation was not found. */
14751  if (!OidIsValid(relId))
14752  return;
14753 
14754  /*
14755  * If the relation does exist, check whether it's an index. But note that
14756  * the relation might have been dropped between the time we did the name
14757  * lookup and now. In that case, there's nothing to do.
14758  */
14759  relkind = get_rel_relkind(relId);
14760  if (!relkind)
14761  return;
14762  if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
14763  relkind != RELKIND_MATVIEW && relkind != RELKIND_PARTITIONED_TABLE)
14764  ereport(ERROR,
14765  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
14766  errmsg("\"%s\" is not a table or materialized view", relation->relname)));
14767 
14768  /* Check permissions */
14769  if (!pg_class_ownercheck(relId, GetUserId()))
14771 }
Oid GetUserId(void)
Definition: miscinit.c:380
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1805
int errcode(int sqlerrcode)
Definition: elog.c:570
#define OidIsValid(objectId)
Definition: c.h:638
char relkind
Definition: pg_class.h:81
char * relname
Definition: primnodes.h:68
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3353
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4755
int errmsg(const char *fmt,...)
Definition: elog.c:784
ObjectType get_relkind_objtype(char relkind)

◆ register_on_commit_action()

void register_on_commit_action ( Oid  relid,
OnCommitAction  action 
)

Definition at line 14519 of file tablecmds.c.

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

Referenced by heap_create_with_catalog().

14520 {
14521  OnCommitItem *oc;
14522  MemoryContext oldcxt;
14523 
14524  /*
14525  * We needn't bother registering the relation unless there is an ON COMMIT
14526  * action we need to take.
14527  */
14529  return;
14530 
14532 
14533  oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
14534  oc->relid = relid;
14535  oc->oncommit = action;
14538 
14539  /*
14540  * We use lcons() here so that ON COMMIT actions are processed in reverse
14541  * order of registration. That might not be essential but it seems
14542  * reasonable.
14543  */
14544  on_commits = lcons(oc, on_commits);
14545 
14546  MemoryContextSwitchTo(oldcxt);
14547 }
OnCommitAction oncommit
Definition: tablecmds.c:110
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
SubTransactionId creating_subid
Definition: tablecmds.c:119
static List * on_commits
Definition: tablecmds.c:123
SubTransactionId deleting_subid
Definition: tablecmds.c:120
List * lcons(void *datum, List *list)
Definition: list.c:453
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:708
#define InvalidSubTransactionId
Definition: c.h:513
void * palloc(Size size)
Definition: mcxt.c:924
MemoryContext CacheMemoryContext
Definition: mcxt.c:47

◆ remove_on_commit_action()

void remove_on_commit_action ( Oid  relid)

Definition at line 14555 of file tablecmds.c.

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

Referenced by heap_drop_with_catalog().

14556 {
14557  ListCell *l;
14558 
14559  foreach(l, on_commits)
14560  {
14561  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
14562 
14563  if (oc->relid == relid)
14564  {
14566  break;
14567  }
14568  }
14569 }
static List * on_commits
Definition: tablecmds.c:123
SubTransactionId deleting_subid
Definition: tablecmds.c:120
#define lfirst(lc)
Definition: pg_list.h:190
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:708

◆ RemoveRelations()

void RemoveRelations ( DropStmt drop)

Definition at line 1223 of file tablecmds.c.

References AcceptInvalidationMessages(), AccessExclusiveLock, add_exact_object_address(), Assert, DropStmt::behavior, ObjectAddress::classId, DropRelationCallbackState::concurrent, DropStmt::concurrent, DROP_CASCADE, DropErrorMsgNonExistent(), elog, ereport, errcode(), errmsg(), ERROR, free_object_addresses(), DropRelationCallbackState::heapOid, 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, DropRelationCallbackState::partParentOid, PERFORM_DELETION_CONCURRENTLY, performMultipleDeletions(), RangeVarCallbackForDropRelation(), RangeVarGetRelidExtended(), relkind, DropRelationCallbackState::relkind, DropStmt::removeType, RVR_MISSING_OK, and ShareUpdateExclusiveLock.

Referenced by ExecDropStmt().

1224 {
1225  ObjectAddresses *objects;
1226  char relkind;
1227  ListCell *cell;
1228  int flags = 0;
1229  LOCKMODE lockmode = AccessExclusiveLock;
1230 
1231  /* DROP CONCURRENTLY uses a weaker lock, and has some restrictions */
1232  if (drop->concurrent)
1233  {
1235  lockmode = ShareUpdateExclusiveLock;
1236  Assert(drop->removeType == OBJECT_INDEX);
1237  if (list_length(drop->objects) != 1)
1238  ereport(ERROR,
1239  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1240  errmsg("DROP INDEX CONCURRENTLY does not support dropping multiple objects")));
1241  if (drop->behavior == DROP_CASCADE)
1242  ereport(ERROR,
1243  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1244  errmsg("DROP INDEX CONCURRENTLY does not support CASCADE")));
1245  }
1246 
1247  /*
1248  * First we identify all the relations, then we delete them in a single
1249  * performMultipleDeletions() call. This is to avoid unwanted DROP
1250  * RESTRICT errors if one of the relations depends on another.
1251  */
1252 
1253  /* Determine required relkind */
1254  switch (drop->removeType)
1255  {
1256  case OBJECT_TABLE:
1257  relkind = RELKIND_RELATION;
1258  break;
1259 
1260  case OBJECT_INDEX:
1261  relkind = RELKIND_INDEX;
1262  break;
1263 
1264  case OBJECT_SEQUENCE:
1265  relkind = RELKIND_SEQUENCE;
1266  break;
1267 
1268  case OBJECT_VIEW:
1269  relkind = RELKIND_VIEW;
1270  break;
1271 
1272  case OBJECT_MATVIEW:
1273  relkind = RELKIND_MATVIEW;
1274  break;
1275 
1276  case OBJECT_FOREIGN_TABLE:
1277  relkind = RELKIND_FOREIGN_TABLE;
1278  break;
1279 
1280  default:
1281  elog(ERROR, "unrecognized drop object type: %d",
1282  (int) drop->removeType);
1283  relkind = 0; /* keep compiler quiet */
1284  break;
1285  }
1286 
1287  /* Lock and validate each relation; build a list of object addresses */
1288  objects = new_object_addresses();
1289 
1290  foreach(cell, drop->objects)
1291  {
1292  RangeVar *rel = makeRangeVarFromNameList((List *) lfirst(cell));
1293  Oid relOid;
1294  ObjectAddress obj;
1296 
1297  /*
1298  * These next few steps are a great deal like relation_openrv, but we
1299  * don't bother building a relcache entry since we don't need it.
1300  *
1301  * Check for shared-cache-inval messages before trying to access the
1302  * relation. This is needed to cover the case where the name
1303  * identifies a rel that has been dropped and recreated since the
1304  * start of our transaction: if we don't flush the old syscache entry,
1305  * then we'll latch onto that entry and suffer an error later.
1306  */
1308 
1309  /* Look up the appropriate relation using namespace search. */
1310  state.relkind = relkind;
1311  state.heapOid = InvalidOid;
1312  state.partParentOid = InvalidOid;
1313  state.concurrent = drop->concurrent;
1314  relOid = RangeVarGetRelidExtended(rel, lockmode, RVR_MISSING_OK,
1316  (void *) &state);
1317 
1318  /* Not there? */
1319  if (!OidIsValid(relOid))
1320  {
1321  DropErrorMsgNonExistent(rel, relkind, drop->missing_ok);
1322  continue;
1323  }
1324 
1325  /* OK, we're ready to delete this one */
1326  obj.classId = RelationRelationId;
1327  obj.objectId = relOid;
1328  obj.objectSubId = 0;
1329 
1330  add_exact_object_address(&obj, objects);
1331  }
1332 
1333  performMultipleDeletions(objects, drop->behavior, flags);
1334 
1335  free_object_addresses(objects);
1336 }
void AcceptInvalidationMessages(void)
Definition: inval.c:681
int LOCKMODE
Definition: lockdefs.h:26
List * objects
Definition: parsenodes.h:2631
bool missing_ok
Definition: parsenodes.h:2634
int errcode(int sqlerrcode)
Definition: elog.c:570
RangeVar * makeRangeVarFromNameList(List *names)
Definition: namespace.c:3054
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2440
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2385
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2680
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:638
ObjectType removeType
Definition: parsenodes.h:2632
char relkind
Definition: pg_class.h:81
#define PERFORM_DELETION_CONCURRENTLY
Definition: dependency.h:135
#define ERROR
Definition: elog.h:43
bool concurrent
Definition: parsenodes.h:2635
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:228
DropBehavior behavior
Definition: parsenodes.h:2633
#define ereport(elevel, rest)
Definition: elog.h:141
static void RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid, Oid oldRelOid, void *arg)
Definition: tablecmds.c:1345
#define InvalidOid
Definition: postgres_ext.h:36
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define Assert(condition)
Definition: c.h:732
#define lfirst(lc)
Definition: pg_list.h:190
Definition: regguts.h:298
static int list_length(const List *l)
Definition: pg_list.h:169
#define AccessExclusiveLock
Definition: lockdefs.h:45
static void DropErrorMsgNonExistent(RangeVar *rel, char rightkind, bool missing_ok)
Definition: tablecmds.c:1148
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
void performMultipleDeletions(const ObjectAddresses *objects, DropBehavior behavior, int flags)
Definition: dependency.c:374
Definition: pg_list.h:50

◆ renameatt()

ObjectAddress renameatt ( RenameStmt stmt)

Definition at line 3078 of file tablecmds.c.

References AccessExclusiveLock, attnum, RenameStmt::behavior, ereport, errmsg(), RangeVar::inh, InvalidObjectAddress, RenameStmt::missing_ok, RenameStmt::newname, NOTICE, ObjectAddressSubSet, OidIsValid, RangeVarCallbackForRenameAttribute(), RangeVarGetRelidExtended(), RenameStmt::relation, OnCommitItem::relid, RangeVar::relname, renameatt_internal(), RVR_MISSING_OK, and RenameStmt::subname.

Referenced by ExecRenameStmt().

3079 {
3080  Oid relid;
3082  ObjectAddress address;
3083 
3084  /* lock level taken here should match renameatt_internal */
3086  stmt->missing_ok ? RVR_MISSING_OK : 0,
3088  NULL);
3089 
3090  if (!OidIsValid(relid))
3091  {
3092  ereport(NOTICE,
3093  (errmsg("relation \"%s\" does not exist, skipping",
3094  stmt->relation->relname)));
3095  return InvalidObjectAddress;
3096  }
3097 
3098  attnum =
3099  renameatt_internal(relid,
3100  stmt->subname, /* old att name */
3101  stmt->newname, /* new att name */
3102  stmt->relation->inh, /* recursive? */
3103  false, /* recursing? */
3104  0, /* expected inhcount */
3105  stmt->behavior);
3106 
3107  ObjectAddressSubSet(address, RelationRelationId, relid, attnum);
3108 
3109  return address;
3110 }
char * subname
Definition: parsenodes.h:2895
char * newname
Definition: parsenodes.h:2897
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:638
char * relname
Definition: primnodes.h:68
bool missing_ok
Definition: parsenodes.h:2899
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:228
#define ereport(elevel, rest)
Definition: elog.h:141
bool inh
Definition: primnodes.h:69
RangeVar * relation
Definition: parsenodes.h:2893
int16 attnum
Definition: pg_attribute.h:79
#define NOTICE
Definition: elog.h:37
static void RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:3058
static AttrNumber renameatt_internal(Oid myrelid, const char *oldattname, const char *newattname, bool recurse, bool recursing, int expected_parents, DropBehavior behavior)
Definition: tablecmds.c:2913
#define ObjectAddressSubSet(addr, class_id, object_id, object_sub_id)
Definition: objectaddress.h:33
#define AccessExclusiveLock
Definition: lockdefs.h:45
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:784
DropBehavior behavior
Definition: parsenodes.h:2898
int16 AttrNumber
Definition: attnum.h:21

◆ RenameConstraint()

ObjectAddress RenameConstraint ( RenameStmt stmt)

Definition at line 3222 of file tablecmds.c.

References AccessExclusiveLock, castNode, checkDomainOwner(), elog, ereport, errmsg(), ERROR, HeapTupleIsValid, RangeVar::inh, InvalidObjectAddress, InvalidOid, makeTypeNameFromNameList(), RenameStmt::missing_ok, RenameStmt::newname, NoLock, NOTICE, RenameStmt::object, OBJECT_DOMCONSTRAINT, ObjectIdGetDatum, OidIsValid, RangeVarCallbackForRenameAttribute(), RangeVarGetRelidExtended(), RenameStmt::relation, ReleaseSysCache(), OnCommitItem::relid, RangeVar::relname, rename_constraint_internal(), RenameStmt::renameType, RowExclusiveLock, RVR_MISSING_OK, SearchSysCache1(), RenameStmt::subname, table_close(), table_open(), typenameTypeId(), and TYPEOID.

Referenced by ExecRenameStmt().

3223 {
3224  Oid relid = InvalidOid;
3225  Oid typid = InvalidOid;
3226 
3227  if (stmt->renameType == OBJECT_DOMCONSTRAINT)
3228  {
3229  Relation rel;
3230  HeapTuple tup;
3231 
3233  rel = table_open(TypeRelationId, RowExclusiveLock);
3234  tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
3235  if (!HeapTupleIsValid(tup))
3236  elog(ERROR, "cache lookup failed for type %u", typid);
3237  checkDomainOwner(tup);
3238  ReleaseSysCache(tup);
3239  table_close(rel, NoLock);
3240  }
3241  else
3242  {
3243  /* lock level taken here should match rename_constraint_internal */
3245  stmt->missing_ok ? RVR_MISSING_OK : 0,
3247  NULL);
3248  if (!OidIsValid(relid))
3249  {
3250  ereport(NOTICE,
3251  (errmsg("relation \"%s\" does not exist, skipping",
3252  stmt->relation->relname)));
3253  return InvalidObjectAddress;
3254  }
3255  }
3256 
3257  return
3258  rename_constraint_internal(relid, typid,
3259  stmt->subname,
3260  stmt->newname,
3261  (stmt->relation &&
3262  stmt->relation->inh), /* recursive? */
3263  false, /* recursing? */
3264  0 /* expected inhcount */ );
3265 
3266 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
char * subname
Definition: parsenodes.h:2895
ObjectType renameType
Definition: parsenodes.h:2891
#define castNode(_type_, nodeptr)
Definition: nodes.h:594
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:3116
char * newname
Definition: parsenodes.h:2897
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:638
char * relname
Definition: primnodes.h:68
bool missing_ok
Definition: parsenodes.h:2899
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
Node * object
Definition: parsenodes.h:2894
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:228
#define ereport(elevel, rest)
Definition: elog.h:141
bool inh
Definition: primnodes.h:69
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1124
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1172
RangeVar * relation
Definition: parsenodes.h:2893
#define InvalidOid
Definition: postgres_ext.h:36
#define NOTICE
Definition: elog.h:37
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static void RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:3058
void checkDomainOwner(HeapTuple tup)
Definition: typecmds.c:3047
#define AccessExclusiveLock
Definition: lockdefs.h:45
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
TypeName * makeTypeNameFromNameList(List *names)
Definition: makefuncs.c:454
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:292

◆ RenameRelation()

ObjectAddress RenameRelation ( RenameStmt stmt)

Definition at line 3273 of file tablecmds.c.

References AccessExclusiveLock, ereport, errmsg(), InvalidObjectAddress, RenameStmt::missing_ok, NOTICE, OBJECT_INDEX, ObjectAddressSet, OidIsValid, RangeVarCallbackForAlterRelation(), RangeVarGetRelidExtended(), RenameStmt::relation, OnCommitItem::relid, RenameRelationInternal(), RenameStmt::renameType, RVR_MISSING_OK, and ShareUpdateExclusiveLock.

Referenced by ExecRenameStmt().

3274 {
3275  bool is_index = stmt->renameType == OBJECT_INDEX;
3276  Oid relid;
3277  ObjectAddress address;
3278 
3279  /*
3280  * Grab an exclusive lock on the target table, index, sequence, view,
3281  * materialized view, or foreign table, which we will NOT release until
3282  * end of transaction.
3283  *
3284  * Lock level used here should match RenameRelationInternal, to avoid lock
3285  * escalation.
3286  */
3287  relid = RangeVarGetRelidExtended(stmt->relation,
3289  stmt->missing_ok ? RVR_MISSING_OK : 0,
3291  (void *) stmt);
3292 
3293  if (!OidIsValid(relid))
3294  {
3295  ereport(NOTICE,
3296  (errmsg("relation \"%s\" does not exist, skipping",
3297  stmt->relation->relname)));
3298  return InvalidObjectAddress;
3299  }
3300 
3301  /* Do the work */
3302  RenameRelationInternal(relid, stmt->newname, false, is_index);
3303 
3304  ObjectAddressSet(address, RelationRelationId, relid);
3305 
3306  return address;
3307 }
ObjectType renameType
Definition: parsenodes.h:2891
char * newname
Definition: parsenodes.h:2897
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:638
char * relname
Definition: primnodes.h:68
bool missing_ok
Definition: parsenodes.h:2899
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:14832
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:228
#define ereport(elevel, rest)
Definition: elog.h:141
RangeVar * relation
Definition: parsenodes.h:2893
#define NOTICE
Definition: elog.h:37
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define AccessExclusiveLock
Definition: lockdefs.h:45
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:784
void RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
Definition: tablecmds.c:3313

◆ RenameRelationInternal()

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

Definition at line 3313 of file tablecmds.c.

References AccessExclusiveLock, 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, RELOID, RenameConstraintById(), RenameTypeInternal(), RowExclusiveLock, SearchSysCacheCopy1, ShareUpdateExclusiveLock, HeapTupleData::t_self, table_close(), and table_open().

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

3314 {
3315  Relation targetrelation;
3316  Relation relrelation; /* for RELATION relation */
3317  HeapTuple reltup;
3318  Form_pg_class relform;
3319  Oid namespaceId;
3320 
3321  /*
3322  * Grab a lock on the target relation, which we will NOT release until end
3323  * of transaction. We need at least a self-exclusive lock so that
3324  * concurrent DDL doesn't overwrite the rename if they start updating
3325  * while still seeing the old version. The lock also guards against
3326  * triggering relcache reloads in concurrent sessions, which might not
3327  * handle this information changing under them. For indexes, we can use a
3328  * reduced lock level because RelationReloadIndexInfo() handles indexes
3329  * specially.
3330  */
3331  targetrelation = relation_open(myrelid, is_index ? ShareUpdateExclusiveLock : AccessExclusiveLock);
3332  namespaceId = RelationGetNamespace(targetrelation);
3333 
3334  /*
3335  * Find relation's pg_class tuple, and make sure newrelname isn't in use.
3336  */
3337  relrelation = table_open(RelationRelationId, RowExclusiveLock);
3338 
3339  reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
3340  if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
3341  elog(ERROR, "cache lookup failed for relation %u", myrelid);
3342  relform = (Form_pg_class) GETSTRUCT(reltup);
3343 
3344  if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
3345  ereport(ERROR,
3346  (errcode(ERRCODE_DUPLICATE_TABLE),
3347  errmsg("relation \"%s\" already exists",
3348  newrelname)));
3349 
3350  /*
3351  * Update pg_class tuple with new relname. (Scribbling on reltup is OK
3352  * because it's a copy...)
3353  */
3354  namestrcpy(&(relform->relname), newrelname);
3355 
3356  CatalogTupleUpdate(relrelation, &reltup->t_self, reltup);
3357 
3358  InvokeObjectPostAlterHookArg(RelationRelationId, myrelid, 0,
3359  InvalidOid, is_internal);
3360 
3361  heap_freetuple(reltup);
3362  table_close(relrelation, RowExclusiveLock);
3363 
3364  /*
3365  * Also rename the associated type, if any.
3366  */
3367  if (OidIsValid(targetrelation->rd_rel->reltype))
3368  RenameTypeInternal(targetrelation->rd_rel->reltype,
3369  newrelname, namespaceId);
3370 
3371  /*
3372  * Also rename the associated constraint, if any.
3373  */
3374  if (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
3375  targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
3376  {
3377  Oid constraintId = get_index_constraint(myrelid);
3378 
3379  if (OidIsValid(constraintId))
3380  RenameConstraintById(constraintId, newrelname);
3381  }
3382 
3383  /*
3384  * Close rel, but keep lock!
3385  */
3386  relation_close(targetrelation, NoLock);
3387 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
int errcode(int sqlerrcode)
Definition: elog.c:570
Form_pg_class rd_rel
Definition: rel.h:83
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
int namestrcpy(Name name, const char *str)
Definition: name.c:250
#define OidIsValid(objectId)
Definition: c.h:638
#define InvokeObjectPostAlterHookArg(classId, objectId, subId, auxiliaryId, is_internal)
Definition: objectaccess.h:166
void RenameConstraintById(Oid conId, const char *newname)
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
ItemPointerData t_self
Definition: htup.h:65
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1687
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:873
#define ereport(elevel, rest)
Definition: elog.h:141
void RenameTypeInternal(Oid typeOid, const char *newTypeName, Oid typeNamespace)
Definition: pg_type.c:709
#define InvalidOid
Definition: postgres_ext.h:36
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:224
FormData_pg_class * Form_pg_class
Definition: pg_class.h:150
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define RelationGetNamespace(relation)
Definition: rel.h:457

◆ SetRelationHasSubclass()

void SetRelationHasSubclass ( Oid  relationId,
bool  relhassubclass 
)

Definition at line 2831 of file tablecmds.c.

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

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

2832 {
2833  Relation relationRelation;
2834  HeapTuple tuple;
2835  Form_pg_class classtuple;
2836 
2837  /*
2838  * Fetch a modifiable copy of the tuple, modify it, update pg_class.
2839  */
2840  relationRelation = table_open(RelationRelationId, RowExclusiveLock);
2841  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
2842  if (!HeapTupleIsValid(tuple))
2843  elog(ERROR, "cache lookup failed for relation %u", relationId);
2844  classtuple = (Form_pg_class) GETSTRUCT(tuple);
2845 
2846  if (classtuple->relhassubclass != relhassubclass)
2847  {
2848  classtuple->relhassubclass = relhassubclass;
2849  CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
2850  }
2851  else
2852  {
2853  /* no need to change tuple, but force relcache rebuild anyway */
2855  }
2856 
2857  heap_freetuple(tuple);
2858  table_close(relationRelation, RowExclusiveLock);
2859 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
bool relhassubclass
Definition: pg_class.h:102
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:224
FormData_pg_class * Form_pg_class
Definition: pg_class.h:150
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
#define elog(elevel,...)
Definition: elog.h:226
void CacheInvalidateRelcacheByTuple(HeapTuple classTuple)
Definition: inval.c:1306
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39