PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
tablecmds.h File Reference
#include "access/htup.h"
#include "catalog/dependency.h"
#include "catalog/objectaddress.h"
#include "nodes/parsenodes.h"
#include "storage/lock.h"
#include "utils/relcache.h"
Include dependency graph for tablecmds.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

ObjectAddress DefineRelation (CreateStmt *stmt, char relkind, Oid ownerId, ObjectAddress *typaddress, const char *queryString)
 
void RemoveRelations (DropStmt *drop)
 
Oid AlterTableLookupRelation (AlterTableStmt *stmt, LOCKMODE lockmode)
 
void AlterTable (Oid relid, LOCKMODE lockmode, AlterTableStmt *stmt)
 
LOCKMODE AlterTableGetLockLevel (List *cmds)
 
void ATExecChangeOwner (Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
 
void AlterTableInternal (Oid relid, List *cmds, bool recurse)
 
Oid AlterTableMoveAll (AlterTableMoveAllStmt *stmt)
 
ObjectAddress AlterTableNamespace (AlterObjectSchemaStmt *stmt, Oid *oldschema)
 
void AlterTableNamespaceInternal (Relation rel, Oid oldNspOid, Oid nspOid, ObjectAddresses *objsMoved)
 
void AlterRelationNamespaceInternal (Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
 
void CheckTableNotInUse (Relation rel, const char *stmt)
 
void ExecuteTruncate (TruncateStmt *stmt)
 
void 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)
 

Function Documentation

void AlterRelationNamespaceInternal ( Relation  classRel,
Oid  relOid,
Oid  oldNspOid,
Oid  newNspOid,
bool  hasDependEntry,
ObjectAddresses objsMoved 
)

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

12517 {
12518  HeapTuple classTup;
12519  Form_pg_class classForm;
12520  ObjectAddress thisobj;
12521  bool already_done = false;
12522 
12523  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
12524  if (!HeapTupleIsValid(classTup))
12525  elog(ERROR, "cache lookup failed for relation %u", relOid);
12526  classForm = (Form_pg_class) GETSTRUCT(classTup);
12527 
12528  Assert(classForm->relnamespace == oldNspOid);
12529 
12530  thisobj.classId = RelationRelationId;
12531  thisobj.objectId = relOid;
12532  thisobj.objectSubId = 0;
12533 
12534  /*
12535  * If the object has already been moved, don't move it again. If it's
12536  * already in the right place, don't move it, but still fire the object
12537  * access hook.
12538  */
12539  already_done = object_address_present(&thisobj, objsMoved);
12540  if (!already_done && oldNspOid != newNspOid)
12541  {
12542  /* check for duplicate name (more friendly than unique-index failure) */
12543  if (get_relname_relid(NameStr(classForm->relname),
12544  newNspOid) != InvalidOid)
12545  ereport(ERROR,
12546  (errcode(ERRCODE_DUPLICATE_TABLE),
12547  errmsg("relation \"%s\" already exists in schema \"%s\"",
12548  NameStr(classForm->relname),
12549  get_namespace_name(newNspOid))));
12550 
12551  /* classTup is a copy, so OK to scribble on */
12552  classForm->relnamespace = newNspOid;
12553 
12554  CatalogTupleUpdate(classRel, &classTup->t_self, classTup);
12555 
12556  /* Update dependency on schema if caller said so */
12557  if (hasDependEntry &&
12559  relOid,
12561  oldNspOid,
12562  newNspOid) != 1)
12563  elog(ERROR, "failed to change schema dependency for relation \"%s\"",
12564  NameStr(classForm->relname));
12565  }
12566  if (!already_done)
12567  {
12568  add_exact_object_address(&thisobj, objsMoved);
12569 
12571  }
12572 
12573  heap_freetuple(classTup);
12574 }
#define NamespaceRelationId
Definition: pg_namespace.h:34
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define RelationRelationId
Definition: pg_class.h:29
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2167
int errcode(int sqlerrcode)
Definition: elog.c:575
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2107
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1372
#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:1683
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3033
#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:675
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:165
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:499
#define elog
Definition: elog.h:219
void AlterTable ( Oid  relid,
LOCKMODE  lockmode,
AlterTableStmt stmt 
)

Definition at line 3076 of file tablecmds.c.

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

Referenced by ProcessUtilitySlow().

3077 {
3078  Relation rel;
3079 
3080  /* Caller is required to provide an adequate lock. */
3081  rel = relation_open(relid, NoLock);
3082 
3083  CheckTableNotInUse(rel, "ALTER TABLE");
3084 
3085  ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode);
3086 }
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
Definition: tablecmds.c:3394
#define NoLock
Definition: lockdefs.h:34
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:2997
bool inh
Definition: primnodes.h:69
RangeVar * relation
Definition: parsenodes.h:1658
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1114
LOCKMODE AlterTableGetLockLevel ( List cmds)

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

