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 "catalog/partition.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 SetRelationHasSubclass (Oid relationId, bool relhassubclass)
 
ObjectAddress renameatt (RenameStmt *stmt)
 
ObjectAddress renameatt_type (RenameStmt *stmt)
 
ObjectAddress RenameConstraint (RenameStmt *stmt)
 
ObjectAddress RenameRelation (RenameStmt *stmt)
 
void RenameRelationInternal (Oid myrelid, const char *newrelname, bool is_internal)
 
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 *noCatalogs)
 
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 12726 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, NamespaceRelationId, NameStr, object_address_present(), ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, RelationRelationId, RELOID, SearchSysCacheCopy1, and HeapTupleData::t_self.

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

12730 {
12731  HeapTuple classTup;
12732  Form_pg_class classForm;
12733  ObjectAddress thisobj;
12734  bool already_done = false;
12735 
12736  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
12737  if (!HeapTupleIsValid(classTup))
12738  elog(ERROR, "cache lookup failed for relation %u", relOid);
12739  classForm = (Form_pg_class) GETSTRUCT(classTup);
12740 
12741  Assert(classForm->relnamespace == oldNspOid);
12742 
12743  thisobj.classId = RelationRelationId;
12744  thisobj.objectId = relOid;
12745  thisobj.objectSubId = 0;
12746 
12747  /*
12748  * If the object has already been moved, don't move it again. If it's
12749  * already in the right place, don't move it, but still fire the object
12750  * access hook.
12751  */
12752  already_done = object_address_present(&thisobj, objsMoved);
12753  if (!already_done && oldNspOid != newNspOid)
12754  {
12755  /* check for duplicate name (more friendly than unique-index failure) */
12756  if (get_relname_relid(NameStr(classForm->relname),
12757  newNspOid) != InvalidOid)
12758  ereport(ERROR,
12759  (errcode(ERRCODE_DUPLICATE_TABLE),
12760  errmsg("relation \"%s\" already exists in schema \"%s\"",
12761  NameStr(classForm->relname),
12762  get_namespace_name(newNspOid))));
12763 
12764  /* classTup is a copy, so OK to scribble on */
12765  classForm->relnamespace = newNspOid;
12766 
12767  CatalogTupleUpdate(classRel, &classTup->t_self, classTup);
12768 
12769  /* Update dependency on schema if caller said so */
12770  if (hasDependEntry &&
12772  relOid,
12774  oldNspOid,
12775  newNspOid) != 1)
12776  elog(ERROR, "failed to change schema dependency for relation \"%s\"",
12777  NameStr(classForm->relname));
12778  }
12779  if (!already_done)
12780  {
12781  add_exact_object_address(&thisobj, objsMoved);
12782 
12784  }
12785 
12786  heap_freetuple(classTup);
12787 }
#define NamespaceRelationId
Definition: pg_namespace.h:34
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
#define RelationRelationId
Definition: pg_class.h:29
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2220
int errcode(int sqlerrcode)
Definition: elog.c:575
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2160
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#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:1702
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3066
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define Assert(condition)
Definition: c.h:670
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:173
int errmsg(const char *fmt,...)
Definition: elog.c:797
long changeDependencyFor(Oid classId, Oid objectId, Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition: pg_depend.c:295
#define NameStr(name)
Definition: c.h:547
#define elog
Definition: elog.h:219

◆ AlterTable()

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

Definition at line 3142 of file tablecmds.c.

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

Referenced by ProcessUtilitySlow().

3143 {
3144  Relation rel;
3145 
3146  /* Caller is required to provide an adequate lock. */
3147  rel = relation_open(relid, NoLock);
3148 
3149  CheckTableNotInUse(rel, "ALTER TABLE");
3150 
3151  ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode);
3152 }
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
Definition: tablecmds.c:3460
#define NoLock
Definition: lockdefs.h:34
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3063
bool inh
Definition: primnodes.h:69
RangeVar * relation
Definition: parsenodes.h:1699
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1120

◆ AlterTableGetLockLevel()

LOCKMODE AlterTableGetLockLevel ( List cmds)

Definition at line 3211 of file tablecmds.c.

References AccessExclusiveLock, AlterTableGetRelOptionsLockLevel(), AT_AddColumn, AT_AddColumnToView, AT_AddConstraint, AT_AddConstraintRecurse, AT_AddIdentity, AT_AddIndex, AT_AddIndexConstraint, AT_AddInherit, AT_AddOf, AT_AddOids, AT_AlterColumnGenericOptions, AT_AlterColumnType, AT_AlterConstraint, AT_AttachPartition, AT_ChangeOwner, 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().

3212 {
3213  /*
3214  * This only works if we read catalog tables using MVCC snapshots.
3215  */
3216  ListCell *lcmd;
3218 
3219  foreach(lcmd, cmds)
3220  {
3221  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3222  LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
3223 
3224  switch (cmd->subtype)
3225  {
3226  /*
3227  * These subcommands rewrite the heap, so require full locks.
3228  */
3229  case AT_AddColumn: /* may rewrite heap, in some cases and visible
3230  * to SELECT */
3231  case AT_SetTableSpace: /* must rewrite heap */
3232  case AT_AlterColumnType: /* must rewrite heap */
3233  case AT_AddOids: /* must rewrite heap */
3234  cmd_lockmode = AccessExclusiveLock;
3235  break;
3236 
3237  /*
3238  * These subcommands may require addition of toast tables. If
3239  * we add a toast table to a table currently being scanned, we
3240  * might miss data added to the new toast table by concurrent
3241  * insert transactions.
3242  */
3243  case AT_SetStorage: /* may add toast tables, see
3244  * ATRewriteCatalogs() */
3245  cmd_lockmode = AccessExclusiveLock;
3246  break;
3247 
3248  /*
3249  * Removing constraints can affect SELECTs that have been
3250  * optimised assuming the constraint holds true.
3251  */
3252  case AT_DropConstraint: /* as DROP INDEX */
3253  case AT_DropNotNull: /* may change some SQL plans */
3254  cmd_lockmode = AccessExclusiveLock;
3255  break;
3256 
3257  /*
3258  * Subcommands that may be visible to concurrent SELECTs
3259  */
3260  case AT_DropColumn: /* change visible to SELECT */
3261  case AT_AddColumnToView: /* CREATE VIEW */
3262  case AT_DropOids: /* calls AT_DropColumn */
3263  case AT_EnableAlwaysRule: /* may change SELECT rules */
3264  case AT_EnableReplicaRule: /* may change SELECT rules */
3265  case AT_EnableRule: /* may change SELECT rules */
3266  case AT_DisableRule: /* may change SELECT rules */
3267  cmd_lockmode = AccessExclusiveLock;
3268  break;
3269 
3270  /*
3271  * Changing owner may remove implicit SELECT privileges
3272  */
3273  case AT_ChangeOwner: /* change visible to SELECT */
3274  cmd_lockmode = AccessExclusiveLock;
3275  break;
3276 
3277  /*
3278  * Changing foreign table options may affect optimization.
3279  */
3280  case AT_GenericOptions:
3282  cmd_lockmode = AccessExclusiveLock;
3283  break;
3284 
3285  /*
3286  * These subcommands affect write operations only.
3287  */
3288  case AT_EnableTrig:
3289  case AT_EnableAlwaysTrig:
3290  case AT_EnableReplicaTrig:
3291  case AT_EnableTrigAll:
3292  case AT_EnableTrigUser:
3293  case AT_DisableTrig:
3294  case AT_DisableTrigAll:
3295  case AT_DisableTrigUser:
3296  cmd_lockmode = ShareRowExclusiveLock;
3297  break;
3298 
3299  /*
3300  * These subcommands affect write operations only. XXX
3301  * Theoretically, these could be ShareRowExclusiveLock.
3302  */
3303  case AT_ColumnDefault:
3304  case AT_AlterConstraint:
3305  case AT_AddIndex: /* from ADD CONSTRAINT */
3306  case AT_AddIndexConstraint:
3307  case AT_ReplicaIdentity:
3308  case AT_SetNotNull:
3309  case AT_EnableRowSecurity:
3310  case AT_DisableRowSecurity:
3311  case AT_ForceRowSecurity:
3312  case AT_NoForceRowSecurity:
3313  case AT_AddIdentity:
3314  case AT_DropIdentity:
3315  case AT_SetIdentity:
3316  cmd_lockmode = AccessExclusiveLock;
3317  break;
3318 
3319  case AT_AddConstraint:
3320  case AT_ProcessedConstraint: /* becomes AT_AddConstraint */
3321  case AT_AddConstraintRecurse: /* becomes AT_AddConstraint */
3322  case AT_ReAddConstraint: /* becomes AT_AddConstraint */
3323  case AT_ReAddDomainConstraint: /* becomes AT_AddConstraint */
3324  if (IsA(cmd->def, Constraint))
3325  {
3326  Constraint *con = (Constraint *) cmd->def;
3327 
3328  switch (con->contype)
3329  {
3330  case CONSTR_EXCLUSION:
3331  case CONSTR_PRIMARY:
3332  case CONSTR_UNIQUE:
3333 
3334  /*
3335  * Cases essentially the same as CREATE INDEX. We
3336  * could reduce the lock strength to ShareLock if
3337  * we can work out how to allow concurrent catalog
3338  * updates. XXX Might be set down to
3339  * ShareRowExclusiveLock but requires further
3340  * analysis.
3341  */
3342  cmd_lockmode = AccessExclusiveLock;
3343  break;
3344  case CONSTR_FOREIGN:
3345 
3346  /*
3347  * We add triggers to both tables when we add a
3348  * Foreign Key, so the lock level must be at least
3349  * as strong as CREATE TRIGGER.
3350  */
3351  cmd_lockmode = ShareRowExclusiveLock;
3352  break;
3353 
3354  default:
3355  cmd_lockmode = AccessExclusiveLock;
3356  }
3357  }
3358  break;
3359 
3360  /*
3361  * These subcommands affect inheritance behaviour. Queries
3362  * started before us will continue to see the old inheritance
3363  * behaviour, while queries started after we commit will see
3364  * new behaviour. No need to prevent reads or writes to the
3365  * subtable while we hook it up though. Changing the TupDesc
3366  * may be a problem, so keep highest lock.
3367  */
3368  case AT_AddInherit:
3369  case AT_DropInherit:
3370  cmd_lockmode = AccessExclusiveLock;
3371  break;
3372 
3373  /*
3374  * These subcommands affect implicit row type conversion. They
3375  * have affects similar to CREATE/DROP CAST on queries. don't
3376  * provide for invalidating parse trees as a result of such
3377  * changes, so we keep these at AccessExclusiveLock.
3378  */
3379  case AT_AddOf:
3380  case AT_DropOf:
3381  cmd_lockmode = AccessExclusiveLock;
3382  break;
3383 
3384  /*
3385  * Only used by CREATE OR REPLACE VIEW which must conflict
3386  * with an SELECTs currently using the view.
3387  */
3388  case AT_ReplaceRelOptions:
3389  cmd_lockmode = AccessExclusiveLock;
3390  break;
3391 
3392  /*
3393  * These subcommands affect general strategies for performance
3394  * and maintenance, though don't change the semantic results
3395  * from normal data reads and writes. Delaying an ALTER TABLE
3396  * behind currently active writes only delays the point where
3397  * the new strategy begins to take effect, so there is no
3398  * benefit in waiting. In this case the minimum restriction
3399  * applies: we don't currently allow concurrent catalog
3400  * updates.
3401  */
3402  case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
3403  case AT_ClusterOn: /* Uses MVCC in getIndexes() */
3404  case AT_DropCluster: /* Uses MVCC in getIndexes() */
3405  case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
3406  case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
3407  cmd_lockmode = ShareUpdateExclusiveLock;
3408  break;
3409 
3410  case AT_SetLogged:
3411  case AT_SetUnLogged:
3412  cmd_lockmode = AccessExclusiveLock;
3413  break;
3414 
3415  case AT_ValidateConstraint: /* Uses MVCC in getConstraints() */
3416  cmd_lockmode = ShareUpdateExclusiveLock;
3417  break;
3418 
3419  /*
3420  * Rel options are more complex than first appears. Options
3421  * are set here for tables, views and indexes; for historical
3422  * reasons these can all be used with ALTER TABLE, so we can't
3423  * decide between them using the basic grammar.
3424  */
3425  case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
3426  * getTables() */
3427  case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
3428  * getTables() */
3429  cmd_lockmode = AlterTableGetRelOptionsLockLevel((List *) cmd->def);
3430  break;
3431 
3432  case AT_AttachPartition:
3433  case AT_DetachPartition:
3434  cmd_lockmode = AccessExclusiveLock;
3435  break;
3436 
3437  default: /* oops */
3438  elog(ERROR, "unrecognized alter table type: %d",
3439  (int) cmd->subtype);
3440  break;
3441  }
3442 
3443  /*
3444  * Take the greatest lockmode from any subcommand
3445  */
3446  if (cmd_lockmode > lockmode)
3447  lockmode = cmd_lockmode;
3448  }
3449 
3450  return lockmode;
3451 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:563
int LOCKMODE
Definition: lockdefs.h:26
AlterTableType subtype
Definition: parsenodes.h:1787
#define ERROR
Definition: elog.h:43
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define lfirst(lc)
Definition: pg_list.h:106
#define ShareRowExclusiveLock
Definition: lockdefs.h:42
LOCKMODE AlterTableGetRelOptionsLockLevel(List *defList)
Definition: reloptions.c:1540
#define AccessExclusiveLock
Definition: lockdefs.h:45
ConstrType contype
Definition: parsenodes.h:2092
#define elog
Definition: elog.h:219
Definition: pg_list.h:45

◆ AlterTableInternal()

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

Definition at line 3166 of file tablecmds.c.

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

Referenced by AlterTableMoveAll(), DefineVirtualRelation(), and index_check_primary_key().

3167 {
3168  Relation rel;
3169  LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
3170 
3171  rel = relation_open(relid, lockmode);
3172 
3174 
3175  ATController(NULL, rel, cmds, recurse, lockmode);
3176 }
int LOCKMODE
Definition: lockdefs.h:26
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
Definition: tablecmds.c:3460
LOCKMODE AlterTableGetLockLevel(List *cmds)
Definition: tablecmds.c:3211
void EventTriggerAlterTableRelid(Oid objectId)
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1120

◆ AlterTableLookupRelation()

Oid AlterTableLookupRelation ( AlterTableStmt stmt,
LOCKMODE  lockmode 
)

Definition at line 3092 of file tablecmds.c.

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

Referenced by ProcessUtilitySlow().

3093 {
3094  return RangeVarGetRelidExtended(stmt->relation, lockmode, stmt->missing_ok, false,
3096  (void *) stmt);
3097 }
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, bool missing_ok, bool nowait, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:218
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:13203
RangeVar * relation
Definition: parsenodes.h:1699

◆ AlterTableMoveAll()

Oid AlterTableMoveAll ( AlterTableMoveAllStmt stmt)

Definition at line 10804 of file tablecmds.c.

References AccessExclusiveLock, AccessShareLock, ACL_CREATE, ACL_KIND_CLASS, ACL_KIND_TABLESPACE, aclcheck_error(), ACLCHECK_NOT_OWNER, ACLCHECK_OK, AlterTableInternal(), Anum_pg_class_reltablespace, AT_SetTableSpace, BTEqualStrategyNumber, ConditionalLockRelationOid(), ereport, errcode(), errmsg(), ERROR, EventTriggerAlterTableEnd(), EventTriggerAlterTableStart(), ForwardScanDirection, get_namespace_name(), get_tablespace_name(), get_tablespace_oid(), GETSTRUCT, GetUserId(), GLOBALTABLESPACE_OID, heap_beginscan_catalog(), heap_close, heap_endscan(), heap_getnext(), heap_open(), HeapTupleGetOid, InvalidOid, isAnyTempNamespace(), IsSystemNamespace(), 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, ObjectIdGetDatum, AlterTableMoveAllStmt::objtype, OidIsValid, AlterTableMoveAllStmt::orig_tablespacename, pg_class_ownercheck(), pg_tablespace_aclcheck(), PG_TOAST_NAMESPACE, RelationRelationId, RELKIND_INDEX, RELKIND_MATVIEW, RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, AlterTableMoveAllStmt::roles, roleSpecsToIds(), ScanKeyInit(), and AlterTableCmd::subtype.

Referenced by ProcessUtilitySlow().

10805 {
10806  List *relations = NIL;
10807  ListCell *l;
10808  ScanKeyData key[1];
10809  Relation rel;
10810  HeapScanDesc scan;
10811  HeapTuple tuple;
10812  Oid orig_tablespaceoid;
10813  Oid new_tablespaceoid;
10814  List *role_oids = roleSpecsToIds(stmt->roles);
10815 
10816  /* Ensure we were not asked to move something we can't */
10817  if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
10818  stmt->objtype != OBJECT_MATVIEW)
10819  ereport(ERROR,
10820  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
10821  errmsg("only tables, indexes, and materialized views exist in tablespaces")));
10822 
10823  /* Get the orig and new tablespace OIDs */
10824  orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
10825  new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
10826 
10827  /* Can't move shared relations in to or out of pg_global */
10828  /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
10829  if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
10830  new_tablespaceoid == GLOBALTABLESPACE_OID)
10831  ereport(ERROR,
10832  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
10833  errmsg("cannot move relations in to or out of pg_global tablespace")));
10834 
10835  /*
10836  * Must have CREATE rights on the new tablespace, unless it is the
10837  * database default tablespace (which all users implicitly have CREATE
10838  * rights on).
10839  */
10840  if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
10841  {
10842  AclResult aclresult;
10843 
10844  aclresult = pg_tablespace_aclcheck(new_tablespaceoid, GetUserId(),
10845  ACL_CREATE);
10846  if (aclresult != ACLCHECK_OK)
10848  get_tablespace_name(new_tablespaceoid));
10849  }
10850 
10851  /*
10852  * Now that the checks are done, check if we should set either to
10853  * InvalidOid because it is our database's default tablespace.
10854  */
10855  if (orig_tablespaceoid == MyDatabaseTableSpace)
10856  orig_tablespaceoid = InvalidOid;
10857 
10858  if (new_tablespaceoid == MyDatabaseTableSpace)
10859  new_tablespaceoid = InvalidOid;
10860 
10861  /* no-op */
10862  if (orig_tablespaceoid == new_tablespaceoid)
10863  return new_tablespaceoid;
10864 
10865  /*
10866  * Walk the list of objects in the tablespace and move them. This will
10867  * only find objects in our database, of course.
10868  */
10869  ScanKeyInit(&key[0],
10871  BTEqualStrategyNumber, F_OIDEQ,
10872  ObjectIdGetDatum(orig_tablespaceoid));
10873 
10875  scan = heap_beginscan_catalog(rel, 1, key);
10876  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
10877  {
10878  Oid relOid = HeapTupleGetOid(tuple);
10879  Form_pg_class relForm;
10880 
10881  relForm = (Form_pg_class) GETSTRUCT(tuple);
10882 
10883  /*
10884  * Do not move objects in pg_catalog as part of this, if an admin
10885  * really wishes to do so, they can issue the individual ALTER
10886  * commands directly.
10887  *
10888  * Also, explicitly avoid any shared tables, temp tables, or TOAST
10889  * (TOAST will be moved with the main table).
10890  */
10891  if (IsSystemNamespace(relForm->relnamespace) || relForm->relisshared ||
10892  isAnyTempNamespace(relForm->relnamespace) ||
10893  relForm->relnamespace == PG_TOAST_NAMESPACE)
10894  continue;
10895 
10896  /* Only move the object type requested */
10897  if ((stmt->objtype == OBJECT_TABLE &&
10898  relForm->relkind != RELKIND_RELATION &&
10899  relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
10900  (stmt->objtype == OBJECT_INDEX &&
10901  relForm->relkind != RELKIND_INDEX) ||
10902  (stmt->objtype == OBJECT_MATVIEW &&
10903  relForm->relkind != RELKIND_MATVIEW))
10904  continue;
10905 
10906  /* Check if we are only moving objects owned by certain roles */
10907  if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
10908  continue;
10909 
10910  /*
10911  * Handle permissions-checking here since we are locking the tables
10912  * and also to avoid doing a bunch of work only to fail part-way. Note
10913  * that permissions will also be checked by AlterTableInternal().
10914  *
10915  * Caller must be considered an owner on the table to move it.
10916  */
10917  if (!pg_class_ownercheck(relOid, GetUserId()))
10919  NameStr(relForm->relname));
10920 
10921  if (stmt->nowait &&
10923  ereport(ERROR,
10924  (errcode(ERRCODE_OBJECT_IN_USE),
10925  errmsg("aborting because lock on relation \"%s.%s\" is not available",
10926  get_namespace_name(relForm->relnamespace),
10927  NameStr(relForm->relname))));
10928  else
10930 
10931  /* Add to our list of objects to move */
10932  relations = lappend_oid(relations, relOid);
10933  }
10934 
10935  heap_endscan(scan);
10937 
10938  if (relations == NIL)
10939  ereport(NOTICE,
10940  (errcode(ERRCODE_NO_DATA_FOUND),
10941  errmsg("no matching relations in tablespace \"%s\" found",
10942  orig_tablespaceoid == InvalidOid ? "(database default)" :
10943  get_tablespace_name(orig_tablespaceoid))));
10944 
10945  /* Everything is locked, loop through and move all of the relations. */
10946  foreach(l, relations)
10947  {
10948  List *cmds = NIL;
10950 
10951  cmd->subtype = AT_SetTableSpace;
10952  cmd->name = stmt->new_tablespacename;
10953 
10954  cmds = lappend(cmds, cmd);
10955 
10957  /* OID is set by AlterTableInternal */
10958  AlterTableInternal(lfirst_oid(l), cmds, false);
10960  }
10961 
10962  return new_tablespaceoid;
10963 }
#define NIL
Definition: pg_list.h:69
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:138
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1380
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4554
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1565
Oid GetUserId(void)
Definition: miscinit.c:284
#define RelationRelationId
Definition: pg_class.h:29
#define Anum_pg_class_reltablespace
Definition: pg_class.h:110
#define RELKIND_MATVIEW
Definition: pg_class.h:165
#define AccessShareLock
Definition: lockdefs.h:36
#define GLOBALTABLESPACE_OID
Definition: pg_tablespace.h:64
Definition: nodes.h:512
int errcode(int sqlerrcode)
Definition: elog.c:575
AlterTableType subtype
Definition: parsenodes.h:1787
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
#define PG_TOAST_NAMESPACE
Definition: pg_namespace.h:74
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
#define OidIsValid(objectId)
Definition: c.h:576
Oid MyDatabaseTableSpace
Definition: globals.c:79
void EventTriggerAlterTableStart(Node *parsetree)
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define ACL_CREATE
Definition: parsenodes.h:82
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3066
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3457
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1405
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
AclResult
Definition: acl.h:178
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1808
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
bool IsSystemNamespace(Oid namespaceId)
Definition: catalog.c:163
#define InvalidOid
Definition: postgres_ext.h:36
#define NOTICE
Definition: elog.h:37
#define makeNode(_type_)
Definition: nodes.h:560
List * roleSpecsToIds(List *memberNames)
Definition: user.c:1396
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:505
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4604
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
void AlterTableInternal(Oid relid, List *cmds, bool recurse)
Definition: tablecmds.c:3166
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1426
#define NameStr(name)
Definition: c.h:547
#define RELKIND_INDEX
Definition: pg_class.h:161
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
bool isAnyTempNamespace(Oid namespaceId)
Definition: namespace.c:3156
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:700
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:105
#define RELKIND_RELATION
Definition: pg_class.h:160
Definition: pg_list.h:45
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define lfirst_oid(lc)
Definition: pg_list.h:108
void EventTriggerAlterTableEnd(void)