3146 {
3147  /*
3148  * This only works if we read catalog tables using MVCC snapshots.
3149  */
3150  ListCell *lcmd;
3152 
3153  foreach(lcmd, cmds)
3154  {
3155  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3156  LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
3157 
3158  switch (cmd->subtype)
3159  {
3160  /*
3161  * These subcommands rewrite the heap, so require full locks.
3162  */
3163  case AT_AddColumn: /* may rewrite heap, in some cases and visible
3164  * to SELECT */
3165  case AT_SetTableSpace: /* must rewrite heap */
3166  case AT_AlterColumnType: /* must rewrite heap */
3167  case AT_AddOids: /* must rewrite heap */
3168  cmd_lockmode = AccessExclusiveLock;
3169  break;
3170 
3171  /*
3172  * These subcommands may require addition of toast tables. If
3173  * we add a toast table to a table currently being scanned, we
3174  * might miss data added to the new toast table by concurrent
3175  * insert transactions.
3176  */
3177  case AT_SetStorage:/* may add toast tables, see
3178  * ATRewriteCatalogs() */
3179  cmd_lockmode = AccessExclusiveLock;
3180  break;
3181 
3182  /*
3183  * Removing constraints can affect SELECTs that have been
3184  * optimised assuming the constraint holds true.
3185  */
3186  case AT_DropConstraint: /* as DROP INDEX */
3187  case AT_DropNotNull: /* may change some SQL plans */
3188  cmd_lockmode = AccessExclusiveLock;
3189  break;
3190 
3191  /*
3192  * Subcommands that may be visible to concurrent SELECTs
3193  */
3194  case AT_DropColumn: /* change visible to SELECT */
3195  case AT_AddColumnToView: /* CREATE VIEW */
3196  case AT_DropOids: /* calls AT_DropColumn */
3197  case AT_EnableAlwaysRule: /* may change SELECT rules */
3198  case AT_EnableReplicaRule: /* may change SELECT rules */
3199  case AT_EnableRule: /* may change SELECT rules */
3200  case AT_DisableRule: /* may change SELECT rules */
3201  cmd_lockmode = AccessExclusiveLock;
3202  break;
3203 
3204  /*
3205  * Changing owner may remove implicit SELECT privileges
3206  */
3207  case AT_ChangeOwner: /* change visible to SELECT */
3208  cmd_lockmode = AccessExclusiveLock;
3209  break;
3210 
3211  /*
3212  * Changing foreign table options may affect optimization.
3213  */
3214  case AT_GenericOptions:
3216  cmd_lockmode = AccessExclusiveLock;
3217  break;
3218 
3219  /*
3220  * These subcommands affect write operations only.
3221  */
3222  case AT_EnableTrig:
3223  case AT_EnableAlwaysTrig:
3224  case AT_EnableReplicaTrig:
3225  case AT_EnableTrigAll:
3226  case AT_EnableTrigUser:
3227  case AT_DisableTrig:
3228  case AT_DisableTrigAll:
3229  case AT_DisableTrigUser:
3230  cmd_lockmode = ShareRowExclusiveLock;
3231  break;
3232 
3233  /*
3234  * These subcommands affect write operations only. XXX
3235  * Theoretically, these could be ShareRowExclusiveLock.
3236  */
3237  case AT_ColumnDefault:
3238  case AT_AlterConstraint:
3239  case AT_AddIndex: /* from ADD CONSTRAINT */
3240  case AT_AddIndexConstraint:
3241  case AT_ReplicaIdentity:
3242  case AT_SetNotNull:
3243  case AT_EnableRowSecurity:
3244  case AT_DisableRowSecurity:
3245  case AT_ForceRowSecurity:
3246  case AT_NoForceRowSecurity:
3247  case AT_AddIdentity:
3248  case AT_DropIdentity:
3249  case AT_SetIdentity:
3250  cmd_lockmode = AccessExclusiveLock;
3251  break;
3252 
3253  case AT_AddConstraint:
3254  case AT_ProcessedConstraint: /* becomes AT_AddConstraint */
3255  case AT_AddConstraintRecurse: /* becomes AT_AddConstraint */
3256  case AT_ReAddConstraint: /* becomes AT_AddConstraint */
3257  if (IsA(cmd->def, Constraint))
3258  {
3259  Constraint *con = (Constraint *) cmd->def;
3260 
3261  switch (con->contype)
3262  {
3263  case CONSTR_EXCLUSION:
3264  case CONSTR_PRIMARY:
3265  case CONSTR_UNIQUE:
3266 
3267  /*
3268  * Cases essentially the same as CREATE INDEX. We
3269  * could reduce the lock strength to ShareLock if
3270  * we can work out how to allow concurrent catalog
3271  * updates. XXX Might be set down to
3272  * ShareRowExclusiveLock but requires further
3273  * analysis.
3274  */
3275  cmd_lockmode = AccessExclusiveLock;
3276  break;
3277  case CONSTR_FOREIGN:
3278 
3279  /*
3280  * We add triggers to both tables when we add a
3281  * Foreign Key, so the lock level must be at least
3282  * as strong as CREATE TRIGGER.
3283  */
3284  cmd_lockmode = ShareRowExclusiveLock;
3285  break;
3286 
3287  default:
3288  cmd_lockmode = AccessExclusiveLock;
3289  }
3290  }
3291  break;
3292 
3293  /*
3294  * These subcommands affect inheritance behaviour. Queries
3295  * started before us will continue to see the old inheritance
3296  * behaviour, while queries started after we commit will see
3297  * new behaviour. No need to prevent reads or writes to the
3298  * subtable while we hook it up though. Changing the TupDesc
3299  * may be a problem, so keep highest lock.
3300  */
3301  case AT_AddInherit:
3302  case AT_DropInherit:
3303  cmd_lockmode = AccessExclusiveLock;
3304  break;
3305 
3306  /*
3307  * These subcommands affect implicit row type conversion. They
3308  * have affects similar to CREATE/DROP CAST on queries. don't
3309  * provide for invalidating parse trees as a result of such
3310  * changes, so we keep these at AccessExclusiveLock.
3311  */
3312  case AT_AddOf:
3313  case AT_DropOf:
3314  cmd_lockmode = AccessExclusiveLock;
3315  break;
3316 
3317  /*
3318  * Only used by CREATE OR REPLACE VIEW which must conflict
3319  * with an SELECTs currently using the view.
3320  */
3321  case AT_ReplaceRelOptions:
3322  cmd_lockmode = AccessExclusiveLock;
3323  break;
3324 
3325  /*
3326  * These subcommands affect general strategies for performance
3327  * and maintenance, though don't change the semantic results
3328  * from normal data reads and writes. Delaying an ALTER TABLE
3329  * behind currently active writes only delays the point where
3330  * the new strategy begins to take effect, so there is no
3331  * benefit in waiting. In this case the minimum restriction
3332  * applies: we don't currently allow concurrent catalog
3333  * updates.
3334  */
3335  case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
3336  case AT_ClusterOn: /* Uses MVCC in getIndexes() */
3337  case AT_DropCluster: /* Uses MVCC in getIndexes() */
3338  case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
3339  case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
3340  cmd_lockmode = ShareUpdateExclusiveLock;
3341  break;
3342 
3343  case AT_SetLogged:
3344  case AT_SetUnLogged:
3345  cmd_lockmode = AccessExclusiveLock;
3346  break;
3347 
3348  case AT_ValidateConstraint: /* Uses MVCC in
3349  * getConstraints() */
3350  cmd_lockmode = ShareUpdateExclusiveLock;
3351  break;
3352 
3353  /*
3354  * Rel options are more complex than first appears. Options
3355  * are set here for tables, views and indexes; for historical
3356  * reasons these can all be used with ALTER TABLE, so we can't
3357  * decide between them using the basic grammar.
3358  */
3359  case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
3360  * getTables() */
3361  case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
3362  * getTables() */
3363  cmd_lockmode = AlterTableGetRelOptionsLockLevel((List *) cmd->def);
3364  break;
3365 
3366  case AT_AttachPartition:
3367  case AT_DetachPartition:
3368  cmd_lockmode = AccessExclusiveLock;
3369  break;
3370 
3371  default: /* oops */
3372  elog(ERROR, "unrecognized alter table type: %d",
3373  (int) cmd->subtype);
3374  break;
3375  }
3376 
3377  /*
3378  * Take the greatest lockmode from any subcommand
3379  */
3380  if (cmd_lockmode > lockmode)
3381  lockmode = cmd_lockmode;
3382  }
3383 
3384  return lockmode;
3385 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
int LOCKMODE
Definition: lockdefs.h:26
AlterTableType subtype
Definition: parsenodes.h:1745
#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:1528
#define AccessExclusiveLock
Definition: lockdefs.h:46
ConstrType contype
Definition: parsenodes.h:2046
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
void AlterTableInternal ( Oid  relid,
List cmds,
bool  recurse 
)

Definition at line 3100 of file tablecmds.c.

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

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

3101 {
3102  Relation rel;
3103  LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
3104 
3105  rel = relation_open(relid, lockmode);
3106 
3108 
3109  ATController(NULL, rel, cmds, recurse, lockmode);
3110 }
int LOCKMODE
Definition: lockdefs.h:26
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
Definition: tablecmds.c:3394
LOCKMODE AlterTableGetLockLevel(List *cmds)
Definition: tablecmds.c:3145
#define NULL
Definition: c.h:229
void EventTriggerAlterTableRelid(Oid objectId)
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1114
Oid AlterTableLookupRelation ( AlterTableStmt stmt,
LOCKMODE  lockmode 
)

Definition at line 3026 of file tablecmds.c.

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

Referenced by ProcessUtilitySlow().

3027 {
3028  return RangeVarGetRelidExtended(stmt->relation, lockmode, stmt->missing_ok, false,
3030  (void *) stmt);
3031 }
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:12990
RangeVar * relation
Definition: parsenodes.h:1658
Oid AlterTableMoveAll ( AlterTableMoveAllStmt stmt)

Definition at line 10612 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, NULL, 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().

10613 {
10614  List *relations = NIL;
10615  ListCell *l;
10616  ScanKeyData key[1];
10617  Relation rel;
10618  HeapScanDesc scan;
10619  HeapTuple tuple;
10620  Oid orig_tablespaceoid;
10621  Oid new_tablespaceoid;
10622  List *role_oids = roleSpecsToIds(stmt->roles);
10623 
10624  /* Ensure we were not asked to move something we can't */
10625  if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
10626  stmt->objtype != OBJECT_MATVIEW)
10627  ereport(ERROR,
10628  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
10629  errmsg("only tables, indexes, and materialized views exist in tablespaces")));
10630 
10631  /* Get the orig and new tablespace OIDs */
10632  orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
10633  new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
10634 
10635  /* Can't move shared relations in to or out of pg_global */
10636  /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
10637  if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
10638  new_tablespaceoid == GLOBALTABLESPACE_OID)
10639  ereport(ERROR,
10640  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
10641  errmsg("cannot move relations in to or out of pg_global tablespace")));
10642 
10643  /*
10644  * Must have CREATE rights on the new tablespace, unless it is the
10645  * database default tablespace (which all users implicitly have CREATE
10646  * rights on).
10647  */
10648  if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
10649  {
10650  AclResult aclresult;
10651 
10652  aclresult = pg_tablespace_aclcheck(new_tablespaceoid, GetUserId(),
10653  ACL_CREATE);
10654  if (aclresult != ACLCHECK_OK)
10656  get_tablespace_name(new_tablespaceoid));
10657  }
10658 
10659  /*
10660  * Now that the checks are done, check if we should set either to
10661  * InvalidOid because it is our database's default tablespace.
10662  */
10663  if (orig_tablespaceoid == MyDatabaseTableSpace)
10664  orig_tablespaceoid = InvalidOid;
10665 
10666  if (new_tablespaceoid == MyDatabaseTableSpace)
10667  new_tablespaceoid = InvalidOid;
10668 
10669  /* no-op */
10670  if (orig_tablespaceoid == new_tablespaceoid)
10671  return new_tablespaceoid;
10672 
10673  /*
10674  * Walk the list of objects in the tablespace and move them. This will
10675  * only find objects in our database, of course.
10676  */
10677  ScanKeyInit(&key[0],
10679  BTEqualStrategyNumber, F_OIDEQ,
10680  ObjectIdGetDatum(orig_tablespaceoid));
10681 
10683  scan = heap_beginscan_catalog(rel, 1, key);
10684  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
10685  {
10686  Oid relOid = HeapTupleGetOid(tuple);
10687  Form_pg_class relForm;
10688 
10689  relForm = (Form_pg_class) GETSTRUCT(tuple);
10690 
10691  /*
10692  * Do not move objects in pg_catalog as part of this, if an admin
10693  * really wishes to do so, they can issue the individual ALTER
10694  * commands directly.
10695  *
10696  * Also, explicitly avoid any shared tables, temp tables, or TOAST
10697  * (TOAST will be moved with the main table).
10698  */
10699  if (IsSystemNamespace(relForm->relnamespace) || relForm->relisshared ||
10700  isAnyTempNamespace(relForm->relnamespace) ||
10701  relForm->relnamespace == PG_TOAST_NAMESPACE)
10702  continue;
10703 
10704  /* Only move the object type requested */
10705  if ((stmt->objtype == OBJECT_TABLE &&
10706  relForm->relkind != RELKIND_RELATION &&
10707  relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
10708  (stmt->objtype == OBJECT_INDEX &&
10709  relForm->relkind != RELKIND_INDEX) ||
10710  (stmt->objtype == OBJECT_MATVIEW &&
10711  relForm->relkind != RELKIND_MATVIEW))
10712  continue;
10713 
10714  /* Check if we are only moving objects owned by certain roles */
10715  if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
10716  continue;
10717 
10718  /*
10719  * Handle permissions-checking here since we are locking the tables
10720  * and also to avoid doing a bunch of work only to fail part-way. Note
10721  * that permissions will also be checked by AlterTableInternal().
10722  *
10723  * Caller must be considered an owner on the table to move it.
10724  */
10725  if (!pg_class_ownercheck(relOid, GetUserId()))
10727  NameStr(relForm->relname));
10728 
10729  if (stmt->nowait &&
10731  ereport(ERROR,
10732  (errcode(ERRCODE_OBJECT_IN_USE),
10733  errmsg("aborting because lock on relation \"%s.%s\" is not available",
10734  get_namespace_name(relForm->relnamespace),
10735  NameStr(relForm->relname))));
10736  else
10738 
10739  /* Add to our list of objects to move */
10740  relations = lappend_oid(relations, relOid);
10741  }
10742 
10743  heap_endscan(scan);
10745 
10746  if (relations == NIL)
10747  ereport(NOTICE,
10748  (errcode(ERRCODE_NO_DATA_FOUND),
10749  errmsg("no matching relations in tablespace \"%s\" found",
10750  orig_tablespaceoid == InvalidOid ? "(database default)" :
10751  get_tablespace_name(orig_tablespaceoid))));
10752 
10753  /* Everything is locked, loop through and move all of the relations. */
10754  foreach(l, relations)
10755  {
10756  List *cmds = NIL;
10758 
10759  cmd->subtype = AT_SetTableSpace;
10760  cmd->name = stmt->new_tablespacename;
10761 
10762  cmds = lappend(cmds, cmd);
10763 
10765  /* OID is set by AlterTableInternal */
10766  AlterTableInternal(lfirst_oid(l), cmds, false);
10768  }
10769 
10770  return new_tablespaceoid;
10771 }
#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:4496
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1578
Oid GetUserId(void)
Definition: miscinit.c:283
#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:509
int errcode(int sqlerrcode)
Definition: elog.c:575
AlterTableType subtype
Definition: parsenodes.h:1745
#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:538
Oid MyDatabaseTableSpace
Definition: globals.c:78
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:3033
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1399
#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:170
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1794
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
bool IsSystemNamespace(Oid namespaceId)
Definition: catalog.c:162
#define InvalidOid
Definition: postgres_ext.h:36
#define NOTICE
Definition: elog.h:37
#define makeNode(_type_)
Definition: nodes.h:557
List * roleSpecsToIds(List *memberNames)
Definition: user.c:1362
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:505
#define NULL
Definition: c.h:229
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4546
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
void AlterTableInternal(Oid relid, List *cmds, bool recurse)
Definition: tablecmds.c:3100
#define AccessExclusiveLock
Definition: lockdefs.h:46
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:499
#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:3113
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
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)
ObjectAddress AlterTableNamespace ( AlterObjectSchemaStmt stmt,
Oid oldschema 
)

Definition at line 12404 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(), AlterObjectSchemaStmt::newschema, NoLock, NOTICE, NULL, ObjectAddressSet, OidIsValid, RangeVarCallbackForAlterRelation(), RangeVarGetAndCheckCreationNamespace(), RangeVarGetRelidExtended(), RelationData::rd_rel, AlterObjectSchemaStmt::relation, relation_close(), relation_open(), RelationGetNamespace, RelationGetRelationName, RelationRelationId, RELKIND_SEQUENCE, RangeVar::relname, and sequenceIsOwned().

Referenced by ExecAlterObjectSchemaStmt().

12405 {
12406  Relation rel;
12407  Oid relid;
12408  Oid oldNspOid;
12409  Oid nspOid;
12410  RangeVar *newrv;
12411  ObjectAddresses *objsMoved;
12412  ObjectAddress myself;
12413 
12415  stmt->missing_ok, false,
12417  (void *) stmt);
12418 
12419  if (!OidIsValid(relid))
12420  {
12421  ereport(NOTICE,
12422  (errmsg("relation \"%s\" does not exist, skipping",
12423  stmt->relation->relname)));
12424  return InvalidObjectAddress;
12425  }
12426 
12427  rel = relation_open(relid, NoLock);
12428 
12429  oldNspOid = RelationGetNamespace(rel);
12430 
12431  /* If it's an owned sequence, disallow moving it by itself. */
12432  if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
12433  {
12434  Oid tableId;
12435  int32 colId;
12436 
12437  if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
12438  sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
12439  ereport(ERROR,
12440  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
12441  errmsg("cannot move an owned sequence into another schema"),
12442  errdetail("Sequence \"%s\" is linked to table \"%s\".",
12444  get_rel_name(tableId))));
12445  }
12446 
12447  /* Get and lock schema OID and check its permissions. */
12448  newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
12450 
12451  /* common checks on switching namespaces */
12452  CheckSetNamespace(oldNspOid, nspOid);
12453 
12454  objsMoved = new_object_addresses();
12455  AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
12456  free_object_addresses(objsMoved);
12457 
12458  ObjectAddressSet(myself, RelationRelationId, relid);
12459 
12460  if (oldschema)
12461  *oldschema = oldNspOid;
12462 
12463  /* close rel, but keep lock until commit */
12464  relation_close(rel, NoLock);
12465 
12466  return myself;
12467 }
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:1260
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2052
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2323
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
signed int int32
Definition: c.h:256
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:12475
#define NoLock
Definition: lockdefs.h:34
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:12990
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define RelationGetRelationName(relation)
Definition: rel.h:437
#define ereport(elevel, rest)
Definition: elog.h:122
void CheckSetNamespace(Oid oldNspOid, Oid nspOid)
Definition: namespace.c:2885
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:508
#define NOTICE
Definition: elog.h:37
#define NULL
Definition: c.h:229
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define AccessExclusiveLock
Definition: lockdefs.h:46
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:797
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1114
#define RELKIND_SEQUENCE
Definition: pg_class.h:162
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1726
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:419
#define RelationGetNamespace(relation)
Definition: rel.h:444
void AlterTableNamespaceInternal ( Relation  rel,
Oid  oldNspOid,
Oid  nspOid,
ObjectAddresses objsMoved 
)