◆ AlterTableNamespace()

ObjectAddress AlterTableNamespace ( AlterObjectSchemaStmt stmt,
Oid oldschema 
)

Definition at line 12617 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, RelationRelationId, OnCommitItem::relid, RELKIND_SEQUENCE, and sequenceIsOwned().

Referenced by ExecAlterObjectSchemaStmt().

12618 {
12619  Relation rel;
12620  Oid relid;
12621  Oid oldNspOid;
12622  Oid nspOid;
12623  RangeVar *newrv;
12624  ObjectAddresses *objsMoved;
12625  ObjectAddress myself;
12626 
12628  stmt->missing_ok, false,
12630  (void *) stmt);
12631 
12632  if (!OidIsValid(relid))
12633  {
12634  ereport(NOTICE,
12635  (errmsg("relation \"%s\" does not exist, skipping",
12636  stmt->relation->relname)));
12637  return InvalidObjectAddress;
12638  }
12639 
12640  rel = relation_open(relid, NoLock);
12641 
12642  oldNspOid = RelationGetNamespace(rel);
12643 
12644  /* If it's an owned sequence, disallow moving it by itself. */
12645  if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
12646  {
12647  Oid tableId;
12648  int32 colId;
12649 
12650  if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
12651  sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
12652  ereport(ERROR,
12653  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
12654  errmsg("cannot move an owned sequence into another schema"),
12655  errdetail("Sequence \"%s\" is linked to table \"%s\".",
12657  get_rel_name(tableId))));
12658  }
12659 
12660  /* Get and lock schema OID and check its permissions. */
12661  newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
12662  nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
12663 
12664  /* common checks on switching namespaces */
12665  CheckSetNamespace(oldNspOid, nspOid);
12666 
12667  objsMoved = new_object_addresses();
12668  AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
12669  free_object_addresses(objsMoved);
12670 
12671  ObjectAddressSet(myself, RelationRelationId, relid);
12672 
12673  if (oldschema)
12674  *oldschema = oldNspOid;
12675 
12676  /* close rel, but keep lock until commit */
12677  relation_close(rel, NoLock);
12678 
12679  return myself;
12680 }
bool sequenceIsOwned(Oid seqId, char deptype, Oid *tableId, int32 *colId)
Definition: pg_depend.c:500
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, bool missing_ok, bool nowait, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:218
#define RelationRelationId
Definition: pg_class.h:29
int errcode(int sqlerrcode)
Definition: elog.c:575
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1266
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2105
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2376
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:576
signed int int32
Definition: c.h:284
char * relname
Definition: primnodes.h:68
#define ERROR
Definition: elog.h:43
void AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:12688
#define NoLock
Definition: lockdefs.h:34
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:13203
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define RelationGetRelationName(relation)
Definition: rel.h:445
#define ereport(elevel, rest)
Definition: elog.h:122
void CheckSetNamespace(Oid oldNspOid, Oid nspOid)
Definition: namespace.c:2928
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:508
#define NOTICE
Definition: elog.h:37
#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:797
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1120
#define RELKIND_SEQUENCE
Definition: pg_class.h:162
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1745
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:421
#define RelationGetNamespace(relation)
Definition: rel.h:452

◆ AlterTableNamespaceInternal()

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

Definition at line 12688 of file tablecmds.c.

References AccessExclusiveLock, AlterConstraintNamespaces(), AlterIndexNamespaces(), AlterRelationNamespaceInternal(), AlterSeqNamespaces(), AlterTypeNamespaceInternal(), Assert, heap_close, heap_open(), RelationData::rd_rel, RelationGetRelid, RelationRelationId, RELKIND_MATVIEW, RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, and RowExclusiveLock.

Referenced by AlterObjectNamespace_oid(), and AlterTableNamespace().

12690 {
12691  Relation classRel;
12692 
12693  Assert(objsMoved != NULL);
12694 
12695  /* OK, modify the pg_class row and pg_depend entry */
12697 
12698  AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
12699  nspOid, true, objsMoved);
12700 
12701  /* Fix the table's row type too */
12702  AlterTypeNamespaceInternal(rel->rd_rel->reltype,
12703  nspOid, false, false, objsMoved);
12704 
12705  /* Fix other dependent stuff */
12706  if (rel->rd_rel->relkind == RELKIND_RELATION ||
12707  rel->rd_rel->relkind == RELKIND_MATVIEW ||
12708  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
12709  {
12710  AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
12711  AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
12712  objsMoved, AccessExclusiveLock);
12713  AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
12714  false, objsMoved);
12715  }
12716 
12717  heap_close(classRel, RowExclusiveLock);
12718 }
#define RelationRelationId
Definition: pg_class.h:29
#define RELKIND_MATVIEW
Definition: pg_class.h:165
Oid AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid, bool isImplicitArray, bool errorOnTableType, ObjectAddresses *objsMoved)
Definition: typecmds.c:3580
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:114
static void AlterIndexNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:12796
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:12841
#define RowExclusiveLock
Definition: lockdefs.h:38
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define Assert(condition)
Definition: c.h:670
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
Definition: tablecmds.c:12726
#define AccessExclusiveLock
Definition: lockdefs.h:45
#define RELKIND_RELATION
Definition: pg_class.h:160
#define RelationGetRelid(relation)
Definition: rel.h:425

◆ AtEOSubXact_on_commit_actions()

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

Definition at line 13093 of file tablecmds.c.

References OnCommitItem::creating_subid, OnCommitItem::deleting_subid, InvalidSubTransactionId, lfirst, list_delete_cell(), list_head(), lnext, and pfree().

Referenced by AbortSubTransaction(), and CommitSubTransaction().

13095 {
13096  ListCell *cur_item;
13097  ListCell *prev_item;
13098 
13099  prev_item = NULL;
13100  cur_item = list_head(on_commits);
13101 
13102  while (cur_item != NULL)
13103  {
13104  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
13105 
13106  if (!isCommit && oc->creating_subid == mySubid)
13107  {
13108  /* cur_item must be removed */
13109  on_commits = list_delete_cell(on_commits, cur_item, prev_item);
13110  pfree(oc);
13111  if (prev_item)
13112  cur_item = lnext(prev_item);
13113  else
13114  cur_item = list_head(on_commits);
13115  }
13116  else
13117  {
13118  /* cur_item must be preserved */
13119  if (oc->creating_subid == mySubid)
13120  oc->creating_subid = parentSubid;
13121  if (oc->deleting_subid == mySubid)
13122  oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
13123  prev_item = cur_item;
13124  cur_item = lnext(prev_item);
13125  }
13126  }
13127 }
SubTransactionId creating_subid
Definition: tablecmds.c:120
void pfree(void *pointer)
Definition: mcxt.c:949
static List * on_commits
Definition: tablecmds.c:124
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define lnext(lc)
Definition: pg_list.h:105
List * list_delete_cell(List *list, ListCell *cell, ListCell *prev)
Definition: list.c:528
SubTransactionId deleting_subid
Definition: tablecmds.c:121
#define lfirst(lc)
Definition: pg_list.h:106
#define InvalidSubTransactionId
Definition: c.h:451

◆ AtEOXact_on_commit_actions()

void AtEOXact_on_commit_actions ( bool  isCommit)

Definition at line 13051 of file tablecmds.c.

References OnCommitItem::creating_subid, OnCommitItem::deleting_subid, InvalidSubTransactionId, lfirst, list_delete_cell(), list_head(), lnext, and pfree().

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

13052 {
13053  ListCell *cur_item;
13054  ListCell *prev_item;
13055 
13056  prev_item = NULL;
13057  cur_item = list_head(on_commits);
13058 
13059  while (cur_item != NULL)
13060  {
13061  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
13062 
13063  if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
13065  {
13066  /* cur_item must be removed */
13067  on_commits = list_delete_cell(on_commits, cur_item, prev_item);
13068  pfree(oc);
13069  if (prev_item)
13070  cur_item = lnext(prev_item);
13071  else
13072  cur_item = list_head(on_commits);
13073  }
13074  else
13075  {
13076  /* cur_item must be preserved */
13079  prev_item = cur_item;
13080  cur_item = lnext(prev_item);
13081  }
13082  }
13083 }
SubTransactionId creating_subid
Definition: tablecmds.c:120
void pfree(void *pointer)
Definition: mcxt.c:949
static List * on_commits
Definition: tablecmds.c:124
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define lnext(lc)
Definition: pg_list.h:105
List * list_delete_cell(List *list, ListCell *cell, ListCell *prev)
Definition: list.c:528
SubTransactionId deleting_subid
Definition: tablecmds.c:121
#define lfirst(lc)
Definition: pg_list.h:106
#define InvalidSubTransactionId
Definition: c.h:451

◆ ATExecChangeOwner()

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

Definition at line 9993 of file tablecmds.c.

References ACL_CREATE, ACL_KIND_CLASS, ACL_KIND_NAMESPACE, aclcheck_error(), ACLCHECK_NOT_OWNER, ACLCHECK_OK, aclnewowner(), AlterTypeOwnerInternal(), Anum_pg_class_relacl, Anum_pg_class_relowner, 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(), GETSTRUCT, GetUserId(), heap_close, heap_freetuple(), heap_modify_tuple(), heap_open(), HeapTupleIsValid, i, InvalidOid, InvokeObjectPostAlterHook, lfirst_oid, list_free(), NameStr, Natts_pg_class, NoLock, ObjectIdGetDatum, pg_class_ownercheck(), pg_namespace_aclcheck(), PointerGetDatum, relation_close(), relation_open(), RelationGetDescr, RelationGetIndexList(), RelationGetRelationName, RelationRelationId, ReleaseSysCache(), RELKIND_COMPOSITE_TYPE, RELKIND_FOREIGN_TABLE, RELKIND_INDEX, RELKIND_MATVIEW, RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_TOASTVALUE, RELKIND_VIEW, RELOID, RowExclusiveLock, SearchSysCache1(), sequenceIsOwned(), superuser(), SysCacheGetAttr(), HeapTupleData::t_self, and WARNING.

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