Definition at line 12475 of file tablecmds.c.

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

Referenced by AlterObjectNamespace_oid(), and AlterTableNamespace().

12477 {
12478  Relation classRel;
12479 
12480  Assert(objsMoved != NULL);
12481 
12482  /* OK, modify the pg_class row and pg_depend entry */
12484 
12485  AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
12486  nspOid, true, objsMoved);
12487 
12488  /* Fix the table's row type too */
12489  AlterTypeNamespaceInternal(rel->rd_rel->reltype,
12490  nspOid, false, false, objsMoved);
12491 
12492  /* Fix other dependent stuff */
12493  if (rel->rd_rel->relkind == RELKIND_RELATION ||
12494  rel->rd_rel->relkind == RELKIND_MATVIEW ||
12495  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
12496  {
12497  AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
12498  AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
12499  objsMoved, AccessExclusiveLock);
12500  AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
12501  false, objsMoved);
12502  }
12503 
12504  heap_close(classRel, RowExclusiveLock);
12505 }
#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:3491
#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:12583
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:12628
#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:1284
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
Definition: tablecmds.c:12513
#define AccessExclusiveLock
Definition: lockdefs.h:46
#define RELKIND_RELATION
Definition: pg_class.h:160
#define RelationGetRelid(relation)
Definition: rel.h:417
void AtEOSubXact_on_commit_actions ( bool  isCommit,
SubTransactionId  mySubid,
SubTransactionId  parentSubid 
)

Definition at line 12880 of file tablecmds.c.

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

Referenced by AbortSubTransaction(), and CommitSubTransaction().

12882 {
12883  ListCell *cur_item;
12884  ListCell *prev_item;
12885 
12886  prev_item = NULL;
12887  cur_item = list_head(on_commits);
12888 
12889  while (cur_item != NULL)
12890  {
12891  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
12892 
12893  if (!isCommit && oc->creating_subid == mySubid)
12894  {
12895  /* cur_item must be removed */
12896  on_commits = list_delete_cell(on_commits, cur_item, prev_item);
12897  pfree(oc);
12898  if (prev_item)
12899  cur_item = lnext(prev_item);
12900  else
12901  cur_item = list_head(on_commits);
12902  }
12903  else
12904  {
12905  /* cur_item must be preserved */
12906  if (oc->creating_subid == mySubid)
12907  oc->creating_subid = parentSubid;
12908  if (oc->deleting_subid == mySubid)
12909  oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
12910  prev_item = cur_item;
12911  cur_item = lnext(prev_item);
12912  }
12913  }
12914 }
SubTransactionId creating_subid
Definition: tablecmds.c:120
void pfree(void *pointer)
Definition: mcxt.c:950
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 NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
#define InvalidSubTransactionId
Definition: c.h:403
void AtEOXact_on_commit_actions ( bool  isCommit)

Definition at line 12838 of file tablecmds.c.

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

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

12839 {
12840  ListCell *cur_item;
12841  ListCell *prev_item;
12842 
12843  prev_item = NULL;
12844  cur_item = list_head(on_commits);
12845 
12846  while (cur_item != NULL)
12847  {
12848  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
12849 
12850  if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
12852  {
12853  /* cur_item must be removed */
12854  on_commits = list_delete_cell(on_commits, cur_item, prev_item);
12855  pfree(oc);
12856  if (prev_item)
12857  cur_item = lnext(prev_item);
12858  else
12859  cur_item = list_head(on_commits);
12860  }
12861  else
12862  {
12863  /* cur_item must be preserved */
12866  prev_item = cur_item;
12867  cur_item = lnext(prev_item);
12868  }
12869  }
12870 }
SubTransactionId creating_subid
Definition: tablecmds.c:120
void pfree(void *pointer)
Definition: mcxt.c:950
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 NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
#define InvalidSubTransactionId
Definition: c.h:403
void ATExecChangeOwner ( Oid  relationOid,
Oid  newOwnerId,
bool  recursing,
LOCKMODE  lockmode 
)

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

9802 {
9803  Relation target_rel;
9804  Relation class_rel;
9805  HeapTuple tuple;
9806  Form_pg_class tuple_class;
9807 
9808  /*
9809  * Get exclusive lock till end of transaction on the target table. Use
9810  * relation_open so that we can work on indexes and sequences.
9811  */
9812  target_rel = relation_open(relationOid, lockmode);
9813 
9814  /* Get its pg_class tuple, too */
9816 
9817  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
9818  if (!HeapTupleIsValid(tuple))
9819  elog(ERROR, "cache lookup failed for relation %u", relationOid);
9820  tuple_class = (Form_pg_class) GETSTRUCT(tuple);
9821 
9822  /* Can we change the ownership of this tuple? */
9823  switch (tuple_class->relkind)
9824  {
9825  case RELKIND_RELATION:
9826  case RELKIND_VIEW:
9827  case RELKIND_MATVIEW:
9828  case RELKIND_FOREIGN_TABLE:
9830  /* ok to change owner */
9831  break;
9832  case RELKIND_INDEX:
9833  if (!recursing)
9834  {
9835  /*
9836  * Because ALTER INDEX OWNER used to be allowed, and in fact
9837  * is generated by old versions of pg_dump, we give a warning
9838  * and do nothing rather than erroring out. Also, to avoid
9839  * unnecessary chatter while restoring those old dumps, say
9840  * nothing at all if the command would be a no-op anyway.
9841  */
9842  if (tuple_class->relowner != newOwnerId)
9843  ereport(WARNING,
9844  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9845  errmsg("cannot change owner of index \"%s\"",
9846  NameStr(tuple_class->relname)),
9847  errhint("Change the ownership of the index's table, instead.")));
9848  /* quick hack to exit via the no-op path */
9849  newOwnerId = tuple_class->relowner;
9850  }
9851  break;
9852  case RELKIND_SEQUENCE:
9853  if (!recursing &&
9854  tuple_class->relowner != newOwnerId)
9855  {
9856  /* if it's an owned sequence, disallow changing it by itself */
9857  Oid tableId;
9858  int32 colId;
9859 
9860  if (sequenceIsOwned(relationOid, DEPENDENCY_AUTO, &tableId, &colId) ||
9861  sequenceIsOwned(relationOid, DEPENDENCY_INTERNAL, &tableId, &colId))
9862  ereport(ERROR,
9863  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9864  errmsg("cannot change owner of sequence \"%s\"",
9865  NameStr(tuple_class->relname)),
9866  errdetail("Sequence \"%s\" is linked to table \"%s\".",
9867  NameStr(tuple_class->relname),
9868  get_rel_name(tableId))));
9869  }
9870  break;
9872  if (recursing)
9873  break;
9874  ereport(ERROR,
9875  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9876  errmsg("\"%s\" is a composite type",
9877  NameStr(tuple_class->relname)),
9878  errhint("Use ALTER TYPE instead.")));
9879  break;
9880  case RELKIND_TOASTVALUE:
9881  if (recursing)
9882  break;
9883  /* FALL THRU */
9884  default:
9885  ereport(ERROR,
9886  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9887  errmsg("\"%s\" is not a table, view, sequence, or foreign table",
9888  NameStr(tuple_class->relname))));
9889  }
9890 
9891  /*
9892  * If the new owner is the same as the existing owner, consider the
9893  * command to have succeeded. This is for dump restoration purposes.
9894  */
9895  if (tuple_class->relowner != newOwnerId)
9896  {
9897  Datum repl_val[Natts_pg_class];
9898  bool repl_null[Natts_pg_class];
9899  bool repl_repl[Natts_pg_class];
9900  Acl *newAcl;
9901  Datum aclDatum;
9902  bool isNull;
9903  HeapTuple newtuple;
9904 
9905  /* skip permission checks when recursing to index or toast table */
9906  if (!recursing)
9907  {
9908  /* Superusers can always do it */
9909  if (!superuser())
9910  {
9911  Oid namespaceOid = tuple_class->relnamespace;
9912  AclResult aclresult;
9913 
9914  /* Otherwise, must be owner of the existing object */
9915  if (!pg_class_ownercheck(relationOid, GetUserId()))
9917  RelationGetRelationName(target_rel));
9918 
9919  /* Must be able to become new owner */
9920  check_is_member_of_role(GetUserId(), newOwnerId);
9921 
9922  /* New owner must have CREATE privilege on namespace */
9923  aclresult = pg_namespace_aclcheck(namespaceOid, newOwnerId,
9924  ACL_CREATE);
9925  if (aclresult != ACLCHECK_OK)
9927  get_namespace_name(namespaceOid));
9928  }
9929  }
9930 
9931  memset(repl_null, false, sizeof(repl_null));
9932  memset(repl_repl, false, sizeof(repl_repl));
9933 
9934  repl_repl[Anum_pg_class_relowner - 1] = true;
9935  repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
9936 
9937  /*
9938  * Determine the modified ACL for the new owner. This is only
9939  * necessary when the ACL is non-null.
9940  */
9941  aclDatum = SysCacheGetAttr(RELOID, tuple,
9943  &isNull);
9944  if (!isNull)
9945  {
9946  newAcl = aclnewowner(DatumGetAclP(aclDatum),
9947  tuple_class->relowner, newOwnerId);
9948  repl_repl[Anum_pg_class_relacl - 1] = true;
9949  repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
9950  }
9951 
9952  newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
9953 
9954  CatalogTupleUpdate(class_rel, &newtuple->t_self, newtuple);
9955 
9956  heap_freetuple(newtuple);
9957 
9958  /*
9959  * We must similarly update any per-column ACLs to reflect the new
9960  * owner; for neatness reasons that's split out as a subroutine.
9961  */
9962  change_owner_fix_column_acls(relationOid,
9963  tuple_class->relowner,
9964  newOwnerId);
9965 
9966  /*
9967  * Update owner dependency reference, if any. A composite type has
9968  * none, because it's tracked for the pg_type entry instead of here;
9969  * indexes and TOAST tables don't have their own entries either.
9970  */
9971  if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
9972  tuple_class->relkind != RELKIND_INDEX &&
9973  tuple_class->relkind != RELKIND_TOASTVALUE)
9975  newOwnerId);
9976 
9977  /*
9978  * Also change the ownership of the table's row type, if it has one
9979  */
9980  if (tuple_class->relkind != RELKIND_INDEX)
9981  AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId);
9982 
9983  /*
9984  * If we are operating on a table or materialized view, also change
9985  * the ownership of any indexes and sequences that belong to the
9986  * relation, as well as its toast table (if it has one).
9987  */
9988  if (tuple_class->relkind == RELKIND_RELATION ||
9989  tuple_class->relkind == RELKIND_MATVIEW ||
9990  tuple_class->relkind == RELKIND_TOASTVALUE)
9991  {
9992  List *index_oid_list;
9993  ListCell *i;
9994 
9995  /* Find all the indexes belonging to this relation */
9996  index_oid_list = RelationGetIndexList(target_rel);
9997 
9998  /* For each index, recursively change its ownership */
9999  foreach(i, index_oid_list)
10000  ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
10001 
10002  list_free(index_oid_list);
10003  }
10004 
10005  if (tuple_class->relkind == RELKIND_RELATION ||
10006  tuple_class->relkind == RELKIND_MATVIEW)
10007  {
10008  /* If it has a toast table, recurse to change its ownership */
10009  if (tuple_class->reltoastrelid != InvalidOid)
10010  ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
10011  true, lockmode);
10012 
10013  /* If it has dependent sequences, recurse to change them too */
10014  change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
10015  }
10016  }
10017 
10019 
10020  ReleaseSysCache(tuple);
10021  heap_close(class_rel, RowExclusiveLock);
10022  relation_close(target_rel, NoLock);
10023 }
#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:656
#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:429
Oid GetUserId(void)
Definition: miscinit.c:283
#define DatumGetAclP(X)
Definition: acl.h:113
#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:1260
void AlterTypeOwnerInternal(Oid typeOid, Oid newOwnerId)
Definition: typecmds.c:3361
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1372
unsigned int Oid
Definition: postgres_ext.h:31
AclResult pg_namespace_aclcheck(Oid nsp_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4484
#define RELKIND_COMPOSITE_TYPE
Definition: pg_class.h:166
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
signed int int32
Definition: c.h:256
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:3033
#define NoLock
Definition: lockdefs.h:34
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define RelationGetRelationName(relation)
Definition: rel.h:437
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
void check_is_member_of_role(Oid member, Oid role)
Definition: acl.c:4859
#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:9801
#define WARNING
Definition: elog.h:40
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
#define RELKIND_TOASTVALUE
Definition: pg_class.h:163
AclResult
Definition: acl.h:170
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1279
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#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:4546
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:10097
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4345
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:10032
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:499
#define RELKIND_INDEX
Definition: pg_class.h:161
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1114
#define elog
Definition: elog.h:219
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:791
#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:1726
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition: acl.c:1035
#define lfirst_oid(lc)
Definition: pg_list.h:108
#define Anum_pg_class_relowner
Definition: pg_class.h:107
void check_of_type ( HeapTuple  typetuple)

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

5011 {
5012  Form_pg_type typ = (Form_pg_type) GETSTRUCT(typetuple);
5013  bool typeOk = false;
5014 
5015  if (typ->typtype == TYPTYPE_COMPOSITE)
5016  {
5017  Relation typeRelation;
5018 
5019  Assert(OidIsValid(typ->typrelid));
5020  typeRelation = relation_open(typ->typrelid, AccessShareLock);
5021  typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
5022 
5023  /*
5024  * Close the parent rel, but keep our AccessShareLock on it until xact
5025  * commit. That will prevent someone else from deleting or ALTERing
5026  * the type before the typed table creation/conversion commits.
5027  */
5028  relation_close(typeRelation, NoLock);
5029  }
5030  if (!typeOk)
5031  ereport(ERROR,
5032  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5033  errmsg("type %s is not a composite type",
5034  format_type_be(HeapTupleGetOid(typetuple)))));
5035 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#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:1260
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:538
#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:675
int errmsg(const char *fmt,...)
Definition: elog.c:797
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1114
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
void CheckTableNotInUse ( Relation  rel,
const char *  stmt 
)

Definition at line 2997 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(), DefineVirtualRelation(), ExecRefreshMatView(), heap_drop_with_catalog(), index_drop(), reindex_index(), and truncate_check_rel().

2998 {
2999  int expected_refcnt;
3000 
3001  expected_refcnt = rel->rd_isnailed ? 2 : 1;
3002  if (rel->rd_refcnt != expected_refcnt)
3003  ereport(ERROR,
3004  (errcode(ERRCODE_OBJECT_IN_USE),
3005  /* translator: first %s is a SQL command, eg ALTER TABLE */
3006  errmsg("cannot %s \"%s\" because "
3007  "it is being used by active queries in this session",
3008  stmt, RelationGetRelationName(rel))));
3009 
3010  if (rel->rd_rel->relkind != RELKIND_INDEX &&
3012  ereport(ERROR,
3013  (errcode(ERRCODE_OBJECT_IN_USE),
3014  /* translator: first %s is a SQL command, eg ALTER TABLE */
3015  errmsg("cannot %s \"%s\" because "
3016  "it has pending trigger events",
3017  stmt, RelationGetRelationName(rel))));
3018 }
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:437
#define ereport(elevel, rest)
Definition: elog.h:122
bool AfterTriggerPendingOnRel(Oid relid)
Definition: trigger.c:5026
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:417
ObjectAddress DefineRelation ( CreateStmt stmt,
char  relkind,
Oid  ownerId,
ObjectAddress typaddress,
const char *  queryString 
)

Definition at line 489 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, tupleDesc::attrs, BuildDescForRelation(), 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_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, CookedConstraint::is_local, CookedConstraint::is_no_inherit, lappend(), lfirst, linitial_oid, list_concat(), list_length(), make_parsestate(), MergeAttributes(), MyDatabaseTableSpace, CookedConstraint::name, NAMEDATALEN, NIL, NoLock, NULL, 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(), RelationGetRelationName, 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(), typenameTypeId(), and view_reloptions().

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

491 {
492  char relname[NAMEDATALEN];
493  Oid namespaceId;
494  Oid relationId;
495  Oid tablespaceId;
496  Relation rel;
498  List *inheritOids;
499  List *old_constraints;
500  bool localHasOids;
501  int parentOidCount;
502  List *rawDefaults;
503  List *cookedDefaults;
504  Datum reloptions;
505  ListCell *listptr;
506  AttrNumber attnum;
507  static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
508  Oid ofTypeId;
509  ObjectAddress address;
510 
511  /*
512  * Truncate relname to appropriate length (probably a waste of time, as
513  * parser should have done this already).
514  */
515  StrNCpy(relname, stmt->relation->relname, NAMEDATALEN);
516 
517  /*
518  * Check consistency of arguments
519  */
520  if (stmt->oncommit != ONCOMMIT_NOOP
522  ereport(ERROR,
523  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
524  errmsg("ON COMMIT can only be used on temporary tables")));
525 
526  if (stmt->partspec != NULL)
527  {
528  if (relkind != RELKIND_RELATION)
529  elog(ERROR, "unexpected relkind: %d", (int) relkind);
530 
531  relkind = RELKIND_PARTITIONED_TABLE;
532  }
533 
534  /*
535  * Look up the namespace in which we are supposed to create the relation,
536  * check we have permission to create there, lock it against concurrent
537  * drop, and mark stmt->relation as RELPERSISTENCE_TEMP if a temporary
538  * namespace is selected.
539  */
540  namespaceId =
542 
543  /*
544  * Security check: disallow creating temp tables from security-restricted
545  * code. This is needed because calling code might not expect untrusted
546  * tables to appear in pg_temp at the front of its search path.
547  */
550  ereport(ERROR,
551  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
552  errmsg("cannot create temporary table within security-restricted operation")));
553 
554  /*
555  * Select tablespace to use. If not specified, use default tablespace
556  * (which may in turn default to database's default).
557  */
558  if (stmt->tablespacename)
559  {
560  tablespaceId = get_tablespace_oid(stmt->tablespacename, false);
561  }
562  else
563  {
564  tablespaceId = GetDefaultTablespace(stmt->relation->relpersistence);
565  /* note InvalidOid is OK in this case */
566  }
567 
568  /* Check permissions except when using database's default */
569  if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
570  {
571  AclResult aclresult;
572 
573  aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
574  ACL_CREATE);
575  if (aclresult != ACLCHECK_OK)
577  get_tablespace_name(tablespaceId));
578  }
579 
580  /* In all cases disallow placing user relations in pg_global */
581  if (tablespaceId == GLOBALTABLESPACE_OID)
582  ereport(ERROR,
583  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
584  errmsg("only shared relations can be placed in pg_global tablespace")));
585 
586  /* Identify user ID that will own the table */
587  if (!OidIsValid(ownerId))
588  ownerId = GetUserId();
589 
590  /*
591  * Parse and validate reloptions, if any.
592  */
593  reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, validnsps,
594  true, false);
595 
596  if (relkind == RELKIND_VIEW)
597  (void) view_reloptions(reloptions, true);
598  else
599  (void) heap_reloptions(relkind, reloptions, true);
600 
601  if (stmt->ofTypename)
602  {
603  AclResult aclresult;
604 
605  ofTypeId = typenameTypeId(NULL, stmt->ofTypename);
606 
607  aclresult = pg_type_aclcheck(ofTypeId, GetUserId(), ACL_USAGE);
608  if (aclresult != ACLCHECK_OK)
609  aclcheck_error_type(aclresult, ofTypeId);
610  }
611  else
612  ofTypeId = InvalidOid;
613 
614  /*
615  * Look up inheritance ancestors and generate relation schema, including
616  * inherited attributes. (Note that stmt->tableElts is destructively
617  * modified by MergeAttributes.)
618  */
619  stmt->tableElts =
621  stmt->relation->relpersistence,
622  stmt->partbound != NULL,
623  &inheritOids, &old_constraints, &parentOidCount);
624 
625  /*
626  * Create a tuple descriptor from the relation schema. Note that this
627  * deals with column names, types, and NOT NULL constraints, but not
628  * default values or CHECK constraints; we handle those below.
629  */
630  descriptor = BuildDescForRelation(stmt->tableElts);
631 
632  /*
633  * Notice that we allow OIDs here only for plain tables and partitioned
634  * tables, even though some other relkinds can support them. This is
635  * necessary because the default_with_oids GUC must apply only to plain
636  * tables and not any other relkind; doing otherwise would break existing
637  * pg_dump files. We could allow explicit "WITH OIDS" while not allowing
638  * default_with_oids to affect other relkinds, but it would complicate
639  * interpretOidsOption().
640  */
641  localHasOids = interpretOidsOption(stmt->options,
642  (relkind == RELKIND_RELATION ||
643  relkind == RELKIND_PARTITIONED_TABLE));
644  descriptor->tdhasoid = (localHasOids || parentOidCount > 0);
645 
646  /*
647  * If a partitioned table doesn't have the system OID column, then none of
648  * its partitions should have it.
649  */
650  if (stmt->partbound && parentOidCount == 0 && localHasOids)
651  ereport(ERROR,
652  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
653  errmsg("cannot create table with OIDs as partition of table without OIDs")));
654 
655  /*
656  * Find columns with default values and prepare for insertion of the
657  * defaults. Pre-cooked (that is, inherited) defaults go into a list of
658  * CookedConstraint structs that we'll pass to heap_create_with_catalog,
659  * while raw defaults go into a list of RawColumnDefault structs that will
660  * be processed by AddRelationNewConstraints. (We can't deal with raw
661  * expressions until we can do transformExpr.)
662  *
663  * We can set the atthasdef flags now in the tuple descriptor; this just
664  * saves StoreAttrDefault from having to do an immediate update of the
665  * pg_attribute rows.
666  */
667  rawDefaults = NIL;
668  cookedDefaults = NIL;
669  attnum = 0;
670 
671  foreach(listptr, stmt->tableElts)
672  {
673  ColumnDef *colDef = lfirst(listptr);
674 
675  attnum++;
676 
677  if (colDef->raw_default != NULL)
678  {
679  RawColumnDefault *rawEnt;
680 
681  Assert(colDef->cooked_default == NULL);
682 
683  rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
684  rawEnt->attnum = attnum;
685  rawEnt->raw_default = colDef->raw_default;
686  rawDefaults = lappend(rawDefaults, rawEnt);
687  descriptor->attrs[attnum - 1]->atthasdef = true;
688  }
689  else if (colDef->cooked_default != NULL)
690  {
691  CookedConstraint *cooked;
692 
693  cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
694  cooked->contype = CONSTR_DEFAULT;
695  cooked->conoid = InvalidOid; /* until created */
696  cooked->name = NULL;
697  cooked->attnum = attnum;
698  cooked->expr = colDef->cooked_default;
699  cooked->skip_validation = false;
700  cooked->is_local = true; /* not used for defaults */
701  cooked->inhcount = 0; /* ditto */
702  cooked->is_no_inherit = false;
703  cookedDefaults = lappend(cookedDefaults, cooked);
704  descriptor->attrs[attnum - 1]->atthasdef = true;
705  }
706 
707  if (colDef->identity)
708  descriptor->attrs[attnum - 1]->attidentity = colDef->identity;
709  }
710 
711  /*
712  * Create the relation. Inherited defaults and constraints are passed in
713  * for immediate handling --- since they don't need parsing, they can be
714  * stored immediately.
715  */
716  relationId = heap_create_with_catalog(relname,
717  namespaceId,
718  tablespaceId,
719  InvalidOid,
720  InvalidOid,
721  ofTypeId,
722  ownerId,
723  descriptor,
724  list_concat(cookedDefaults,
725  old_constraints),
726  relkind,
727  stmt->relation->relpersistence,
728  false,
729  false,
730  localHasOids,
731  parentOidCount,
732  stmt->oncommit,
733  reloptions,
734  true,
736  false,
737  typaddress);
738 
739  /* Store inheritance information for new rel. */
740  StoreCatalogInheritance(relationId, inheritOids, stmt->partbound != NULL);
741 
742  /*
743  * We must bump the command counter to make the newly-created relation
744  * tuple visible for opening.
745  */
747 
748  /*
749  * Open the new relation and acquire exclusive lock on it. This isn't
750  * really necessary for locking out other backends (since they can't see
751  * the new rel anyway until we commit), but it keeps the lock manager from
752  * complaining about deadlock risks.
753  */
754  rel = relation_open(relationId, AccessExclusiveLock);
755 
756  /* Process and store partition bound, if any. */
757  if (stmt->partbound)
758  {
759  Node *bound;
760  ParseState *pstate;
761  Oid parentId = linitial_oid(inheritOids);
762  Relation parent;
763 
764  /* Already have strong enough lock on the parent */
765  parent = heap_open(parentId, NoLock);
766 
767  /*
768  * We are going to try to validate the partition bound specification
769  * against the partition key of parentRel, so it better have one.
770  */
771  if (parent->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
772  ereport(ERROR,
773  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
774  errmsg("\"%s\" is not partitioned",
775  RelationGetRelationName(parent))));
776 
777  /* Tranform the bound values */
778  pstate = make_parsestate(NULL);
779  pstate->p_sourcetext = queryString;
780  bound = transformPartitionBound(pstate, parent, stmt->partbound);
781 
782  /*
783  * Check first that the new partition's bound is valid and does not
784  * overlap with any of existing partitions of the parent - note that
785  * it does not return on error.
786  */
787  check_new_partition_bound(relname, parent, bound);
788 
789  /* Update the pg_class entry. */
790  StorePartitionBound(rel, parent, bound);
791 
792  heap_close(parent, NoLock);
793 
794  /*
795  * The code that follows may also update the pg_class tuple to update
796  * relnumchecks, so bump up the command counter to avoid the "already
797  * updated by self" error.
798  */
800  }
801 
802  /*
803  * Process the partitioning specification (if any) and store the partition
804  * key information into the catalog.
805  */
806  if (stmt->partspec)
807  {
808  char strategy;
809  int partnatts;
810  AttrNumber partattrs[PARTITION_MAX_KEYS];
811  Oid partopclass[PARTITION_MAX_KEYS];
812  Oid partcollation[PARTITION_MAX_KEYS];
813  List *partexprs = NIL;
814 
815  /*
816  * We need to transform the raw parsetrees corresponding to partition
817  * expressions into executable expression trees. Like column defaults
818  * and CHECK constraints, we could not have done the transformation
819  * earlier.
820  */
821  stmt->partspec = transformPartitionSpec(rel, stmt->partspec,
822  &strategy);
824  partattrs, &partexprs, partopclass,
825  partcollation);
826 
827  partnatts = list_length(stmt->partspec->partParams);
828  StorePartitionKey(rel, strategy, partnatts, partattrs, partexprs,
829  partopclass, partcollation);
830  }
831 
832  /*
833  * Now add any newly specified column default values and CHECK constraints
834  * to the new relation. These are passed to us in the form of raw
835  * parsetrees; we need to transform them to executable expression trees
836  * before they can be added. The most convenient way to do that is to
837  * apply the parser's transformExpr routine, but transformExpr doesn't
838  * work unless we have a pre-existing relation. So, the transformation has
839  * to be postponed to this final step of CREATE TABLE.
840  */
841  if (rawDefaults || stmt->constraints)
842  AddRelationNewConstraints(rel, rawDefaults, stmt->constraints,
843  true, true, false);
844 
845  ObjectAddressSet(address, RelationRelationId, relationId);
846 
847  /*
848  * Clean up. We keep lock on new relation (although it shouldn't be
849  * visible to anyone else anyway, until commit).
850  */
851  relation_close(rel, NoLock);
852 
853  return address;
854 }
RangeVar * relation
Definition: parsenodes.h:1968
bytea * heap_reloptions(char relkind, Datum reloptions, bool validate)
Definition: reloptions.c:1409
#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:1977
List * inhRelations
Definition: parsenodes.h:1970
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4496
bool is_no_inherit
Definition: heap.h:38
bool tdhasoid
Definition: tupdesc.h:79
void StorePartitionKey(Relation rel, char strategy, int16 partnatts, AttrNumber *partattrs, List *partexprs, Oid *partopclass, Oid *partcollation)
Definition: heap.c:3086
AttrNumber attnum
Definition: heap.h:24
List * partParams
Definition: parsenodes.h:777
Oid GetUserId(void)
Definition: miscinit.c:283
Node * transformPartitionBound(ParseState *pstate, Relation parent, Node *bound)
char identity
Definition: parsenodes.h:650
#define RelationRelationId
Definition: pg_class.h:29
Form_pg_attribute * attrs
Definition: tupdesc.h:74
#define GLOBALTABLESPACE_OID
Definition: pg_tablespace.h:64
Definition: nodes.h:509
int errcode(int sqlerrcode)
Definition: elog.c:575
#define PARTITION_MAX_KEYS
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1260
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
#define OidIsValid(objectId)
Definition: c.h:538
static void StoreCatalogInheritance(Oid relationId, List *supers, bool child_is_partition)
Definition: tablecmds.c:2280
Oid GetDefaultTablespace(char relpersistence)
Definition: tablespace.c:1111
static PartitionSpec * transformPartitionSpec(Relation rel, PartitionSpec *partspec, char *strategy)
Definition: tablecmds.c:13114
void aclcheck_error_type(AclResult aclerr, Oid typeOid)
Definition: aclchk.c:3457
Oid MyDatabaseTableSpace
Definition: globals.c:78
static void ComputePartitionAttrs(Relation rel, List *partParams, AttrNumber *partattrs, List **partexprs, Oid *partopclass, Oid *partcollation)
Definition: tablecmds.c:13186
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
bytea * view_reloptions(Datum reloptions, bool validate)
Definition: reloptions.c:1377
List * constraints
Definition: parsenodes.h:1975
#define NAMEDATALEN
Node * cooked_default
Definition: parsenodes.h:649
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:3399
void check_new_partition_bound(char *relname, Relation parent, Node *bound)
Definition: partition.c:668
#define RelationGetRelationName(relation)
Definition: rel.h:437
List * options
Definition: parsenodes.h:1976
Node * raw_default
Definition: heap.h:25
#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:168
ConstrType contype
Definition: heap.h:30
#define ereport(elevel, rest)
Definition: elog.h:122
Node * raw_default
Definition: parsenodes.h:648
List * lappend(List *list, void *datum)
Definition: list.c:128
char * tablespacename
Definition: parsenodes.h:1978
void StorePartitionBound(Relation rel, Relation parent, Node *bound)
Definition: heap.c:3222
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:170
uintptr_t Datum
Definition: postgres.h:372
void CommandCounterIncrement(void)
Definition: xact.c:922
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
Node * partbound
Definition: parsenodes.h:1972
Datum transformRelOptions(Datum oldOptions, List *defList, char *namspace, char *validnsps[], bool ignoreOids, bool isReset)
Definition: reloptions.c:745
bool allowSystemTableMods
Definition: globals.c:111
#define InvalidOid
Definition: postgres_ext.h:36
List * tableElts
Definition: parsenodes.h:1969
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
#define StrNCpy(dst, src, len)
Definition: c.h:830
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:415
#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:1602
#define AccessExclusiveLock
Definition: lockdefs.h:46
void * palloc(Size size)
Definition: mcxt.c:849
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:1019
Oid conoid
Definition: heap.h:31
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1114
Node * expr
Definition: heap.h:34
#define elog
Definition: elog.h:219
TupleDesc BuildDescForRelation(List *schema)
Definition: tupdesc.c:681
#define RELPERSISTENCE_TEMP
Definition: pg_class.h:172
AclResult pg_type_aclcheck(Oid type_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4534
#define RELKIND_RELATION
Definition: pg_class.h:160
PartitionSpec * partspec
Definition: parsenodes.h:1973
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
char * name
Definition: heap.h:32
List * AddRelationNewConstraints(Relation rel, List *newColDefaults, List *newConstraints, bool allow_merge, bool is_local, bool is_internal)
Definition: heap.c:2201
TypeName * ofTypename
Definition: parsenodes.h:1974
bool is_local
Definition: heap.h:36
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:274
void ExecuteTruncate ( TruncateStmt stmt)

Definition at line 1177 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, NULL, 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(), RELKIND_PARTITIONED_TABLE, RELPERSISTENCE_UNLOGGED, ResetSequence(), TruncateStmt::restart_seqs, and truncate_check_rel().

Referenced by standard_ProcessUtility().

1178 {
1179  List *rels = NIL;
1180  List *relids = NIL;
1181  List *seq_relids = NIL;
1182  EState *estate;
1183  ResultRelInfo *resultRelInfos;
1184  ResultRelInfo *resultRelInfo;
1185  SubTransactionId mySubid;
1186  ListCell *cell;
1187 
1188  /*
1189  * Open, exclusive-lock, and check all the explicitly-specified relations
1190  */
1191  foreach(cell, stmt->relations)
1192  {
1193  RangeVar *rv = lfirst(cell);
1194  Relation rel;
1195  bool recurse = rv->inh;
1196  Oid myrelid;
1197 
1198  rel = heap_openrv(rv, AccessExclusiveLock);
1199  myrelid = RelationGetRelid(rel);
1200  /* don't throw error for "TRUNCATE foo, foo" */
1201  if (list_member_oid(relids, myrelid))
1202  {
1204  continue;
1205  }
1206  truncate_check_rel(rel);
1207  rels = lappend(rels, rel);
1208  relids = lappend_oid(relids, myrelid);
1209 
1210  if (recurse)
1211  {
1212  ListCell *child;
1213  List *children;
1214 
1215  children = find_all_inheritors(myrelid, AccessExclusiveLock, NULL);
1216 
1217  foreach(child, children)
1218  {
1219  Oid childrelid = lfirst_oid(child);
1220 
1221  if (list_member_oid(relids, childrelid))
1222  continue;
1223 
1224  /* find_all_inheritors already got lock */
1225  rel = heap_open(childrelid, NoLock);
1226  truncate_check_rel(rel);
1227  rels = lappend(rels, rel);
1228  relids = lappend_oid(relids, childrelid);
1229  }
1230  }
1231  else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1232  ereport(ERROR,
1233  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1234  errmsg("cannot truncate only a partitioned table"),
1235  errhint("Do not specify the ONLY keyword, or use truncate only on the partitions directly.")));
1236  }
1237 
1238  /*
1239  * In CASCADE mode, suck in all referencing relations as well. This
1240  * requires multiple iterations to find indirectly-dependent relations. At
1241  * each phase, we need to exclusive-lock new rels before looking for their
1242  * dependencies, else we might miss something. Also, we check each rel as
1243  * soon as we open it, to avoid a faux pas such as holding lock for a long
1244  * time on a rel we have no permissions for.
1245  */
1246  if (stmt->behavior == DROP_CASCADE)
1247  {
1248  for (;;)
1249  {
1250  List *newrelids;
1251 
1252  newrelids = heap_truncate_find_FKs(relids);
1253  if (newrelids == NIL)
1254  break; /* nothing else to add */
1255 
1256  foreach(cell, newrelids)
1257  {
1258  Oid relid = lfirst_oid(cell);
1259  Relation rel;
1260 
1261  rel = heap_open(relid, AccessExclusiveLock);
1262  ereport(NOTICE,
1263  (errmsg("truncate cascades to table \"%s\"",
1264  RelationGetRelationName(rel))));
1265  truncate_check_rel(rel);
1266  rels = lappend(rels, rel);
1267  relids = lappend_oid(relids, relid);
1268  }
1269  }
1270  }
1271 
1272  /*
1273  * Check foreign key references. In CASCADE mode, this should be
1274  * unnecessary since we just pulled in all the references; but as a
1275  * cross-check, do it anyway if in an Assert-enabled build.
1276  */
1277 #ifdef USE_ASSERT_CHECKING
1278  heap_truncate_check_FKs(rels, false);
1279 #else
1280  if (stmt->behavior == DROP_RESTRICT)
1281  heap_truncate_check_FKs(rels, false);
1282 #endif
1283 
1284  /*
1285  * If we are asked to restart sequences, find all the sequences, lock them
1286  * (we need AccessExclusiveLock for ResetSequence), and check permissions.
1287  * We want to do this early since it's pointless to do all the truncation
1288  * work only to fail on sequence permissions.
1289  */
1290  if (stmt->restart_seqs)
1291  {
1292  foreach(cell, rels)
1293  {
1294  Relation rel = (Relation) lfirst(cell);
1295  List *seqlist = getOwnedSequences(RelationGetRelid(rel), 0);
1296  ListCell *seqcell;
1297 
1298  foreach(seqcell, seqlist)
1299  {
1300  Oid seq_relid = lfirst_oid(seqcell);
1301  Relation seq_rel;
1302 
1303  seq_rel = relation_open(seq_relid, AccessExclusiveLock);
1304 
1305  /* This check must match AlterSequence! */
1306  if (!pg_class_ownercheck(seq_relid, GetUserId()))
1308  RelationGetRelationName(seq_rel));
1309 
1310  seq_relids = lappend_oid(seq_relids, seq_relid);
1311 
1312  relation_close(seq_rel, NoLock);
1313  }
1314  }
1315  }
1316 
1317  /* Prepare to catch AFTER triggers. */
1319 
1320  /*
1321  * To fire triggers, we'll need an EState as well as a ResultRelInfo for
1322  * each relation. We don't need to call ExecOpenIndices, though.
1323  */
1324  estate = CreateExecutorState();
1325  resultRelInfos = (ResultRelInfo *)
1326  palloc(list_length(rels) * sizeof(ResultRelInfo));
1327  resultRelInfo = resultRelInfos;
1328  foreach(cell, rels)
1329  {
1330  Relation rel = (Relation) lfirst(cell);
1331 
1332  InitResultRelInfo(resultRelInfo,
1333  rel,
1334  0, /* dummy rangetable index */
1335  NULL,
1336  0);
1337  resultRelInfo++;
1338  }
1339  estate->es_result_relations = resultRelInfos;
1340  estate->es_num_result_relations = list_length(rels);
1341 
1342  /*
1343  * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
1344  * truncating (this is because one of them might throw an error). Also, if
1345  * we were to allow them to prevent statement execution, that would need
1346  * to be handled here.
1347  */
1348  resultRelInfo = resultRelInfos;
1349  foreach(cell, rels)
1350  {
1351  estate->es_result_relation_info = resultRelInfo;
1352  ExecBSTruncateTriggers(estate, resultRelInfo);
1353  resultRelInfo++;
1354  }
1355 
1356  /*
1357  * OK, truncate each table.
1358  */
1359  mySubid = GetCurrentSubTransactionId();
1360 
1361  foreach(cell, rels)
1362  {
1363  Relation rel = (Relation) lfirst(cell);
1364 
1365  /* Skip partitioned tables as there is nothing to do */
1366  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1367  continue;
1368 
1369  /*
1370  * Normally, we need a transaction-safe truncation here. However, if
1371  * the table was either created in the current (sub)transaction or has
1372  * a new relfilenode in the current (sub)transaction, then we can just
1373  * truncate it in-place, because a rollback would cause the whole
1374  * table or the current physical file to be thrown away anyway.
1375  */
1376  if (rel->rd_createSubid == mySubid ||
1377  rel->rd_newRelfilenodeSubid == mySubid)
1378  {
1379  /* Immediate, non-rollbackable truncation is OK */
1380  heap_truncate_one_rel(rel);
1381  }
1382  else
1383  {
1384  Oid heap_relid;
1385  Oid toast_relid;
1386  MultiXactId minmulti;
1387 
1388  /*
1389  * This effectively deletes all rows in the table, and may be done
1390  * in a serializable transaction. In that case we must record a
1391  * rw-conflict in to this transaction from each transaction
1392  * holding a predicate lock on the table.
1393  */
1395 
1396  minmulti = GetOldestMultiXactId();
1397 
1398  /*
1399  * Need the full transaction-safe pushups.
1400  *
1401  * Create a new empty storage file for the relation, and assign it
1402  * as the relfilenode value. The old storage file is scheduled for
1403  * deletion at commit.
1404  */
1405  RelationSetNewRelfilenode(rel, rel->rd_rel->relpersistence,
1406  RecentXmin, minmulti);
1407  if (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED)
1408  heap_create_init_fork(rel);
1409 
1410  heap_relid = RelationGetRelid(rel);
1411  toast_relid = rel->rd_rel->reltoastrelid;
1412 
1413  /*
1414  * The same for the toast table, if any.
1415  */
1416  if (OidIsValid(toast_relid))
1417  {
1418  rel = relation_open(toast_relid, AccessExclusiveLock);
1419  RelationSetNewRelfilenode(rel, rel->rd_rel->relpersistence,
1420  RecentXmin, minmulti);
1421  if (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED)
1422  heap_create_init_fork(rel);
1423  heap_close(rel, NoLock);
1424  }
1425 
1426  /*
1427  * Reconstruct the indexes to match, and we're done.
1428  */
1430  }
1431 
1432  pgstat_count_truncate(rel);
1433  }
1434 
1435  /*
1436  * Restart owned sequences if we were asked to.
1437  */
1438  foreach(cell, seq_relids)
1439  {
1440  Oid seq_relid = lfirst_oid(cell);
1441 
1442  ResetSequence(seq_relid);
1443  }
1444 
1445  /*
1446  * Process all AFTER STATEMENT TRUNCATE triggers.
1447  */
1448  resultRelInfo = resultRelInfos;
1449  foreach(cell, rels)
1450  {
1451  estate->es_result_relation_info = resultRelInfo;
1452  ExecASTruncateTriggers(estate, resultRelInfo);
1453  resultRelInfo++;
1454  }
1455 
1456  /* Handle queued AFTER triggers */
1457  AfterTriggerEndQuery(estate);
1458 
1459  /* We can clean up the EState now */
1460  FreeExecutorState(estate);
1461 
1462  /* And close the rels (can't do this while EState still holds refs) */
1463  foreach(cell, rels)
1464  {
1465  Relation rel = (Relation) lfirst(cell);
1466 
1467  heap_close(rel, NoLock);
1468  }
1469 }
#define NIL
Definition: pg_list.h:69
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, Relation partition_root, int instrument_options)
Definition: execMain.c:1297
void RelationSetNewRelfilenode(Relation relation, char persistence, TransactionId freezeXid, MultiXactId minmulti)
Definition: relcache.c:3416
int errhint(const char *fmt,...)
Definition: elog.c:987
#define RELPERSISTENCE_UNLOGGED
Definition: pg_class.h:171
Oid GetUserId(void)
Definition: miscinit.c:283
void heap_truncate_one_rel(Relation rel)
Definition: heap.c:2873
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:2910
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1260
SubTransactionId rd_newRelfilenodeSubid
Definition: rel.h:111
uint32 SubTransactionId
Definition: c.h:401
#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:538
void FreeExecutorState(EState *estate)
Definition: execUtils.c:178
DropBehavior behavior
Definition: parsenodes.h:2558
struct RelationData * Relation
Definition: relcache.h:21
void ExecBSTruncateTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:2833
#define ERROR
Definition: elog.h:43
struct ResultRelInfo ResultRelInfo
List * relations
Definition: parsenodes.h:2556
#define NoLock
Definition: lockdefs.h:34
void heap_create_init_fork(Relation rel)
Definition: heap.c:1380
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
ResultRelInfo * es_result_relations
Definition: execnodes.h:421
bool restart_seqs
Definition: parsenodes.h:2557
void ExecASTruncateTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:2885
#define RelationGetRelationName(relation)
Definition: rel.h:437
void pgstat_count_truncate(Relation rel)
Definition: pgstat.c:2008
#define ereport(elevel, rest)
Definition: elog.h:122
EState * CreateExecutorState(void)
Definition: execUtils.c:80
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:1475
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
int es_num_result_relations
Definition: execnodes.h:422
Relation heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1312
#define NOTICE
Definition: elog.h:37
void AfterTriggerBeginQuery(void)
Definition: trigger.c:4168
TransactionId MultiXactId
Definition: c.h:407
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:505
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:649
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4546
static int list_length(const List *l)
Definition: pg_list.h:89
void CheckTableForSerializableConflictIn(Relation relation)
Definition: predicate.c:4391
#define AccessExclusiveLock
Definition: lockdefs.h:46
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:167
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:4188
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1114
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:122
void ResetSequence(Oid seq_relid)
Definition: sequence.c:267
bool reindex_relation(Oid relid, int flags, int options)
Definition: index.c:3509
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:417
List * heap_truncate_find_FKs(List *relationIds)
Definition: heap.c:3002
#define lfirst_oid(lc)
Definition: pg_list.h:108
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:423
void find_composite_type_dependencies ( Oid  typeOid,
Relation  origRelation,
const char *  origTypeName 
)