9994 {
9995  Relation target_rel;
9996  Relation class_rel;
9997  HeapTuple tuple;
9998  Form_pg_class tuple_class;
9999 
10000  /*
10001  * Get exclusive lock till end of transaction on the target table. Use
10002  * relation_open so that we can work on indexes and sequences.
10003  */
10004  target_rel = relation_open(relationOid, lockmode);
10005 
10006  /* Get its pg_class tuple, too */
10008 
10009  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
10010  if (!HeapTupleIsValid(tuple))
10011  elog(ERROR, "cache lookup failed for relation %u", relationOid);
10012  tuple_class = (Form_pg_class) GETSTRUCT(tuple);
10013 
10014  /* Can we change the ownership of this tuple? */
10015  switch (tuple_class->relkind)
10016  {
10017  case RELKIND_RELATION:
10018  case RELKIND_VIEW:
10019  case RELKIND_MATVIEW:
10020  case RELKIND_FOREIGN_TABLE:
10022  /* ok to change owner */
10023  break;
10024  case RELKIND_INDEX:
10025  if (!recursing)
10026  {
10027  /*
10028  * Because ALTER INDEX OWNER used to be allowed, and in fact
10029  * is generated by old versions of pg_dump, we give a warning
10030  * and do nothing rather than erroring out. Also, to avoid
10031  * unnecessary chatter while restoring those old dumps, say
10032  * nothing at all if the command would be a no-op anyway.
10033  */
10034  if (tuple_class->relowner != newOwnerId)
10035  ereport(WARNING,
10036  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10037  errmsg("cannot change owner of index \"%s\"",
10038  NameStr(tuple_class->relname)),
10039  errhint("Change the ownership of the index's table, instead.")));
10040  /* quick hack to exit via the no-op path */
10041  newOwnerId = tuple_class->relowner;
10042  }
10043  break;
10044  case RELKIND_SEQUENCE:
10045  if (!recursing &&
10046  tuple_class->relowner != newOwnerId)
10047  {
10048  /* if it's an owned sequence, disallow changing it by itself */
10049  Oid tableId;
10050  int32 colId;
10051 
10052  if (sequenceIsOwned(relationOid, DEPENDENCY_AUTO, &tableId, &colId) ||
10053  sequenceIsOwned(relationOid, DEPENDENCY_INTERNAL, &tableId, &colId))
10054  ereport(ERROR,
10055  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10056  errmsg("cannot change owner of sequence \"%s\"",
10057  NameStr(tuple_class->relname)),
10058  errdetail("Sequence \"%s\" is linked to table \"%s\".",
10059  NameStr(tuple_class->relname),
10060  get_rel_name(tableId))));
10061  }
10062  break;
10064  if (recursing)
10065  break;
10066  ereport(ERROR,
10067  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10068  errmsg("\"%s\" is a composite type",
10069  NameStr(tuple_class->relname)),
10070  errhint("Use ALTER TYPE instead.")));
10071  break;
10072  case RELKIND_TOASTVALUE:
10073  if (recursing)
10074  break;
10075  /* FALL THRU */
10076  default:
10077  ereport(ERROR,
10078  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10079  errmsg("\"%s\" is not a table, view, sequence, or foreign table",
10080  NameStr(tuple_class->relname))));
10081  }
10082 
10083  /*
10084  * If the new owner is the same as the existing owner, consider the
10085  * command to have succeeded. This is for dump restoration purposes.
10086  */
10087  if (tuple_class->relowner != newOwnerId)
10088  {
10089  Datum repl_val[Natts_pg_class];
10090  bool repl_null[Natts_pg_class];
10091  bool repl_repl[Natts_pg_class];
10092  Acl *newAcl;
10093  Datum aclDatum;
10094  bool isNull;
10095  HeapTuple newtuple;
10096 
10097  /* skip permission checks when recursing to index or toast table */
10098  if (!recursing)
10099  {
10100  /* Superusers can always do it */
10101  if (!superuser())
10102  {
10103  Oid namespaceOid = tuple_class->relnamespace;
10104  AclResult aclresult;
10105 
10106  /* Otherwise, must be owner of the existing object */
10107  if (!pg_class_ownercheck(relationOid, GetUserId()))
10109  RelationGetRelationName(target_rel));
10110 
10111  /* Must be able to become new owner */
10112  check_is_member_of_role(GetUserId(), newOwnerId);
10113 
10114  /* New owner must have CREATE privilege on namespace */
10115  aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
10116  ACL_CREATE);
10117  if (aclresult != ACLCHECK_OK)
10119  get_namespace_name(namespaceOid));
10120  }
10121  }
10122 
10123  memset(repl_null, false, sizeof(repl_null));
10124  memset(repl_repl, false, sizeof(repl_repl));
10125 
10126  repl_repl[Anum_pg_class_relowner - 1] = true;
10127  repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
10128 
10129  /*
10130  * Determine the modified ACL for the new owner. This is only
10131  * necessary when the ACL is non-null.
10132  */
10133  aclDatum = SysCacheGetAttr(RELOID, tuple,
10135  &isNull);
10136  if (!isNull)
10137  {
10138  newAcl = aclnewowner(DatumGetAclP(aclDatum),
10139  tuple_class->relowner, newOwnerId);
10140  repl_repl[Anum_pg_class_relacl - 1] = true;
10141  repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
10142  }
10143 
10144  newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
10145 
10146  CatalogTupleUpdate(class_rel, &newtuple->t_self, newtuple);
10147 
10148  heap_freetuple(newtuple);
10149 
10150  /*
10151  * We must similarly update any per-column ACLs to reflect the new
10152  * owner; for neatness reasons that's split out as a subroutine.
10153  */
10154  change_owner_fix_column_acls(relationOid,
10155  tuple_class->relowner,
10156  newOwnerId);
10157 
10158  /*
10159  * Update owner dependency reference, if any. A composite type has
10160  * none, because it's tracked for the pg_type entry instead of here;
10161  * indexes and TOAST tables don't have their own entries either.
10162  */
10163  if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
10164  tuple_class->relkind != RELKIND_INDEX &&
10165  tuple_class->relkind != RELKIND_TOASTVALUE)
10167  newOwnerId);
10168 
10169  /*
10170  * Also change the ownership of the table's row type, if it has one
10171  */
10172  if (tuple_class->relkind != RELKIND_INDEX)
10173  AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId);
10174 
10175  /*
10176  * If we are operating on a table or materialized view, also change
10177  * the ownership of any indexes and sequences that belong to the
10178  * relation, as well as its toast table (if it has one).
10179  */
10180  if (tuple_class->relkind == RELKIND_RELATION ||
10181  tuple_class->relkind == RELKIND_MATVIEW ||
10182  tuple_class->relkind == RELKIND_TOASTVALUE)
10183  {
10184  List *index_oid_list;
10185  ListCell *i;
10186 
10187  /* Find all the indexes belonging to this relation */
10188  index_oid_list = RelationGetIndexList(target_rel);
10189 
10190  /* For each index, recursively change its ownership */
10191  foreach(i, index_oid_list)
10192  ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
10193 
10194  list_free(index_oid_list);
10195  }
10196 
10197  if (tuple_class->relkind == RELKIND_RELATION ||
10198  tuple_class->relkind == RELKIND_MATVIEW)
10199  {
10200  /* If it has a toast table, recurse to change its ownership */
10201  if (tuple_class->reltoastrelid != InvalidOid)
10202  ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
10203  true, lockmode);
10204 
10205  /* If it has dependent sequences, recurse to change them too */
10206  change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
10207  }
10208  }
10209 
10211 
10212  ReleaseSysCache(tuple);
10213  heap_close(class_rel, RowExclusiveLock);
10214  relation_close(target_rel, NoLock);
10215 }
#define Natts_pg_class
Definition: pg_class.h:102
int errhint(const char *fmt,...)
Definition: elog.c:987
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
#define Anum_pg_class_relacl
Definition: pg_class.h:133
bool sequenceIsOwned(Oid seqId, char deptype, Oid *tableId, int32 *colId)
Definition: pg_depend.c:500
#define RelationGetDescr(relation)
Definition: rel.h:437
Oid GetUserId(void)
Definition: miscinit.c:284
#define DatumGetAclP(X)
Definition: acl.h:121
#define PointerGetDatum(X)
Definition: postgres.h:562
#define RelationRelationId
Definition: pg_class.h:29
#define RELKIND_MATVIEW
Definition: pg_class.h:165
int errcode(int sqlerrcode)
Definition: elog.c:575
bool superuser(void)
Definition: superuser.c:47
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1266
void AlterTypeOwnerInternal(Oid typeOid, Oid newOwnerId)
Definition: typecmds.c:3450
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
unsigned int Oid
Definition: postgres_ext.h:31
AclResult pg_namespace_aclcheck(Oid nsp_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4542
#define RELKIND_COMPOSITE_TYPE
Definition: pg_class.h:166
signed int int32
Definition: c.h:284
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
Definition: pg_shdepend.c:304
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define ACL_CREATE
Definition: parsenodes.h:82
ItemPointerData t_self
Definition: htup.h:65
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3066
#define NoLock
Definition: lockdefs.h:34
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3457
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define RelationGetRelationName(relation)
Definition: rel.h:445
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
void check_is_member_of_role(Oid member, Oid role)
Definition: acl.c:4879
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
void ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
Definition: tablecmds.c:9993
#define WARNING
Definition: elog.h:40
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
#define RELKIND_TOASTVALUE
Definition: pg_class.h:163
AclResult
Definition: acl.h:178
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1368
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4604
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
static void change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
Definition: tablecmds.c:10289
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4360
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
static void change_owner_fix_column_acls(Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
Definition: tablecmds.c:10224
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define RELKIND_VIEW
Definition: pg_class.h:164
void list_free(List *list)
Definition: list.c:1133
int i
#define NameStr(name)
Definition: c.h:547
#define RELKIND_INDEX
Definition: pg_class.h:161
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1120
#define elog
Definition: elog.h:219
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:794
#define RELKIND_RELATION
Definition: pg_class.h:160
#define RELKIND_SEQUENCE
Definition: pg_class.h:162
Definition: pg_list.h:45
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1745
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition: acl.c:1052
#define lfirst_oid(lc)
Definition: pg_list.h:108
#define Anum_pg_class_relowner
Definition: pg_class.h:107

◆ check_of_type()

void check_of_type ( HeapTuple  typetuple)

Definition at line 5109 of file tablecmds.c.

References AccessShareLock, Assert, ereport, errcode(), errmsg(), ERROR, format_type_be(), GETSTRUCT, HeapTupleGetOid, NoLock, OidIsValid, RelationData::rd_rel, relation_close(), relation_open(), RELKIND_COMPOSITE_TYPE, and TYPTYPE_COMPOSITE.

Referenced by ATExecAddOf(), and transformOfType().

5110 {
5111  Form_pg_type typ = (Form_pg_type) GETSTRUCT(typetuple);
5112  bool typeOk = false;
5113 
5114  if (typ->typtype == TYPTYPE_COMPOSITE)
5115  {
5116  Relation typeRelation;
5117 
5118  Assert(OidIsValid(typ->typrelid));
5119  typeRelation = relation_open(typ->typrelid, AccessShareLock);
5120  typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
5121 
5122  /*
5123  * Close the parent rel, but keep our AccessShareLock on it until xact
5124  * commit. That will prevent someone else from deleting or ALTERing
5125  * the type before the typed table creation/conversion commits.
5126  */
5127  relation_close(typeRelation, NoLock);
5128  }
5129  if (!typeOk)
5130  ereport(ERROR,
5131  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5132  errmsg("type %s is not a composite type",
5133  format_type_be(HeapTupleGetOid(typetuple)))));
5134 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
#define TYPTYPE_COMPOSITE
Definition: pg_type.h:721
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:575
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1266
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
FormData_pg_type * Form_pg_type
Definition: pg_type.h:233
Form_pg_class rd_rel
Definition: rel.h:114
#define OidIsValid(objectId)
Definition: c.h:576
#define RELKIND_COMPOSITE_TYPE
Definition: pg_class.h:166
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
#define ereport(elevel, rest)
Definition: elog.h:122
#define Assert(condition)
Definition: c.h:670
int errmsg(const char *fmt,...)
Definition: elog.c:797
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1120
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:700

◆ CheckTableNotInUse()

void CheckTableNotInUse ( Relation  rel,
const char *  stmt 
)

Definition at line 3063 of file tablecmds.c.

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

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

3064 {
3065  int expected_refcnt;
3066 
3067  expected_refcnt = rel->rd_isnailed ? 2 : 1;
3068  if (rel->rd_refcnt != expected_refcnt)
3069  ereport(ERROR,
3070  (errcode(ERRCODE_OBJECT_IN_USE),
3071  /* translator: first %s is a SQL command, eg ALTER TABLE */
3072  errmsg("cannot %s \"%s\" because "
3073  "it is being used by active queries in this session",
3074  stmt, RelationGetRelationName(rel))));
3075 
3076  if (rel->rd_rel->relkind != RELKIND_INDEX &&
3078  ereport(ERROR,
3079  (errcode(ERRCODE_OBJECT_IN_USE),
3080  /* translator: first %s is a SQL command, eg ALTER TABLE */
3081  errmsg("cannot %s \"%s\" because "
3082  "it has pending trigger events",
3083  stmt, RelationGetRelationName(rel))));
3084 }
bool rd_isnailed
Definition: rel.h:91
int errcode(int sqlerrcode)
Definition: elog.c:575
Form_pg_class rd_rel
Definition: rel.h:114
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:445
#define ereport(elevel, rest)
Definition: elog.h:122
bool AfterTriggerPendingOnRel(Oid relid)
Definition: trigger.c:5360
int errmsg(const char *fmt,...)
Definition: elog.c:797
int rd_refcnt
Definition: rel.h:88
#define RELKIND_INDEX
Definition: pg_class.h:161
#define RelationGetRelid(relation)
Definition: rel.h:425

◆ DefineRelation()

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

Definition at line 505 of file tablecmds.c.

References AccessExclusiveLock, ACL_CREATE, ACL_KIND_TABLESPACE, ACL_USAGE, aclcheck_error(), aclcheck_error_type(), ACLCHECK_OK, AddRelationNewConstraints(), allowSystemTableMods, Assert, RawColumnDefault::attnum, CookedConstraint::attnum, BuildDescForRelation(), check_default_allows_bound(), check_new_partition_bound(), CommandCounterIncrement(), ComputePartitionAttrs(), CookedConstraint::conoid, CONSTR_DEFAULT, CreateStmt::constraints, CookedConstraint::contype, ColumnDef::cooked_default, elog, ereport, errcode(), errmsg(), ERROR, CookedConstraint::expr, get_default_oid_from_partdesc(), get_tablespace_name(), get_tablespace_oid(), GetDefaultTablespace(), GetUserId(), GLOBALTABLESPACE_OID, heap_close, heap_create_with_catalog(), heap_open(), HEAP_RELOPT_NAMESPACES, heap_reloptions(), ColumnDef::identity, CookedConstraint::inhcount, CreateStmt::inhRelations, InSecurityRestrictedOperation(), interpretOidsOption(), InvalidOid, PartitionBoundSpec::is_default, CookedConstraint::is_local, CookedConstraint::is_no_inherit, lappend(), lfirst, linitial_oid, list_concat(), list_length(), make_parsestate(), MergeAttributes(), MyDatabaseTableSpace, CookedConstraint::name, NAMEDATALEN, NIL, NoLock, 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(), RawColumnDefault::raw_default, ColumnDef::raw_default, RelationData::rd_rel, CreateStmt::relation, relation_close(), relation_open(), RelationGetPartitionDesc, RelationGetRelationName, RelationGetRelid, RelationRelationId, RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, RELKIND_VIEW, RangeVar::relname, RangeVar::relpersistence, RELPERSISTENCE_TEMP, CookedConstraint::skip_validation, StoreCatalogInheritance(), StorePartitionBound(), StorePartitionKey(), StrNCpy, CreateStmt::tableElts, CreateStmt::tablespacename, tupleDesc::tdhasoid, transformPartitionBound(), transformPartitionSpec(), transformRelOptions(), TupleDescAttr, typenameTypeId(), update_default_partition_oid(), and view_reloptions().

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

507 {
508  char relname[NAMEDATALEN];
509  Oid namespaceId;
510  Oid relationId;
511  Oid tablespaceId;
512  Relation rel;
514  List *inheritOids;
515  List *old_constraints;
516  bool localHasOids;
517  int parentOidCount;
518  List *rawDefaults;
519  List *cookedDefaults;
520  Datum reloptions;
521  ListCell *listptr;
522  AttrNumber attnum;
523  static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
524  Oid ofTypeId;
525  ObjectAddress address;
526 
527  /*
528  * Truncate relname to appropriate length (probably a waste of time, as
529  * parser should have done this already).
530  */
531  StrNCpy(relname, stmt->relation->relname, NAMEDATALEN);
532 
533  /*
534  * Check consistency of arguments
535  */
536  if (stmt->oncommit != ONCOMMIT_NOOP
538  ereport(ERROR,
539  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
540  errmsg("ON COMMIT can only be used on temporary tables")));
541 
542  if (stmt->partspec != NULL)
543  {
544  if (relkind != RELKIND_RELATION)
545  elog(ERROR, "unexpected relkind: %d", (int) relkind);
546 
547  relkind = RELKIND_PARTITIONED_TABLE;
548  }
549 
550  /*
551  * Look up the namespace in which we are supposed to create the relation,
552  * check we have permission to create there, lock it against concurrent
553  * drop, and mark stmt->relation as RELPERSISTENCE_TEMP if a temporary
554  * namespace is selected.
555  */
556  namespaceId =
558 
559  /*
560  * Security check: disallow creating temp tables from security-restricted
561  * code. This is needed because calling code might not expect untrusted
562  * tables to appear in pg_temp at the front of its search path.
563  */
566  ereport(ERROR,
567  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
568  errmsg("cannot create temporary table within security-restricted operation")));
569 
570  /*
571  * Select tablespace to use. If not specified, use default tablespace
572  * (which may in turn default to database's default).
573  */
574  if (stmt->tablespacename)
575  {
576  tablespaceId = get_tablespace_oid(stmt->tablespacename, false);
577  }
578  else
579  {
580  tablespaceId = GetDefaultTablespace(stmt->relation->relpersistence);
581  /* note InvalidOid is OK in this case */
582  }
583 
584  /* Check permissions except when using database's default */
585  if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
586  {
587  AclResult aclresult;
588 
589  aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
590  ACL_CREATE);
591  if (aclresult != ACLCHECK_OK)
593  get_tablespace_name(tablespaceId));
594  }
595 
596  /* In all cases disallow placing user relations in pg_global */
597  if (tablespaceId == GLOBALTABLESPACE_OID)
598  ereport(ERROR,
599  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
600  errmsg("only shared relations can be placed in pg_global tablespace")));
601 
602  /* Identify user ID that will own the table */
603  if (!OidIsValid(ownerId))
604  ownerId = GetUserId();
605 
606  /*
607  * Parse and validate reloptions, if any.
608  */
609  reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, validnsps,
610  true, false);
611 
612  if (relkind == RELKIND_VIEW)
613  (void) view_reloptions(reloptions, true);
614  else
615  (void) heap_reloptions(relkind, reloptions, true);
616 
617  if (stmt->ofTypename)
618  {
619  AclResult aclresult;
620 
621  ofTypeId = typenameTypeId(NULL, stmt->ofTypename);
622 
623  aclresult = pg_type_aclcheck(ofTypeId, GetUserId(), ACL_USAGE);
624  if (aclresult != ACLCHECK_OK)
625  aclcheck_error_type(aclresult, ofTypeId);
626  }
627  else
628  ofTypeId = InvalidOid;
629 
630  /*
631  * Look up inheritance ancestors and generate relation schema, including
632  * inherited attributes. (Note that stmt->tableElts is destructively
633  * modified by MergeAttributes.)
634  */
635  stmt->tableElts =
637  stmt->relation->relpersistence,
638  stmt->partbound != NULL,
639  &inheritOids, &old_constraints, &parentOidCount);
640 
641  /*
642  * Create a tuple descriptor from the relation schema. Note that this
643  * deals with column names, types, and NOT NULL constraints, but not
644  * default values or CHECK constraints; we handle those below.
645  */
646  descriptor = BuildDescForRelation(stmt->tableElts);
647 
648  /*
649  * Notice that we allow OIDs here only for plain tables and partitioned
650  * tables, even though some other relkinds can support them. This is
651  * necessary because the default_with_oids GUC must apply only to plain
652  * tables and not any other relkind; doing otherwise would break existing
653  * pg_dump files. We could allow explicit "WITH OIDS" while not allowing
654  * default_with_oids to affect other relkinds, but it would complicate
655  * interpretOidsOption().
656  */
657  localHasOids = interpretOidsOption(stmt->options,
658  (relkind == RELKIND_RELATION ||
659  relkind == RELKIND_PARTITIONED_TABLE));
660  descriptor->tdhasoid = (localHasOids || parentOidCount > 0);
661 
662  /*
663  * If a partitioned table doesn't have the system OID column, then none of
664  * its partitions should have it.
665  */
666  if (stmt->partbound && parentOidCount == 0 && localHasOids)
667  ereport(ERROR,
668  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
669  errmsg("cannot create table with OIDs as partition of table without OIDs")));
670 
671  /*
672  * Find columns with default values and prepare for insertion of the
673  * defaults. Pre-cooked (that is, inherited) defaults go into a list of
674  * CookedConstraint structs that we'll pass to heap_create_with_catalog,
675  * while raw defaults go into a list of RawColumnDefault structs that will
676  * be processed by AddRelationNewConstraints. (We can't deal with raw
677  * expressions until we can do transformExpr.)
678  *
679  * We can set the atthasdef flags now in the tuple descriptor; this just
680  * saves StoreAttrDefault from having to do an immediate update of the
681  * pg_attribute rows.
682  */
683  rawDefaults = NIL;
684  cookedDefaults = NIL;
685  attnum = 0;
686 
687  foreach(listptr, stmt->tableElts)
688  {
689  ColumnDef *colDef = lfirst(listptr);
690  Form_pg_attribute attr;
691 
692  attnum++;
693  attr = TupleDescAttr(descriptor, attnum - 1);
694 
695  if (colDef->raw_default != NULL)
696  {
697  RawColumnDefault *rawEnt;
698 
699  Assert(colDef->cooked_default == NULL);
700 
701  rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
702  rawEnt->attnum = attnum;
703  rawEnt->raw_default = colDef->raw_default;
704  rawDefaults = lappend(rawDefaults, rawEnt);
705  attr->atthasdef = true;
706  }
707  else if (colDef->cooked_default != NULL)
708  {
709  CookedConstraint *cooked;
710 
711  cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
712  cooked->contype = CONSTR_DEFAULT;
713  cooked->conoid = InvalidOid; /* until created */
714  cooked->name = NULL;
715  cooked->attnum = attnum;
716  cooked->expr = colDef->cooked_default;
717  cooked->skip_validation = false;
718  cooked->is_local = true; /* not used for defaults */
719  cooked->inhcount = 0; /* ditto */
720  cooked->is_no_inherit = false;
721  cookedDefaults = lappend(cookedDefaults, cooked);
722  attr->atthasdef = true;
723  }
724 
725  if (colDef->identity)
726  attr->attidentity = colDef->identity;
727  }
728 
729  /*
730  * Create the relation. Inherited defaults and constraints are passed in
731  * for immediate handling --- since they don't need parsing, they can be
732  * stored immediately.
733  */
734  relationId = heap_create_with_catalog(relname,
735  namespaceId,
736  tablespaceId,
737  InvalidOid,
738  InvalidOid,
739  ofTypeId,
740  ownerId,
741  descriptor,
742  list_concat(cookedDefaults,
743  old_constraints),
744  relkind,
745  stmt->relation->relpersistence,
746  false,
747  false,
748  localHasOids,
749  parentOidCount,
750  stmt->oncommit,
751  reloptions,
752  true,
754  false,
755  typaddress);
756 
757  /* Store inheritance information for new rel. */
758  StoreCatalogInheritance(relationId, inheritOids, stmt->partbound != NULL);
759 
760  /*
761  * We must bump the command counter to make the newly-created relation
762  * tuple visible for opening.
763  */
765 
766  /*
767  * Open the new relation and acquire exclusive lock on it. This isn't
768  * really necessary for locking out other backends (since they can't see
769  * the new rel anyway until we commit), but it keeps the lock manager from
770  * complaining about deadlock risks.
771  */
772  rel = relation_open(relationId, AccessExclusiveLock);
773 
774  /* Process and store partition bound, if any. */
775  if (stmt->partbound)
776  {
777  PartitionBoundSpec *bound;
778  ParseState *pstate;
779  Oid parentId = linitial_oid(inheritOids),
780  defaultPartOid;
781  Relation parent,
782  defaultRel = NULL;
783 
784  /* Already have strong enough lock on the parent */
785  parent = heap_open(parentId, NoLock);
786 
787  /*
788  * We are going to try to validate the partition bound specification
789  * against the partition key of parentRel, so it better have one.
790  */
791  if (parent->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
792  ereport(ERROR,
793  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
794  errmsg("\"%s\" is not partitioned",
795  RelationGetRelationName(parent))));
796 
797  /*
798  * The partition constraint of the default partition depends on the
799  * partition bounds of every other partition. It is possible that
800  * another backend might be about to execute a query on the default
801  * partition table, and that the query relies on previously cached
802  * default partition constraints. We must therefore take a table lock
803  * strong enough to prevent all queries on the default partition from
804  * proceeding until we commit and send out a shared-cache-inval notice
805  * that will make them update their index lists.
806  *
807  * Order of locking: The relation being added won't be visible to
808  * other backends until it is committed, hence here in
809  * DefineRelation() the order of locking the default partition and the
810  * relation being added does not matter. But at all other places we
811  * need to lock the default relation before we lock the relation being
812  * added or removed i.e. we should take the lock in same order at all
813  * the places such that lock parent, lock default partition and then
814  * lock the partition so as to avoid a deadlock.
815  */
816  defaultPartOid =
818  if (OidIsValid(defaultPartOid))
819  defaultRel = heap_open(defaultPartOid, AccessExclusiveLock);
820 
821  /* Tranform the bound values */
822  pstate = make_parsestate(NULL);
823  pstate->p_sourcetext = queryString;
824 
825  bound = transformPartitionBound(pstate, parent, stmt->partbound);
826 
827  /*
828  * Check first that the new partition's bound is valid and does not
829  * overlap with any of existing partitions of the parent.
830  */
831  check_new_partition_bound(relname, parent, bound);
832 
833  /*
834  * If the default partition exists, its partition constraints will
835  * change after the addition of this new partition such that it won't
836  * allow any row that qualifies for this new partition. So, check that
837  * the existing data in the default partition satisfies the constraint
838  * as it will exist after adding this partition.
839  */
840  if (OidIsValid(defaultPartOid))
841  {
842  check_default_allows_bound(parent, defaultRel, bound);
843  /* Keep the lock until commit. */
844  heap_close(defaultRel, NoLock);
845  }
846 
847  /* Update the pg_class entry. */
848  StorePartitionBound(rel, parent, bound);
849 
850  /* Update the default partition oid */
851  if (bound->is_default)
852  update_default_partition_oid(RelationGetRelid(parent), relationId);
853 
854  heap_close(parent, NoLock);
855 
856  /*
857  * The code that follows may also update the pg_class tuple to update
858  * relnumchecks, so bump up the command counter to avoid the "already
859  * updated by self" error.
860  */
862  }
863 
864  /*
865  * Process the partitioning specification (if any) and store the partition
866  * key information into the catalog.
867  */
868  if (stmt->partspec)
869  {
870  char strategy;
871  int partnatts;
872  AttrNumber partattrs[PARTITION_MAX_KEYS];
873  Oid partopclass[PARTITION_MAX_KEYS];
874  Oid partcollation[PARTITION_MAX_KEYS];
875  List *partexprs = NIL;
876 
877  partnatts = list_length(stmt->partspec->partParams);
878 
879  /* Protect fixed-size arrays here and in executor */
880  if (partnatts > PARTITION_MAX_KEYS)
881  ereport(ERROR,
882  (errcode(ERRCODE_TOO_MANY_COLUMNS),
883  errmsg("cannot partition using more than %d columns",
885 
886  /*
887  * We need to transform the raw parsetrees corresponding to partition
888  * expressions into executable expression trees. Like column defaults
889  * and CHECK constraints, we could not have done the transformation
890  * earlier.
891  */
892  stmt->partspec = transformPartitionSpec(rel, stmt->partspec,
893  &strategy);
894 
896  partattrs, &partexprs, partopclass,
897  partcollation, strategy);
898 
899  StorePartitionKey(rel, strategy, partnatts, partattrs, partexprs,
900  partopclass, partcollation);
901  }
902 
903  /*
904  * Now add any newly specified column default values and CHECK constraints
905  * to the new relation. These are passed to us in the form of raw
906  * parsetrees; we need to transform them to executable expression trees
907  * before they can be added. The most convenient way to do that is to
908  * apply the parser's transformExpr routine, but transformExpr doesn't
909  * work unless we have a pre-existing relation. So, the transformation has
910  * to be postponed to this final step of CREATE TABLE.
911  */
912  if (rawDefaults || stmt->constraints)
913  AddRelationNewConstraints(rel, rawDefaults, stmt->constraints,
914  true, true, false);
915 
916  ObjectAddressSet(address, RelationRelationId, relationId);
917 
918  /*
919  * Clean up. We keep lock on new relation (although it shouldn't be
920  * visible to anyone else anyway, until commit).
921  */
922  relation_close(rel, NoLock);
923 
924  return address;
925 }
RangeVar * relation
Definition: parsenodes.h:2014
bytea * heap_reloptions(char relkind, Datum reloptions, bool validate)
Definition: reloptions.c:1421
#define NIL
Definition: pg_list.h:69
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1380
OnCommitAction oncommit
Definition: parsenodes.h:2023
List * inhRelations
Definition: parsenodes.h:2016
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4554
bool is_no_inherit
Definition: heap.h:38
bool tdhasoid
Definition: tupdesc.h:82
void StorePartitionKey(Relation rel, char strategy, int16 partnatts, AttrNumber *partattrs, List *partexprs, Oid *partopclass, Oid *partcollation)
Definition: heap.c:3114
AttrNumber attnum
Definition: heap.h:24
List * partParams
Definition: parsenodes.h:782
Oid GetUserId(void)
Definition: miscinit.c:284
char identity
Definition: parsenodes.h:649
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:90
#define RelationRelationId
Definition: pg_class.h:29
void update_default_partition_oid(Oid parentId, Oid defaultPartId)
Definition: partition.c:2953
#define GLOBALTABLESPACE_OID
Definition: pg_tablespace.h:64
int errcode(int sqlerrcode)
Definition: elog.c:575
#define PARTITION_MAX_KEYS
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1266
List * list_concat(List *list1, List *list2)
Definition: list.c:321
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
static void ComputePartitionAttrs(Relation rel, List *partParams, AttrNumber *partattrs, List **partexprs, Oid *partopclass, Oid *partcollation, char strategy)
Definition: tablecmds.c:13414
#define OidIsValid(objectId)
Definition: c.h:576
void check_default_allows_bound(Relation parent, Relation default_rel, PartitionBoundSpec *new_spec)
Definition: partition.c:1211
static void StoreCatalogInheritance(Oid relationId, List *supers, bool child_is_partition)
Definition: tablecmds.c:2352
void check_new_partition_bound(char *relname, Relation parent, PartitionBoundSpec *spec)
Definition: partition.c:938
Datum transformRelOptions(Datum oldOptions, List *defList, const char *namspace, char *validnsps[], bool ignoreOids, bool isReset)
Definition: reloptions.c:755
Oid GetDefaultTablespace(char relpersistence)
Definition: tablespace.c:1111
static PartitionSpec * transformPartitionSpec(Relation rel, PartitionSpec *partspec, char *strategy)
Definition: tablecmds.c:13329
void aclcheck_error_type(AclResult aclerr, Oid typeOid)
Definition: aclchk.c:3515
Oid MyDatabaseTableSpace
Definition: globals.c:79
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
bytea * view_reloptions(Datum reloptions, bool validate)
Definition: reloptions.c:1389
List * constraints
Definition: parsenodes.h:2021
PartitionBoundSpec * transformPartitionBound(ParseState *pstate, Relation parent, PartitionBoundSpec *spec)
#define NAMEDATALEN
PartitionBoundSpec * partbound
Definition: parsenodes.h:2018
Node * cooked_default
Definition: parsenodes.h:648
char * relname
Definition: primnodes.h:68
AttrNumber attnum
Definition: heap.h:33
#define ERROR
Definition: elog.h:43
#define ACL_CREATE
Definition: parsenodes.h:82
int inhcount
Definition: heap.h:37
#define NoLock
Definition: lockdefs.h:34
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3457
#define RelationGetRelationName(relation)
Definition: rel.h:445
List * options
Definition: parsenodes.h:2022
Node * raw_default
Definition: heap.h:25
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
#define ACL_USAGE
Definition: parsenodes.h:80
bool skip_validation
Definition: heap.h:35
#define HEAP_RELOPT_NAMESPACES
Definition: reloptions.h:59
const char * p_sourcetext
Definition: parse_node.h:172
ConstrType contype
Definition: heap.h:30
#define ereport(elevel, rest)
Definition: elog.h:122
Node * raw_default
Definition: parsenodes.h:647
List * lappend(List *list, void *datum)
Definition: list.c:128
char * tablespacename
Definition: parsenodes.h:2024
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:508
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
AclResult
Definition: acl.h:178
uintptr_t Datum
Definition: postgres.h:372
void CommandCounterIncrement(void)
Definition: xact.c:915
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
bool allowSystemTableMods
Definition: globals.c:112
#define InvalidOid
Definition: postgres_ext.h:36
void StorePartitionBound(Relation rel, Relation parent, PartitionBoundSpec *bound)
Definition: heap.c:3254
List * tableElts
Definition: parsenodes.h:2015
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
#define StrNCpy(dst, src, len)
Definition: c.h:826
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:416
#define linitial_oid(l)
Definition: pg_list.h:113
static int list_length(const List *l)
Definition: pg_list.h:89
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
char relpersistence
Definition: primnodes.h:71
bool interpretOidsOption(List *defList, bool allowOids)
Definition: parse_clause.c:255
static List * MergeAttributes(List *schema, List *supers, char relpersistence, bool is_partition, List **supOids, List **supconstr, int *supOidCount)
Definition: tablecmds.c:1673
#define AccessExclusiveLock
Definition: lockdefs.h:45
void * palloc(Size size)
Definition: mcxt.c:848
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1426
#define RELKIND_VIEW
Definition: pg_class.h:164
Oid heap_create_with_catalog(const char *relname, Oid relnamespace, Oid reltablespace, Oid relid, Oid reltypeid, Oid reloftypeid, Oid ownerid, TupleDesc tupdesc, List *cooked_constraints, char relkind, char relpersistence, bool shared_relation, bool mapped_relation, bool oidislocal, int oidinhcount, OnCommitAction oncommit, Datum reloptions, bool use_user_acl, bool allow_system_table_mods, bool is_internal, ObjectAddress *typaddress)
Definition: heap.c:1021
Oid conoid
Definition: heap.h:31
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1120
Node * expr
Definition: heap.h:34
#define elog
Definition: elog.h:219
TupleDesc BuildDescForRelation(List *schema)
Definition: tupdesc.c:689
#define RELPERSISTENCE_TEMP
Definition: pg_class.h:172
AclResult pg_type_aclcheck(Oid type_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4592
#define RELKIND_RELATION
Definition: pg_class.h:160
PartitionSpec * partspec
Definition: parsenodes.h:2019
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
char * name
Definition: heap.h:32
#define RelationGetRelid(relation)
Definition: rel.h:425
Oid get_default_oid_from_partdesc(PartitionDesc partdesc)
Definition: partition.c:2911
List * AddRelationNewConstraints(Relation rel, List *newColDefaults, List *newConstraints, bool allow_merge, bool is_local, bool is_internal)
Definition: heap.c:2229
TypeName * ofTypename
Definition: parsenodes.h:2020
#define RelationGetPartitionDesc(relation)
Definition: rel.h:641
bool is_local
Definition: heap.h:36
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:274

◆ ExecuteTruncate()

void ExecuteTruncate ( TruncateStmt stmt)

Definition at line 1248 of file tablecmds.c.

References AccessExclusiveLock, ACL_KIND_CLASS, aclcheck_error(), ACLCHECK_NOT_OWNER, AfterTriggerBeginQuery(), AfterTriggerEndQuery(), TruncateStmt::behavior, CheckTableForSerializableConflictIn(), CreateExecutorState(), DROP_CASCADE, DROP_RESTRICT, ereport, errcode(), errhint(), errmsg(), ERROR, EState::es_num_result_relations, EState::es_result_relation_info, EState::es_result_relations, ExecASTruncateTriggers(), ExecBSTruncateTriggers(), find_all_inheritors(), FreeExecutorState(), GetCurrentSubTransactionId(), GetOldestMultiXactId(), getOwnedSequences(), GetUserId(), heap_close, heap_create_init_fork(), heap_open(), heap_openrv(), heap_truncate_check_FKs(), heap_truncate_find_FKs(), heap_truncate_one_rel(), RangeVar::inh, InitResultRelInfo(), lappend(), lappend_oid(), lfirst, lfirst_oid, list_length(), list_member_oid(), NIL, NoLock, NOTICE, OidIsValid, palloc(), pg_class_ownercheck(), pgstat_count_truncate(), RelationData::rd_createSubid, RelationData::rd_newRelfilenodeSubid, RelationData::rd_rel, RecentXmin, REINDEX_REL_PROCESS_TOAST, reindex_relation(), relation_close(), relation_open(), RelationGetRelationName, RelationGetRelid, TruncateStmt::relations, RelationSetNewRelfilenode(), OnCommitItem::relid, RELKIND_PARTITIONED_TABLE, RELPERSISTENCE_UNLOGGED, ResetSequence(), TruncateStmt::restart_seqs, and truncate_check_rel().

Referenced by standard_ProcessUtility().

1249 {
1250  List *rels = NIL;
1251  List *relids = NIL;
1252  List *seq_relids = NIL;
1253  EState *estate;
1254  ResultRelInfo *resultRelInfos;
1255  ResultRelInfo *resultRelInfo;
1256  SubTransactionId mySubid;
1257  ListCell *cell;
1258 
1259  /*
1260  * Open, exclusive-lock, and check all the explicitly-specified relations
1261  */
1262  foreach(cell, stmt->relations)
1263  {
1264  RangeVar *rv = lfirst(cell);
1265  Relation rel;
1266  bool recurse = rv->inh;
1267  Oid myrelid;
1268 
1269  rel = heap_openrv(rv, AccessExclusiveLock);
1270  myrelid = RelationGetRelid(rel);
1271  /* don't throw error for "TRUNCATE foo, foo" */
1272  if (list_member_oid(relids, myrelid))
1273  {
1275  continue;
1276  }
1277  truncate_check_rel(rel);
1278  rels = lappend(rels, rel);
1279  relids = lappend_oid(relids, myrelid);
1280 
1281  if (recurse)
1282  {
1283  ListCell *child;
1284  List *children;
1285 
1286  children = find_all_inheritors(myrelid, AccessExclusiveLock, NULL);
1287 
1288  foreach(child, children)
1289  {
1290  Oid childrelid = lfirst_oid(child);
1291 
1292  if (list_member_oid(relids, childrelid))
1293  continue;
1294 
1295  /* find_all_inheritors already got lock */
1296  rel = heap_open(childrelid, NoLock);
1297  truncate_check_rel(rel);
1298  rels = lappend(rels, rel);
1299  relids = lappend_oid(relids, childrelid);
1300  }
1301  }
1302  else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1303  ereport(ERROR,
1304  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1305  errmsg("cannot truncate only a partitioned table"),
1306  errhint("Do not specify the ONLY keyword, or use truncate only on the partitions directly.")));
1307  }
1308 
1309  /*
1310  * In CASCADE mode, suck in all referencing relations as well. This
1311  * requires multiple iterations to find indirectly-dependent relations. At
1312  * each phase, we need to exclusive-lock new rels before looking for their
1313  * dependencies, else we might miss something. Also, we check each rel as
1314  * soon as we open it, to avoid a faux pas such as holding lock for a long
1315  * time on a rel we have no permissions for.
1316  */
1317  if (stmt->behavior == DROP_CASCADE)
1318  {
1319  for (;;)
1320  {
1321  List *newrelids;
1322 
1323  newrelids = heap_truncate_find_FKs(relids);
1324  if (newrelids == NIL)
1325  break; /* nothing else to add */
1326 
1327  foreach(cell, newrelids)
1328  {
1329  Oid relid = lfirst_oid(cell);
1330  Relation rel;
1331 
1332  rel = heap_open(relid, AccessExclusiveLock);
1333  ereport(NOTICE,
1334  (errmsg("truncate cascades to table \"%s\"",
1335  RelationGetRelationName(rel))));
1336  truncate_check_rel(rel);
1337  rels = lappend(rels, rel);
1338  relids = lappend_oid(relids, relid);
1339  }
1340  }
1341  }
1342 
1343  /*
1344  * Check foreign key references. In CASCADE mode, this should be
1345  * unnecessary since we just pulled in all the references; but as a
1346  * cross-check, do it anyway if in an Assert-enabled build.
1347  */
1348 #ifdef USE_ASSERT_CHECKING
1349  heap_truncate_check_FKs(rels, false);
1350 #else
1351  if (stmt->behavior == DROP_RESTRICT)
1352  heap_truncate_check_FKs(rels, false);
1353 #endif
1354 
1355  /*
1356  * If we are asked to restart sequences, find all the sequences, lock them
1357  * (we need AccessExclusiveLock for ResetSequence), and check permissions.
1358  * We want to do this early since it's pointless to do all the truncation
1359  * work only to fail on sequence permissions.
1360  */
1361  if (stmt->restart_seqs)
1362  {
1363  foreach(cell, rels)
1364  {
1365  Relation rel = (Relation) lfirst(cell);
1366  List *seqlist = getOwnedSequences(RelationGetRelid(rel), 0);
1367  ListCell *seqcell;
1368 
1369  foreach(seqcell, seqlist)
1370  {
1371  Oid seq_relid = lfirst_oid(seqcell);
1372  Relation seq_rel;
1373 
1374  seq_rel = relation_open(seq_relid, AccessExclusiveLock);
1375 
1376  /* This check must match AlterSequence! */
1377  if (!pg_class_ownercheck(seq_relid, GetUserId()))
1379  RelationGetRelationName(seq_rel));
1380 
1381  seq_relids = lappend_oid(seq_relids, seq_relid);
1382 
1383  relation_close(seq_rel, NoLock);
1384  }
1385  }
1386  }
1387 
1388  /* Prepare to catch AFTER triggers. */
1390 
1391  /*
1392  * To fire triggers, we'll need an EState as well as a ResultRelInfo for
1393  * each relation. We don't need to call ExecOpenIndices, though.
1394  */
1395  estate = CreateExecutorState();
1396  resultRelInfos = (ResultRelInfo *)
1397  palloc(list_length(rels) * sizeof(ResultRelInfo));
1398  resultRelInfo = resultRelInfos;
1399  foreach(cell, rels)
1400  {
1401  Relation rel = (Relation) lfirst(cell);
1402 
1403  InitResultRelInfo(resultRelInfo,
1404  rel,
1405  0, /* dummy rangetable index */
1406  NULL,
1407  0);
1408  resultRelInfo++;
1409  }
1410  estate->es_result_relations = resultRelInfos;
1411  estate->es_num_result_relations = list_length(rels);
1412 
1413  /*
1414  * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
1415  * truncating (this is because one of them might throw an error). Also, if
1416  * we were to allow them to prevent statement execution, that would need
1417  * to be handled here.
1418  */
1419  resultRelInfo = resultRelInfos;
1420  foreach(cell, rels)
1421  {
1422  estate->es_result_relation_info = resultRelInfo;
1423  ExecBSTruncateTriggers(estate, resultRelInfo);
1424  resultRelInfo++;
1425  }
1426 
1427  /*
1428  * OK, truncate each table.
1429  */
1430  mySubid = GetCurrentSubTransactionId();
1431 
1432  foreach(cell, rels)
1433  {
1434  Relation rel = (Relation) lfirst(cell);
1435 
1436  /* Skip partitioned tables as there is nothing to do */
1437  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1438  continue;
1439 
1440  /*
1441  * Normally, we need a transaction-safe truncation here. However, if
1442  * the table was either created in the current (sub)transaction or has
1443  * a new relfilenode in the current (sub)transaction, then we can just
1444  * truncate it in-place, because a rollback would cause the whole
1445  * table or the current physical file to be thrown away anyway.
1446  */
1447  if (rel->rd_createSubid == mySubid ||
1448  rel->rd_newRelfilenodeSubid == mySubid)
1449  {
1450  /* Immediate, non-rollbackable truncation is OK */
1451  heap_truncate_one_rel(rel);
1452  }
1453  else
1454  {
1455  Oid heap_relid;
1456  Oid toast_relid;
1457  MultiXactId minmulti;
1458 
1459  /*
1460  * This effectively deletes all rows in the table, and may be done
1461  * in a serializable transaction. In that case we must record a
1462  * rw-conflict in to this transaction from each transaction
1463  * holding a predicate lock on the table.
1464  */
1466 
1467  minmulti = GetOldestMultiXactId();
1468 
1469  /*
1470  * Need the full transaction-safe pushups.
1471  *
1472  * Create a new empty storage file for the relation, and assign it
1473  * as the relfilenode value. The old storage file is scheduled for
1474  * deletion at commit.
1475  */
1476  RelationSetNewRelfilenode(rel, rel->rd_rel->relpersistence,
1477  RecentXmin, minmulti);
1478  if (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED)
1479  heap_create_init_fork(rel);
1480 
1481  heap_relid = RelationGetRelid(rel);
1482  toast_relid = rel->rd_rel->reltoastrelid;
1483 
1484  /*
1485  * The same for the toast table, if any.
1486  */
1487  if (OidIsValid(toast_relid))
1488  {
1489  rel = relation_open(toast_relid, AccessExclusiveLock);
1490  RelationSetNewRelfilenode(rel, rel->rd_rel->relpersistence,
1491  RecentXmin, minmulti);
1492  if (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED)
1493  heap_create_init_fork(rel);
1494  heap_close(rel, NoLock);
1495  }
1496 
1497  /*
1498  * Reconstruct the indexes to match, and we're done.
1499  */
1501  }
1502 
1503  pgstat_count_truncate(rel);
1504  }
1505 
1506  /*
1507  * Restart owned sequences if we were asked to.
1508  */
1509  foreach(cell, seq_relids)
1510  {
1511  Oid seq_relid = lfirst_oid(cell);
1512 
1513  ResetSequence(seq_relid);
1514  }
1515 
1516  /*
1517  * Process all AFTER STATEMENT TRUNCATE triggers.
1518  */
1519  resultRelInfo = resultRelInfos;
1520  foreach(cell, rels)
1521  {
1522  estate->es_result_relation_info = resultRelInfo;
1523  ExecASTruncateTriggers(estate, resultRelInfo);
1524  resultRelInfo++;
1525  }
1526 
1527  /* Handle queued AFTER triggers */
1528  AfterTriggerEndQuery(estate);
1529 
1530  /* We can clean up the EState now */
1531  FreeExecutorState(estate);
1532 
1533  /* And close the rels (can't do this while EState still holds refs) */
1534  foreach(cell, rels)
1535  {
1536  Relation rel = (Relation) lfirst(cell);
1537 
1538  heap_close(rel, NoLock);
1539  }
1540 }
#define NIL
Definition: pg_list.h:69
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, Relation partition_root, int instrument_options)
Definition: execMain.c:1306
void RelationSetNewRelfilenode(Relation relation, char persistence, TransactionId freezeXid, MultiXactId minmulti)
Definition: relcache.c:3430
int errhint(const char *fmt,...)
Definition: elog.c:987
#define RELPERSISTENCE_UNLOGGED
Definition: pg_class.h:171
Oid GetUserId(void)
Definition: miscinit.c:284
void heap_truncate_one_rel(Relation rel)
Definition: heap.c:2901
int errcode(int sqlerrcode)
Definition: elog.c:575
TransactionId RecentXmin
Definition: snapmgr.c:165
void heap_truncate_check_FKs(List *relations, bool tempTables)
Definition: heap.c:2938
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1266
SubTransactionId rd_newRelfilenodeSubid
Definition: rel.h:111
uint32 SubTransactionId
Definition: c.h:449
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
#define OidIsValid(objectId)
Definition: c.h:576
void FreeExecutorState(EState *estate)
Definition: execUtils.c:186
DropBehavior behavior
Definition: parsenodes.h:2605
struct RelationData * Relation
Definition: relcache.h:26
void ExecBSTruncateTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:2944
#define ERROR
Definition: elog.h:43
struct ResultRelInfo ResultRelInfo
List * relations
Definition: parsenodes.h:2603
#define NoLock
Definition: lockdefs.h:34
void heap_create_init_fork(Relation rel)
Definition: heap.c:1382
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3457
ResultRelInfo * es_result_relations
Definition: execnodes.h:442
bool restart_seqs
Definition: parsenodes.h:2604
void ExecASTruncateTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:2996
#define RelationGetRelationName(relation)
Definition: rel.h:445
void pgstat_count_truncate(Relation rel)
Definition: pgstat.c:2008
#define ereport(elevel, rest)
Definition: elog.h:122
EState * CreateExecutorState(void)
Definition: execUtils.c:81
bool inh
Definition: primnodes.h:69
List * lappend(List *list, void *datum)
Definition: list.c:128
SubTransactionId rd_createSubid
Definition: rel.h:110
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
MultiXactId GetOldestMultiXactId(void)
Definition: multixact.c:2491
List * getOwnedSequences(Oid relid, AttrNumber attnum)
Definition: pg_depend.c:548
static void truncate_check_rel(Relation rel)
Definition: tablecmds.c:1546
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
int es_num_result_relations
Definition: execnodes.h:443
Relation heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1318
#define NOTICE
Definition: elog.h:37
void AfterTriggerBeginQuery(void)
Definition: trigger.c:4526
TransactionId MultiXactId
Definition: c.h:455
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:505
#define lfirst(lc)
Definition: pg_list.h:106
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:642
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4604
static int list_length(const List *l)
Definition: pg_list.h:89
void CheckTableForSerializableConflictIn(Relation relation)
Definition: predicate.c:4410
#define AccessExclusiveLock
Definition: lockdefs.h:45
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:167
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:4546
void * palloc(Size size)
Definition: mcxt.c:848
int errmsg(const char *fmt,...)
Definition: elog.c:797
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1120
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:125
void ResetSequence(Oid seq_relid)
Definition: sequence.c:269
bool reindex_relation(Oid relid, int flags, int options)
Definition: index.c:3518
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:425
List * heap_truncate_find_FKs(List *relationIds)
Definition: heap.c:3030
#define lfirst_oid(lc)
Definition: pg_list.h:108
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:444

◆ find_composite_type_dependencies()

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

Definition at line 4944 of file tablecmds.c.

References AccessShareLock, Anum_pg_depend_refclassid, Anum_pg_depend_refobjid, BTEqualStrategyNumber, check_stack_depth(), DependReferenceIndexId, DependRelationId, ereport, errcode(), errmsg(), ERROR, find_composite_type_dependencies(), GETSTRUCT, heap_open(), HeapTupleIsValid, NameStr, ObjectIdGetDatum, OidIsValid, RelationData::rd_att, RelationData::rd_rel, relation_close(), relation_open(), RelationGetRelationName, RelationRelationId, RELKIND_COMPOSITE_TYPE, RELKIND_FOREIGN_TABLE, RELKIND_MATVIEW, RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), TupleDescAttr, and TypeRelationId.

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

4946 {
4947  Relation depRel;
4948  ScanKeyData key[2];
4949  SysScanDesc depScan;
4950  HeapTuple depTup;
4951 
4952  /* since this function recurses, it could be driven to stack overflow */
4954 
4955  /*
4956  * We scan pg_depend to find those things that depend on the given type.
4957  * (We assume we can ignore refobjsubid for a type.)
4958  */
4960 
4961  ScanKeyInit(&key[0],
4963  BTEqualStrategyNumber, F_OIDEQ,
4965  ScanKeyInit(&key[1],
4967  BTEqualStrategyNumber, F_OIDEQ,
4968  ObjectIdGetDatum(typeOid));
4969 
4970  depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
4971  NULL, 2, key);
4972 
4973  while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
4974  {
4975  Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
4976  Relation rel;
4977  Form_pg_attribute att;
4978 
4979  /* Check for directly dependent types */
4980  if (pg_depend->classid == TypeRelationId)
4981  {
4982  /*
4983  * This must be an array, domain, or range containing the given
4984  * type, so recursively check for uses of this type. Note that
4985  * any error message will mention the original type not the
4986  * container; this is intentional.
4987  */
4988  find_composite_type_dependencies(pg_depend->objid,
4989  origRelation, origTypeName);
4990  continue;
4991  }
4992 
4993  /* Else, ignore dependees that aren't user columns of relations */
4994  /* (we assume system columns are never of interesting types) */
4995  if (pg_depend->classid != RelationRelationId ||
4996  pg_depend->objsubid <= 0)
4997  continue;
4998 
4999  rel = relation_open(pg_depend->objid, AccessShareLock);
5000  att = TupleDescAttr(rel->rd_att, pg_depend->objsubid - 1);
5001 
5002  if (rel->rd_rel->relkind == RELKIND_RELATION ||
5003  rel->rd_rel->relkind == RELKIND_MATVIEW ||
5004  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
5005  {
5006  if (origTypeName)
5007  ereport(ERROR,
5008  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5009  errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
5010  origTypeName,
5012  NameStr(att->attname))));
5013  else if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
5014  ereport(ERROR,
5015  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5016  errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
5017  RelationGetRelationName(origRelation),
5019  NameStr(att->attname))));
5020  else if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
5021  ereport(ERROR,
5022  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5023  errmsg("cannot alter foreign table \"%s\" because column \"%s.%s\" uses its row type",
5024  RelationGetRelationName(origRelation),
5026  NameStr(att->attname))));
5027  else
5028  ereport(ERROR,
5029  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5030  errmsg("cannot alter table \"%s\" because column \"%s.%s\" uses its row type",
5031  RelationGetRelationName(origRelation),
5033  NameStr(att->attname))));
5034  }
5035  else if (OidIsValid(rel->rd_rel->reltype))
5036  {
5037  /*
5038  * A view or composite type itself isn't a problem, but we must
5039  * recursively check for indirect dependencies via its rowtype.
5040  */
5042  origRelation, origTypeName);
5043  }
5044 
5046  }
5047 
5048  systable_endscan(depScan);
5049 
5051 }
#define Anum_pg_depend_refobjid
Definition: pg_depend.h:72
#define Anum_pg_depend_refclassid
Definition: pg_depend.h:71
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:499
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:90
#define RelationRelationId
Definition: pg_class.h:29
#define DependReferenceIndexId
Definition: indexing.h:147
void find_composite_type_dependencies(Oid typeOid, Relation origRelation, const char *origTypeName)
Definition: tablecmds.c:4944
#define DependRelationId
Definition: pg_depend.h:29
#define RELKIND_MATVIEW
Definition: pg_class.h:165
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:575
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1266
Form_pg_class rd_rel
Definition: rel.h:114
#define TypeRelationId
Definition: pg_type.h:34
#define OidIsValid(objectId)
Definition: c.h:576
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:328
#define RELKIND_COMPOSITE_TYPE
Definition: pg_class.h:166
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:416
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
void check_stack_depth(void)
Definition: postgres.c:3150
#define RelationGetRelationName(relation)
Definition: rel.h:445
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
FormData_pg_depend * Form_pg_depend
Definition: pg_depend.h:61
#define ereport(elevel, rest)
Definition: elog.h:122
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
TupleDesc rd_att
Definition: rel.h:115
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:547
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1120
#define RELKIND_RELATION
Definition: pg_class.h:160
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ PartConstraintImpliedByRelConstraint()