Definition at line 4855 of file tablecmds.c.

References AccessShareLock, Anum_pg_depend_refclassid, Anum_pg_depend_refobjid, tupleDesc::attrs, BTEqualStrategyNumber, DependReferenceIndexId, DependRelationId, ereport, errcode(), errmsg(), ERROR, find_composite_type_dependencies(), get_array_type(), GETSTRUCT, heap_open(), HeapTupleIsValid, NameStr, NULL, 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(), and TypeRelationId.

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

4857 {
4858  Relation depRel;
4859  ScanKeyData key[2];
4860  SysScanDesc depScan;
4861  HeapTuple depTup;
4862  Oid arrayOid;
4863 
4864  /*
4865  * We scan pg_depend to find those things that depend on the rowtype. (We
4866  * assume we can ignore refobjsubid for a rowtype.)
4867  */
4869 
4870  ScanKeyInit(&key[0],
4872  BTEqualStrategyNumber, F_OIDEQ,
4874  ScanKeyInit(&key[1],
4876  BTEqualStrategyNumber, F_OIDEQ,
4877  ObjectIdGetDatum(typeOid));
4878 
4879  depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
4880  NULL, 2, key);
4881 
4882  while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
4883  {
4884  Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
4885  Relation rel;
4886  Form_pg_attribute att;
4887 
4888  /* Ignore dependees that aren't user columns of relations */
4889  /* (we assume system columns are never of rowtypes) */
4890  if (pg_depend->classid != RelationRelationId ||
4891  pg_depend->objsubid <= 0)
4892  continue;
4893 
4894  rel = relation_open(pg_depend->objid, AccessShareLock);
4895  att = rel->rd_att->attrs[pg_depend->objsubid - 1];
4896 
4897  if (rel->rd_rel->relkind == RELKIND_RELATION ||
4898  rel->rd_rel->relkind == RELKIND_MATVIEW ||
4899  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
4900  {
4901  if (origTypeName)
4902  ereport(ERROR,
4903  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4904  errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
4905  origTypeName,
4907  NameStr(att->attname))));
4908  else if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
4909  ereport(ERROR,
4910  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4911  errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
4912  RelationGetRelationName(origRelation),
4914  NameStr(att->attname))));
4915  else if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
4916  ereport(ERROR,
4917  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4918  errmsg("cannot alter foreign table \"%s\" because column \"%s.%s\" uses its row type",
4919  RelationGetRelationName(origRelation),
4921  NameStr(att->attname))));
4922  else
4923  ereport(ERROR,
4924  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4925  errmsg("cannot alter table \"%s\" because column \"%s.%s\" uses its row type",
4926  RelationGetRelationName(origRelation),
4928  NameStr(att->attname))));
4929  }
4930  else if (OidIsValid(rel->rd_rel->reltype))
4931  {
4932  /*
4933  * A view or composite type itself isn't a problem, but we must
4934  * recursively check for indirect dependencies via its rowtype.
4935  */
4937  origRelation, origTypeName);
4938  }
4939 
4941  }
4942 
4943  systable_endscan(depScan);
4944 
4946 
4947  /*
4948  * If there's an array type for the rowtype, must check for uses of it,
4949  * too.
4950  */
4951  arrayOid = get_array_type(typeOid);
4952  if (OidIsValid(arrayOid))
4953  find_composite_type_dependencies(arrayOid, origRelation, origTypeName);
4954 }
#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:656
Oid get_array_type(Oid typid)
Definition: lsyscache.c:2512
#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:4855
#define DependRelationId
Definition: pg_depend.h:29
Form_pg_attribute * attrs
Definition: tupdesc.h:74
#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:1260
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
#define TypeRelationId
Definition: pg_type.h:34
#define OidIsValid(objectId)
Definition: c.h:538
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
#define RelationGetRelationName(relation)
Definition: rel.h:437
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:1284
TupleDesc rd_att
Definition: rel.h:115
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:499
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:1114
#define RELKIND_RELATION
Definition: pg_class.h:160
#define BTEqualStrategyNumber
Definition: stratnum.h:31
void PreCommit_on_commit_actions ( void  )

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