bool PartConstraintImpliedByRelConstraint ( Relation  scanrel,
List partConstraint 
)

Definition at line 13628 of file tablecmds.c.

References NullTest::arg, NullTest::argisrow, canonicalize_qual(), constrCheck::ccbin, constrCheck::ccvalid, tupleConstr::check, eval_const_expressions(), tupleConstr::has_not_null, i, IS_NOT_NULL, lappend(), list_concat(), list_make1, NullTest::location, make_ands_explicit(), make_ands_implicit(), makeNode, makeVar(), tupleDesc::natts, NIL, NullTest::nulltesttype, tupleConstr::num_check, predicate_implied_by(), RelationData::rd_att, RelationGetDescr, stringToNode(), and TupleDescAttr.

Referenced by check_default_allows_bound(), and ValidatePartitionConstraints().

13630 {
13631  List *existConstraint = NIL;
13632  TupleConstr *constr = RelationGetDescr(scanrel)->constr;
13633  int num_check,
13634  i;
13635 
13636  if (constr && constr->has_not_null)
13637  {
13638  int natts = scanrel->rd_att->natts;
13639 
13640  for (i = 1; i <= natts; i++)
13641  {
13642  Form_pg_attribute att = TupleDescAttr(scanrel->rd_att, i - 1);
13643 
13644  if (att->attnotnull && !att->attisdropped)
13645  {
13646  NullTest *ntest = makeNode(NullTest);
13647 
13648  ntest->arg = (Expr *) makeVar(1,
13649  i,
13650  att->atttypid,
13651  att->atttypmod,
13652  att->attcollation,
13653  0);
13654  ntest->nulltesttype = IS_NOT_NULL;
13655 
13656  /*
13657  * argisrow=false is correct even for a composite column,
13658  * because attnotnull does not represent a SQL-spec IS NOT
13659  * NULL test in such a case, just IS DISTINCT FROM NULL.
13660  */
13661  ntest->argisrow = false;
13662  ntest->location = -1;
13663  existConstraint = lappend(existConstraint, ntest);
13664  }
13665  }
13666  }
13667 
13668  num_check = (constr != NULL) ? constr->num_check : 0;
13669  for (i = 0; i < num_check; i++)
13670  {
13671  Node *cexpr;
13672 
13673  /*
13674  * If this constraint hasn't been fully validated yet, we must ignore
13675  * it here.
13676  */
13677  if (!constr->check[i].ccvalid)
13678  continue;
13679 
13680  cexpr = stringToNode(constr->check[i].ccbin);
13681 
13682  /*
13683  * Run each expression through const-simplification and
13684  * canonicalization. It is necessary, because we will be comparing it
13685  * to similarly-processed partition constraint expressions, and may
13686  * fail to detect valid matches without this.
13687  */
13688  cexpr = eval_const_expressions(NULL, cexpr);
13689  cexpr = (Node *) canonicalize_qual((Expr *) cexpr);
13690 
13691  existConstraint = list_concat(existConstraint,
13692  make_ands_implicit((Expr *) cexpr));
13693  }
13694 
13695  if (existConstraint != NIL)
13696  existConstraint = list_make1(make_ands_explicit(existConstraint));
13697 
13698  /* And away we go ... */
13699  return predicate_implied_by(partConstraint, existConstraint, true);
13700 }
#define NIL
Definition: pg_list.h:69
bool predicate_implied_by(List *predicate_list, List *clause_list, bool clause_is_check)
Definition: predtest.c:135
void * stringToNode(char *str)
Definition: read.c:38
#define RelationGetDescr(relation)
Definition: rel.h:437
ConstrCheck * check
Definition: tupdesc.h:40
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:90
char * ccbin
Definition: tupdesc.h:31
Definition: nodes.h:512
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2459
List * list_concat(List *list1, List *list2)
Definition: list.c:321
int natts
Definition: tupdesc.h:79
Expr * make_ands_explicit(List *andclauses)
Definition: clauses.c:367
#define list_make1(x1)
Definition: pg_list.h:139
List * make_ands_implicit(Expr *clause)
Definition: clauses.c:378
Expr * arg
Definition: primnodes.h:1187
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:67
bool has_not_null
Definition: tupdesc.h:43
List * lappend(List *list, void *datum)
Definition: list.c:128
Expr * canonicalize_qual(Expr *qual)
Definition: prepqual.c:286
TupleDesc rd_att
Definition: rel.h:115
NullTestType nulltesttype
Definition: primnodes.h:1188
#define makeNode(_type_)
Definition: nodes.h:560
int location
Definition: primnodes.h:1190
bool ccvalid
Definition: tupdesc.h:32
int i
bool argisrow
Definition: primnodes.h:1189
uint16 num_check
Definition: tupdesc.h:42
Definition: pg_list.h:45