12768 {
12769  ListCell *l;
12770  List *oids_to_truncate = NIL;
12771 
12772  foreach(l, on_commits)
12773  {
12774  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
12775 
12776  /* Ignore entry if already dropped in this xact */
12778  continue;
12779 
12780  switch (oc->oncommit)
12781  {
12782  case ONCOMMIT_NOOP:
12784  /* Do nothing (there shouldn't be such entries, actually) */
12785  break;
12786  case ONCOMMIT_DELETE_ROWS:
12787 
12788  /*
12789  * If this transaction hasn't accessed any temporary
12790  * relations, we can skip truncating ON COMMIT DELETE ROWS
12791  * tables, as they must still be empty.
12792  */
12794  oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
12795  break;
12796  case ONCOMMIT_DROP:
12797  {
12798  ObjectAddress object;
12799 
12800  object.classId = RelationRelationId;
12801  object.objectId = oc->relid;
12802  object.objectSubId = 0;
12803 
12804  /*
12805  * Since this is an automatic drop, rather than one
12806  * directly initiated by the user, we pass the
12807  * PERFORM_DELETION_INTERNAL flag.
12808  */
12809  performDeletion(&object,
12811 
12812  /*
12813  * Note that table deletion will call
12814  * remove_on_commit_action, so the entry should get marked
12815  * as deleted.
12816  */
12818  break;
12819  }
12820  }
12821  }
12822  if (oids_to_truncate != NIL)
12823  {
12824  heap_truncate(oids_to_truncate);
12825  CommandCounterIncrement(); /* XXX needed? */
12826  }
12827 }
#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:87
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:922
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
void heap_truncate(List *relids)
Definition: heap.c:2832
#define InvalidSubTransactionId
Definition: c.h:403
Definition: pg_list.h:45
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:174
void RangeVarCallbackOwnsRelation ( const RangeVar relation,
Oid  relId,
Oid  oldRelId,
void *  noCatalogs 
)

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

12960 {
12961  HeapTuple tuple;
12962 
12963  /* Nothing to do if the relation was not found. */
12964  if (!OidIsValid(relId))
12965  return;
12966 
12967  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
12968  if (!HeapTupleIsValid(tuple)) /* should not happen */
12969  elog(ERROR, "cache lookup failed for relation %u", relId);
12970 
12971  if (!pg_class_ownercheck(relId, GetUserId()))
12973  relation->relname);
12974 
12975  if (!allowSystemTableMods &&
12976  IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
12977  ereport(ERROR,
12978  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
12979  errmsg("permission denied: \"%s\" is a system catalog",
12980  relation->relname)));
12981 
12982  ReleaseSysCache(tuple);
12983 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
Oid GetUserId(void)
Definition: miscinit.c:283
int errcode(int sqlerrcode)
Definition: elog.c:575
#define OidIsValid(objectId)
Definition: c.h:538
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
Definition: catalog.c:74
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:3399
#define ereport(elevel, rest)
Definition: elog.h:122
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
bool allowSystemTableMods
Definition: globals.c:111
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4546
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
void RangeVarCallbackOwnsTable ( const RangeVar relation,
Oid  relId,
Oid  oldRelId,
void *  arg 
)

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

12927 {
12928  char relkind;
12929 
12930  /* Nothing to do if the relation was not found. */
12931  if (!OidIsValid(relId))
12932  return;
12933 
12934  /*
12935  * If the relation does exist, check whether it's an index. But note that
12936  * the relation might have been dropped between the time we did the name
12937  * lookup and now. In that case, there's nothing to do.
12938  */
12939  relkind = get_rel_relkind(relId);
12940  if (!relkind)
12941  return;
12942  if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
12943  relkind != RELKIND_MATVIEW && relkind != RELKIND_PARTITIONED_TABLE)
12944  ereport(ERROR,
12945  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
12946  errmsg("\"%s\" is not a table or materialized view", relation->relname)));
12947 
12948  /* Check permissions */
12949  if (!pg_class_ownercheck(relId, GetUserId()))
12951 }
Oid GetUserId(void)
Definition: miscinit.c:283
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1801
#define RELKIND_MATVIEW
Definition: pg_class.h:165
int errcode(int sqlerrcode)
Definition: elog.c:575
#define OidIsValid(objectId)
Definition: c.h:538
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:3399
#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:4546
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define RELKIND_RELATION
Definition: pg_class.h:160
void register_on_commit_action ( Oid  relid,
OnCommitAction  action 
)

Definition at line 12713 of file tablecmds.c.

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

12714 {
12715  OnCommitItem *oc;
12716  MemoryContext oldcxt;
12717 
12718  /*
12719  * We needn't bother registering the relation unless there is an ON COMMIT
12720  * action we need to take.
12721  */
12722  if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
12723  return;
12724 
12726 
12727  oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
12728  oc->relid = relid;
12729  oc->oncommit = action;
12732 
12733  on_commits = lcons(oc, on_commits);
12734 
12735  MemoryContextSwitchTo(oldcxt);
12736 }
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:649
#define InvalidSubTransactionId
Definition: c.h:403
void * palloc(Size size)
Definition: mcxt.c:849
MemoryContext CacheMemoryContext
Definition: mcxt.c:46
void remove_on_commit_action ( Oid  relid)

Definition at line 12744 of file tablecmds.c.

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

Referenced by heap_drop_with_catalog().

12745 {
12746  ListCell *l;
12747 
12748  foreach(l, on_commits)
12749  {
12750  OnCommitItem *oc = (OnCommitItem *) lfirst(l);
12751 
12752  if (oc->relid == relid)
12753  {
12755  break;
12756  }
12757  }
12758 }
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:649
void RemoveRelations ( DropStmt drop)

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

937 {
938  ObjectAddresses *objects;
939  char relkind;
940  ListCell *cell;
941  int flags = 0;
942  LOCKMODE lockmode = AccessExclusiveLock;
943 
944  /* DROP CONCURRENTLY uses a weaker lock, and has some restrictions */
945  if (drop->concurrent)
946  {
948  lockmode = ShareUpdateExclusiveLock;
949  Assert(drop->removeType == OBJECT_INDEX);
950  if (list_length(drop->objects) != 1)
951  ereport(ERROR,
952  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
953  errmsg("DROP INDEX CONCURRENTLY does not support dropping multiple objects")));
954  if (drop->behavior == DROP_CASCADE)
955  ereport(ERROR,
956  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
957  errmsg("DROP INDEX CONCURRENTLY does not support CASCADE")));
958  }
959 
960  /*
961  * First we identify all the relations, then we delete them in a single
962  * performMultipleDeletions() call. This is to avoid unwanted DROP
963  * RESTRICT errors if one of the relations depends on another.
964  */
965 
966  /* Determine required relkind */
967  switch (drop->removeType)
968  {
969  case OBJECT_TABLE:
970  relkind = RELKIND_RELATION;
971  break;
972 
973  case OBJECT_INDEX:
974  relkind = RELKIND_INDEX;
975  break;
976 
977  case OBJECT_SEQUENCE:
978  relkind = RELKIND_SEQUENCE;
979  break;
980 
981  case OBJECT_VIEW:
982  relkind = RELKIND_VIEW;
983  break;
984 
985  case OBJECT_MATVIEW:
986  relkind = RELKIND_MATVIEW;
987  break;
988 
990  relkind = RELKIND_FOREIGN_TABLE;
991  break;
992 
993  default:
994  elog(ERROR, "unrecognized drop object type: %d",
995  (int) drop->removeType);
996  relkind = 0; /* keep compiler quiet */
997  break;
998  }
999 
1000  /* Lock and validate each relation; build a list of object addresses */
1001  objects = new_object_addresses();
1002 
1003  foreach(cell, drop->objects)
1004  {
1005  RangeVar *rel = makeRangeVarFromNameList((List *) lfirst(cell));
1006  Oid relOid;
1007  ObjectAddress obj;
1009 
1010  /*
1011  * These next few steps are a great deal like relation_openrv, but we
1012  * don't bother building a relcache entry since we don't need it.
1013  *
1014  * Check for shared-cache-inval messages before trying to access the
1015  * relation. This is needed to cover the case where the name
1016  * identifies a rel that has been dropped and recreated since the
1017  * start of our transaction: if we don't flush the old syscache entry,
1018  * then we'll latch onto that entry and suffer an error later.
1019  */
1021 
1022  /* Look up the appropriate relation using namespace search. */
1023  state.relkind = relkind;
1024  state.heapOid = InvalidOid;
1025  state.partParentOid = InvalidOid;
1026  state.concurrent = drop->concurrent;
1027  relOid = RangeVarGetRelidExtended(rel, lockmode, true,
1028  false,
1030  (void *) &state);
1031 
1032  /* Not there? */
1033  if (!OidIsValid(relOid))
1034  {
1035  DropErrorMsgNonExistent(rel, relkind, drop->missing_ok);
1036  continue;
1037  }
1038 
1039  /* OK, we're ready to delete this one */
1041  obj.objectId = relOid;
1042  obj.objectSubId = 0;
1043 
1044  add_exact_object_address(&obj, objects);
1045  }
1046 
1047  performMultipleDeletions(objects, drop->behavior, flags);
1048 
1049  free_object_addresses(objects);
1050 }
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:2542
bool missing_ok
Definition: parsenodes.h:2545
#define RELKIND_MATVIEW
Definition: pg_class.h:165
int errcode(int sqlerrcode)
Definition: elog.c:575
RangeVar * makeRangeVarFromNameList(List *names)
Definition: namespace.c:2980
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2107
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2052
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2323
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
ObjectType removeType
Definition: parsenodes.h:2543
#define PERFORM_DELETION_CONCURRENTLY
Definition: dependency.h:175
#define ERROR
Definition: elog.h:43
bool concurrent
Definition: parsenodes.h:2546
DropBehavior behavior
Definition: parsenodes.h:2544
#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:1059
#define InvalidOid
Definition: postgres_ext.h:36
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define Assert(condition)
Definition: c.h:675
#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:46
static void DropErrorMsgNonExistent(RangeVar *rel, char rightkind, bool missing_ok)
Definition: tablecmds.c:861
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
ObjectAddress renameatt ( RenameStmt stmt)