◆ PreCommit_on_commit_actions()

void PreCommit_on_commit_actions ( void  )

Definition at line 12980 of file tablecmds.c.

References Assert, ObjectAddress::classId, CommandCounterIncrement(), OnCommitItem::deleting_subid, DROP_CASCADE, heap_truncate(), InvalidSubTransactionId, lappend_oid(), lfirst, MyXactFlags, NIL, OnCommitItem::oncommit, ONCOMMIT_DELETE_ROWS, ONCOMMIT_DROP, ONCOMMIT_NOOP, ONCOMMIT_PRESERVE_ROWS, PERFORM_DELETION_INTERNAL, performDeletion(), RelationRelationId, OnCommitItem::relid, and XACT_FLAGS_ACCESSEDTEMPREL.

Referenced by CommitTransaction(), and PrepareTransaction().

12981 {
12982  ListCell *l;
12983  List *oids_to_truncate = NIL;
12984 
12985  foreach(l, on_commits)
12986  {
12987  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
12988 
12989  /* Ignore entry if already dropped in this xact */
12991  continue;
12992 
12993  switch (oc->oncommit)
12994  {
12995  case ONCOMMIT_NOOP:
12997  /* Do nothing (there shouldn't be such entries, actually) */
12998  break;
12999  case ONCOMMIT_DELETE_ROWS:
13000 
13001  /*
13002  * If this transaction hasn't accessed any temporary
13003  * relations, we can skip truncating ON COMMIT DELETE ROWS
13004  * tables, as they must still be empty.
13005  */
13007  oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
13008  break;
13009  case ONCOMMIT_DROP:
13010  {
13011  ObjectAddress object;
13012 
13013  object.classId = RelationRelationId;
13014  object.objectId = oc->relid;
13015  object.objectSubId = 0;
13016 
13017  /*
13018  * Since this is an automatic drop, rather than one
13019  * directly initiated by the user, we pass the
13020  * PERFORM_DELETION_INTERNAL flag.
13021  */
13022  performDeletion(&object,
13024 
13025  /*
13026  * Note that table deletion will call
13027  * remove_on_commit_action, so the entry should get marked
13028  * as deleted.
13029  */
13031  break;
13032  }
13033  }
13034  }
13035  if (oids_to_truncate != NIL)
13036  {
13037  heap_truncate(oids_to_truncate);
13038  CommandCounterIncrement(); /* XXX needed? */
13039  }
13040 }
#define NIL
Definition: pg_list.h:69
OnCommitAction oncommit
Definition: tablecmds.c:111
#define RelationRelationId
Definition: pg_class.h:29
#define XACT_FLAGS_ACCESSEDTEMPREL
Definition: xact.h:86
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
static List * on_commits
Definition: tablecmds.c:124
void performDeletion(const ObjectAddress *object, DropBehavior behavior, int flags)
Definition: dependency.c:303
int MyXactFlags
Definition: xact.c:118
SubTransactionId deleting_subid
Definition: tablecmds.c:121
void CommandCounterIncrement(void)
Definition: xact.c:915
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
void heap_truncate(List *relids)
Definition: heap.c:2860
#define InvalidSubTransactionId
Definition: c.h:451
Definition: pg_list.h:45
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:174

◆ RangeVarCallbackOwnsRelation()

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

Definition at line 13171 of file tablecmds.c.

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

Referenced by AlterSequence(), and ProcessUtilitySlow().

13173 {
13174  HeapTuple tuple;
13175 
13176  /* Nothing to do if the relation was not found. */
13177  if (!OidIsValid(relId))
13178  return;
13179 
13180  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
13181  if (!HeapTupleIsValid(tuple)) /* should not happen */
13182  elog(ERROR, "cache lookup failed for relation %u", relId);
13183 
13184  if (!pg_class_ownercheck(relId, GetUserId()))
13186  relation->relname);
13187 
13188  if (!allowSystemTableMods &&
13189  IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
13190  ereport(ERROR,
13191  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
13192  errmsg("permission denied: \"%s\" is a system catalog",
13193  relation->relname)));
13194 
13195  ReleaseSysCache(tuple);
13196 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
Oid GetUserId(void)
Definition: miscinit.c:284
int errcode(int sqlerrcode)
Definition: elog.c:575
#define OidIsValid(objectId)
Definition: c.h:576
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
Definition: catalog.c:75
char * relname
Definition: primnodes.h:68
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3457
#define ereport(elevel, rest)
Definition: elog.h:122
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
bool allowSystemTableMods
Definition: globals.c:112
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4604
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219

◆ RangeVarCallbackOwnsTable()

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

Definition at line 13138 of file tablecmds.c.

References ACL_KIND_CLASS, aclcheck_error(), ACLCHECK_NOT_OWNER, ereport, errcode(), errmsg(), ERROR, get_rel_relkind(), GetUserId(), OidIsValid, pg_class_ownercheck(), DropRelationCallbackState::relkind, RELKIND_MATVIEW, RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, RELKIND_TOASTVALUE, and RangeVar::relname.

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

13140 {
13141  char relkind;
13142 
13143  /* Nothing to do if the relation was not found. */
13144  if (!OidIsValid(relId))
13145  return;
13146 
13147  /*
13148  * If the relation does exist, check whether it's an index. But note that
13149  * the relation might have been dropped between the time we did the name
13150  * lookup and now. In that case, there's nothing to do.
13151  */
13152  relkind = get_rel_relkind(relId);
13153  if (!relkind)
13154  return;
13155  if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
13156  relkind != RELKIND_MATVIEW && relkind != RELKIND_PARTITIONED_TABLE)
13157  ereport(ERROR,
13158  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
13159  errmsg("\"%s\" is not a table or materialized view", relation->relname)));
13160 
13161  /* Check permissions */
13162  if (!pg_class_ownercheck(relId, GetUserId()))
13164 }
Oid GetUserId(void)
Definition: miscinit.c:284
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1820
#define RELKIND_MATVIEW
Definition: pg_class.h:165
int errcode(int sqlerrcode)
Definition: elog.c:575
#define OidIsValid(objectId)
Definition: c.h:576
char * relname
Definition: primnodes.h:68
#define ERROR
Definition: elog.h:43
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3457
#define ereport(elevel, rest)
Definition: elog.h:122
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
#define RELKIND_TOASTVALUE
Definition: pg_class.h:163
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4604
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define RELKIND_RELATION
Definition: pg_class.h:160

◆ register_on_commit_action()

void register_on_commit_action ( Oid  relid,
OnCommitAction  action 
)

Definition at line 12926 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().

12927 {
12928  OnCommitItem *oc;
12929  MemoryContext oldcxt;
12930 
12931  /*
12932  * We needn't bother registering the relation unless there is an ON COMMIT
12933  * action we need to take.
12934  */
12936  return;
12937 
12939 
12940  oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
12941  oc->relid = relid;
12942  oc->oncommit = action;
12945 
12946  on_commits = lcons(oc, on_commits);
12947 
12948  MemoryContextSwitchTo(oldcxt);
12949 }
OnCommitAction oncommit
Definition: tablecmds.c:111
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
SubTransactionId creating_subid
Definition: tablecmds.c:120
static List * on_commits
Definition: tablecmds.c:124
SubTransactionId deleting_subid
Definition: tablecmds.c:121
List * lcons(void *datum, List *list)
Definition: list.c:259
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:642
#define InvalidSubTransactionId
Definition: c.h:451
void * palloc(Size size)
Definition: mcxt.c:848
MemoryContext CacheMemoryContext
Definition: mcxt.c:46

◆ remove_on_commit_action()

void remove_on_commit_action ( Oid  relid)

Definition at line 12957 of file tablecmds.c.

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

Referenced by heap_drop_with_catalog().

12958 {
12959  ListCell *l;
12960 
12961  foreach(l, on_commits)
12962  {
12963  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
12964 
12965  if (oc->relid == relid)
12966  {
12968  break;
12969  }
12970  }
12971 }
static List * on_commits
Definition: tablecmds.c:124
SubTransactionId deleting_subid
Definition: tablecmds.c:121
#define lfirst(lc)
Definition: pg_list.h:106
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:642

◆ RemoveRelations()

void RemoveRelations ( DropStmt drop)

Definition at line 1007 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(), RelationRelationId, DropRelationCallbackState::relkind, RELKIND_FOREIGN_TABLE, RELKIND_INDEX, RELKIND_MATVIEW, RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW, DropStmt::removeType, and ShareUpdateExclusiveLock.

Referenced by ExecDropStmt().