Definition at line 2669 of file tablecmds.c.

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

Referenced by ExecRenameStmt().

2670 {
2671  Oid relid;
2672  AttrNumber attnum;
2673  ObjectAddress address;
2674 
2675  /* lock level taken here should match renameatt_internal */
2677  stmt->missing_ok, false,
2679  NULL);
2680 
2681  if (!OidIsValid(relid))
2682  {
2683  ereport(NOTICE,
2684  (errmsg("relation \"%s\" does not exist, skipping",
2685  stmt->relation->relname)));
2686  return InvalidObjectAddress;
2687  }
2688 
2689  attnum =
2690  renameatt_internal(relid,
2691  stmt->subname, /* old att name */
2692  stmt->newname, /* new att name */
2693  stmt->relation->inh, /* recursive? */
2694  false, /* recursing? */
2695  0, /* expected inhcount */
2696  stmt->behavior);
2697 
2698  ObjectAddressSubSet(address, RelationRelationId, relid, attnum);
2699 
2700  return address;
2701 }
char * subname
Definition: parsenodes.h:2770
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:2772
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
char * relname
Definition: primnodes.h:68
bool missing_ok
Definition: parsenodes.h:2774
#define ereport(elevel, rest)
Definition: elog.h:122
bool inh
Definition: primnodes.h:69
RangeVar * relation
Definition: parsenodes.h:2768
#define NOTICE
Definition: elog.h:37
static void RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:2649
#define NULL
Definition: c.h:229
static AttrNumber renameatt_internal(Oid myrelid, const char *oldattname, const char *newattname, bool recurse, bool recursing, int expected_parents, DropBehavior behavior)
Definition: tablecmds.c:2504
#define ObjectAddressSubSet(addr, class_id, object_id, object_sub_id)
Definition: objectaddress.h:33
#define AccessExclusiveLock
Definition: lockdefs.h:46
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:797
DropBehavior behavior
Definition: parsenodes.h:2773
int16 AttrNumber
Definition: attnum.h:21
ObjectAddress renameatt_type ( RenameStmt stmt)
ObjectAddress RenameConstraint ( RenameStmt stmt)

Definition at line 2806 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, NULL, RenameStmt::object, OBJECT_DOMCONSTRAINT, ObjectIdGetDatum, OidIsValid, RangeVarCallbackForRenameAttribute(), RangeVarGetRelidExtended(), RenameStmt::relation, ReleaseSysCache(), RangeVar::relname, rename_constraint_internal(), RenameStmt::renameType, RowExclusiveLock, SearchSysCache1, RenameStmt::subname, typenameTypeId(), TYPEOID, and TypeRelationId.

Referenced by ExecRenameStmt().

2807 {
2808  Oid relid = InvalidOid;
2809  Oid typid = InvalidOid;
2810 
2811  if (stmt->renameType == OBJECT_DOMCONSTRAINT)
2812  {
2813  Relation rel;
2814  HeapTuple tup;
2815 
2818  tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2819  if (!HeapTupleIsValid(tup))
2820  elog(ERROR, "cache lookup failed for type %u", typid);
2821  checkDomainOwner(tup);
2822  ReleaseSysCache(tup);
2823  heap_close(rel, NoLock);
2824  }
2825  else
2826  {
2827  /* lock level taken here should match rename_constraint_internal */
2829  stmt->missing_ok, false,
2831  NULL);
2832  if (!OidIsValid(relid))
2833  {
2834  ereport(NOTICE,
2835  (errmsg("relation \"%s\" does not exist, skipping",
2836  stmt->relation->relname)));
2837  return InvalidObjectAddress;
2838  }
2839  }
2840 
2841  return
2842  rename_constraint_internal(relid, typid,
2843  stmt->subname,
2844  stmt->newname,
2845  (stmt->relation &&
2846  stmt->relation->inh), /* recursive? */
2847  false, /* recursing? */
2848  0 /* expected inhcount */ );
2849 
2850 }
char * subname
Definition: parsenodes.h:2770
ObjectType renameType
Definition: parsenodes.h:2766
#define castNode(_type_, nodeptr)
Definition: nodes.h:578
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:2707
char * newname
Definition: parsenodes.h:2772
unsigned int Oid
Definition: postgres_ext.h:31
#define TypeRelationId
Definition: pg_type.h:34
#define OidIsValid(objectId)
Definition: c.h:538
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
char * relname
Definition: primnodes.h:68
bool missing_ok
Definition: parsenodes.h:2774
#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:2769
#define ereport(elevel, rest)
Definition: elog.h:122
bool inh
Definition: primnodes.h:69
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
RangeVar * relation
Definition: parsenodes.h:2768
#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:2649
#define NULL
Definition: c.h:229
void checkDomainOwner(HeapTuple tup)
Definition: typecmds.c:2952
#define AccessExclusiveLock
Definition: lockdefs.h:46
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:797
TypeName * makeTypeNameFromNameList(List *names)
Definition: makefuncs.c:453
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:274
ObjectAddress RenameRelation ( RenameStmt stmt)

Definition at line 2857 of file tablecmds.c.

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

Referenced by ExecRenameStmt().

2858 {
2859  Oid relid;
2860  ObjectAddress address;
2861 
2862  /*
2863  * Grab an exclusive lock on the target table, index, sequence, view,
2864  * materialized view, or foreign table, which we will NOT release until
2865  * end of transaction.
2866  *
2867  * Lock level used here should match RenameRelationInternal, to avoid lock
2868  * escalation.
2869  */
2871  stmt->missing_ok, false,
2873  (void *) stmt);
2874 
2875  if (!OidIsValid(relid))
2876  {
2877  ereport(NOTICE,
2878  (errmsg("relation \"%s\" does not exist, skipping",
2879  stmt->relation->relname)));
2880  return InvalidObjectAddress;
2881  }
2882 
2883  /* Do the work */
2884  RenameRelationInternal(relid, stmt->newname, false);
2885 
2886  ObjectAddressSet(address, RelationRelationId, relid);
2887 
2888  return address;
2889 }
void RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal)
Definition: tablecmds.c:2901
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:2772
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
char * relname
Definition: primnodes.h:68
bool missing_ok
Definition: parsenodes.h:2774
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:12990
#define ereport(elevel, rest)
Definition: elog.h:122
RangeVar * relation
Definition: parsenodes.h:2768
#define NOTICE
Definition: elog.h:37
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define AccessExclusiveLock
Definition: lockdefs.h:46
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:797
void RenameRelationInternal ( Oid  myrelid,
const char *  newrelname,
bool  is_internal 
)

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

2902 {
2903  Relation targetrelation;
2904  Relation relrelation; /* for RELATION relation */
2905  HeapTuple reltup;
2906  Form_pg_class relform;
2907  Oid namespaceId;
2908 
2909  /*
2910  * Grab an exclusive lock on the target table, index, sequence, view,
2911  * materialized view, or foreign table, which we will NOT release until
2912  * end of transaction.
2913  */
2914  targetrelation = relation_open(myrelid, AccessExclusiveLock);
2915  namespaceId = RelationGetNamespace(targetrelation);
2916 
2917  /*
2918  * Find relation's pg_class tuple, and make sure newrelname isn't in use.
2919  */
2921 
2922  reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
2923  if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
2924  elog(ERROR, "cache lookup failed for relation %u", myrelid);
2925  relform = (Form_pg_class) GETSTRUCT(reltup);
2926 
2927  if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
2928  ereport(ERROR,
2929  (errcode(ERRCODE_DUPLICATE_TABLE),
2930  errmsg("relation \"%s\" already exists",
2931  newrelname)));
2932 
2933  /*
2934  * Update pg_class tuple with new relname. (Scribbling on reltup is OK
2935  * because it's a copy...)
2936  */
2937  namestrcpy(&(relform->relname), newrelname);
2938 
2939  CatalogTupleUpdate(relrelation, &reltup->t_self, reltup);
2940 
2942  InvalidOid, is_internal);
2943 
2944  heap_freetuple(reltup);
2945  heap_close(relrelation, RowExclusiveLock);
2946 
2947  /*
2948  * Also rename the associated type, if any.
2949  */
2950  if (OidIsValid(targetrelation->rd_rel->reltype))
2951  RenameTypeInternal(targetrelation->rd_rel->reltype,
2952  newrelname, namespaceId);
2953 
2954  /*
2955  * Also rename the associated constraint, if any.
2956  */
2957  if (targetrelation->rd_rel->relkind == RELKIND_INDEX)
2958  {
2959  Oid constraintId = get_index_constraint(myrelid);
2960 
2961  if (OidIsValid(constraintId))
2962  RenameConstraintById(constraintId, newrelname);
2963  }
2964 
2965  /*
2966  * Close rel, but keep exclusive lock!
2967  */
2968  relation_close(targetrelation, NoLock);
2969 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#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:1260
#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:1372
unsigned int Oid
Definition: postgres_ext.h:31
int namestrcpy(Name name, const char *str)
Definition: name.c:217
#define OidIsValid(objectId)
Definition: c.h:538
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:1683
#define NoLock
Definition: lockdefs.h:34
#define InvokeObjectPostAlterHookArg(classId, objectId, subId,auxiliaryId, is_internal)
Definition: objectaccess.h:166
#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:1284
#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:165
#define AccessExclusiveLock
Definition: lockdefs.h:46
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:1114
#define elog
Definition: elog.h:219
#define RelationGetNamespace(relation)
Definition: rel.h:444
void SetRelationHasSubclass ( Oid  relationId,
bool  relhassubclass 
)

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

2424 {
2425  Relation relationRelation;
2426  HeapTuple tuple;
2427  Form_pg_class classtuple;
2428 
2429  /*
2430  * Fetch a modifiable copy of the tuple, modify it, update pg_class.
2431  */
2432  relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
2433  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
2434  if (!HeapTupleIsValid(tuple))
2435  elog(ERROR, "cache lookup failed for relation %u", relationId);
2436  classtuple = (Form_pg_class) GETSTRUCT(tuple);
2437 
2438  if (classtuple->relhassubclass != relhassubclass)
2439  {
2440  classtuple->relhassubclass = relhassubclass;
2441  CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
2442  }
2443  else
2444  {
2445  /* no need to change tuple, but force relcache rebuild anyway */
2447  }
2448 
2449  heap_freetuple(tuple);
2450  heap_close(relationRelation, RowExclusiveLock);
2451 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define RelationRelationId
Definition: pg_class.h:29
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1372
#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:1284
#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:165
void CacheInvalidateRelcacheByTuple(HeapTuple classTuple)
Definition: inval.c:1269
#define elog
Definition: elog.h:219