1008 {
1009  ObjectAddresses *objects;
1010  char relkind;
1011  ListCell *cell;
1012  int flags = 0;
1013  LOCKMODE lockmode = AccessExclusiveLock;
1014 
1015  /* DROP CONCURRENTLY uses a weaker lock, and has some restrictions */
1016  if (drop->concurrent)
1017  {
1019  lockmode = ShareUpdateExclusiveLock;
1020  Assert(drop->removeType == OBJECT_INDEX);
1021  if (list_length(drop->objects) != 1)
1022  ereport(ERROR,
1023  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1024  errmsg("DROP INDEX CONCURRENTLY does not support dropping multiple objects")));
1025  if (drop->behavior == DROP_CASCADE)
1026  ereport(ERROR,
1027  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1028  errmsg("DROP INDEX CONCURRENTLY does not support CASCADE")));
1029  }
1030 
1031  /*
1032  * First we identify all the relations, then we delete them in a single
1033  * performMultipleDeletions() call. This is to avoid unwanted DROP
1034  * RESTRICT errors if one of the relations depends on another.
1035  */
1036 
1037  /* Determine required relkind */
1038  switch (drop->removeType)
1039  {
1040  case OBJECT_TABLE:
1041  relkind = RELKIND_RELATION;
1042  break;
1043 
1044  case OBJECT_INDEX:
1045  relkind = RELKIND_INDEX;
1046  break;
1047 
1048  case OBJECT_SEQUENCE:
1049  relkind = RELKIND_SEQUENCE;
1050  break;
1051 
1052  case OBJECT_VIEW:
1053  relkind = RELKIND_VIEW;
1054  break;
1055 
1056  case OBJECT_MATVIEW:
1057  relkind = RELKIND_MATVIEW;
1058  break;
1059 
1060  case OBJECT_FOREIGN_TABLE:
1061  relkind = RELKIND_FOREIGN_TABLE;
1062  break;
1063 
1064  default:
1065  elog(ERROR, "unrecognized drop object type: %d",
1066  (int) drop->removeType);
1067  relkind = 0; /* keep compiler quiet */
1068  break;
1069  }
1070 
1071  /* Lock and validate each relation; build a list of object addresses */
1072  objects = new_object_addresses();
1073 
1074  foreach(cell, drop->objects)
1075  {
1076  RangeVar *rel = makeRangeVarFromNameList((List *) lfirst(cell));
1077  Oid relOid;
1078  ObjectAddress obj;
1080 
1081  /*
1082  * These next few steps are a great deal like relation_openrv, but we
1083  * don't bother building a relcache entry since we don't need it.
1084  *
1085  * Check for shared-cache-inval messages before trying to access the
1086  * relation. This is needed to cover the case where the name
1087  * identifies a rel that has been dropped and recreated since the
1088  * start of our transaction: if we don't flush the old syscache entry,
1089  * then we'll latch onto that entry and suffer an error later.
1090  */
1092 
1093  /* Look up the appropriate relation using namespace search. */
1094  state.relkind = relkind;
1095  state.heapOid = InvalidOid;
1096  state.partParentOid = InvalidOid;
1097  state.concurrent = drop->concurrent;
1098  relOid = RangeVarGetRelidExtended(rel, lockmode, true,
1099  false,
1101  (void *) &state);
1102 
1103  /* Not there? */
1104  if (!OidIsValid(relOid))
1105  {
1106  DropErrorMsgNonExistent(rel, relkind, drop->missing_ok);
1107  continue;
1108  }
1109 
1110  /* OK, we're ready to delete this one */
1112  obj.objectId = relOid;
1113  obj.objectSubId = 0;
1114 
1115  add_exact_object_address(&obj, objects);
1116  }
1117 
1118  performMultipleDeletions(objects, drop->behavior, flags);
1119 
1120  free_object_addresses(objects);
1121 }
void AcceptInvalidationMessages(void)
Definition: inval.c:679
int LOCKMODE
Definition: lockdefs.h:26
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, bool missing_ok, bool nowait, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:218
#define RelationRelationId
Definition: pg_class.h:29
List * objects
Definition: parsenodes.h:2589
bool missing_ok
Definition: parsenodes.h:2592
#define RELKIND_MATVIEW
Definition: pg_class.h:165
int errcode(int sqlerrcode)
Definition: elog.c:575
RangeVar * makeRangeVarFromNameList(List *names)
Definition: namespace.c:3023
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2160
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2105
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2376
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:576
ObjectType removeType
Definition: parsenodes.h:2590
#define PERFORM_DELETION_CONCURRENTLY
Definition: dependency.h:175
#define ERROR
Definition: elog.h:43
bool concurrent
Definition: parsenodes.h:2593
DropBehavior behavior
Definition: parsenodes.h:2591
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
#define ereport(elevel, rest)
Definition: elog.h:122
static void RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid, Oid oldRelOid, void *arg)
Definition: tablecmds.c:1130
#define InvalidOid
Definition: postgres_ext.h:36
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
Definition: regguts.h:298
static int list_length(const List *l)
Definition: pg_list.h:89
#define AccessExclusiveLock
Definition: lockdefs.h:45
static void DropErrorMsgNonExistent(RangeVar *rel, char rightkind, bool missing_ok)
Definition: tablecmds.c:932
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define RELKIND_VIEW
Definition: pg_class.h:164
#define RELKIND_INDEX
Definition: pg_class.h:161
void performMultipleDeletions(const ObjectAddresses *objects, DropBehavior behavior, int flags)
Definition: dependency.c:362
#define elog
Definition: elog.h:219
#define RELKIND_RELATION
Definition: pg_class.h:160
#define RELKIND_SEQUENCE
Definition: pg_class.h:162
Definition: pg_list.h:45

◆ renameatt()

ObjectAddress renameatt ( RenameStmt stmt)

Definition at line 2735 of file tablecmds.c.

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

Referenced by ExecRenameStmt().

2736 {
2737  Oid relid;
2738  AttrNumber attnum;
2739  ObjectAddress address;
2740 
2741  /* lock level taken here should match renameatt_internal */
2743  stmt->missing_ok, false,
2745  NULL);
2746 
2747  if (!OidIsValid(relid))
2748  {
2749  ereport(NOTICE,
2750  (errmsg("relation \"%s\" does not exist, skipping",
2751  stmt->relation->relname)));
2752  return InvalidObjectAddress;
2753  }
2754 
2755  attnum =
2756  renameatt_internal(relid,
2757  stmt->subname, /* old att name */
2758  stmt->newname, /* new att name */
2759  stmt->relation->inh, /* recursive? */
2760  false, /* recursing? */
2761  0, /* expected inhcount */
2762  stmt->behavior);
2763 
2764  ObjectAddressSubSet(address, RelationRelationId, relid, attnum);
2765 
2766  return address;
2767 }
char * subname
Definition: parsenodes.h:2829
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, bool missing_ok, bool nowait, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:218
#define RelationRelationId
Definition: pg_class.h:29
char * newname
Definition: parsenodes.h:2831
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:576
char * relname
Definition: primnodes.h:68
bool missing_ok
Definition: parsenodes.h:2833
#define ereport(elevel, rest)
Definition: elog.h:122
bool inh
Definition: primnodes.h:69
RangeVar * relation
Definition: parsenodes.h:2827
#define NOTICE
Definition: elog.h:37
static void RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:2715
static AttrNumber renameatt_internal(Oid myrelid, const char *oldattname, const char *newattname, bool recurse, bool recursing, int expected_parents, DropBehavior behavior)
Definition: tablecmds.c:2570
#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:797
DropBehavior behavior
Definition: parsenodes.h:2832
int16 AttrNumber
Definition: attnum.h:21

◆ renameatt_type()

ObjectAddress renameatt_type ( RenameStmt stmt)

◆ RenameConstraint()

ObjectAddress RenameConstraint ( RenameStmt stmt)

Definition at line 2872 of file tablecmds.c.

References AccessExclusiveLock, castNode, checkDomainOwner(), elog, ereport, errmsg(), ERROR, heap_close, heap_open(), 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, SearchSysCache1(), RenameStmt::subname, typenameTypeId(), TYPEOID, and TypeRelationId.

Referenced by ExecRenameStmt().

2873 {
2874  Oid relid = InvalidOid;
2875  Oid typid = InvalidOid;
2876 
2877  if (stmt->renameType == OBJECT_DOMCONSTRAINT)
2878  {
2879  Relation rel;
2880  HeapTuple tup;
2881 
2884  tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2885  if (!HeapTupleIsValid(tup))
2886  elog(ERROR, "cache lookup failed for type %u", typid);
2887  checkDomainOwner(tup);
2888  ReleaseSysCache(tup);
2889  heap_close(rel, NoLock);
2890  }
2891  else
2892  {
2893  /* lock level taken here should match rename_constraint_internal */
2895  stmt->missing_ok, false,
2897  NULL);
2898  if (!OidIsValid(relid))
2899  {
2900  ereport(NOTICE,
2901  (errmsg("relation \"%s\" does not exist, skipping",
2902  stmt->relation->relname)));
2903  return InvalidObjectAddress;
2904  }
2905  }
2906 
2907  return
2908  rename_constraint_internal(relid, typid,
2909  stmt->subname,
2910  stmt->newname,
2911  (stmt->relation &&
2912  stmt->relation->inh), /* recursive? */
2913  false, /* recursing? */
2914  0 /* expected inhcount */ );
2915 
2916 }
char * subname
Definition: parsenodes.h:2829
ObjectType renameType
Definition: parsenodes.h:2825
#define castNode(_type_, nodeptr)
Definition: nodes.h:581
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, bool missing_ok, bool nowait, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:218
#define heap_close(r, l)
Definition: heapam.h:97
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:2773
char * newname
Definition: parsenodes.h:2831
unsigned int Oid
Definition: postgres_ext.h:31
#define TypeRelationId
Definition: pg_type.h:34
#define OidIsValid(objectId)
Definition: c.h:576
char * relname
Definition: primnodes.h:68
bool missing_ok
Definition: parsenodes.h:2833
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
Node * object
Definition: parsenodes.h:2828
#define ereport(elevel, rest)
Definition: elog.h:122
bool inh
Definition: primnodes.h:69
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
RangeVar * relation
Definition: parsenodes.h:2827
#define InvalidOid
Definition: postgres_ext.h:36
#define NOTICE
Definition: elog.h:37
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
static void RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:2715
void checkDomainOwner(HeapTuple tup)
Definition: typecmds.c:3041
#define AccessExclusiveLock
Definition: lockdefs.h:45
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:797
TypeName * makeTypeNameFromNameList(List *names)
Definition: makefuncs.c:455
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:274

◆ RenameRelation()

ObjectAddress RenameRelation ( RenameStmt stmt)

Definition at line 2923 of file tablecmds.c.

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

Referenced by ExecRenameStmt().

2924 {
2925  Oid relid;
2926  ObjectAddress address;
2927 
2928  /*
2929  * Grab an exclusive lock on the target table, index, sequence, view,
2930  * materialized view, or foreign table, which we will NOT release until
2931  * end of transaction.
2932  *
2933  * Lock level used here should match RenameRelationInternal, to avoid lock
2934  * escalation.
2935  */
2937  stmt->missing_ok, false,
2939  (void *) stmt);
2940 
2941  if (!OidIsValid(relid))
2942  {
2943  ereport(NOTICE,
2944  (errmsg("relation \"%s\" does not exist, skipping",
2945  stmt->relation->relname)));
2946  return InvalidObjectAddress;
2947  }
2948 
2949  /* Do the work */
2950  RenameRelationInternal(relid, stmt->newname, false);
2951 
2952  ObjectAddressSet(address, RelationRelationId, relid);
2953 
2954  return address;
2955 }
void RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal)
Definition: tablecmds.c:2967
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, bool missing_ok, bool nowait, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:218
#define RelationRelationId
Definition: pg_class.h:29
char * newname
Definition: parsenodes.h:2831
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:576
char * relname
Definition: primnodes.h:68
bool missing_ok
Definition: parsenodes.h:2833
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:13203
#define ereport(elevel, rest)
Definition: elog.h:122
RangeVar * relation
Definition: parsenodes.h:2827
#define NOTICE
Definition: elog.h:37
#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:797

◆ RenameRelationInternal()

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

Definition at line 2967 of file tablecmds.c.

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

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

2968 {
2969  Relation targetrelation;
2970  Relation relrelation; /* for RELATION relation */
2971  HeapTuple reltup;
2972  Form_pg_class relform;
2973  Oid namespaceId;
2974 
2975  /*
2976  * Grab an exclusive lock on the target table, index, sequence, view,
2977  * materialized view, or foreign table, which we will NOT release until
2978  * end of transaction.
2979  */
2980  targetrelation = relation_open(myrelid, AccessExclusiveLock);
2981  namespaceId = RelationGetNamespace(targetrelation);
2982 
2983  /*
2984  * Find relation's pg_class tuple, and make sure newrelname isn't in use.
2985  */
2987 
2988  reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
2989  if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
2990  elog(ERROR, "cache lookup failed for relation %u", myrelid);
2991  relform = (Form_pg_class) GETSTRUCT(reltup);
2992 
2993  if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
2994  ereport(ERROR,
2995  (errcode(ERRCODE_DUPLICATE_TABLE),
2996  errmsg("relation \"%s\" already exists",
2997  newrelname)));
2998 
2999  /*
3000  * Update pg_class tuple with new relname. (Scribbling on reltup is OK
3001  * because it's a copy...)
3002  */
3003  namestrcpy(&(relform->relname), newrelname);
3004 
3005  CatalogTupleUpdate(relrelation, &reltup->t_self, reltup);
3006 
3008  InvalidOid, is_internal);
3009 
3010  heap_freetuple(reltup);
3011  heap_close(relrelation, RowExclusiveLock);
3012 
3013  /*
3014  * Also rename the associated type, if any.
3015  */
3016  if (OidIsValid(targetrelation->rd_rel->reltype))
3017  RenameTypeInternal(targetrelation->rd_rel->reltype,
3018  newrelname, namespaceId);
3019 
3020  /*
3021  * Also rename the associated constraint, if any.
3022  */
3023  if (targetrelation->rd_rel->relkind == RELKIND_INDEX)
3024  {
3025  Oid constraintId = get_index_constraint(myrelid);
3026 
3027  if (OidIsValid(constraintId))
3028  RenameConstraintById(constraintId, newrelname);
3029  }
3030 
3031  /*
3032  * Close rel, but keep exclusive lock!
3033  */
3034  relation_close(targetrelation, NoLock);
3035 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
#define RelationRelationId
Definition: pg_class.h:29
int errcode(int sqlerrcode)
Definition: elog.c:575
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1266
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:114
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
unsigned int Oid
Definition: postgres_ext.h:31
int namestrcpy(Name name, const char *str)
Definition: name.c:216
#define OidIsValid(objectId)
Definition: c.h:576
#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:513
#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:1702
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:684
#define ereport(elevel, rest)
Definition: elog.h:122
void RenameTypeInternal(Oid typeOid, const char *newTypeName, Oid typeNamespace)
Definition: pg_type.c:692
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:173
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define RELKIND_INDEX
Definition: pg_class.h:161
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1120
#define elog
Definition: elog.h:219
#define RelationGetNamespace(relation)
Definition: rel.h:452

◆ SetRelationHasSubclass()

void SetRelationHasSubclass ( Oid  relationId,
bool  relhassubclass 
)

Definition at line 2489 of file tablecmds.c.

References CacheInvalidateRelcacheByTuple(), CatalogTupleUpdate(), elog, ERROR, GETSTRUCT, heap_close, heap_freetuple(), heap_open(), HeapTupleIsValid, ObjectIdGetDatum, RelationRelationId, RELOID, RowExclusiveLock, SearchSysCacheCopy1, and HeapTupleData::t_self.

Referenced by acquire_inherited_sample_rows(), and StoreCatalogInheritance1().

2490 {
2491  Relation relationRelation;
2492  HeapTuple tuple;
2493  Form_pg_class classtuple;
2494 
2495  /*
2496  * Fetch a modifiable copy of the tuple, modify it, update pg_class.
2497  */
2498  relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
2499  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
2500  if (!HeapTupleIsValid(tuple))
2501  elog(ERROR, "cache lookup failed for relation %u", relationId);
2502  classtuple = (Form_pg_class) GETSTRUCT(tuple);
2503 
2504  if (classtuple->relhassubclass != relhassubclass)
2505  {
2506  classtuple->relhassubclass = relhassubclass;
2507  CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
2508  }
2509  else
2510  {
2511  /* no need to change tuple, but force relcache rebuild anyway */
2513  }
2514 
2515  heap_freetuple(tuple);
2516  heap_close(relationRelation, RowExclusiveLock);
2517 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
#define RelationRelationId
Definition: pg_class.h:29
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:173
void CacheInvalidateRelcacheByTuple(HeapTuple classTuple)
Definition: inval.c:1269
#define elog
Definition: elog.h:219